From 05ab5ba0cf5b0c45bee6081facfabbb355e1cd73 Mon Sep 17 00:00:00 2001 From: piexel Date: Tue, 6 Oct 2026 13:46:55 +0200 Subject: [PATCH] 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"; + } +}