From 6ca6fc6989064990dbf83630bc7c1b1bef587fa2 Mon Sep 17 00:00:00 2001 From: Daniel Mills Date: Wed, 14 Jul 2021 02:34:13 -0400 Subject: [PATCH] Cleanup SRC --- src/main/java/com/volmit/iris/Iris.java | 770 ++- .../java/com/volmit/iris/IrisSettings.java | 383 +- .../volmit/iris/generator/IrisComplex.java | 619 ++- .../com/volmit/iris/generator/IrisEngine.java | 28 +- .../iris/generator/IrisEngineCompound.java | 118 +- .../iris/generator/IrisEngineEffects.java | 36 +- .../iris/generator/IrisEngineFramework.java | 20 +- .../iris/generator/IrisEngineParallax.java | 3 +- .../iris/generator/IrisWorldManager.java | 69 +- .../generator/actuator/IrisBiomeActuator.java | 16 +- .../actuator/IrisDecorantActuator.java | 60 +- .../actuator/IrisTerrainActuator.java | 54 +- .../decorator/IrisCeilingDecorator.java | 25 +- .../decorator/IrisEngineDecorator.java | 25 +- .../decorator/IrisSeaFloorDecorator.java | 31 +- .../decorator/IrisSeaSurfaceDecorator.java | 27 +- .../decorator/IrisShoreLineDecorator.java | 27 +- .../decorator/IrisSurfaceDecorator.java | 60 +- .../generator/modifier/IrisCaveModifier.java | 124 +- .../modifier/IrisDepositModifier.java | 53 +- .../generator/modifier/IrisPostModifier.java | 282 +- .../modifier/IrisRavineModifier.java | 133 +- .../com/volmit/iris/generator/noise/CNG.java | 832 ++-- .../iris/generator/noise/CNGFactory.java | 5 +- .../iris/generator/noise/CellGenerator.java | 123 +- .../iris/generator/noise/CellHeightNoise.java | 52 +- .../iris/generator/noise/CellularNoise.java | 45 +- .../iris/generator/noise/CubicNoise.java | 46 +- .../iris/generator/noise/FastNoise.java | 4430 ++++++++--------- .../iris/generator/noise/FastNoiseDouble.java | 4419 ++++++++-------- .../iris/generator/noise/FlatNoise.java | 35 +- .../noise/FractalBillowPerlinNoise.java | 59 +- .../noise/FractalBillowSimplexNoise.java | 59 +- .../generator/noise/FractalCubicNoise.java | 48 +- .../noise/FractalFBMSimplexNoise.java | 59 +- .../noise/FractalRigidMultiSimplexNoise.java | 59 +- .../iris/generator/noise/GlobNoise.java | 52 +- .../iris/generator/noise/NoiseFactory.java | 5 +- .../iris/generator/noise/NoiseGenerator.java | 20 +- .../iris/generator/noise/NoiseType.java | 42 +- .../iris/generator/noise/OctaveNoise.java | 5 +- .../iris/generator/noise/PerlinNoise.java | 146 +- .../generator/noise/RarityCellGenerator.java | 89 +- .../iris/generator/noise/SimplexNoise.java | 129 +- .../iris/generator/noise/VascularNoise.java | 52 +- .../iris/generator/noise/WhiteNoise.java | 53 +- .../iris/manager/ConversionManager.java | 424 +- .../com/volmit/iris/manager/EditManager.java | 161 +- .../volmit/iris/manager/IrisBoardManager.java | 194 +- .../volmit/iris/manager/IrisDataManager.java | 317 +- .../com/volmit/iris/manager/IrisProject.java | 1198 +++-- .../volmit/iris/manager/ProjectManager.java | 913 ++-- .../volmit/iris/manager/SchemaBuilder.java | 1855 +++---- .../com/volmit/iris/manager/WandManager.java | 468 +- .../iris/manager/command/CommandIris.java | 92 +- .../manager/command/CommandIrisDownload.java | 68 +- .../manager/command/CommandIrisMetrics.java | 86 +- .../manager/command/CommandIrisReload.java | 46 +- .../command/CommandIrisUpdateProject.java | 51 +- .../iris/manager/command/PermissionIris.java | 43 +- .../manager/command/PermissionIrisStudio.java | 37 +- .../command/jigsaw/CommandIrisJigsaw.java | 80 +- .../command/jigsaw/CommandIrisJigsawEdit.java | 84 +- .../command/jigsaw/CommandIrisJigsawExit.java | 23 +- .../command/jigsaw/CommandIrisJigsawNew.java | 91 +- .../jigsaw/CommandIrisJigsawPlace.java | 83 +- .../command/jigsaw/CommandIrisJigsawSave.java | 73 +- .../command/object/CommandIrisObject.java | 99 +- .../object/CommandIrisObjectContract.java | 103 +- .../command/object/CommandIrisObjectDust.java | 64 +- .../object/CommandIrisObjectExpand.java | 103 +- .../command/object/CommandIrisObjectP1.java | 111 +- .../command/object/CommandIrisObjectP2.java | 109 +- .../object/CommandIrisObjectPaste.java | 139 +- .../command/object/CommandIrisObjectSave.java | 139 +- .../object/CommandIrisObjectShift.java | 105 +- .../command/object/CommandIrisObjectWand.java | 70 +- .../command/object/CommandIrisObjectXAY.java | 155 +- .../command/object/CommandIrisObjectXPY.java | 135 +- .../command/studio/CommandIrisStudio.java | 119 +- .../studio/CommandIrisStudioBeautify.java | 127 +- .../studio/CommandIrisStudioClose.java | 118 +- .../studio/CommandIrisStudioConvert.java | 51 +- .../studio/CommandIrisStudioCreate.java | 88 +- .../studio/CommandIrisStudioEditBiome.java | 90 +- .../studio/CommandIrisStudioExplorer.java | 78 +- .../CommandIrisStudioExplorerGenerator.java | 107 +- .../command/studio/CommandIrisStudioGoto.java | 212 +- .../studio/CommandIrisStudioHotload.java | 79 +- .../command/studio/CommandIrisStudioLoot.java | 161 +- .../command/studio/CommandIrisStudioMap.java | 80 +- .../command/studio/CommandIrisStudioOpen.java | 62 +- .../studio/CommandIrisStudioPackage.java | 86 +- .../studio/CommandIrisStudioProfile.java | 383 +- .../studio/CommandIrisStudioSummon.java | 108 +- .../studio/CommandIrisStudioTPStudio.java | 84 +- .../studio/CommandIrisStudioUpdate.java | 72 +- .../manager/command/what/CommandIrisWhat.java | 62 +- .../command/what/CommandIrisWhatBiome.java | 112 +- .../command/what/CommandIrisWhatBlock.java | 126 +- .../command/what/CommandIrisWhatHand.java | 101 +- .../command/what/CommandIrisWhatObjects.java | 370 +- .../command/world/CommandIrisCreate.java | 413 +- .../manager/command/world/CommandIrisFix.java | 93 +- .../command/world/CommandIrisPregen.java | 263 +- .../command/world/CommandIrisRegen.java | 42 +- .../command/world/CommandIrisUpdateWorld.java | 88 +- .../manager/command/world/CommandLocate.java | 17 +- .../volmit/iris/manager/edit/BlockEditor.java | 27 +- .../volmit/iris/manager/edit/BlockSignal.java | 23 +- .../iris/manager/edit/BukkitBlockEditor.java | 89 +- .../iris/manager/edit/DustRevealer.java | 38 +- .../iris/manager/edit/JigsawEditor.java | 104 +- .../iris/manager/edit/WEBlockEditor.java | 101 +- .../volmit/iris/manager/gui/IrisRenderer.java | 47 +- .../volmit/iris/manager/gui/IrisVision.java | 535 +- .../iris/manager/gui/NoiseExplorer.java | 541 +- .../com/volmit/iris/manager/gui/Renderer.java | 7 +- .../volmit/iris/manager/gui/TileRender.java | 3 +- .../com/volmit/iris/manager/link/BKLink.java | 39 +- .../iris/manager/link/CitizensLink.java | 51 +- .../iris/manager/link/MultiverseCoreLink.java | 215 +- .../iris/manager/link/MythicMobsLink.java | 76 +- .../volmit/iris/manager/report/Report.java | 16 +- src/main/java/com/volmit/iris/nms/INMS.java | 91 +- .../java/com/volmit/iris/nms/INMSBinding.java | 28 +- .../volmit/iris/nms/v17_1/NMSBinding17_1.java | 237 +- .../com/volmit/iris/nms/v1X/NMSBinding1X.java | 82 +- .../com/volmit/iris/object/CarvingMode.java | 35 +- .../volmit/iris/object/DecorationPart.java | 33 +- .../com/volmit/iris/object/FontStyle.java | 21 +- .../com/volmit/iris/object/InferredType.java | 45 +- .../iris/object/InterpolationMethod.java | 166 +- .../volmit/iris/object/InventorySlotType.java | 33 +- .../iris/object/IrisAttributeModifier.java | 109 +- .../iris/object/IrisAxisRotationClamp.java | 122 +- .../com/volmit/iris/object/IrisBiome.java | 1188 ++--- .../iris/object/IrisBiomeGeneratorLink.java | 76 +- .../volmit/iris/object/IrisBiomeMutation.java | 148 +- .../iris/object/IrisBiomePaletteLayer.java | 173 +- .../com/volmit/iris/object/IrisBlockData.java | 313 +- .../volmit/iris/object/IrisBlockDrops.java | 114 +- .../volmit/iris/object/IrisCarveLayer.java | 113 +- .../com/volmit/iris/object/IrisCaveFluid.java | 70 +- .../com/volmit/iris/object/IrisCaveLayer.java | 48 +- .../com/volmit/iris/object/IrisColor.java | 126 +- .../com/volmit/iris/object/IrisCompat.java | 591 ++- .../object/IrisCompatabilityBlockFilter.java | 68 +- .../object/IrisCompatabilityItemFilter.java | 69 +- .../com/volmit/iris/object/IrisDecorator.java | 348 +- .../iris/object/IrisDepositGenerator.java | 210 +- .../com/volmit/iris/object/IrisDimension.java | 886 ++-- .../iris/object/IrisDimensionIndex.java | 42 +- .../com/volmit/iris/object/IrisDirection.java | 846 ++-- .../com/volmit/iris/object/IrisEffect.java | 432 +- .../volmit/iris/object/IrisEnchantment.java | 124 +- .../com/volmit/iris/object/IrisEntity.java | 435 +- .../iris/object/IrisEntityInitialSpawn.java | 101 +- .../iris/object/IrisEntitySpawnOverride.java | 111 +- .../com/volmit/iris/object/IrisFeature.java | 9 +- .../iris/object/IrisFeaturePositional.java | 65 +- .../iris/object/IrisFeaturePotential.java | 3 +- .../com/volmit/iris/object/IrisGenerator.java | 454 +- .../iris/object/IrisGeneratorStyle.java | 108 +- .../volmit/iris/object/IrisInterpolator.java | 46 +- .../volmit/iris/object/IrisJigsawPiece.java | 135 +- .../iris/object/IrisJigsawPieceConnector.java | 120 +- .../iris/object/IrisJigsawPlacement.java | 23 +- .../volmit/iris/object/IrisJigsawPool.java | 15 +- .../iris/object/IrisJigsawStructure.java | 176 +- .../object/IrisJigsawStructurePlacement.java | 21 +- .../java/com/volmit/iris/object/IrisLoot.java | 436 +- .../volmit/iris/object/IrisLootReference.java | 59 +- .../com/volmit/iris/object/IrisLootTable.java | 96 +- .../iris/object/IrisMaterialPalette.java | 152 +- .../iris/object/IrisNoiseGenerator.java | 205 +- .../com/volmit/iris/object/IrisObject.java | 2070 ++++---- .../volmit/iris/object/IrisObjectLimit.java | 36 +- .../volmit/iris/object/IrisObjectLoot.java | 17 +- .../iris/object/IrisObjectPlacement.java | 429 +- .../volmit/iris/object/IrisObjectReplace.java | 84 +- .../iris/object/IrisObjectRotation.java | 907 ++-- .../volmit/iris/object/IrisObjectScale.java | 115 +- .../iris/object/IrisObjectTranslate.java | 90 +- .../com/volmit/iris/object/IrisPosition.java | 63 +- .../volmit/iris/object/IrisPosition2D.java | 15 +- .../volmit/iris/object/IrisPotionEffect.java | 137 +- .../com/volmit/iris/object/IrisRange.java | 29 +- .../volmit/iris/object/IrisRareObject.java | 30 +- .../com/volmit/iris/object/IrisRegion.java | 1071 ++-- .../volmit/iris/object/IrisRegionRidge.java | 220 +- .../volmit/iris/object/IrisRegionSpot.java | 122 +- .../volmit/iris/object/IrisRegistrant.java | 9 +- .../iris/object/IrisShapedGeneratorStyle.java | 68 +- .../com/volmit/iris/object/IrisSlopeClip.java | 53 +- .../java/com/volmit/iris/object/LootMode.java | 21 +- .../com/volmit/iris/object/NoiseStyle.java | 676 ++- .../volmit/iris/object/ObjectPlaceMode.java | 57 +- .../volmit/iris/object/tile/TileBanner.java | 50 +- .../com/volmit/iris/object/tile/TileData.java | 53 +- .../com/volmit/iris/object/tile/TileSign.java | 2 +- .../volmit/iris/object/tile/TileSpawner.java | 2 +- .../volmit/iris/pregen/DirectWorldWriter.java | 107 +- .../com/volmit/iris/pregen/Pregenerator.java | 1258 +++-- .../iris/scaffold/IrisWorldCreator.java | 39 +- .../com/volmit/iris/scaffold/IrisWorlds.java | 77 +- .../iris/scaffold/cache/AtomicCache.java | 169 +- .../com/volmit/iris/scaffold/cache/Cache.java | 22 +- .../iris/scaffold/cache/Multicache.java | 7 +- .../iris/scaffold/data/DataPalette.java | 43 +- .../iris/scaffold/data/DataProvider.java | 5 +- .../volmit/iris/scaffold/data/IOAdapter.java | 11 +- .../iris/scaffold/data/io/Deserializer.java | 53 +- .../scaffold/data/io/ExceptionBiFunction.java | 4 +- .../data/io/ExceptionTriConsumer.java | 2 +- .../iris/scaffold/data/io/MaxDepthIO.java | 16 +- .../data/io/MaxDepthReachedException.java | 6 +- .../iris/scaffold/data/io/Serializer.java | 31 +- .../scaffold/data/io/StringDeserializer.java | 48 +- .../scaffold/data/io/StringSerializer.java | 46 +- .../volmit/iris/scaffold/data/mca/Chunk.java | 1156 ++--- .../scaffold/data/mca/CompressionType.java | 60 +- .../scaffold/data/mca/ExceptionFunction.java | 2 +- .../iris/scaffold/data/mca/LoadFlags.java | 32 +- .../iris/scaffold/data/mca/MCAFile.java | 536 +- .../iris/scaffold/data/mca/MCAUtil.java | 396 +- .../iris/scaffold/data/mca/Section.java | 714 +-- .../scaffold/data/nbt/io/NBTDeserializer.java | 35 +- .../scaffold/data/nbt/io/NBTInputStream.java | 224 +- .../scaffold/data/nbt/io/NBTOutputStream.java | 235 +- .../scaffold/data/nbt/io/NBTSerializer.java | 37 +- .../iris/scaffold/data/nbt/io/NBTUtil.java | 115 +- .../iris/scaffold/data/nbt/io/NamedTag.java | 36 +- .../scaffold/data/nbt/io/ParseException.java | 32 +- .../data/nbt/io/SNBTDeserializer.java | 27 +- .../iris/scaffold/data/nbt/io/SNBTParser.java | 423 +- .../scaffold/data/nbt/io/SNBTSerializer.java | 14 +- .../iris/scaffold/data/nbt/io/SNBTUtil.java | 12 +- .../iris/scaffold/data/nbt/io/SNBTWriter.java | 203 +- .../scaffold/data/nbt/io/StringPointer.java | 190 +- .../iris/scaffold/data/nbt/tag/ArrayTag.java | 61 +- .../scaffold/data/nbt/tag/ByteArrayTag.java | 56 +- .../iris/scaffold/data/nbt/tag/ByteTag.java | 66 +- .../scaffold/data/nbt/tag/CompoundTag.java | 418 +- .../iris/scaffold/data/nbt/tag/DoubleTag.java | 54 +- .../iris/scaffold/data/nbt/tag/EndTag.java | 42 +- .../iris/scaffold/data/nbt/tag/FloatTag.java | 54 +- .../scaffold/data/nbt/tag/IntArrayTag.java | 56 +- .../iris/scaffold/data/nbt/tag/IntTag.java | 54 +- .../iris/scaffold/data/nbt/tag/ListTag.java | 509 +- .../scaffold/data/nbt/tag/LongArrayTag.java | 56 +- .../iris/scaffold/data/nbt/tag/LongTag.java | 54 +- .../data/nbt/tag/NonNullEntrySet.java | 200 +- .../iris/scaffold/data/nbt/tag/NumberTag.java | 50 +- .../iris/scaffold/data/nbt/tag/ShortTag.java | 54 +- .../iris/scaffold/data/nbt/tag/StringTag.java | 72 +- .../iris/scaffold/data/nbt/tag/Tag.java | 310 +- .../iris/scaffold/engine/BlockUpdater.java | 6 +- .../volmit/iris/scaffold/engine/Engine.java | 226 +- .../iris/scaffold/engine/EngineActuator.java | 5 +- .../engine/EngineAssignedActuator.java | 6 +- .../engine/EngineAssignedBiModifier.java | 6 +- .../engine/EngineAssignedComponent.java | 3 +- .../engine/EngineAssignedModifier.java | 6 +- .../engine/EngineAssignedWorldManager.java | 30 +- .../scaffold/engine/EngineBiModifier.java | 4 +- .../iris/scaffold/engine/EngineComponent.java | 54 +- .../engine/EngineCompositeGenerator.java | 347 +- .../iris/scaffold/engine/EngineCompound.java | 114 +- .../iris/scaffold/engine/EngineData.java | 14 +- .../iris/scaffold/engine/EngineDecorator.java | 13 +- .../iris/scaffold/engine/EngineEffects.java | 4 +- .../iris/scaffold/engine/EngineFramework.java | 28 +- .../iris/scaffold/engine/EngineMetrics.java | 3 +- .../iris/scaffold/engine/EngineModifier.java | 4 +- .../engine/EngineParallaxManager.java | 420 +- .../iris/scaffold/engine/EnginePlayer.java | 32 +- .../iris/scaffold/engine/EngineTarget.java | 12 +- .../scaffold/engine/EngineWorldManager.java | 17 +- .../volmit/iris/scaffold/engine/Fallible.java | 21 +- .../iris/scaffold/engine/GeneratorAccess.java | 42 +- .../iris/scaffold/engine/Hotloadable.java | 2 +- .../iris/scaffold/engine/IrisAccess.java | 190 +- .../scaffold/engine/IrisAccessProvider.java | 2 +- .../iris/scaffold/engine/LootProvider.java | 8 +- .../scaffold/engine/PregeneratedData.java | 21 +- .../com/volmit/iris/scaffold/hunk/Hunk.java | 2578 +++++----- .../volmit/iris/scaffold/hunk/HunkFace.java | 15 +- .../scaffold/hunk/io/BasicHunkIOAdapter.java | 23 +- .../iris/scaffold/hunk/io/HunkIOAdapter.java | 19 +- .../iris/scaffold/hunk/io/HunkRegion.java | 124 +- .../scaffold/hunk/io/HunkRegionSlice.java | 426 +- .../hunk/io/PaletteHunkIOAdapter.java | 31 +- .../iris/scaffold/hunk/storage/ArrayHunk.java | 51 +- .../hunk/storage/AtomicDoubleHunk.java | 49 +- .../scaffold/hunk/storage/AtomicHunk.java | 54 +- .../hunk/storage/AtomicIntegerHunk.java | 52 +- .../scaffold/hunk/storage/AtomicLongHunk.java | 52 +- .../scaffold/hunk/storage/MappedHunk.java | 81 +- .../scaffold/hunk/storage/StorageHunk.java | 35 +- .../hunk/storage/SynchronizedArrayHunk.java | 66 +- .../scaffold/hunk/view/BiomeGridHunkView.java | 59 +- .../hunk/view/ChunkBiomeHunkView.java | 67 +- .../scaffold/hunk/view/ChunkDataHunkView.java | 82 +- .../scaffold/hunk/view/ChunkHunkView.java | 67 +- .../scaffold/hunk/view/DriftHunkView.java | 78 +- .../scaffold/hunk/view/FringedHunkView.java | 23 +- .../iris/scaffold/hunk/view/HunkView.java | 104 +- .../scaffold/hunk/view/InvertedHunkView.java | 66 +- .../scaffold/hunk/view/ListeningHunk.java | 27 +- .../iris/scaffold/hunk/view/ReadOnlyHunk.java | 27 +- .../scaffold/hunk/view/RotatedXHunkView.java | 94 +- .../scaffold/hunk/view/RotatedYHunkView.java | 96 +- .../scaffold/hunk/view/RotatedZHunkView.java | 86 +- .../hunk/view/SynchronizedHunkView.java | 26 +- .../scaffold/hunk/view/WriteTrackHunk.java | 26 +- .../iris/scaffold/jigsaw/PlannedPiece.java | 76 +- .../scaffold/jigsaw/PlannedStructure.java | 205 +- .../lighting/BlockFaceSetSection.java | 2 +- .../scaffold/lighting/FlatRegionInfo.java | 23 +- .../scaffold/lighting/FlatRegionInfoMap.java | 23 +- .../scaffold/lighting/LightingAutoClean.java | 15 +- .../scaffold/lighting/LightingCategory.java | 14 +- .../iris/scaffold/lighting/LightingChunk.java | 24 +- .../lighting/LightingChunkNeighboring.java | 6 +- .../iris/scaffold/lighting/LightingCube.java | 88 +- .../lighting/LightingCubeNeighboring.java | 4 +- .../lighting/LightingForcedChunkCache.java | 13 +- .../scaffold/lighting/LightingService.java | 34 +- .../iris/scaffold/lighting/LightingTask.java | 6 +- .../scaffold/lighting/LightingTaskBatch.java | 23 +- .../scaffold/lighting/LightingTaskWorld.java | 7 +- .../iris/scaffold/lighting/LightingUtil.java | 6 +- .../scaffold/lighting/TimeDurationFormat.java | 4 +- .../scaffold/parallax/ParallaxAccess.java | 48 +- .../scaffold/parallax/ParallaxChunkMeta.java | 5 +- .../scaffold/parallax/ParallaxRegion.java | 309 +- .../iris/scaffold/parallax/ParallaxWorld.java | 385 +- .../iris/scaffold/parallel/BurstExecutor.java | 106 +- .../iris/scaffold/parallel/BurstedHunk.java | 9 +- .../iris/scaffold/parallel/GridLock.java | 50 +- .../iris/scaffold/parallel/MultiBurst.java | 105 +- .../scaffold/stream/ArraySignificance.java | 88 +- .../iris/scaffold/stream/BasicLayer.java | 34 +- .../iris/scaffold/stream/BasicStream.java | 9 +- .../iris/scaffold/stream/ProceduralLayer.java | 13 +- .../scaffold/stream/ProceduralStream.java | 926 ++-- .../iris/scaffold/stream/Significance.java | 9 +- .../stream/arithmetic/AddingStream.java | 64 +- .../stream/arithmetic/ClampedStream.java | 61 +- .../CoordinateBitShiftLeftStream.java | 50 +- .../CoordinateBitShiftRightStream.java | 50 +- .../stream/arithmetic/DividingStream.java | 64 +- .../stream/arithmetic/FittedStream.java | 76 +- .../stream/arithmetic/MaxingStream.java | 64 +- .../stream/arithmetic/MinningStream.java | 64 +- .../stream/arithmetic/ModuloStream.java | 64 +- .../stream/arithmetic/MultiplyingStream.java | 64 +- .../stream/arithmetic/OffsetStream.java | 58 +- .../stream/arithmetic/RadialStream.java | 64 +- .../arithmetic/RoundingDoubleStream.java | 57 +- .../stream/arithmetic/SlopeStream.java | 64 +- .../stream/arithmetic/SubtractingStream.java | 64 +- .../stream/arithmetic/ZoomStream.java | 58 +- .../convert/AwareConversionStream2D.java | 69 +- .../convert/AwareConversionStream3D.java | 69 +- .../convert/CachedConversionStream.java | 78 +- .../stream/convert/ConversionStream.java | 83 +- .../stream/convert/ForceDoubleStream.java | 50 +- .../stream/convert/RoundingStream.java | 57 +- .../stream/convert/SelectionStream.java | 81 +- .../stream/convert/SignificanceStream.java | 110 +- .../scaffold/stream/convert/To3DStream.java | 46 +- .../stream/interpolation/BiHermiteStream.java | 138 +- .../interpolation/BiStarcastStream.java | 80 +- .../stream/interpolation/BicubicStream.java | 123 +- .../stream/interpolation/BilinearStream.java | 91 +- .../stream/interpolation/Interpolated.java | 61 +- .../interpolation/InterpolatingStream.java | 67 +- .../stream/interpolation/Interpolator.java | 19 +- .../interpolation/InterpolatorFactory.java | 147 +- .../interpolation/TriHermiteStream.java | 243 +- .../interpolation/TriStarcastStream.java | 82 +- .../stream/interpolation/TricubicStream.java | 241 +- .../stream/interpolation/TrilinearStream.java | 111 +- .../scaffold/stream/sources/CNGStream.java | 84 +- .../stream/sources/FunctionStream.java | 58 +- .../stream/utility/CachedStream2D.java | 65 +- .../stream/utility/NullSafeStream.java | 72 +- .../stream/utility/ProfiledStream.java | 249 +- .../stream/utility/SemaphoreStream.java | 60 +- .../stream/utility/SynchronizedStream.java | 56 +- src/main/java/com/volmit/iris/util/AR.java | 35 +- .../com/volmit/iris/util/AlignedPoint.java | 62 +- .../java/com/volmit/iris/util/ArrayType.java | 13 +- .../com/volmit/iris/util/AtomicAverage.java | 138 +- .../iris/util/AtomicRollingSequence.java | 148 +- .../java/com/volmit/iris/util/Average.java | 134 +- .../com/volmit/iris/util/AxisAlignedBB.java | 115 +- src/main/java/com/volmit/iris/util/B.java | 1065 ++-- .../java/com/volmit/iris/util/BiomeMap.java | 26 +- .../com/volmit/iris/util/BlockPosition.java | 113 +- src/main/java/com/volmit/iris/util/Board.java | 207 +- .../java/com/volmit/iris/util/BoardEntry.java | 59 +- .../com/volmit/iris/util/BoardManager.java | 124 +- .../com/volmit/iris/util/BoardProvider.java | 17 +- .../com/volmit/iris/util/BoardSettings.java | 11 +- .../com/volmit/iris/util/BoardUpdateTask.java | 1 - .../com/volmit/iris/util/ByteArrayTag.java | 20 +- .../java/com/volmit/iris/util/ByteTag.java | 18 +- src/main/java/com/volmit/iris/util/C.java | 1336 +++-- src/main/java/com/volmit/iris/util/CDou.java | 84 +- .../java/com/volmit/iris/util/Callback.java | 20 +- .../java/com/volmit/iris/util/CallbackCV.java | 5 +- .../com/volmit/iris/util/CancellableTask.java | 5 +- .../com/volmit/iris/util/CarveResult.java | 16 +- .../java/com/volmit/iris/util/CaveResult.java | 23 +- .../com/volmit/iris/util/ChronoLatch.java | 53 +- .../com/volmit/iris/util/ChunkPosition.java | 91 +- .../java/com/volmit/iris/util/Chunker.java | 78 +- .../java/com/volmit/iris/util/Command.java | 11 +- .../com/volmit/iris/util/CompoundTag.java | 77 +- .../java/com/volmit/iris/util/Consumer2.java | 5 +- .../java/com/volmit/iris/util/Consumer3.java | 5 +- .../java/com/volmit/iris/util/Consumer4.java | 5 +- .../java/com/volmit/iris/util/Consumer5.java | 5 +- .../java/com/volmit/iris/util/Consumer6.java | 5 +- .../java/com/volmit/iris/util/Consumer7.java | 5 +- .../java/com/volmit/iris/util/Consumer8.java | 5 +- .../java/com/volmit/iris/util/Contained.java | 42 +- .../java/com/volmit/iris/util/Control.java | 9 +- .../java/com/volmit/iris/util/Controller.java | 96 +- .../java/com/volmit/iris/util/Converter.java | 9 +- .../java/com/volmit/iris/util/Cuboid.java | 1486 +++--- .../com/volmit/iris/util/CuboidException.java | 12 +- .../volmit/iris/util/CustomOutputStream.java | 12 +- src/main/java/com/volmit/iris/util/DOP.java | 27 +- .../com/volmit/iris/util/DataPalette.java | 173 +- src/main/java/com/volmit/iris/util/Denv.java | 5 +- .../java/com/volmit/iris/util/DependsOn.java | 10 +- src/main/java/com/volmit/iris/util/Desc.java | 11 +- .../java/com/volmit/iris/util/Dimension.java | 123 +- .../com/volmit/iris/util/DimensionFace.java | 27 +- .../java/com/volmit/iris/util/Direction.java | 826 ++- .../com/volmit/iris/util/DontObfuscate.java | 9 +- .../volmit/iris/util/DoubleArrayUtils.java | 45 +- .../java/com/volmit/iris/util/DoubleTag.java | 18 +- .../java/com/volmit/iris/util/Element.java | 51 +- .../com/volmit/iris/util/ElementEvent.java | 16 +- .../java/com/volmit/iris/util/EndTag.java | 16 +- .../java/com/volmit/iris/util/FakeWorld.java | 1658 +++--- .../com/volmit/iris/util/FileWatcher.java | 53 +- .../com/volmit/iris/util/FinalInteger.java | 46 +- .../java/com/volmit/iris/util/FloatTag.java | 18 +- .../com/volmit/iris/util/FolderWatcher.java | 175 +- src/main/java/com/volmit/iris/util/Form.java | 2800 +++++------ .../java/com/volmit/iris/util/Function2.java | 5 +- .../java/com/volmit/iris/util/Function3.java | 5 +- .../java/com/volmit/iris/util/Function4.java | 5 +- .../java/com/volmit/iris/util/GBiset.java | 108 +- .../com/volmit/iris/util/GListAdapter.java | 60 +- .../com/volmit/iris/util/GroupedExecutor.java | 165 +- src/main/java/com/volmit/iris/util/HTTP.java | 320 +- .../com/volmit/iris/util/HTTPTokener.java | 103 +- .../java/com/volmit/iris/util/HeightMap.java | 28 +- .../volmit/iris/util/HeightedFakeWorld.java | 1675 +++---- .../java/com/volmit/iris/util/IActivator.java | 3 +- .../java/com/volmit/iris/util/ICommand.java | 77 +- .../com/volmit/iris/util/IController.java | 21 +- src/main/java/com/volmit/iris/util/ING.java | 10 +- src/main/java/com/volmit/iris/util/IO.java | 3423 ++++++------- .../java/com/volmit/iris/util/IORunnable.java | 5 +- .../com/volmit/iris/util/IObjectPlacer.java | 21 +- .../volmit/iris/util/IPostBlockAccess.java | 15 +- src/main/java/com/volmit/iris/util/IRare.java | 12 +- src/main/java/com/volmit/iris/util/Info.java | 10 +- .../java/com/volmit/iris/util/Instance.java | 9 +- .../com/volmit/iris/util/IntArrayTag.java | 18 +- .../java/com/volmit/iris/util/IntTag.java | 18 +- .../volmit/iris/util/InterpolationType.java | 14 +- .../volmit/iris/util/InvertedBiomeGrid.java | 71 +- .../volmit/iris/util/IrisBiomeStorage.java | 110 +- .../volmit/iris/util/IrisInterpolation.java | 1860 ++++--- .../java/com/volmit/iris/util/IrisLock.java | 60 +- .../com/volmit/iris/util/IrisMathHelper.java | 882 ++-- src/main/java/com/volmit/iris/util/J.java | 591 +-- .../java/com/volmit/iris/util/JSONArray.java | 1983 ++++---- .../com/volmit/iris/util/JSONException.java | 74 +- .../java/com/volmit/iris/util/JSONML.java | 941 ++-- .../java/com/volmit/iris/util/JSONObject.java | 3572 ++++++------- .../java/com/volmit/iris/util/JSONString.java | 17 +- .../com/volmit/iris/util/JSONStringer.java | 51 +- .../com/volmit/iris/util/JSONTokener.java | 860 ++-- .../java/com/volmit/iris/util/JSONWriter.java | 600 +-- .../java/com/volmit/iris/util/JarScanner.java | 129 +- src/main/java/com/volmit/iris/util/KList.java | 1411 +++--- src/main/java/com/volmit/iris/util/KMap.java | 656 ++- src/main/java/com/volmit/iris/util/KSet.java | 33 +- .../java/com/volmit/iris/util/KeyPair.java | 57 +- .../volmit/iris/util/LinkedTerrainChunk.java | 338 +- .../java/com/volmit/iris/util/ListTag.java | 20 +- .../java/com/volmit/iris/util/LongTag.java | 18 +- .../java/com/volmit/iris/util/Looper.java | 47 +- src/main/java/com/volmit/iris/util/M.java | 709 ++- .../com/volmit/iris/util/MaterialBlock.java | 188 +- .../java/com/volmit/iris/util/MathHelper.java | 923 ++-- .../java/com/volmit/iris/util/MaxNumber.java | 11 +- .../java/com/volmit/iris/util/Metrics.java | 32 +- .../com/volmit/iris/util/MetricsLite.java | 657 ++- .../java/com/volmit/iris/util/MinNumber.java | 11 +- .../com/volmit/iris/util/MortarCommand.java | 332 +- .../volmit/iris/util/MortarPermission.java | 132 +- .../com/volmit/iris/util/MortarSender.java | 327 +- .../com/volmit/iris/util/NBTConstants.java | 18 +- .../com/volmit/iris/util/NBTInputStream.java | 12 +- .../com/volmit/iris/util/NBTOutputStream.java | 17 +- .../java/com/volmit/iris/util/NBTUtils.java | 12 +- .../java/com/volmit/iris/util/NMSVersion.java | 207 +- .../com/volmit/iris/util/NastyFunction.java | 5 +- .../com/volmit/iris/util/NastyFuture.java | 5 +- .../com/volmit/iris/util/NastyRunnable.java | 5 +- .../com/volmit/iris/util/NibbleArray.java | 298 +- .../com/volmit/iris/util/NoiseInjector.java | 5 +- .../com/volmit/iris/util/NoiseProvider.java | 6 +- .../com/volmit/iris/util/NoiseProvider3.java | 6 +- src/main/java/com/volmit/iris/util/O.java | 74 +- .../iris/util/ObjectResourceLoader.java | 364 +- .../java/com/volmit/iris/util/Observable.java | 21 +- .../java/com/volmit/iris/util/Observer.java | 5 +- .../com/volmit/iris/util/ParticleSender.java | 166 +- .../java/com/volmit/iris/util/Permission.java | 9 +- .../java/com/volmit/iris/util/Point3d.java | 158 +- .../java/com/volmit/iris/util/Point3f.java | 168 +- .../java/com/volmit/iris/util/Point4d.java | 198 +- .../java/com/volmit/iris/util/Point4f.java | 282 +- .../volmit/iris/util/PrecisionStopwatch.java | 163 +- src/main/java/com/volmit/iris/util/Queue.java | 37 +- .../com/volmit/iris/util/QueueExecutor.java | 74 +- src/main/java/com/volmit/iris/util/RNG.java | 270 +- .../com/volmit/iris/util/ReactiveFolder.java | 46 +- .../volmit/iris/util/RegistryListBiome.java | 9 +- .../iris/util/RegistryListBlockType.java | 9 +- .../iris/util/RegistryListDimension.java | 9 +- .../volmit/iris/util/RegistryListEntity.java | 9 +- .../volmit/iris/util/RegistryListFont.java | 9 +- .../iris/util/RegistryListGenerator.java | 9 +- .../iris/util/RegistryListItemType.java | 9 +- .../volmit/iris/util/RegistryListJigsaw.java | 3 +- .../iris/util/RegistryListJigsawPiece.java | 3 +- .../iris/util/RegistryListJigsawPool.java | 3 +- .../volmit/iris/util/RegistryListLoot.java | 9 +- .../iris/util/RegistryListMythical.java | 9 +- .../volmit/iris/util/RegistryListObject.java | 9 +- .../volmit/iris/util/RegistryListRegion.java | 9 +- .../java/com/volmit/iris/util/Required.java | 9 +- .../com/volmit/iris/util/ResourceLoader.java | 397 +- .../com/volmit/iris/util/RollingSequence.java | 146 +- .../com/volmit/iris/util/RouterCommand.java | 62 +- src/main/java/com/volmit/iris/util/S.java | 17 +- .../com/volmit/iris/util/SKConversion.java | 62 +- src/main/java/com/volmit/iris/util/SR.java | 35 +- .../com/volmit/iris/util/ScoreDirection.java | 13 +- .../java/com/volmit/iris/util/ShortTag.java | 18 +- .../java/com/volmit/iris/util/Shrinkwrap.java | 33 +- .../com/volmit/iris/util/ShurikenQueue.java | 137 +- .../java/com/volmit/iris/util/Spiraled.java | 5 +- .../java/com/volmit/iris/util/Spiraler.java | 105 +- .../java/com/volmit/iris/util/StringTag.java | 18 +- .../java/com/volmit/iris/util/Supplier2.java | 5 +- .../java/com/volmit/iris/util/Supplier3.java | 5 +- .../java/com/volmit/iris/util/Switch.java | 39 +- src/main/java/com/volmit/iris/util/Tag.java | 16 +- .../com/volmit/iris/util/TaskExecutor.java | 332 +- .../com/volmit/iris/util/TerrainChunk.java | 205 +- .../com/volmit/iris/util/ThreadMonitor.java | 121 +- .../java/com/volmit/iris/util/Tuple2d.java | 666 ++- .../java/com/volmit/iris/util/Tuple2f.java | 666 ++- .../java/com/volmit/iris/util/Tuple3d.java | 789 ++- .../java/com/volmit/iris/util/Tuple3f.java | 793 ++- .../java/com/volmit/iris/util/Tuple4d.java | 909 ++-- .../java/com/volmit/iris/util/Tuple4f.java | 1162 +++-- .../java/com/volmit/iris/util/UIElement.java | 400 +- .../volmit/iris/util/UIStaticDecorator.java | 21 +- .../com/volmit/iris/util/UIVoidDecorator.java | 12 +- .../java/com/volmit/iris/util/UIWindow.java | 980 ++-- src/main/java/com/volmit/iris/util/V.java | 220 +- .../com/volmit/iris/util/VecMathUtil.java | 26 +- .../java/com/volmit/iris/util/Vector2d.java | 128 +- .../java/com/volmit/iris/util/Vector2f.java | 128 +- .../java/com/volmit/iris/util/Vector3d.java | 139 +- .../java/com/volmit/iris/util/Vector3f.java | 131 +- .../java/com/volmit/iris/util/VectorMath.java | 1321 +++-- .../java/com/volmit/iris/util/Violator.java | 428 +- .../com/volmit/iris/util/VirtualCommand.java | 266 +- .../volmit/iris/util/VoidOutputStream.java | 12 +- .../com/volmit/iris/util/VolmitPlugin.java | 1480 +++--- .../java/com/volmit/iris/util/WeightMap.java | 70 +- .../com/volmit/iris/util/WeightedRandom.java | 4 +- .../java/com/volmit/iris/util/Window.java | 69 +- .../com/volmit/iris/util/WindowDecorator.java | 5 +- .../volmit/iris/util/WindowResolution.java | 54 +- .../java/com/volmit/iris/util/Wrapper.java | 102 +- .../java/com/volmit/iris/util/Writable.java | 7 +- src/main/java/com/volmit/iris/util/XML.java | 1019 ++-- .../java/com/volmit/iris/util/XMLTokener.java | 725 ++- 605 files changed, 53283 insertions(+), 64305 deletions(-) diff --git a/src/main/java/com/volmit/iris/Iris.java b/src/main/java/com/volmit/iris/Iris.java index 0f37d7384..fd87af8e7 100644 --- a/src/main/java/com/volmit/iris/Iris.java +++ b/src/main/java/com/volmit/iris/Iris.java @@ -1,18 +1,15 @@ package com.volmit.iris; -import com.google.gson.Gson; import com.volmit.iris.manager.*; import com.volmit.iris.manager.command.CommandIris; -import com.volmit.iris.manager.command.world.CommandLocate; import com.volmit.iris.manager.command.PermissionIris; +import com.volmit.iris.manager.command.world.CommandLocate; import com.volmit.iris.manager.link.BKLink; import com.volmit.iris.manager.link.CitizensLink; import com.volmit.iris.manager.link.MultiverseCoreLink; import com.volmit.iris.manager.link.MythicMobsLink; import com.volmit.iris.nms.INMS; import com.volmit.iris.object.IrisCompat; -import com.volmit.iris.object.IrisObject; -import com.volmit.iris.object.IrisObjectPlacement; import com.volmit.iris.scaffold.IrisWorlds; import com.volmit.iris.scaffold.engine.EngineCompositeGenerator; import com.volmit.iris.util.*; @@ -21,523 +18,424 @@ import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.command.Command; import org.bukkit.command.CommandSender; -import org.bukkit.event.EventHandler; import org.bukkit.event.HandlerList; import org.bukkit.event.Listener; -import org.bukkit.event.player.AsyncPlayerChatEvent; import org.bukkit.generator.ChunkGenerator; import org.bukkit.plugin.Plugin; -import java.io.*; +import java.io.BufferedInputStream; +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; import java.net.URL; -import java.util.List; import java.util.concurrent.Callable; -public class Iris extends VolmitPlugin implements Listener -{ - public static KList executors = new KList<>(); - public static Iris instance; - public static ProjectManager proj; - public static ConversionManager convert; - public static WandManager wand; - public static EditManager edit; - public static IrisBoardManager board; - public static BKLink linkBK; - public static MultiverseCoreLink linkMultiverseCore; - public static MythicMobsLink linkMythicMobs; - public static CitizensLink linkCitizens; - private static final Queue syncJobs = new ShurikenQueue<>(); - public static boolean customModels = doesSupportCustomModels(); - public static boolean awareEntities = doesSupportAwareness(); - public static boolean biome3d = doesSupport3DBiomes(); - public static boolean lowMemoryMode = false; - public static IrisCompat compat; - public static FileWatcher configWatcher; +public class Iris extends VolmitPlugin implements Listener { + public static KList executors = new KList<>(); + public static Iris instance; + public static ProjectManager proj; + public static ConversionManager convert; + public static WandManager wand; + public static EditManager edit; + public static IrisBoardManager board; + public static BKLink linkBK; + public static MultiverseCoreLink linkMultiverseCore; + public static MythicMobsLink linkMythicMobs; + public static CitizensLink linkCitizens; + private static final Queue syncJobs = new ShurikenQueue<>(); + public static boolean customModels = doesSupportCustomModels(); + public static boolean awareEntities = doesSupportAwareness(); + public static boolean biome3d = doesSupport3DBiomes(); + public static boolean lowMemoryMode = false; + public static IrisCompat compat; + public static FileWatcher configWatcher; - @Permission - public static PermissionIris perm; + @Permission + public static PermissionIris perm; - @com.volmit.iris.util.Command - public CommandIris commandIris; + @com.volmit.iris.util.Command + public CommandIris commandIris; - public Iris() - { - instance = this; - INMS.get(); - IO.delete(new File("iris")); - lowMemoryMode = Runtime.getRuntime().maxMemory() < 4000000000L; // 4 * 1000 * 1000 * 1000 // 4; - } + public Iris() { + instance = this; + INMS.get(); + IO.delete(new File("iris")); + lowMemoryMode = Runtime.getRuntime().maxMemory() < 4000000000L; // 4 * 1000 * 1000 * 1000 // 4; + } - public static int getThreadCount() - { - int tc = IrisSettings.get().getConcurrency().getThreadCount(); + public static int getThreadCount() { + int tc = IrisSettings.get().getConcurrency().getThreadCount(); - if(tc <= 0) - { - int p = Runtime.getRuntime().availableProcessors(); + if (tc <= 0) { + int p = Runtime.getRuntime().availableProcessors(); - return p > 16 ? 16 : p < 4 ? 4 : p; - } + return p > 16 ? 16 : p < 4 ? 4 : p; + } - return tc; - } + return tc; + } - private static boolean doesSupport3DBiomes() - { - try - { - int v = Integer.parseInt(Bukkit.getBukkitVersion().split("\\Q-\\E")[0].split("\\Q.\\E")[1]); + private static boolean doesSupport3DBiomes() { + try { + int v = Integer.parseInt(Bukkit.getBukkitVersion().split("\\Q-\\E")[0].split("\\Q.\\E")[1]); - return v >= 15; - } + return v >= 15; + } catch (Throwable e) { - catch(Throwable e) - { + } - } + return false; + } - return false; - } + private static boolean doesSupportCustomModels() { + try { + int v = Integer.parseInt(Bukkit.getBukkitVersion().split("\\Q-\\E")[0].split("\\Q.\\E")[1]); - private static boolean doesSupportCustomModels() - { - try - { - int v = Integer.parseInt(Bukkit.getBukkitVersion().split("\\Q-\\E")[0].split("\\Q.\\E")[1]); + return v >= 14; + } catch (Throwable e) { - return v >= 14; - } + } - catch(Throwable e) - { + return false; + } - } + private static boolean doesSupportAwareness() { + try { + int v = Integer.parseInt(Bukkit.getBukkitVersion().split("\\Q-\\E")[0].split("\\Q.\\E")[1]); - return false; - } + return v >= 15; + } catch (Throwable e) { - private static boolean doesSupportAwareness() - { - try - { - int v = Integer.parseInt(Bukkit.getBukkitVersion().split("\\Q-\\E")[0].split("\\Q.\\E")[1]); + } - return v >= 15; - } - - catch(Throwable e) - { - - } - - return false; - } + return false; + } @Override - public void start() - { + public void start() { - } + } - @Override - public void stop() - { + @Override + public void stop() { - } + } - @Override - public String getTag(String subTag) - { - return C.BOLD + "" + C.DARK_GRAY + "[" + C.BOLD + "" + C.GREEN + "Iris" + C.BOLD + C.DARK_GRAY + "]" + C.RESET + "" + C.GRAY + ": "; - } + @Override + public String getTag(String subTag) { + return C.BOLD + "" + C.DARK_GRAY + "[" + C.BOLD + "" + C.GREEN + "Iris" + C.BOLD + C.DARK_GRAY + "]" + C.RESET + "" + C.GRAY + ": "; + } - public void onEnable() - { - instance = this; - try { - compat = IrisCompat.configured(getDataFile("compat.json")); - } catch (IOException e){ - // Do nothing. Everything continues properly but the exception is still there. - } - proj = new ProjectManager(); - convert = new ConversionManager(); - wand = new WandManager(); - board = new IrisBoardManager(); - linkMultiverseCore = new MultiverseCoreLink(); - linkBK = new BKLink(); - linkMythicMobs = new MythicMobsLink(); - edit = new EditManager(); - configWatcher = new FileWatcher(getDataFile("settings.json")); - J.a(() -> IO.delete(getTemp())); - J.a(this::bstats); - J.s(this::splash, 20); - J.sr(this::tickQueue, 0); - J.ar(this::checkConfigHotload, 50); - PaperLib.suggestPaper(this); - getServer().getPluginManager().registerEvents(new CommandLocate(), this); - getServer().getPluginManager().registerEvents(new WandManager() ,this); - super.onEnable(); - Bukkit.getPluginManager().registerEvents(this, this); - } + public void onEnable() { + instance = this; + try { + compat = IrisCompat.configured(getDataFile("compat.json")); + } catch (IOException e) { + // Do nothing. Everything continues properly but the exception is still there. + } + proj = new ProjectManager(); + convert = new ConversionManager(); + wand = new WandManager(); + board = new IrisBoardManager(); + linkMultiverseCore = new MultiverseCoreLink(); + linkBK = new BKLink(); + linkMythicMobs = new MythicMobsLink(); + edit = new EditManager(); + configWatcher = new FileWatcher(getDataFile("settings.json")); + J.a(() -> IO.delete(getTemp())); + J.a(this::bstats); + J.s(this::splash, 20); + J.sr(this::tickQueue, 0); + J.ar(this::checkConfigHotload, 50); + PaperLib.suggestPaper(this); + getServer().getPluginManager().registerEvents(new CommandLocate(), this); + getServer().getPluginManager().registerEvents(new WandManager(), this); + super.onEnable(); + Bukkit.getPluginManager().registerEvents(this, this); + } - private void checkConfigHotload() { - if(configWatcher.checkModified()) - { - IrisSettings.invalidate(); - IrisSettings.get(); - configWatcher.checkModified(); - Iris.info("Hotloaded settings.json"); - } - } + private void checkConfigHotload() { + if (configWatcher.checkModified()) { + IrisSettings.invalidate(); + IrisSettings.get(); + configWatcher.checkModified(); + Iris.info("Hotloaded settings.json"); + } + } - public void onDisable() - { - if(IrisSettings.get().isStudio()) - { - proj.close(); + public void onDisable() { + if (IrisSettings.get().isStudio()) { + proj.close(); - for(World i : Bukkit.getWorlds()) - { - if(IrisWorlds.isIrisWorld(i)) - { - IrisWorlds.access(i).close(); - } - } + for (World i : Bukkit.getWorlds()) { + if (IrisWorlds.isIrisWorld(i)) { + IrisWorlds.access(i).close(); + } + } - for(GroupedExecutor i : executors) - { - i.close(); - } - } + for (GroupedExecutor i : executors) { + i.close(); + } + } - executors.clear(); - board.disable(); - Bukkit.getScheduler().cancelTasks(this); - HandlerList.unregisterAll((Plugin) this); - super.onDisable(); - } + executors.clear(); + board.disable(); + Bukkit.getScheduler().cancelTasks(this); + HandlerList.unregisterAll((Plugin) this); + super.onDisable(); + } - public static void sq(Runnable r) - { - synchronized(syncJobs) - { - syncJobs.queue(r); - } - } + public static void sq(Runnable r) { + synchronized (syncJobs) { + syncJobs.queue(r); + } + } - private void tickQueue() - { - synchronized(Iris.syncJobs) - { - if(!Iris.syncJobs.hasNext()) - { - return; - } + private void tickQueue() { + synchronized (Iris.syncJobs) { + if (!Iris.syncJobs.hasNext()) { + return; + } - long ms = M.ms(); + long ms = M.ms(); - while(Iris.syncJobs.hasNext() && M.ms() - ms < 25) - { - try - { - Iris.syncJobs.next().run(); - } + while (Iris.syncJobs.hasNext() && M.ms() - ms < 25) { + try { + Iris.syncJobs.next().run(); + } catch (Throwable e) { + e.printStackTrace(); + } + } + } + } - catch(Throwable e) - { - e.printStackTrace(); - } - } - } - } + private void bstats() { + if (IrisSettings.get().getGeneral().isPluginMetrics()) { + J.s(() -> { + Metrics m = new Metrics(Iris.instance, 8757); - private void bstats() - { - if(IrisSettings.get().getGeneral().isPluginMetrics()) - { - J.s(() -> { - Metrics m = new Metrics(Iris.instance, 8757); + m.addCustomChart(new Metrics.SingleLineChart("custom_dimensions", new Callable() { + @Override + public Integer call() throws Exception { + return ProjectManager.countUniqueDimensions(); + } + })); - m.addCustomChart(new Metrics.SingleLineChart("custom_dimensions", new Callable() { - @Override - public Integer call() throws Exception { - return ProjectManager.countUniqueDimensions(); - } - })); + m.addCustomChart(new Metrics.SimplePie("using_custom_dimensions", new Callable() { + @Override + public String call() throws Exception { + return ProjectManager.countUniqueDimensions() > 0 ? "Active Projects" : "No Projects"; + } + })); + }); + } + } - m.addCustomChart(new Metrics.SimplePie("using_custom_dimensions", new Callable() { - @Override - public String call() throws Exception { - return ProjectManager.countUniqueDimensions() > 0 ? "Active Projects" : "No Projects"; - } - })); - }); - } - } + public static File getTemp() { + return instance.getDataFolder("cache", "temp"); + } - public static File getTemp() - { - return instance.getDataFolder("cache", "temp"); - } + @Override + public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { + return super.onCommand(sender, command, label, args); + } - @Override - public boolean onCommand(CommandSender sender, Command command, String label, String[] args) - { - return super.onCommand(sender, command, label, args); - } - - public void imsg(CommandSender s, String msg) - { - s.sendMessage(C.GREEN + "[" + C.DARK_GRAY + "Iris" + C.GREEN + "]" + C.GRAY + ": " + msg); - } + public void imsg(CommandSender s, String msg) { + s.sendMessage(C.GREEN + "[" + C.DARK_GRAY + "Iris" + C.GREEN + "]" + C.GRAY + ": " + msg); + } + @Override + public ChunkGenerator getDefaultWorldGenerator(String worldName, String id) { + String dimension = IrisSettings.get().getGenerator().getDefaultWorldType(); - @Override - public ChunkGenerator getDefaultWorldGenerator(String worldName, String id) - { - String dimension = IrisSettings.get().getGenerator().getDefaultWorldType(); + if (id != null && !id.isEmpty()) { + dimension = id; + Iris.info("Generator ID: " + id + " requested by bukkit/plugin. Assuming IrisDimension: " + id); + } - if(id != null && !id.isEmpty()) - { - dimension = id; - Iris.info("Generator ID: " + id + " requested by bukkit/plugin. Assuming IrisDimension: " + id); - } + return new EngineCompositeGenerator(dimension, true); + } - return new EngineCompositeGenerator(dimension, true); - } + public static void msg(String string) { + try { + if (instance == null) { + System.out.println("[Iris]: " + string); + return; + } - public static void msg(String string) - { - try - { - if(instance == null) - { - System.out.println("[Iris]: " + string); - return; - } + String msg = C.GRAY + "[" + C.GREEN + "Iris" + C.GRAY + "]: " + string; + Bukkit.getConsoleSender().sendMessage(msg); + } catch (Throwable e) { + System.out.println("[Iris]: " + string); + } + } - String msg = C.GRAY + "[" + C.GREEN + "Iris" + C.GRAY + "]: " + string; - Bukkit.getConsoleSender().sendMessage(msg); - } + public static File getCached(String name, String url) { + String h = IO.hash(name + "@" + url); + File f = Iris.instance.getDataFile("cache", h.substring(0, 2), h.substring(3, 5), h); - catch(Throwable e) - { - System.out.println("[Iris]: " + string); - } - } + if (!f.exists()) { + try (BufferedInputStream in = new BufferedInputStream(new URL(url).openStream()); FileOutputStream fileOutputStream = new FileOutputStream(f)) { + byte[] dataBuffer = new byte[1024]; + int bytesRead; + while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) { + fileOutputStream.write(dataBuffer, 0, bytesRead); + Iris.verbose("Aquiring " + name); + } + } catch (IOException ignored) { - public static File getCached(String name, String url) - { - String h = IO.hash(name + "@" + url); - File f = Iris.instance.getDataFile("cache", h.substring(0, 2), h.substring(3, 5), h); + } + } - if(!f.exists()) - { - try(BufferedInputStream in = new BufferedInputStream(new URL(url).openStream()); FileOutputStream fileOutputStream = new FileOutputStream(f)) - { - byte[] dataBuffer = new byte[1024]; - int bytesRead; - while((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) - { - fileOutputStream.write(dataBuffer, 0, bytesRead); - Iris.verbose("Aquiring " + name); - } - } + return f.exists() ? f : null; + } - catch(IOException ignored) - { + public static String getNonCached(String name, String url) { + String h = IO.hash(name + "*" + url); + File f = Iris.instance.getDataFile("cache", h.substring(0, 2), h.substring(3, 5), h); - } - } + try (BufferedInputStream in = new BufferedInputStream(new URL(url).openStream()); FileOutputStream fileOutputStream = new FileOutputStream(f)) { + byte[] dataBuffer = new byte[1024]; + int bytesRead; + while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) { + fileOutputStream.write(dataBuffer, 0, bytesRead); + } + } catch (IOException ignored) { - return f.exists() ? f : null; - } + } - public static String getNonCached(String name, String url) - { - String h = IO.hash(name + "*" + url); - File f = Iris.instance.getDataFile("cache", h.substring(0, 2), h.substring(3, 5), h); + try { + return IO.readAll(f); + } catch (IOException ignored) { - try(BufferedInputStream in = new BufferedInputStream(new URL(url).openStream()); FileOutputStream fileOutputStream = new FileOutputStream(f)) - { - byte[] dataBuffer = new byte[1024]; - int bytesRead; - while((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) - { - fileOutputStream.write(dataBuffer, 0, bytesRead); - } - } + } - catch(IOException ignored) - { + return ""; + } - } + public static File getNonCachedFile(String name, String url) { + String h = IO.hash(name + "*" + url); + File f = Iris.instance.getDataFile("cache", h.substring(0, 2), h.substring(3, 5), h); + Iris.verbose("Download " + name + " -> " + url); + try (BufferedInputStream in = new BufferedInputStream(new URL(url).openStream()); FileOutputStream fileOutputStream = new FileOutputStream(f)) { + byte[] dataBuffer = new byte[1024]; + int bytesRead; + while ((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) { + fileOutputStream.write(dataBuffer, 0, bytesRead); + } + } catch (IOException e) { + e.printStackTrace(); + } - try - { - return IO.readAll(f); - } + return f; + } - catch(IOException ignored) - { + public static void warn(String string) { + msg(C.YELLOW + string); + } - } + public static void error(String string) { + msg(C.RED + string); + } - return ""; - } + public static void verbose(String string) { + try { + if (IrisSettings.get().getGeneral().isVerbose()) { + msg(C.GRAY + string); + } + } catch (Throwable e) { + msg(C.GRAY + string); + } + } - public static File getNonCachedFile(String name, String url) - { - String h = IO.hash(name + "*" + url); - File f = Iris.instance.getDataFile("cache", h.substring(0, 2), h.substring(3, 5), h); - Iris.verbose("Download " + name + " -> " + url); - try(BufferedInputStream in = new BufferedInputStream(new URL(url).openStream()); FileOutputStream fileOutputStream = new FileOutputStream(f)) - { - byte[] dataBuffer = new byte[1024]; - int bytesRead; - while((bytesRead = in.read(dataBuffer, 0, 1024)) != -1) - { - fileOutputStream.write(dataBuffer, 0, bytesRead); - } - } + public static void success(String string) { + msg(C.GREEN + string); + } - catch(IOException e) - { - e.printStackTrace(); - } + public static void info(String string) { + msg(C.WHITE + string); + } - return f; - } + public void hit(long hits2) { + board.hits.put(hits2); + } - public static void warn(String string) - { - msg(C.YELLOW + string); - } + public void splash() { + if (!IrisSettings.get().getGeneral().isSplashLogoStartup()) { + return; + } - public static void error(String string) - { - msg(C.RED + string); - } + // @NoArgsConstructor + String padd = Form.repeat(" ", 8); + String padd2 = Form.repeat(" ", 4); + String[] info = {"", "", "", "", "", padd2 + C.GREEN + " Iris", padd2 + C.GRAY + " by " + C.randomColor() + "V" + C.randomColor() + "o" + C.randomColor() + "l" + C.randomColor() + "m" + C.randomColor() + "i" + C.randomColor() + "t" + C.randomColor() + "S" + C.randomColor() + "o" + C.randomColor() + "f" + C.randomColor() + "t" + C.randomColor() + "w" + C.randomColor() + "a" + C.randomColor() + "r" + C.randomColor() + "e", padd2 + C.GRAY + " v" + getDescription().getVersion(), + }; + String[] splash = {padd + C.GRAY + " @@@@@@@@@@@@@@" + C.DARK_GRAY + "@@@", padd + C.GRAY + " @@&&&&&&&&&" + C.DARK_GRAY + "&&&&&&" + C.GREEN + " .(((()))). ", padd + C.GRAY + "@@@&&&&&&&&" + C.DARK_GRAY + "&&&&&" + C.GREEN + " .((((((())))))). ", padd + C.GRAY + "@@@&&&&&" + C.DARK_GRAY + "&&&&&&&" + C.GREEN + " ((((((((())))))))) " + C.GRAY + " @", padd + C.GRAY + "@@@&&&&" + C.DARK_GRAY + "@@@@@&" + C.GREEN + " ((((((((-))))))))) " + C.GRAY + " @@", padd + C.GRAY + "@@@&&" + C.GREEN + " ((((((({ })))))))) " + C.GRAY + " &&@@@", padd + C.GRAY + "@@" + C.GREEN + " ((((((((-))))))))) " + C.DARK_GRAY + "&@@@@@" + C.GRAY + "&&&&@@@", padd + C.GRAY + "@" + C.GREEN + " ((((((((())))))))) " + C.DARK_GRAY + "&&&&&" + C.GRAY + "&&&&&&&@@@", padd + C.GRAY + "" + C.GREEN + " '((((((()))))))' " + C.DARK_GRAY + "&&&&&" + C.GRAY + "&&&&&&&&@@@", padd + C.GRAY + "" + C.GREEN + " '(((())))' " + C.DARK_GRAY + "&&&&&&&&" + C.GRAY + "&&&&&&&@@", padd + C.GRAY + " " + C.DARK_GRAY + "@@@" + C.GRAY + "@@@@@@@@@@@@@@" + }; + //@done + Iris.info("Server type & version: " + Bukkit.getVersion()); + Iris.info("Bukkit version: " + Bukkit.getBukkitVersion()); + Iris.info("Java version: " + getJavaVersion()); + for (int i = 0; i < info.length; i++) { + splash[i] += info[i]; + } - public static void verbose(String string) - { - try - { - if(IrisSettings.get().getGeneral().isVerbose()) - { - msg(C.GRAY + string); - } - } + Iris.info("\n\n " + new KList<>(splash).toString("\n") + "\n"); - catch(Throwable e) - { - msg(C.GRAY + string); - } - } + if (lowMemoryMode) { + Iris.verbose("* Low Memory mode Activated! For better performance, allocate 4gb or more to this server."); + } - public static void success(String string) - { - msg(C.GREEN + string); - } + if (!biome3d) { + Iris.verbose("* This version of minecraft does not support 3D biomes (1.15 and up). Iris will generate as normal, but biome colors will not vary underground & in the sky."); + } - public static void info(String string) - { - msg(C.WHITE + string); - } + if (!customModels) { + Iris.verbose("* This version of minecraft does not support custom model data in loot items (1.14 and up). Iris will generate as normal, but loot will not have custom models."); + } - public void hit(long hits2) - { - board.hits.put(hits2); - } + if (!doesSupportAwareness()) { + Iris.verbose("* This version of minecraft does not support entity awareness."); + } + } - public void splash() - { - if(!IrisSettings.get().getGeneral().isSplashLogoStartup()) - { - return; - } + @SuppressWarnings("deprecation") + public static void later(NastyRunnable object) { + Bukkit.getScheduler().scheduleAsyncDelayedTask(instance, () -> + { + try { + object.run(); + } catch (Throwable e) { + e.printStackTrace(); + } + }, RNG.r.i(100, 1200)); + } - // @NoArgsConstructor - String padd = Form.repeat(" ", 8); - String padd2 = Form.repeat(" ", 4); - String[] info = {"", "", "", "", "", padd2 + C.GREEN + " Iris", padd2 + C.GRAY + " by " + C.randomColor() + "V" + C.randomColor() + "o" + C.randomColor() + "l" + C.randomColor() + "m" + C.randomColor() + "i" + C.randomColor() + "t" + C.randomColor() + "S" + C.randomColor() + "o" + C.randomColor() + "f" + C.randomColor() + "t" + C.randomColor() + "w" + C.randomColor() + "a" + C.randomColor() + "r" + C.randomColor() + "e", padd2 + C.GRAY + " v" + getDescription().getVersion(), - }; - String[] splash = {padd + C.GRAY + " @@@@@@@@@@@@@@" + C.DARK_GRAY + "@@@", padd + C.GRAY + " @@&&&&&&&&&" + C.DARK_GRAY + "&&&&&&" + C.GREEN + " .(((()))). ", padd + C.GRAY + "@@@&&&&&&&&" + C.DARK_GRAY + "&&&&&" + C.GREEN + " .((((((())))))). ", padd + C.GRAY + "@@@&&&&&" + C.DARK_GRAY + "&&&&&&&" + C.GREEN + " ((((((((())))))))) " + C.GRAY + " @", padd + C.GRAY + "@@@&&&&" + C.DARK_GRAY + "@@@@@&" + C.GREEN + " ((((((((-))))))))) " + C.GRAY + " @@", padd + C.GRAY + "@@@&&" + C.GREEN + " ((((((({ })))))))) " + C.GRAY + " &&@@@", padd + C.GRAY + "@@" + C.GREEN + " ((((((((-))))))))) " + C.DARK_GRAY + "&@@@@@" + C.GRAY + "&&&&@@@", padd + C.GRAY + "@" + C.GREEN + " ((((((((())))))))) " + C.DARK_GRAY + "&&&&&" + C.GRAY + "&&&&&&&@@@", padd + C.GRAY + "" + C.GREEN + " '((((((()))))))' " + C.DARK_GRAY + "&&&&&" + C.GRAY + "&&&&&&&&@@@", padd + C.GRAY + "" + C.GREEN + " '(((())))' " + C.DARK_GRAY + "&&&&&&&&" + C.GRAY + "&&&&&&&@@", padd + C.GRAY + " " + C.DARK_GRAY + "@@@" + C.GRAY + "@@@@@@@@@@@@@@" - }; - //@done - Iris.info("Server type & version: " + Bukkit.getVersion()); - Iris.info("Bukkit version: " + Bukkit.getBukkitVersion()); - Iris.info("Java version: " + getJavaVersion()); - for(int i = 0; i < info.length; i++) - { - splash[i] += info[i]; - } + public static int jobCount() { + return syncJobs.size(); + } - Iris.info("\n\n " + new KList<>(splash).toString("\n") + "\n"); + public static void clearQueues() { + synchronized (syncJobs) { + syncJobs.clear(); + } + } - if(lowMemoryMode) - { - Iris.verbose("* Low Memory mode Activated! For better performance, allocate 4gb or more to this server."); - } - - if(!biome3d) - { - Iris.verbose("* This version of minecraft does not support 3D biomes (1.15 and up). Iris will generate as normal, but biome colors will not vary underground & in the sky."); - } - - if(!customModels) - { - Iris.verbose("* This version of minecraft does not support custom model data in loot items (1.14 and up). Iris will generate as normal, but loot will not have custom models."); - } - - if(!doesSupportAwareness()) - { - Iris.verbose("* This version of minecraft does not support entity awareness."); - } - } - - @SuppressWarnings("deprecation") - public static void later(NastyRunnable object) - { - Bukkit.getScheduler().scheduleAsyncDelayedTask(instance, () -> - { - try - { - object.run(); - } - - catch(Throwable e) - { - e.printStackTrace(); - } - }, RNG.r.i(100, 1200)); - } - - public static int jobCount() - { - return syncJobs.size(); - } - - public static void clearQueues() - { - synchronized(syncJobs) - { - syncJobs.clear(); - } - } - - private static int getJavaVersion() { - String version = System.getProperty("java.version"); - if(version.startsWith("1.")) { - version = version.substring(2, 3); - } else { - int dot = version.indexOf("."); - if(dot != -1) { version = version.substring(0, dot); } - } return Integer.parseInt(version); - } + private static int getJavaVersion() { + String version = System.getProperty("java.version"); + if (version.startsWith("1.")) { + version = version.substring(2, 3); + } else { + int dot = version.indexOf("."); + if (dot != -1) { + version = version.substring(0, dot); + } + } + return Integer.parseInt(version); + } public boolean isMCA() { - return IrisSettings.get().getGenerator().isMcaPregenerator(); + return IrisSettings.get().getGenerator().isMcaPregenerator(); } } diff --git a/src/main/java/com/volmit/iris/IrisSettings.java b/src/main/java/com/volmit/iris/IrisSettings.java index fe590974a..24342c048 100644 --- a/src/main/java/com/volmit/iris/IrisSettings.java +++ b/src/main/java/com/volmit/iris/IrisSettings.java @@ -8,258 +8,215 @@ import java.io.File; import java.io.IOException; @Data -public class IrisSettings -{ - public static transient IrisSettings settings; - private IrisSettingsCache cache = new IrisSettingsCache(); - private IrisSettingsConcurrency concurrency = new IrisSettingsConcurrency(); - private IrisSettingsParallax parallax = new IrisSettingsParallax(); - private IrisSettingsGeneral general = new IrisSettingsGeneral(); - private IrisSettingsGUI gui = new IrisSettingsGUI(); - private IrisSettingsGenerator generator = new IrisSettingsGenerator(); - private IrisSettingsStudio studio = new IrisSettingsStudio(); +public class IrisSettings { + public static transient IrisSettings settings; + private IrisSettingsCache cache = new IrisSettingsCache(); + private IrisSettingsConcurrency concurrency = new IrisSettingsConcurrency(); + private IrisSettingsParallax parallax = new IrisSettingsParallax(); + private IrisSettingsGeneral general = new IrisSettingsGeneral(); + private IrisSettingsGUI gui = new IrisSettingsGUI(); + private IrisSettingsGenerator generator = new IrisSettingsGenerator(); + private IrisSettingsStudio studio = new IrisSettingsStudio(); - @DontObfuscate - public int configurationVersion = 3; + @DontObfuscate + public int configurationVersion = 3; - public boolean isStudio() { - return getStudio().isStudio(); - } + public boolean isStudio() { + return getStudio().isStudio(); + } - public boolean isUseServerLaunchedGuis() { - return getGui().isUseServerLaunchedGuis(); - } + public boolean isUseServerLaunchedGuis() { + return getGui().isUseServerLaunchedGuis(); + } - public long getParallaxRegionEvictionMS() { - return getParallax().getParallaxRegionEvictionMS(); - } + public long getParallaxRegionEvictionMS() { + return getParallax().getParallaxRegionEvictionMS(); + } - @Data - public static class IrisSettingsCache - { - @DontObfuscate - public int streamingCacheSize = 8192; - } + @Data + public static class IrisSettingsCache { + @DontObfuscate + public int streamingCacheSize = 8192; + } - @Data - public static class IrisSettingsConcurrency - { - @DontObfuscate - public int threadCount = -1; - } + @Data + public static class IrisSettingsConcurrency { + @DontObfuscate + public int threadCount = -1; + } - @Data - public static class IrisSettingsParallax - { - @DontObfuscate - public int parallaxRegionEvictionMS = 15000; + @Data + public static class IrisSettingsParallax { + @DontObfuscate + public int parallaxRegionEvictionMS = 15000; - @DontObfuscate - public int parallaxChunkEvictionMS = 5000; - } + @DontObfuscate + public int parallaxChunkEvictionMS = 5000; + } - @Data - public static class IrisSettingsGeneral - { + @Data + public static class IrisSettingsGeneral { - @DontObfuscate - public boolean commandSounds = true; + @DontObfuscate + public boolean commandSounds = true; - @DontObfuscate - public boolean verbose = false; + @DontObfuscate + public boolean verbose = false; - @DontObfuscate - public boolean ignoreWorldEdit = false; + @DontObfuscate + public boolean ignoreWorldEdit = false; - @DontObfuscate - public boolean disableNMS = false; + @DontObfuscate + public boolean disableNMS = false; - @DontObfuscate - public boolean pluginMetrics = true; + @DontObfuscate + public boolean pluginMetrics = true; - @DontObfuscate - public boolean splashLogoStartup = true; - } + @DontObfuscate + public boolean splashLogoStartup = true; + } - @Data - public static class IrisSettingsGUI - { - @DontObfuscate - public boolean useServerLaunchedGuis = true; + @Data + public static class IrisSettingsGUI { + @DontObfuscate + public boolean useServerLaunchedGuis = true; - @DontObfuscate - public boolean maximumPregenGuiFPS = false; + @DontObfuscate + public boolean maximumPregenGuiFPS = false; - @DontObfuscate - public boolean localPregenGui = true; - } + @DontObfuscate + public boolean localPregenGui = true; + } - @Data - public static class IrisSettingsGenerator - { - @DontObfuscate - public String defaultWorldType = "overworld"; + @Data + public static class IrisSettingsGenerator { + @DontObfuscate + public String defaultWorldType = "overworld"; - @DontObfuscate - public boolean mcaPregenerator = false; + @DontObfuscate + public boolean mcaPregenerator = false; - @DontObfuscate - public boolean systemEffects = true; + @DontObfuscate + public boolean systemEffects = true; - @DontObfuscate - public boolean systemEntitySpawnOverrides = true; + @DontObfuscate + public boolean systemEntitySpawnOverrides = true; - @DontObfuscate - public boolean systemEntityInitialSpawns = true; + @DontObfuscate + public boolean systemEntityInitialSpawns = true; - @DontObfuscate - public int maxBiomeChildDepth = 5; + @DontObfuscate + public int maxBiomeChildDepth = 5; - } + } - @Data - public static class IrisSettingsStudio - { + @Data + public static class IrisSettingsStudio { - @DontObfuscate - public boolean studio = true; + @DontObfuscate + public boolean studio = true; - @DontObfuscate - public boolean openVSCode = true; + @DontObfuscate + public boolean openVSCode = true; - @DontObfuscate - public boolean disableTimeAndWeather = true; - } + @DontObfuscate + public boolean disableTimeAndWeather = true; + } - public static IrisSettings get() - { - if(settings != null) - { - return settings; - } + public static IrisSettings get() { + if (settings != null) { + return settings; + } - IrisSettings defaults = new IrisSettings(); - JSONObject def = new JSONObject(new Gson().toJson(defaults)); - if(settings == null) - { - settings = new IrisSettings(); + IrisSettings defaults = new IrisSettings(); + JSONObject def = new JSONObject(new Gson().toJson(defaults)); + if (settings == null) { + settings = new IrisSettings(); - File s = Iris.instance.getDataFile("settings.json"); + File s = Iris.instance.getDataFile("settings.json"); - if(!s.exists()) - { - try - { - IO.writeAll(s, new JSONObject(new Gson().toJson(settings)).toString(4)); - } + if (!s.exists()) { + try { + IO.writeAll(s, new JSONObject(new Gson().toJson(settings)).toString(4)); + } catch (JSONException | IOException e) { + e.printStackTrace(); + } + } else { + try { + String ss = IO.readAll(s); + settings = new Gson().fromJson(ss, IrisSettings.class); - catch(JSONException | IOException e) - { - e.printStackTrace(); - } - } + J.a(() -> + { + try { + JSONObject j = new JSONObject(ss); + boolean u = false; + for (String i : def.keySet()) { + if (!j.has(i)) { + u = true; + j.put(i, def.get(i)); + Iris.warn("Adding new config key: " + i); + } + } - else - { - try - { - String ss = IO.readAll(s); - settings = new Gson().fromJson(ss, IrisSettings.class); + for (String i : new KSet<>(j.keySet())) { + if (!def.has(i)) { + u = true; + j.remove(i); + Iris.warn("Removing unused config key: " + i); + } + } - J.a(() -> - { - try - { - JSONObject j = new JSONObject(ss); - boolean u = false; - for(String i : def.keySet()) - { - if(!j.has(i)) - { - u = true; - j.put(i, def.get(i)); - Iris.warn("Adding new config key: " + i); - } - } + if (u) { + try { + IO.writeAll(s, j.toString(4)); + Iris.info("Updated Configuration Files"); + } catch (Throwable e) { + e.printStackTrace(); + } + } + } catch (Throwable ee) { + Iris.error("Configuration Error in settings.json! " + ee.getClass().getSimpleName() + ": " + ee.getMessage()); + Iris.warn("Attempting to fix configuration while retaining valid in-memory settings..."); - for(String i : new KSet<>(j.keySet())) - { - if(!def.has(i)) - { - u = true; - j.remove(i); - Iris.warn("Removing unused config key: " + i); - } - } + try { + IO.writeAll(s, new JSONObject(new Gson().toJson(settings)).toString(4)); + Iris.info("Configuration Fixed!"); + } catch (IOException e) { + e.printStackTrace(); + Iris.error("ERROR! CONFIGURATION IMPOSSIBLE TO READ! Using an unmodifiable configuration from memory. Please delete the settings.json at some point to try to restore configurability!"); + } + } + }); + } catch (Throwable ee) { + Iris.error("Configuration Error in settings.json! " + ee.getClass().getSimpleName() + ": " + ee.getMessage()); + Iris.warn("Attempting to fix configuration while retaining valid in-memory settings..."); - if(u) - { - try - { - IO.writeAll(s, j.toString(4)); - Iris.info("Updated Configuration Files"); - } + try { + IO.writeAll(s, new JSONObject(new Gson().toJson(settings)).toString(4)); + Iris.info("Configuration Fixed!"); + } catch (IOException e) { + e.printStackTrace(); + Iris.error("ERROR! CONFIGURATION IMPOSSIBLE TO READ! Using an unmodifiable configuration from memory. Please delete the settings.json at some point to try to restore configurability!"); + } + } + } - catch(Throwable e) - { - e.printStackTrace(); - } - } - } + if (!s.exists()) { + try { + IO.writeAll(s, new JSONObject(new Gson().toJson(settings)).toString(4)); + } catch (JSONException | IOException e) { + e.printStackTrace(); + } + } + } - catch(Throwable ee) - { - Iris.error("Configuration Error in settings.json! " + ee.getClass().getSimpleName() + ": " + ee.getMessage()); - Iris.warn("Attempting to fix configuration while retaining valid in-memory settings..."); + return settings; + } - try { - IO.writeAll(s, new JSONObject(new Gson().toJson(settings)).toString(4)); - Iris.info("Configuration Fixed!"); - } catch (IOException e) { - e.printStackTrace(); - Iris.error("ERROR! CONFIGURATION IMPOSSIBLE TO READ! Using an unmodifiable configuration from memory. Please delete the settings.json at some point to try to restore configurability!"); - } - } - }); - } - - catch(Throwable ee) - { - Iris.error("Configuration Error in settings.json! " + ee.getClass().getSimpleName() + ": " + ee.getMessage()); - Iris.warn("Attempting to fix configuration while retaining valid in-memory settings..."); - - try { - IO.writeAll(s, new JSONObject(new Gson().toJson(settings)).toString(4)); - Iris.info("Configuration Fixed!"); - } catch (IOException e) { - e.printStackTrace(); - Iris.error("ERROR! CONFIGURATION IMPOSSIBLE TO READ! Using an unmodifiable configuration from memory. Please delete the settings.json at some point to try to restore configurability!"); - } - } - } - - if(!s.exists()) - { - try - { - IO.writeAll(s, new JSONObject(new Gson().toJson(settings)).toString(4)); - } - - catch(JSONException | IOException e) - { - e.printStackTrace(); - } - } - } - - return settings; - } - - public static void invalidate() - { - synchronized(settings) - { - settings = null; - } - } + public static void invalidate() { + synchronized (settings) { + settings = null; + } + } } diff --git a/src/main/java/com/volmit/iris/generator/IrisComplex.java b/src/main/java/com/volmit/iris/generator/IrisComplex.java index efc0d06be..5f9a95f17 100644 --- a/src/main/java/com/volmit/iris/generator/IrisComplex.java +++ b/src/main/java/com/volmit/iris/generator/IrisComplex.java @@ -12,377 +12,340 @@ import com.volmit.iris.scaffold.data.DataProvider; import com.volmit.iris.scaffold.engine.Engine; import com.volmit.iris.scaffold.stream.ProceduralStream; import com.volmit.iris.scaffold.stream.interpolation.Interpolated; -import com.volmit.iris.util.*; +import com.volmit.iris.util.CaveResult; +import com.volmit.iris.util.KList; +import com.volmit.iris.util.M; +import com.volmit.iris.util.RNG; import lombok.Data; import org.bukkit.Material; import org.bukkit.block.Biome; import org.bukkit.block.data.BlockData; @Data -public class IrisComplex implements DataProvider -{ - private RNG rng; - private double fluidHeight; - private IrisDataManager data; - private KList generators; - private static final BlockData AIR = Material.AIR.createBlockData(); - private ProceduralStream regionStream; - private ProceduralStream bridgeStream; - private ProceduralStream landBiomeStream; - private ProceduralStream caveBiomeStream; - private ProceduralStream seaBiomeStream; - private ProceduralStream shoreBiomeStream; - private ProceduralStream baseBiomeStream; - private ProceduralStream trueBiomeStream; - private ProceduralStream trueBiomeDerivativeStream; - private ProceduralStream heightStream; - private ProceduralStream objectChanceStream; - private ProceduralStream maxHeightStream; - private ProceduralStream overlayStream; - private ProceduralStream heightFluidStream; - private ProceduralStream trueHeightStream; - private ProceduralStream slopeStream; - private ProceduralStream rngStream; - private ProceduralStream chunkRngStream; - private ProceduralStream terrainSurfaceDecoration; - private ProceduralStream terrainCeilingDecoration; - private ProceduralStream terrainCaveSurfaceDecoration; - private ProceduralStream terrainCaveCeilingDecoration; - private ProceduralStream seaSurfaceDecoration; - private ProceduralStream seaFloorDecoration; - private ProceduralStream shoreSurfaceDecoration; - private ProceduralStream rockStream; - private ProceduralStream fluidStream; - private IrisBiome focus; +public class IrisComplex implements DataProvider { + private RNG rng; + private double fluidHeight; + private IrisDataManager data; + private KList generators; + private static final BlockData AIR = Material.AIR.createBlockData(); + private ProceduralStream regionStream; + private ProceduralStream bridgeStream; + private ProceduralStream landBiomeStream; + private ProceduralStream caveBiomeStream; + private ProceduralStream seaBiomeStream; + private ProceduralStream shoreBiomeStream; + private ProceduralStream baseBiomeStream; + private ProceduralStream trueBiomeStream; + private ProceduralStream trueBiomeDerivativeStream; + private ProceduralStream heightStream; + private ProceduralStream objectChanceStream; + private ProceduralStream maxHeightStream; + private ProceduralStream overlayStream; + private ProceduralStream heightFluidStream; + private ProceduralStream trueHeightStream; + private ProceduralStream slopeStream; + private ProceduralStream rngStream; + private ProceduralStream chunkRngStream; + private ProceduralStream terrainSurfaceDecoration; + private ProceduralStream terrainCeilingDecoration; + private ProceduralStream terrainCaveSurfaceDecoration; + private ProceduralStream terrainCaveCeilingDecoration; + private ProceduralStream seaSurfaceDecoration; + private ProceduralStream seaFloorDecoration; + private ProceduralStream shoreSurfaceDecoration; + private ProceduralStream rockStream; + private ProceduralStream fluidStream; + private IrisBiome focus; - public ProceduralStream getBiomeStream(InferredType type) - { - switch(type) - { - case CAVE: - return caveBiomeStream; - case LAND: - return landBiomeStream; - case SEA: - return seaBiomeStream; - case SHORE: - return shoreBiomeStream; - case DEFER: - case LAKE: - case RIVER: - default: - break; - } + public ProceduralStream getBiomeStream(InferredType type) { + switch (type) { + case CAVE: + return caveBiomeStream; + case LAND: + return landBiomeStream; + case SEA: + return seaBiomeStream; + case SHORE: + return shoreBiomeStream; + case DEFER: + case LAKE: + case RIVER: + default: + break; + } - return null; - } + return null; + } - public IrisComplex(Engine engine) - { - int cacheSize = IrisSettings.get().getCache().getStreamingCacheSize(); - this.rng = new RNG(engine.getWorld().getSeed()); - this.data = engine.getData(); - double height = engine.getHeight(); - fluidHeight = engine.getDimension().getFluidHeight(); - generators = new KList<>(); - focus = engine.getFocus(); - IrisRegion focusRegion = focus != null ? findRegion(focus, engine) : null; - RNG rng = new RNG(engine.getWorld().getSeed()); - //@builder - engine.getDimension().getRegions().forEach((i) -> data.getRegionLoader().load(i) - .getAllBiomes(this).forEach((b) -> b - .getGenerators() - .forEach((c) -> registerGenerator(c.getCachedGenerator(this))))); - overlayStream = ProceduralStream.ofDouble((x, z) -> 0D); - engine.getDimension().getOverlayNoise().forEach((i) -> overlayStream.add((x, z) -> i.get(rng, x, z))); - rngStream = ProceduralStream.of((x, z) -> new RNG(((x.longValue()) << 32) | (z.longValue() & 0xffffffffL)) - .nextParallelRNG(engine.getWorld().getSeed()), Interpolated.RNG); - chunkRngStream = rngStream.blockToChunkCoords(); - rockStream = engine.getDimension().getRockPalette().getLayerGenerator(rng.nextParallelRNG(45), data).stream() - .select(engine.getDimension().getRockPalette().getBlockData(data)); - fluidStream = engine.getDimension().getFluidPalette().getLayerGenerator(rng.nextParallelRNG(78), data).stream() - .select(engine.getDimension().getFluidPalette().getBlockData(data)); - regionStream = focusRegion != null ? - ProceduralStream.of((x,z) -> focusRegion, - Interpolated.of(a -> 0D, a -> focusRegion)) - : engine.getDimension().getRegionStyle().create(rng.nextParallelRNG(883)).stream() - .zoom(engine.getDimension().getRegionZoom()) - .selectRarity(engine.getDimension().getRegions()) - .convertCached((s) -> data.getRegionLoader().load(s)).cache2D(cacheSize); - caveBiomeStream = regionStream.convert((r) - -> engine.getDimension().getCaveBiomeStyle().create(rng.nextParallelRNG(1221)).stream() - .zoom(r.getCaveBiomeZoom()) - .selectRarity(r.getCaveBiomes()) - .onNull("") - .convertCached((s) -> { - if(s.isEmpty()) - { - return new IrisBiome(); - } + public IrisComplex(Engine engine) { + int cacheSize = IrisSettings.get().getCache().getStreamingCacheSize(); + this.rng = new RNG(engine.getWorld().getSeed()); + this.data = engine.getData(); + double height = engine.getHeight(); + fluidHeight = engine.getDimension().getFluidHeight(); + generators = new KList<>(); + focus = engine.getFocus(); + IrisRegion focusRegion = focus != null ? findRegion(focus, engine) : null; + RNG rng = new RNG(engine.getWorld().getSeed()); + //@builder + engine.getDimension().getRegions().forEach((i) -> data.getRegionLoader().load(i) + .getAllBiomes(this).forEach((b) -> b + .getGenerators() + .forEach((c) -> registerGenerator(c.getCachedGenerator(this))))); + overlayStream = ProceduralStream.ofDouble((x, z) -> 0D); + engine.getDimension().getOverlayNoise().forEach((i) -> overlayStream.add((x, z) -> i.get(rng, x, z))); + rngStream = ProceduralStream.of((x, z) -> new RNG(((x.longValue()) << 32) | (z.longValue() & 0xffffffffL)) + .nextParallelRNG(engine.getWorld().getSeed()), Interpolated.RNG); + chunkRngStream = rngStream.blockToChunkCoords(); + rockStream = engine.getDimension().getRockPalette().getLayerGenerator(rng.nextParallelRNG(45), data).stream() + .select(engine.getDimension().getRockPalette().getBlockData(data)); + fluidStream = engine.getDimension().getFluidPalette().getLayerGenerator(rng.nextParallelRNG(78), data).stream() + .select(engine.getDimension().getFluidPalette().getBlockData(data)); + regionStream = focusRegion != null ? + ProceduralStream.of((x, z) -> focusRegion, + Interpolated.of(a -> 0D, a -> focusRegion)) + : engine.getDimension().getRegionStyle().create(rng.nextParallelRNG(883)).stream() + .zoom(engine.getDimension().getRegionZoom()) + .selectRarity(engine.getDimension().getRegions()) + .convertCached((s) -> data.getRegionLoader().load(s)).cache2D(cacheSize); + caveBiomeStream = regionStream.convert((r) + -> engine.getDimension().getCaveBiomeStyle().create(rng.nextParallelRNG(1221)).stream() + .zoom(r.getCaveBiomeZoom()) + .selectRarity(r.getCaveBiomes()) + .onNull("") + .convertCached((s) -> { + if (s.isEmpty()) { + return new IrisBiome(); + } - return data.getBiomeLoader().load(s) - .setInferredType(InferredType.CAVE); - }) - ).convertAware2D(ProceduralStream::get).cache2D(cacheSize); - landBiomeStream = regionStream.convert((r) - -> engine.getDimension().getLandBiomeStyle().create(rng.nextParallelRNG(234234234)).stream() - .zoom(r.getLandBiomeZoom()) - .selectRarity(r.getLandBiomes()) - .convertCached((s) -> data.getBiomeLoader().load(s) - .setInferredType(InferredType.LAND)) - ).convertAware2D(ProceduralStream::get) - .cache2D(cacheSize); - seaBiomeStream = regionStream.convert((r) - -> engine.getDimension().getSeaBiomeStyle().create(rng.nextParallelRNG(11232323)).stream() - .zoom(r.getSeaBiomeZoom()) - .selectRarity(r.getSeaBiomes()) - .convertCached((s) -> data.getBiomeLoader().load(s) - .setInferredType(InferredType.SEA)) - ).convertAware2D(ProceduralStream::get) - .cache2D(cacheSize); - shoreBiomeStream = regionStream.convert((r) - -> engine.getDimension().getShoreBiomeStyle().create(rng.nextParallelRNG(7787845)).stream() - .zoom(r.getShoreBiomeZoom()) - .selectRarity(r.getShoreBiomes()) - .convertCached((s) -> data.getBiomeLoader().load(s) - .setInferredType(InferredType.SHORE)) - ).convertAware2D(ProceduralStream::get).cache2D(cacheSize); - bridgeStream = focus != null ? ProceduralStream.of((x,z)->focus.getInferredType(), - Interpolated.of(a -> 0D, a -> focus.getInferredType())) : - engine.getDimension().getContinentalStyle().create(rng.nextParallelRNG(234234565)) - .bake().scale(1D / engine.getDimension().getContinentZoom()).bake().stream() - .convert((v) -> v >= engine.getDimension().getLandChance() ? InferredType.SEA : InferredType.LAND); - baseBiomeStream = focus != null ? ProceduralStream.of((x,z) -> focus, - Interpolated.of(a -> 0D, a -> focus)) : - bridgeStream.convertAware2D((t, x, z) -> t.equals(InferredType.SEA) - ? seaBiomeStream.get(x, z) : landBiomeStream.get(x, z)) - .convertAware2D(this::implode).cache2D(cacheSize); - heightStream = ProceduralStream.of((x, z) -> { - IrisBiome b = focus != null ? focus : baseBiomeStream.get(x, z); - return getHeight(engine, b, x, z, engine.getWorld().getSeed()); - }, Interpolated.DOUBLE).cache2D(cacheSize); - slopeStream = heightStream.slope(3).interpolate().bilinear(3, 3).cache2D(cacheSize); - objectChanceStream = ProceduralStream.ofDouble((x, z) -> { - AtomicDouble str = new AtomicDouble(1D); - engine.getFramework().getEngineParallax().forEachFeature(x, z, (i) - -> str.set(Math.min(str.get(), i.getObjectChanceModifier(x, z)))); - return str.get(); - }); + return data.getBiomeLoader().load(s) + .setInferredType(InferredType.CAVE); + }) + ).convertAware2D(ProceduralStream::get).cache2D(cacheSize); + landBiomeStream = regionStream.convert((r) + -> engine.getDimension().getLandBiomeStyle().create(rng.nextParallelRNG(234234234)).stream() + .zoom(r.getLandBiomeZoom()) + .selectRarity(r.getLandBiomes()) + .convertCached((s) -> data.getBiomeLoader().load(s) + .setInferredType(InferredType.LAND)) + ).convertAware2D(ProceduralStream::get) + .cache2D(cacheSize); + seaBiomeStream = regionStream.convert((r) + -> engine.getDimension().getSeaBiomeStyle().create(rng.nextParallelRNG(11232323)).stream() + .zoom(r.getSeaBiomeZoom()) + .selectRarity(r.getSeaBiomes()) + .convertCached((s) -> data.getBiomeLoader().load(s) + .setInferredType(InferredType.SEA)) + ).convertAware2D(ProceduralStream::get) + .cache2D(cacheSize); + shoreBiomeStream = regionStream.convert((r) + -> engine.getDimension().getShoreBiomeStyle().create(rng.nextParallelRNG(7787845)).stream() + .zoom(r.getShoreBiomeZoom()) + .selectRarity(r.getShoreBiomes()) + .convertCached((s) -> data.getBiomeLoader().load(s) + .setInferredType(InferredType.SHORE)) + ).convertAware2D(ProceduralStream::get).cache2D(cacheSize); + bridgeStream = focus != null ? ProceduralStream.of((x, z) -> focus.getInferredType(), + Interpolated.of(a -> 0D, a -> focus.getInferredType())) : + engine.getDimension().getContinentalStyle().create(rng.nextParallelRNG(234234565)) + .bake().scale(1D / engine.getDimension().getContinentZoom()).bake().stream() + .convert((v) -> v >= engine.getDimension().getLandChance() ? InferredType.SEA : InferredType.LAND); + baseBiomeStream = focus != null ? ProceduralStream.of((x, z) -> focus, + Interpolated.of(a -> 0D, a -> focus)) : + bridgeStream.convertAware2D((t, x, z) -> t.equals(InferredType.SEA) + ? seaBiomeStream.get(x, z) : landBiomeStream.get(x, z)) + .convertAware2D(this::implode).cache2D(cacheSize); + heightStream = ProceduralStream.of((x, z) -> { + IrisBiome b = focus != null ? focus : baseBiomeStream.get(x, z); + return getHeight(engine, b, x, z, engine.getWorld().getSeed()); + }, Interpolated.DOUBLE).cache2D(cacheSize); + slopeStream = heightStream.slope(3).interpolate().bilinear(3, 3).cache2D(cacheSize); + objectChanceStream = ProceduralStream.ofDouble((x, z) -> { + AtomicDouble str = new AtomicDouble(1D); + engine.getFramework().getEngineParallax().forEachFeature(x, z, (i) + -> str.set(Math.min(str.get(), i.getObjectChanceModifier(x, z)))); + return str.get(); + }); - trueBiomeStream = focus != null ? ProceduralStream.of((x,y) -> focus, Interpolated.of(a -> 0D, - b -> focus)) : heightStream - .convertAware2D((h, x, z) -> - fixBiomeType(h, baseBiomeStream.get(x, z), - regionStream.get(x, z), x, z, fluidHeight)).cache2D(cacheSize); - trueBiomeDerivativeStream = trueBiomeStream.convert(IrisBiome::getDerivative).cache2D(cacheSize); - heightFluidStream = heightStream.max(fluidHeight).cache2D(cacheSize); - maxHeightStream = ProceduralStream.ofDouble((x, z) -> height); - terrainSurfaceDecoration = trueBiomeStream - .convertAware2D((b, xx,zz) -> decorateFor(b, xx, zz, DecorationPart.NONE)); - terrainCeilingDecoration = trueBiomeStream - .convertAware2D((b, xx,zz) -> decorateFor(b, xx, zz, DecorationPart.CEILING)); - terrainCaveSurfaceDecoration = caveBiomeStream - .convertAware2D((b, xx,zz) -> decorateFor(b, xx, zz, DecorationPart.NONE)); - terrainCaveCeilingDecoration = caveBiomeStream - .convertAware2D((b, xx,zz) -> decorateFor(b, xx, zz, DecorationPart.CEILING)); - shoreSurfaceDecoration = trueBiomeStream - .convertAware2D((b, xx,zz) -> decorateFor(b, xx, zz, DecorationPart.SHORE_LINE)); - seaSurfaceDecoration = trueBiomeStream - .convertAware2D((b, xx,zz) -> decorateFor(b, xx, zz, DecorationPart.SEA_SURFACE)); - seaFloorDecoration = trueBiomeStream - .convertAware2D((b, xx,zz) -> decorateFor(b, xx, zz, DecorationPart.SEA_FLOOR)); - trueHeightStream = ProceduralStream.of((x, z) -> { - int rx = (int) Math.round(engine.modifyX(x)); - int rz = (int) Math.round(engine.modifyZ(z)); - int heightf = (int) Math.round(getHeightStream().get(rx, rz)); - int m = heightf; + trueBiomeStream = focus != null ? ProceduralStream.of((x, y) -> focus, Interpolated.of(a -> 0D, + b -> focus)) : heightStream + .convertAware2D((h, x, z) -> + fixBiomeType(h, baseBiomeStream.get(x, z), + regionStream.get(x, z), x, z, fluidHeight)).cache2D(cacheSize); + trueBiomeDerivativeStream = trueBiomeStream.convert(IrisBiome::getDerivative).cache2D(cacheSize); + heightFluidStream = heightStream.max(fluidHeight).cache2D(cacheSize); + maxHeightStream = ProceduralStream.ofDouble((x, z) -> height); + terrainSurfaceDecoration = trueBiomeStream + .convertAware2D((b, xx, zz) -> decorateFor(b, xx, zz, DecorationPart.NONE)); + terrainCeilingDecoration = trueBiomeStream + .convertAware2D((b, xx, zz) -> decorateFor(b, xx, zz, DecorationPart.CEILING)); + terrainCaveSurfaceDecoration = caveBiomeStream + .convertAware2D((b, xx, zz) -> decorateFor(b, xx, zz, DecorationPart.NONE)); + terrainCaveCeilingDecoration = caveBiomeStream + .convertAware2D((b, xx, zz) -> decorateFor(b, xx, zz, DecorationPart.CEILING)); + shoreSurfaceDecoration = trueBiomeStream + .convertAware2D((b, xx, zz) -> decorateFor(b, xx, zz, DecorationPart.SHORE_LINE)); + seaSurfaceDecoration = trueBiomeStream + .convertAware2D((b, xx, zz) -> decorateFor(b, xx, zz, DecorationPart.SEA_SURFACE)); + seaFloorDecoration = trueBiomeStream + .convertAware2D((b, xx, zz) -> decorateFor(b, xx, zz, DecorationPart.SEA_FLOOR)); + trueHeightStream = ProceduralStream.of((x, z) -> { + int rx = (int) Math.round(engine.modifyX(x)); + int rz = (int) Math.round(engine.modifyZ(z)); + int heightf = (int) Math.round(getHeightStream().get(rx, rz)); + int m = heightf; - if(engine.getDimension().isCarving()) - { - if(engine.getDimension().isCarved(rx, m, rz, ((IrisTerrainActuator)engine.getFramework().getTerrainActuator()).getRng(), heightf)) - { - m--; + if (engine.getDimension().isCarving()) { + if (engine.getDimension().isCarved(rx, m, rz, ((IrisTerrainActuator) engine.getFramework().getTerrainActuator()).getRng(), heightf)) { + m--; - while(engine.getDimension().isCarved(rx, m, rz, ((IrisTerrainActuator)engine.getFramework().getTerrainActuator()).getRng(), heightf)) - { - m--; - } - } - } + while (engine.getDimension().isCarved(rx, m, rz, ((IrisTerrainActuator) engine.getFramework().getTerrainActuator()).getRng(), heightf)) { + m--; + } + } + } - if(engine.getDimension().isCaves()) - { - KList caves = ((IrisCaveModifier)engine.getFramework().getCaveModifier()).genCaves(rx, rz, 0, 0, null); - boolean again = true; + if (engine.getDimension().isCaves()) { + KList caves = ((IrisCaveModifier) engine.getFramework().getCaveModifier()).genCaves(rx, rz, 0, 0, null); + boolean again = true; - while(again) - { - again = false; - for(CaveResult i : caves) - { - if(i.getCeiling() > m && i.getFloor() < m) - { - m = i.getFloor(); - again = true; - } - } - } - } + while (again) { + again = false; + for (CaveResult i : caves) { + if (i.getCeiling() > m && i.getFloor() < m) { + m = i.getFloor(); + again = true; + } + } + } + } - return m; - }, Interpolated.INT).cache2D(cacheSize); - //@done - } - private IrisRegion findRegion(IrisBiome focus, Engine engine) { - for(IrisRegion i : engine.getDimension().getAllRegions(engine)) - { - if(i.getAllBiomeIds().contains(focus.getLoadKey())) - { - return i; - } - } + return m; + }, Interpolated.INT).cache2D(cacheSize); + //@done + } - return null; - } + private IrisRegion findRegion(IrisBiome focus, Engine engine) { + for (IrisRegion i : engine.getDimension().getAllRegions(engine)) { + if (i.getAllBiomeIds().contains(focus.getLoadKey())) { + return i; + } + } - private IrisDecorator decorateFor(IrisBiome b, double x, double z, DecorationPart part) - { - RNG rngc = chunkRngStream.get(x, z); + return null; + } - for(IrisDecorator i : b.getDecorators()) - { - if(!i.getPartOf().equals(part)) - { - continue; - } + private IrisDecorator decorateFor(IrisBiome b, double x, double z, DecorationPart part) { + RNG rngc = chunkRngStream.get(x, z); - BlockData block = i.getBlockData(b, rngc, x, z, data); + for (IrisDecorator i : b.getDecorators()) { + if (!i.getPartOf().equals(part)) { + continue; + } - if(block != null) - { - return i; - } - } + BlockData block = i.getBlockData(b, rngc, x, z, data); - return null; - } + if (block != null) { + return i; + } + } - private IrisBiome implode(IrisBiome b, Double x, Double z) - { - if(b.getChildren().isEmpty()) - { - return b; - } + return null; + } - return implode(b, x, z, 3); - } + private IrisBiome implode(IrisBiome b, Double x, Double z) { + if (b.getChildren().isEmpty()) { + return b; + } - private IrisBiome implode(IrisBiome b, Double x, Double z, int max) - { - if(max < 0) - { - return b; - } + return implode(b, x, z, 3); + } - if(b.getChildren().isEmpty()) - { - return b; - } + private IrisBiome implode(IrisBiome b, Double x, Double z, int max) { + if (max < 0) { + return b; + } - CNG childCell = b.getChildrenGenerator(rng, 123, b.getChildShrinkFactor()); - KList chx = b.getRealChildren(this).copy(); - chx.add(b); - IrisBiome biome = childCell.fitRarity(chx, x, z); - biome.setInferredType(b.getInferredType()); - return implode(biome, x, z, max - 1); - } + if (b.getChildren().isEmpty()) { + return b; + } - private IrisBiome fixBiomeType(Double height, IrisBiome biome, IrisRegion region, Double x, Double z, double fluidHeight) - { - double sh = region.getShoreHeight(x, z); + CNG childCell = b.getChildrenGenerator(rng, 123, b.getChildShrinkFactor()); + KList chx = b.getRealChildren(this).copy(); + chx.add(b); + IrisBiome biome = childCell.fitRarity(chx, x, z); + biome.setInferredType(b.getInferredType()); + return implode(biome, x, z, max - 1); + } - if(height >= fluidHeight-1 && height <= fluidHeight + sh && !biome.isShore()) - { - return shoreBiomeStream.get(x, z); - } + private IrisBiome fixBiomeType(Double height, IrisBiome biome, IrisRegion region, Double x, Double z, double fluidHeight) { + double sh = region.getShoreHeight(x, z); - if(height > fluidHeight + sh && !biome.isLand()) - { - return landBiomeStream.get(x, z); - } + if (height >= fluidHeight - 1 && height <= fluidHeight + sh && !biome.isShore()) { + return shoreBiomeStream.get(x, z); + } - if(height < fluidHeight && !biome.isAquatic()) - { - return seaBiomeStream.get(x, z); - } + if (height > fluidHeight + sh && !biome.isLand()) { + return landBiomeStream.get(x, z); + } - if(height == fluidHeight && !biome.isShore()) - { - return shoreBiomeStream.get(x, z); - } + if (height < fluidHeight && !biome.isAquatic()) { + return seaBiomeStream.get(x, z); + } - return biome; - } + if (height == fluidHeight && !biome.isShore()) { + return shoreBiomeStream.get(x, z); + } - private double getHeight(Engine engine, IrisBiome b, double x, double z, long seed) - { - double h = 0; + return biome; + } - for(IrisGenerator gen : generators) - { - double hi = gen.getInterpolator().interpolate(x, z, (xx, zz) -> - { - try - { - IrisBiome bx = baseBiomeStream.get(xx, zz); + private double getHeight(Engine engine, IrisBiome b, double x, double z, long seed) { + double h = 0; - return bx.getGenLinkMax(gen.getLoadKey()); - } + for (IrisGenerator gen : generators) { + double hi = gen.getInterpolator().interpolate(x, z, (xx, zz) -> + { + try { + IrisBiome bx = baseBiomeStream.get(xx, zz); - catch(Throwable e) - { - Iris.warn("Failed to sample hi biome at " + xx + " " + zz + " using the generator " + gen.getLoadKey()); - } + return bx.getGenLinkMax(gen.getLoadKey()); + } catch (Throwable e) { + Iris.warn("Failed to sample hi biome at " + xx + " " + zz + " using the generator " + gen.getLoadKey()); + } - return 0; - }); + return 0; + }); - double lo = gen.getInterpolator().interpolate(x, z, (xx, zz) -> - { - try - { - IrisBiome bx = baseBiomeStream.get(xx, zz); + double lo = gen.getInterpolator().interpolate(x, z, (xx, zz) -> + { + try { + IrisBiome bx = baseBiomeStream.get(xx, zz); - return bx.getGenLinkMin(gen.getLoadKey()); - } + return bx.getGenLinkMin(gen.getLoadKey()); + } catch (Throwable e) { + Iris.warn("Failed to sample lo biome at " + xx + " " + zz + " using the generator " + gen.getLoadKey()); + } - catch(Throwable e) - { - Iris.warn("Failed to sample lo biome at " + xx + " " + zz + " using the generator " + gen.getLoadKey()); - } + return 0; + }); - return 0; - }); + h += M.lerp(lo, hi, gen.getHeight(x, z, seed + 239945)); + } - h += M.lerp(lo, hi, gen.getHeight(x, z, seed + 239945)); - } + AtomicDouble noise = new AtomicDouble(h + fluidHeight + overlayStream.get(x, z)); + engine.getFramework().getEngineParallax().forEachFeature(x, z, (i) + -> noise.set(i.filter(x, z, noise.get()))); + return Math.min(engine.getHeight(), Math.max(noise.get(), 0)); + } - AtomicDouble noise = new AtomicDouble(h + fluidHeight + overlayStream.get(x,z)); - engine.getFramework().getEngineParallax().forEachFeature(x, z, (i) - -> noise.set(i.filter(x, z, noise.get()))); - return Math.min(engine.getHeight(), Math.max(noise.get(), 0)); - } + private void registerGenerator(IrisGenerator cachedGenerator) { + for (IrisGenerator i : generators) { + if (i.getLoadKey().equals(cachedGenerator.getLoadKey())) { + return; + } + } - private void registerGenerator(IrisGenerator cachedGenerator) - { - for(IrisGenerator i : generators) - { - if(i.getLoadKey().equals(cachedGenerator.getLoadKey())) - { - return; - } - } - - generators.add(cachedGenerator); - } + generators.add(cachedGenerator); + } } diff --git a/src/main/java/com/volmit/iris/generator/IrisEngine.java b/src/main/java/com/volmit/iris/generator/IrisEngine.java index 37bfa0117..d1327fb19 100644 --- a/src/main/java/com/volmit/iris/generator/IrisEngine.java +++ b/src/main/java/com/volmit/iris/generator/IrisEngine.java @@ -2,7 +2,6 @@ package com.volmit.iris.generator; import com.volmit.iris.Iris; import com.volmit.iris.object.IrisBiome; -import com.volmit.iris.scaffold.cache.AtomicCache; import com.volmit.iris.scaffold.engine.*; import com.volmit.iris.scaffold.hunk.Hunk; import com.volmit.iris.util.J; @@ -19,8 +18,7 @@ import org.jetbrains.annotations.NotNull; import java.util.Random; -public class IrisEngine extends BlockPopulator implements Engine -{ +public class IrisEngine extends BlockPopulator implements Engine { @Getter private final EngineCompound compound; @@ -54,8 +52,7 @@ public class IrisEngine extends BlockPopulator implements Engine private int cacheId; private final int art; - public IrisEngine(EngineTarget target, EngineCompound compound, int index) - { + public IrisEngine(EngineTarget target, EngineCompound compound, int index) { Iris.info("Initializing Engine: " + target.getWorld().getName() + "/" + target.getDimension().getLoadKey() + " (" + target.getHeight() + " height)"); metrics = new EngineMetrics(32); this.target = target; @@ -72,8 +69,7 @@ public class IrisEngine extends BlockPopulator implements Engine } @Override - public void close() - { + public void close() { J.car(art); closed = true; getWorldManager().close(); @@ -102,11 +98,10 @@ public class IrisEngine extends BlockPopulator implements Engine @Override public void generate(int x, int z, Hunk vblocks, Hunk vbiomes) { - try - { + try { PrecisionStopwatch p = PrecisionStopwatch.start(); - Hunk blocks = vblocks.synchronize().listen((xx,y,zz,t) -> catchBlockUpdates(x+xx,y+getMinHeight(),z+zz, t)); - getFramework().getEngineParallax().generateParallaxArea(x>>4, z>>4); + Hunk blocks = vblocks.synchronize().listen((xx, y, zz, t) -> catchBlockUpdates(x + xx, y + getMinHeight(), z + zz, t)); + getFramework().getEngineParallax().generateParallaxArea(x >> 4, z >> 4); getFramework().getBiomeActuator().actuate(x, z, vbiomes); getFramework().getTerrainActuator().actuate(x, z, blocks); getFramework().getCaveModifier().modify(x, z, blocks); @@ -116,18 +111,14 @@ public class IrisEngine extends BlockPopulator implements Engine getFramework().getEngineParallax().insertParallax(x, z, blocks); getFramework().getDepositModifier().modify(x, z, blocks); getMetrics().getTotal().put(p.getMilliseconds()); - } - - catch(Throwable e) - { + } catch (Throwable e) { fail("Failed to generate " + x + ", " + z, e); } } @Override public IrisBiome getFocus() { - if(getDimension().getFocus() == null || getDimension().getFocus().trim().isEmpty()) - { + if (getDimension().getFocus() == null || getDimension().getFocus().trim().isEmpty()) { return null; } @@ -135,8 +126,7 @@ public class IrisEngine extends BlockPopulator implements Engine } @Override - public void populate(@NotNull World world, @NotNull Random random, @NotNull Chunk c) - { + public void populate(@NotNull World world, @NotNull Random random, @NotNull Chunk c) { getWorldManager().spawnInitialEntities(c); updateChunk(c); placeTiles(c); diff --git a/src/main/java/com/volmit/iris/generator/IrisEngineCompound.java b/src/main/java/com/volmit/iris/generator/IrisEngineCompound.java index cd2e042c4..ebaec7962 100644 --- a/src/main/java/com/volmit/iris/generator/IrisEngineCompound.java +++ b/src/main/java/com/volmit/iris/generator/IrisEngineCompound.java @@ -14,10 +14,6 @@ import com.volmit.iris.scaffold.parallel.MultiBurst; import com.volmit.iris.util.*; import lombok.Getter; import lombok.Setter; -import net.minecraft.core.BlockPosition; -import net.minecraft.world.level.chunk.ChunkGenerator; -import net.minecraft.world.level.levelgen.feature.StructureGenerator; -import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.block.data.BlockData; @@ -27,14 +23,7 @@ import org.bukkit.event.world.WorldSaveEvent; import org.bukkit.generator.BlockPopulator; import java.io.File; -import java.lang.reflect.Field; -import java.lang.reflect.InvocationTargetException; -import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashSet; import java.util.List; -import java.util.Set; -import java.util.concurrent.CompletableFuture; public class IrisEngineCompound implements EngineCompound { @Getter @@ -65,8 +54,7 @@ public class IrisEngineCompound implements EngineCompound { @Setter private boolean studio; - public IrisEngineCompound(World world, IrisDimension rootDimension, IrisDataManager data, int maximumThreads) - { + public IrisEngineCompound(World world, IrisDimension rootDimension, IrisDataManager data, int maximumThreads) { wallClock = new AtomicRollingSequence(32); this.rootDimension = rootDimension; Iris.info("Initializing Engine Composite for " + world.getName()); @@ -78,58 +66,47 @@ public class IrisEngineCompound implements EngineCompound { saveEngineMetadata(); populators = new KList<>(); - if(rootDimension.getDimensionalComposite().isEmpty()) - { + if (rootDimension.getDimensionalComposite().isEmpty()) { burster = null; // TODO: WARNING HEIGHT engines = new Engine[]{new IrisEngine(new EngineTarget(world, rootDimension, data, 256, maximumThreads), this, 0)}; defaultEngine = engines[0]; - } - - else - { + } else { double totalWeight = 0D; engines = new Engine[rootDimension.getDimensionalComposite().size()]; burster = engines.length > 1 ? new MultiBurst(engines.length) : null; int threadDist = (Math.max(2, maximumThreads - engines.length)) / engines.length; - if((threadDist * engines.length) + engines.length > maximumThreads) - { + if ((threadDist * engines.length) + engines.length > maximumThreads) { Iris.warn("Using " + ((threadDist * engines.length) + engines.length) + " threads instead of the configured " + maximumThreads + " maximum thread count due to the requirements of this dimension!"); } - for(IrisDimensionIndex i : rootDimension.getDimensionalComposite()) - { + for (IrisDimensionIndex i : rootDimension.getDimensionalComposite()) { totalWeight += i.getWeight(); } int buf = 0; - for(int i = 0; i < engines.length; i++) - { + for (int i = 0; i < engines.length; i++) { IrisDimensionIndex index = rootDimension.getDimensionalComposite().get(i); IrisDimension dimension = data.getDimensionLoader().load(index.getDimension()); // TODO: WARNING HEIGHT - engines[i] = new IrisEngine(new EngineTarget(world, dimension, data.copy(), (int)Math.floor(256D * (index.getWeight() / totalWeight)), index.isInverted(), threadDist), this, i); + engines[i] = new IrisEngine(new EngineTarget(world, dimension, data.copy(), (int) Math.floor(256D * (index.getWeight() / totalWeight)), index.isInverted(), threadDist), this, i); engines[i].setMinHeight(buf); buf += engines[i].getHeight(); - if(index.isPrimary()) - { + if (index.isPrimary()) { defaultEngine = engines[i]; } } - if(defaultEngine == null) - { + if (defaultEngine == null) { defaultEngine = engines[0]; } } - for(Engine i : engines) - { - if(i instanceof BlockPopulator) - { + for (Engine i : engines) { + if (i instanceof BlockPopulator) { populators.add((BlockPopulator) i); } } @@ -137,40 +114,33 @@ public class IrisEngineCompound implements EngineCompound { Iris.instance.registerListener(this); } - public List getStrongholdPositions() - { + public List getStrongholdPositions() { return engineMetadata.getStrongholdPositions(); } @EventHandler - public void on(WorldSaveEvent e) - { - if(world != null &&e.getWorld().equals(world)) - { + public void on(WorldSaveEvent e) { + if (world != null && e.getWorld().equals(world)) { save(); } } - public void printMetrics(CommandSender sender) - { + public void printMetrics(CommandSender sender) { KMap totals = new KMap<>(); KMap weights = new KMap<>(); double masterWallClock = wallClock.getAverage(); - for(int i = 0; i < getSize(); i++) - { + for (int i = 0; i < getSize(); i++) { Engine e = getEngine(i); KMap timings = e.getMetrics().pull(); double totalWeight = 0; double wallClock = e.getMetrics().getTotal().getAverage(); - for(double j : timings.values()) - { + for (double j : timings.values()) { totalWeight += j; } - for(String j : timings.k()) - { + for (String j : timings.k()) { weights.put(e.getName() + "[" + e.getIndex() + "]." + j, (wallClock / totalWeight) * timings.get(j)); } @@ -179,44 +149,38 @@ public class IrisEngineCompound implements EngineCompound { double mtotals = 0; - for(double i : totals.values()) - { - mtotals+=i; + for (double i : totals.values()) { + mtotals += i; } - for(String i : totals.k()) - { + for (String i : totals.k()) { totals.put(i, (masterWallClock / mtotals) * totals.get(i)); } double v = 0; - for(double i : weights.values()) - { - v+=i; + for (double i : weights.values()) { + v += i; } - for(String i : weights.k()) - { + for (String i : weights.k()) { weights.put(i, weights.get(i) / v); } sender.sendMessage("Total: " + C.BOLD + C.WHITE + Form.duration(masterWallClock, 0)); - for(String i : totals.k()) - { - sender.sendMessage(" Engine " + C.UNDERLINE + C.GREEN + i + C.RESET + ": " + C.BOLD + C.WHITE + Form.duration(totals.get(i), 0)); + for (String i : totals.k()) { + sender.sendMessage(" Engine " + C.UNDERLINE + C.GREEN + i + C.RESET + ": " + C.BOLD + C.WHITE + Form.duration(totals.get(i), 0)); } sender.sendMessage("Details: "); - for(String i : weights.sortKNumber().reverse()) - { - String befb = C.UNDERLINE +""+ C.GREEN + "" + i.split("\\Q[\\E")[0] + C.RESET + C.GRAY + "["; - String num = C.GOLD + i.split("\\Q[\\E")[1].split("]")[0] + C.RESET + C.GRAY + "]."; - String afb = C.ITALIC +""+ C.AQUA + i.split("\\Q]\\E")[1].substring(1) + C.RESET + C.GRAY; + for (String i : weights.sortKNumber().reverse()) { + String befb = C.UNDERLINE + "" + C.GREEN + "" + i.split("\\Q[\\E")[0] + C.RESET + C.GRAY + "["; + String num = C.GOLD + i.split("\\Q[\\E")[1].split("]")[0] + C.RESET + C.GRAY + "]."; + String afb = C.ITALIC + "" + C.AQUA + i.split("\\Q]\\E")[1].substring(1) + C.RESET + C.GRAY; - sender.sendMessage(" " + befb + num + afb + ": " + C.BOLD + C.WHITE + Form.pc(weights.get(i), 0)); + sender.sendMessage(" " + befb + num + afb + ": " + C.BOLD + C.WHITE + Form.pc(weights.get(i), 0)); } } @@ -225,30 +189,23 @@ public class IrisEngineCompound implements EngineCompound { } @Override - public void generate(int x, int z, Hunk blocks, Hunk postblocks, Hunk biomes) - { + public void generate(int x, int z, Hunk blocks, Hunk postblocks, Hunk biomes) { recycle(); PrecisionStopwatch p = PrecisionStopwatch.start(); - if(engines.length == 1 && !getEngine(0).getTarget().isInverted()) - { + if (engines.length == 1 && !getEngine(0).getTarget().isInverted()) { engines[0].generate(x, z, blocks, biomes); - } - - else - { + } else { int i; int offset = 0; - for(i = 0; i < engines.length; i++) - { + for (i = 0; i < engines.length; i++) { Engine engine = engines[i]; int doffset = offset; int height = engine.getTarget().getHeight(); Hunk cblock = Hunk.newArrayHunk(16, height, 16); Hunk cbiome = Hunk.newArrayHunk(16, height, 16); - if(engine.getTarget().isInverted()) - { + if (engine.getTarget().isInverted()) { cblock = cblock.invertY(); cbiome = cbiome.invertY(); } @@ -301,8 +258,7 @@ public class IrisEngineCompound implements EngineCompound { @Override public void hotload() { - for(int i = 0; i < getSize(); i++) - { + for (int i = 0; i < getSize(); i++) { getEngine(i).hotload(); } } diff --git a/src/main/java/com/volmit/iris/generator/IrisEngineEffects.java b/src/main/java/com/volmit/iris/generator/IrisEngineEffects.java index f6ce72e4b..34f9d423f 100644 --- a/src/main/java/com/volmit/iris/generator/IrisEngineEffects.java +++ b/src/main/java/com/volmit/iris/generator/IrisEngineEffects.java @@ -15,8 +15,8 @@ import java.util.UUID; import java.util.concurrent.Semaphore; public class IrisEngineEffects extends EngineAssignedComponent implements EngineEffects { - private KMap players; - private Semaphore limit; + private final KMap players; + private final Semaphore limit; public IrisEngineEffects(Engine engine) { super(engine, "FX"); @@ -30,28 +30,20 @@ public class IrisEngineEffects extends EngineAssignedComponent implements Engine if (pr == null) return; //Fix for paper returning a world with a null playerlist - for(Player i : pr) - { + for (Player i : pr) { Location l = i.getLocation(); boolean pcc = players.containsKey(i.getUniqueId()); - if(getEngine().contains(l)) - { - if(!pcc) - { + if (getEngine().contains(l)) { + if (!pcc) { players.put(i.getUniqueId(), new EnginePlayer(getEngine(), i)); } - } - - else if(pcc) - { + } else if (pcc) { players.remove(i.getUniqueId()); } } - for(UUID i : players.k()) - { - if(!pr.contains(players.get(i).getPlayer())) - { + for (UUID i : players.k()) { + if (!pr.contains(players.get(i).getPlayer())) { players.remove(i); } } @@ -59,17 +51,14 @@ public class IrisEngineEffects extends EngineAssignedComponent implements Engine @Override public void tickRandomPlayer() { - if(limit.tryAcquire()) - { - if(M.r(0.02)) - { + if (limit.tryAcquire()) { + if (M.r(0.02)) { updatePlayerMap(); limit.release(); return; } - if(players.isEmpty()) - { + if (players.isEmpty()) { limit.release(); return; } @@ -78,8 +67,7 @@ public class IrisEngineEffects extends EngineAssignedComponent implements Engine int max = players.size(); PrecisionStopwatch p = new PrecisionStopwatch(); - while(max-- > 0 && M.ms() - p.getMilliseconds() < limitms) - { + while (max-- > 0 && M.ms() - p.getMilliseconds() < limitms) { players.v().getRandom().tick(); } diff --git a/src/main/java/com/volmit/iris/generator/IrisEngineFramework.java b/src/main/java/com/volmit/iris/generator/IrisEngineFramework.java index d1f8058dc..45abdf0ed 100644 --- a/src/main/java/com/volmit/iris/generator/IrisEngineFramework.java +++ b/src/main/java/com/volmit/iris/generator/IrisEngineFramework.java @@ -52,8 +52,7 @@ public class IrisEngineFramework implements EngineFramework { private final AtomicBoolean cleaning; private final ChronoLatch cleanLatch; - public IrisEngineFramework(Engine engine) - { + public IrisEngineFramework(Engine engine) { this.engine = engine; this.complex = new IrisComplex(getEngine()); this.engineParallax = new IrisEngineParallax(getEngine()); @@ -70,27 +69,21 @@ public class IrisEngineFramework implements EngineFramework { @Override public synchronized void recycle() { - if(!cleanLatch.flip()) - { + if (!cleanLatch.flip()) { return; } - if (cleaning.get()) - { + if (cleaning.get()) { cleanLatch.flipDown(); return; } cleaning.set(true); - try - { + try { getEngine().getParallax().cleanup(); getData().getObjectLoader().clean(); - } - - catch(Throwable e) - { + } catch (Throwable e) { Iris.error("Cleanup failed!"); e.printStackTrace(); } @@ -99,8 +92,7 @@ public class IrisEngineFramework implements EngineFramework { } @Override - public void close() - { + public void close() { getEngineParallax().close(); getTerrainActuator().close(); getDecorantActuator().close(); diff --git a/src/main/java/com/volmit/iris/generator/IrisEngineParallax.java b/src/main/java/com/volmit/iris/generator/IrisEngineParallax.java index 5e72bf6c0..71ba8716d 100644 --- a/src/main/java/com/volmit/iris/generator/IrisEngineParallax.java +++ b/src/main/java/com/volmit/iris/generator/IrisEngineParallax.java @@ -11,8 +11,7 @@ public class IrisEngineParallax implements EngineParallaxManager { @Getter private final int parallaxSize; - public IrisEngineParallax(Engine engine) - { + public IrisEngineParallax(Engine engine) { this.engine = engine; parallaxSize = computeParallaxSize(); } diff --git a/src/main/java/com/volmit/iris/generator/IrisWorldManager.java b/src/main/java/com/volmit/iris/generator/IrisWorldManager.java index 2ae5aec77..77a229c97 100644 --- a/src/main/java/com/volmit/iris/generator/IrisWorldManager.java +++ b/src/main/java/com/volmit/iris/generator/IrisWorldManager.java @@ -14,7 +14,7 @@ import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntitySpawnEvent; -public class IrisWorldManager extends EngineAssignedWorldManager { +public class IrisWorldManager extends EngineAssignedWorldManager { private boolean spawnable; public IrisWorldManager(Engine engine) { @@ -36,13 +36,12 @@ public class IrisWorldManager extends EngineAssignedWorldManager { public void spawnInitialEntities(Chunk c) { RNG rng = new RNG(Cache.key(c)); - getEngine().getParallaxAccess().getEntitiesR(c.getX(), c.getZ()).iterateSync((x,y,z,e) -> { - if(e != null) - { + getEngine().getParallaxAccess().getEntitiesR(c.getX(), c.getZ()).iterateSync((x, y, z, e) -> { + if (e != null) { IrisEntity en = getData().getEntityLoader().load(e); - if(en != null){ - en.spawn(getEngine(), new Location(c.getWorld(), x+(c.getX()<<4),y,z+(c.getZ()<<4))); + if (en != null) { + en.spawn(getEngine(), new Location(c.getWorld(), x + (c.getX() << 4), y, z + (c.getZ() << 4))); } } }); @@ -61,17 +60,13 @@ public class IrisWorldManager extends EngineAssignedWorldManager { } @Override - public void onEntitySpawn(EntitySpawnEvent e) - { - if(getTarget().getWorld() == null || !getTarget().getWorld().equals(e.getEntity().getWorld())) - { + public void onEntitySpawn(EntitySpawnEvent e) { + if (getTarget().getWorld() == null || !getTarget().getWorld().equals(e.getEntity().getWorld())) { return; } - try - { - if(!IrisSettings.get().getGenerator().isSystemEntitySpawnOverrides()) - { + try { + if (!IrisSettings.get().getGenerator().isSystemEntitySpawnOverrides()) { return; } @@ -81,14 +76,12 @@ public class IrisWorldManager extends EngineAssignedWorldManager { J.a(() -> { - if(spawnable) - { + if (spawnable) { IrisDimension dim = getDimension(); IrisRegion region = getEngine().getRegion(x, z); IrisBiome above = getEngine().getSurfaceBiome(x, z); IrisBiome bbelow = getEngine().getBiome(x, y, z); - if(above.getLoadKey().equals(bbelow.getLoadKey())) - { + if (above.getLoadKey().equals(bbelow.getLoadKey())) { bbelow = null; } @@ -96,54 +89,40 @@ public class IrisWorldManager extends EngineAssignedWorldManager { J.s(() -> { - if(below != null) - { - if(trySpawn(below.getEntitySpawnOverrides(), e)) - { + if (below != null) { + if (trySpawn(below.getEntitySpawnOverrides(), e)) { return; } } - if(trySpawn(above.getEntitySpawnOverrides(), e)) - { + if (trySpawn(above.getEntitySpawnOverrides(), e)) { return; } - if(trySpawn(region.getEntitySpawnOverrides(), e)) - { + if (trySpawn(region.getEntitySpawnOverrides(), e)) { return; } - if(trySpawn(dim.getEntitySpawnOverrides(), e)) - { + if (trySpawn(dim.getEntitySpawnOverrides(), e)) { return; } }); } }); - } - - catch(Throwable xe) - { + } catch (Throwable xe) { } } - private boolean trySpawn(KList s, EntitySpawnEvent e) - { - for(IrisEntitySpawnOverride i : s) - { + private boolean trySpawn(KList s, EntitySpawnEvent e) { + for (IrisEntitySpawnOverride i : s) { spawnable = false; - if(i.on(getEngine(), e.getLocation(), e.getEntityType(), e) != null) - { + if (i.on(getEngine(), e.getLocation(), e.getEntityType(), e) != null) { e.setCancelled(true); e.getEntity().remove(); return true; - } - - else - { + } else { spawnable = true; } } @@ -151,10 +130,8 @@ public class IrisWorldManager extends EngineAssignedWorldManager { return false; } - private void trySpawn(KList s, Chunk c, RNG rng) - { - for(IrisEntityInitialSpawn i : s) - { + private void trySpawn(KList s, Chunk c, RNG rng) { + for (IrisEntityInitialSpawn i : s) { i.spawn(getEngine(), c, rng); } } diff --git a/src/main/java/com/volmit/iris/generator/actuator/IrisBiomeActuator.java b/src/main/java/com/volmit/iris/generator/actuator/IrisBiomeActuator.java index d4e4e935a..3c082c73a 100644 --- a/src/main/java/com/volmit/iris/generator/actuator/IrisBiomeActuator.java +++ b/src/main/java/com/volmit/iris/generator/actuator/IrisBiomeActuator.java @@ -9,8 +9,7 @@ import com.volmit.iris.util.PrecisionStopwatch; import com.volmit.iris.util.RNG; import org.bukkit.block.Biome; -public class IrisBiomeActuator extends EngineAssignedActuator -{ +public class IrisBiomeActuator extends EngineAssignedActuator { public IrisBiomeActuator(Engine engine) { super(engine, "Biome"); } @@ -18,20 +17,17 @@ public class IrisBiomeActuator extends EngineAssignedActuator @Override public void onActuate(int x, int z, Hunk h) { PrecisionStopwatch p = PrecisionStopwatch.start(); - int zf,hh; + int zf, hh; BurstExecutor burst = MultiBurst.burst.burst(h.getWidth() * h.getDepth()); - for(int xf = 0; xf < h.getWidth(); xf++) - { - for(zf = 0; zf < h.getDepth(); zf++) - { + for (int xf = 0; xf < h.getWidth(); xf++) { + for (zf = 0; zf < h.getDepth(); zf++) { int xxf = xf; int zzf = zf; burst.queue(() -> { - Biome v = getComplex().getTrueBiomeStream().get(modX(xxf+x), modZ(zzf+z)).getSkyBiome(RNG.r, x, 0, z); - for(int i = 0; i < h.getHeight(); i++) - { + Biome v = getComplex().getTrueBiomeStream().get(modX(xxf + x), modZ(zzf + z)).getSkyBiome(RNG.r, x, 0, z); + for (int i = 0; i < h.getHeight(); i++) { h.set(xxf, i, zzf, v); } }); diff --git a/src/main/java/com/volmit/iris/generator/actuator/IrisDecorantActuator.java b/src/main/java/com/volmit/iris/generator/actuator/IrisDecorantActuator.java index 7b766b2cc..7eb360bfd 100644 --- a/src/main/java/com/volmit/iris/generator/actuator/IrisDecorantActuator.java +++ b/src/main/java/com/volmit/iris/generator/actuator/IrisDecorantActuator.java @@ -1,25 +1,20 @@ package com.volmit.iris.generator.actuator; -import com.volmit.iris.generator.decorator.IrisSeaFloorDecorator; +import com.volmit.iris.generator.decorator.*; import com.volmit.iris.object.IrisBiome; -import com.volmit.iris.util.PrecisionStopwatch; -import com.volmit.iris.util.RNG; -import com.volmit.iris.generator.decorator.IrisCeilingDecorator; -import com.volmit.iris.generator.decorator.IrisSeaSurfaceDecorator; -import com.volmit.iris.generator.decorator.IrisShoreLineDecorator; -import com.volmit.iris.generator.decorator.IrisSurfaceDecorator; import com.volmit.iris.scaffold.engine.Engine; import com.volmit.iris.scaffold.engine.EngineAssignedActuator; import com.volmit.iris.scaffold.engine.EngineDecorator; import com.volmit.iris.scaffold.hunk.Hunk; +import com.volmit.iris.util.PrecisionStopwatch; +import com.volmit.iris.util.RNG; import lombok.Getter; import org.bukkit.Material; import org.bukkit.block.data.BlockData; import java.util.function.Predicate; -public class IrisDecorantActuator extends EngineAssignedActuator -{ +public class IrisDecorantActuator extends EngineAssignedActuator { private static final Predicate PREDICATE_SOLID = (b) -> b != null && !b.getMaterial().isAir() && !b.getMaterial().equals(Material.WATER) && !b.getMaterial().equals(Material.LAVA); private final RNG rng; @Getter @@ -47,8 +42,7 @@ public class IrisDecorantActuator extends EngineAssignedActuator @Override public void onActuate(int x, int z, Hunk output) { - if(!getEngine().getDimension().isDecorate()) - { + if (!getEngine().getDimension().isDecorate()) { return; } @@ -57,10 +51,8 @@ public class IrisDecorantActuator extends EngineAssignedActuator int j, realX, realZ, height; IrisBiome biome, cave; - for(int i = 0; i < output.getWidth(); i++) - { - for(j = 0; j < output.getDepth(); j++) - { + for (int i = 0; i < output.getWidth(); i++) { + for (j = 0; j < output.getDepth(); j++) { boolean solid; int emptyFor = 0; int lastSolid = 0; @@ -70,49 +62,38 @@ public class IrisDecorantActuator extends EngineAssignedActuator biome = getComplex().getTrueBiomeStream().get(realX, realZ); cave = shouldRay ? getComplex().getCaveBiomeStream().get(realX, realZ) : null; - if(biome.getDecorators().isEmpty() && (cave == null || cave.getDecorators().isEmpty())) - { + if (biome.getDecorators().isEmpty() && (cave == null || cave.getDecorators().isEmpty())) { continue; } - if(height == getDimension().getFluidHeight()) - { + if (height == getDimension().getFluidHeight()) { getShoreLineDecorator().decorate(i, j, - realX, (int) Math.round(modX(x + i+1)), (int) Math.round(modX(x + i-1)), - realZ, (int) Math.round(modZ(z + j+1)), (int) Math.round(modZ(z + j-1)), + realX, (int) Math.round(modX(x + i + 1)), (int) Math.round(modX(x + i - 1)), + realZ, (int) Math.round(modZ(z + j + 1)), (int) Math.round(modZ(z + j - 1)), output, biome, height, getEngine().getHeight() - height); - } - else if (height == getDimension().getFluidHeight() + 1) - { + } else if (height == getDimension().getFluidHeight() + 1) { getSeaSurfaceDecorator().decorate(i, j, - realX, (int) Math.round(modX(x + i+1)), (int) Math.round(modX(x + i-1)), - realZ, (int) Math.round(modZ(z + j+1)), (int) Math.round(modZ(z + j-1)), + realX, (int) Math.round(modX(x + i + 1)), (int) Math.round(modX(x + i - 1)), + realZ, (int) Math.round(modZ(z + j + 1)), (int) Math.round(modZ(z + j - 1)), output, biome, height, getEngine().getHeight() - getDimension().getFluidHeight()); - } - else if(height < getDimension().getFluidHeight()) - { + } else if (height < getDimension().getFluidHeight()) { getSeaFloorDecorator().decorate(i, j, realX, realZ, output, biome, height + 1, getDimension().getFluidHeight()); } getSurfaceDecorator().decorate(i, j, realX, realZ, output, biome, height, getEngine().getHeight() - height); - if(cave != null && cave.getDecorators().isNotEmpty()) - { - for(int k = height; k > 0; k--) - { + if (cave != null && cave.getDecorators().isNotEmpty()) { + for (int k = height; k > 0; k--) { solid = PREDICATE_SOLID.test(output.get(i, k, j)); - if(solid) - { + if (solid) { if (emptyFor > 0) { getSurfaceDecorator().decorate(i, j, realX, realZ, output, cave, k, emptyFor); getCeilingDecorator().decorate(i, j, realX, realZ, output, cave, lastSolid - 1, emptyFor); emptyFor = 0; } lastSolid = k; - } - else - { + } else { emptyFor++; } } @@ -123,8 +104,7 @@ public class IrisDecorantActuator extends EngineAssignedActuator getEngine().getMetrics().getDecoration().put(p.getMilliseconds()); } - private boolean shouldRayDecorate() - { + private boolean shouldRayDecorate() { return getEngine().getDimension().isCarving() || getEngine().getDimension().isCaves() || getEngine().getDimension().isRavines(); } } diff --git a/src/main/java/com/volmit/iris/generator/actuator/IrisTerrainActuator.java b/src/main/java/com/volmit/iris/generator/actuator/IrisTerrainActuator.java index 79886d562..edb19256e 100644 --- a/src/main/java/com/volmit/iris/generator/actuator/IrisTerrainActuator.java +++ b/src/main/java/com/volmit/iris/generator/actuator/IrisTerrainActuator.java @@ -1,18 +1,17 @@ package com.volmit.iris.generator.actuator; import com.volmit.iris.object.IrisBiome; -import com.volmit.iris.util.KList; -import com.volmit.iris.util.PrecisionStopwatch; -import com.volmit.iris.util.RNG; import com.volmit.iris.scaffold.engine.Engine; import com.volmit.iris.scaffold.engine.EngineAssignedActuator; import com.volmit.iris.scaffold.hunk.Hunk; +import com.volmit.iris.util.KList; +import com.volmit.iris.util.PrecisionStopwatch; +import com.volmit.iris.util.RNG; import lombok.Getter; import org.bukkit.Material; import org.bukkit.block.data.BlockData; -public class IrisTerrainActuator extends EngineAssignedActuator -{ +public class IrisTerrainActuator extends EngineAssignedActuator { private static final BlockData AIR = Material.AIR.createBlockData(); private static final BlockData BEDROCK = Material.BEDROCK.createBlockData(); private static final BlockData CAVE_AIR = Material.CAVE_AIR.createBlockData(); @@ -37,56 +36,46 @@ public class IrisTerrainActuator extends EngineAssignedActuator IrisBiome biome; KList blocks, fblocks; - for(int xf = 0; xf < h.getWidth(); xf++) - { - for(zf = 0; zf < h.getDepth(); zf++) - { + for (int xf = 0; xf < h.getWidth(); xf++) { + for (zf = 0; zf < h.getDepth(); zf++) { realX = (int) modX(xf + x); realZ = (int) modZ(zf + z); b = hasUnder ? (int) Math.round(getDimension().getUndercarriage().get(rng, realX, realZ)) : 0; he = (int) Math.round(Math.min(h.getHeight(), getComplex().getHeightStream().get(realX, realZ))); - hf = (int) Math.round(Math.max(Math.min(h.getHeight(), getDimension().getFluidHeight()), he)); + hf = Math.round(Math.max(Math.min(h.getHeight(), getDimension().getFluidHeight()), he)); biome = getComplex().getTrueBiomeStream().get(realX, realZ); blocks = null; fblocks = null; - if(hf < b) - { + if (hf < b) { continue; } - for(i = hf; i >= b; i--) { - if (i >= h.getHeight()) - { + for (i = hf; i >= b; i--) { + if (i >= h.getHeight()) { continue; } - if(i == b) - { - if(getDimension().isBedrock()) - { + if (i == b) { + if (getDimension().isBedrock()) { h.set(xf, i, zf, BEDROCK); lastBedrock = i; continue; } } - if(carving && getDimension().isCarved(realX, i, realZ, rng, he)) - { + if (carving && getDimension().isCarved(realX, i, realZ, rng, he)) { continue; } - if(i > he && i <= hf) - { + if (i > he && i <= hf) { fdepth = hf - i; - if(fblocks == null) - { + if (fblocks == null) { fblocks = biome.generateSeaLayers(realX, realZ, rng, hf - he, getData()); } - if(fblocks.hasIndex(fdepth)) - { + if (fblocks.hasIndex(fdepth)) { h.set(xf, i, zf, fblocks.get(fdepth)); continue; } @@ -95,16 +84,13 @@ public class IrisTerrainActuator extends EngineAssignedActuator continue; } - if(i <= he) - { + if (i <= he) { depth = he - i; - if(blocks == null) - { - blocks = biome.generateLayers(realX, realZ, rng, (int)he, (int)he, getData(), getComplex()); + if (blocks == null) { + blocks = biome.generateLayers(realX, realZ, rng, he, he, getData(), getComplex()); } - if(blocks.hasIndex(depth)) - { + if (blocks.hasIndex(depth)) { h.set(xf, i, zf, blocks.get(depth)); continue; } diff --git a/src/main/java/com/volmit/iris/generator/decorator/IrisCeilingDecorator.java b/src/main/java/com/volmit/iris/generator/decorator/IrisCeilingDecorator.java index bbc2e6233..b080bdd82 100644 --- a/src/main/java/com/volmit/iris/generator/decorator/IrisCeilingDecorator.java +++ b/src/main/java/com/volmit/iris/generator/decorator/IrisCeilingDecorator.java @@ -8,8 +8,7 @@ import com.volmit.iris.scaffold.engine.Engine; import com.volmit.iris.scaffold.hunk.Hunk; import org.bukkit.block.data.BlockData; -public class IrisCeilingDecorator extends IrisEngineDecorator -{ +public class IrisCeilingDecorator extends IrisEngineDecorator { public IrisCeilingDecorator(Engine engine) { super(engine, "Ceiling", DecorationPart.CEILING); } @@ -18,32 +17,24 @@ public class IrisCeilingDecorator extends IrisEngineDecorator public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, Hunk data, IrisBiome biome, int height, int max) { IrisDecorator decorator = getDecorator(biome, realX, realZ); - if(decorator != null) - { - if(!decorator.isStacking()) - { - if(height >= 0 || height < getEngine().getHeight()) - { + if (decorator != null) { + if (!decorator.isStacking()) { + if (height >= 0 || height < getEngine().getHeight()) { data.set(x, height, z, decorator.getBlockData100(biome, getRng(), realX, realZ, getData())); } - } - - else - { + } else { int stack = decorator.getHeight(getRng().nextParallelRNG(Cache.key(realX, realZ)), realX, realZ, getData()); stack = Math.min(max + 1, stack); BlockData top = decorator.getBlockDataForTop(biome, getRng(), realX, realZ, getData()); BlockData fill = decorator.getBlockData100(biome, getRng(), realX, realZ, getData()); - for(int i = 0; i < stack; i++) - { - if(height - i < 0 || height - i > getEngine().getHeight()) - { + for (int i = 0; i < stack; i++) { + if (height - i < 0 || height - i > getEngine().getHeight()) { continue; } - double threshold = (((double)i) / (double)(stack - 1)); + double threshold = (((double) i) / (double) (stack - 1)); data.set(x, height - i, z, threshold >= decorator.getTopThreshold() ? top : fill); } } diff --git a/src/main/java/com/volmit/iris/generator/decorator/IrisEngineDecorator.java b/src/main/java/com/volmit/iris/generator/decorator/IrisEngineDecorator.java index cf13c242e..d8dbd0655 100644 --- a/src/main/java/com/volmit/iris/generator/decorator/IrisEngineDecorator.java +++ b/src/main/java/com/volmit/iris/generator/decorator/IrisEngineDecorator.java @@ -5,11 +5,11 @@ import com.volmit.iris.object.DecorationPart; import com.volmit.iris.object.IrisBiome; import com.volmit.iris.object.IrisDecorator; import com.volmit.iris.scaffold.cache.Cache; -import com.volmit.iris.util.KList; -import com.volmit.iris.util.RNG; import com.volmit.iris.scaffold.engine.Engine; import com.volmit.iris.scaffold.engine.EngineAssignedComponent; import com.volmit.iris.scaffold.engine.EngineDecorator; +import com.volmit.iris.util.KList; +import com.volmit.iris.util.RNG; import lombok.Getter; public abstract class IrisEngineDecorator extends EngineAssignedComponent implements EngineDecorator { @@ -26,28 +26,21 @@ public abstract class IrisEngineDecorator extends EngineAssignedComponent implem this.rng = new RNG(getSeed() + 29356788 - (part.ordinal() * 10439677)); } - protected IrisDecorator getDecorator(IrisBiome biome, double realX, double realZ) - { + protected IrisDecorator getDecorator(IrisBiome biome, double realX, double realZ) { KList v = new KList<>(); - RNG rng = new RNG(Cache.key((int)realX, (int)realZ)); + RNG rng = new RNG(Cache.key((int) realX, (int) realZ)); - for(IrisDecorator i : biome.getDecorators()) - { - try - { - if(i.getPartOf().equals(part) && i.getBlockData(biome, this.rng, realX, realZ, getData()) != null) - { + for (IrisDecorator i : biome.getDecorators()) { + try { + if (i.getPartOf().equals(part) && i.getBlockData(biome, this.rng, realX, realZ, getData()) != null) { v.add(i); } - } - - catch(Throwable e) - { + } catch (Throwable e) { Iris.error("PART OF: " + biome.getLoadFile().getAbsolutePath() + " HAS AN INVALID DECORATOR near 'partOf'!!!"); } } - if(v.isNotEmpty()) { + if (v.isNotEmpty()) { return v.get(rng.nextInt(v.size())); } diff --git a/src/main/java/com/volmit/iris/generator/decorator/IrisSeaFloorDecorator.java b/src/main/java/com/volmit/iris/generator/decorator/IrisSeaFloorDecorator.java index 3422126cb..480b58ac5 100644 --- a/src/main/java/com/volmit/iris/generator/decorator/IrisSeaFloorDecorator.java +++ b/src/main/java/com/volmit/iris/generator/decorator/IrisSeaFloorDecorator.java @@ -8,49 +8,40 @@ import com.volmit.iris.scaffold.engine.Engine; import com.volmit.iris.scaffold.hunk.Hunk; import org.bukkit.block.data.BlockData; -public class IrisSeaFloorDecorator extends IrisEngineDecorator -{ +public class IrisSeaFloorDecorator extends IrisEngineDecorator { public IrisSeaFloorDecorator(Engine engine) { super(engine, "Sea Floor", DecorationPart.SEA_FLOOR); } @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()) { + if (height <= getDimension().getFluidHeight()) { IrisDecorator decorator = getDecorator(biome, realX, realZ); - if(decorator != null) - { - if(!decorator.isStacking()) - { - if(height >= 0 || height < getEngine().getHeight()) - { + if (decorator != null) { + if (!decorator.isStacking()) { + if (height >= 0 || height < getEngine().getHeight()) { data.set(x, height, z, decorator.getBlockData100(biome, getRng(), realX, realZ, getData())); } - } - else - { + } else { int stack = decorator.getHeight(getRng().nextParallelRNG(Cache.key(realX, realZ)), realX, realZ, getData()); stack = Math.min(stack, getDimension().getFluidHeight() - height + 2); BlockData top = decorator.getBlockDataForTop(biome, getRng(), realX, realZ, getData()); BlockData fill = decorator.getBlockData100(biome, getRng(), realX, realZ, getData()); - for(int i = 0; i < stack; i++) - { - if(height - i < 0 || height - i > getEngine().getHeight()) - { + for (int i = 0; i < stack; i++) { + if (height - i < 0 || height - i > getEngine().getHeight()) { continue; } - if(height+i > getDimension().getFluidHeight()) - { + if (height + i > getDimension().getFluidHeight()) { continue; } - double threshold = ((double)i) / (stack - 1); - data.set(x, height+i, z, threshold >= decorator.getTopThreshold() ? top : fill); + double threshold = ((double) i) / (stack - 1); + data.set(x, height + i, z, threshold >= decorator.getTopThreshold() ? top : fill); } } } diff --git a/src/main/java/com/volmit/iris/generator/decorator/IrisSeaSurfaceDecorator.java b/src/main/java/com/volmit/iris/generator/decorator/IrisSeaSurfaceDecorator.java index fce545940..2400a7608 100644 --- a/src/main/java/com/volmit/iris/generator/decorator/IrisSeaSurfaceDecorator.java +++ b/src/main/java/com/volmit/iris/generator/decorator/IrisSeaSurfaceDecorator.java @@ -8,8 +8,7 @@ import com.volmit.iris.scaffold.engine.Engine; import com.volmit.iris.scaffold.hunk.Hunk; import org.bukkit.block.data.BlockData; -public class IrisSeaSurfaceDecorator extends IrisEngineDecorator -{ +public class IrisSeaSurfaceDecorator extends IrisEngineDecorator { public IrisSeaSurfaceDecorator(Engine engine) { super(engine, "Sea Surface", DecorationPart.SEA_SURFACE); } @@ -18,30 +17,22 @@ public class IrisSeaSurfaceDecorator extends IrisEngineDecorator public void decorate(int x, int z, int realX, int realX1, int realX_1, int realZ, int realZ1, int realZ_1, Hunk data, IrisBiome biome, int height, int max) { IrisDecorator decorator = getDecorator(biome, realX, realZ); - if(decorator != null) - { - if(!decorator.isStacking()) - { - if(height >= 0 || height < getEngine().getHeight()) - { - data.set(x, getDimension().getFluidHeight()+1, z, decorator.getBlockData100(biome, getRng(), realX, realZ, getData())); + if (decorator != null) { + if (!decorator.isStacking()) { + if (height >= 0 || height < getEngine().getHeight()) { + data.set(x, getDimension().getFluidHeight() + 1, z, decorator.getBlockData100(biome, getRng(), realX, realZ, getData())); } - } - - else - { + } else { int stack = decorator.getHeight(getRng().nextParallelRNG(Cache.key(realX, realZ)), realX, realZ, getData()); BlockData top = decorator.getBlockDataForTop(biome, getRng(), realX, realZ, getData()); BlockData fill = decorator.getBlockData100(biome, getRng(), realX, realZ, getData()); - for(int i = 0; i < stack; i++) - { - if(height - i < 0 || height - i > getEngine().getHeight()) - { + for (int i = 0; i < stack; i++) { + if (height - i < 0 || height - i > getEngine().getHeight()) { continue; } - double threshold = ((double)i) / (stack - 1); + double threshold = ((double) i) / (stack - 1); data.set(x, getDimension().getFluidHeight() + 1 + i, z, threshold >= decorator.getTopThreshold() ? top : fill); } } diff --git a/src/main/java/com/volmit/iris/generator/decorator/IrisShoreLineDecorator.java b/src/main/java/com/volmit/iris/generator/decorator/IrisShoreLineDecorator.java index d1ae3dd42..4476dbac9 100644 --- a/src/main/java/com/volmit/iris/generator/decorator/IrisShoreLineDecorator.java +++ b/src/main/java/com/volmit/iris/generator/decorator/IrisShoreLineDecorator.java @@ -8,8 +8,7 @@ import com.volmit.iris.scaffold.engine.Engine; import com.volmit.iris.scaffold.hunk.Hunk; import org.bukkit.block.data.BlockData; -public class IrisShoreLineDecorator extends IrisEngineDecorator -{ +public class IrisShoreLineDecorator extends IrisEngineDecorator { public IrisShoreLineDecorator(Engine engine) { super(engine, "Shore Line", DecorationPart.SHORE_LINE); } @@ -17,32 +16,26 @@ public class IrisShoreLineDecorator extends IrisEngineDecorator @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()) { + if (height == getDimension().getFluidHeight()) { if (Math.round(getComplex().getHeightStream().get(realX1, realZ)) < getComplex().getFluidHeight() || Math.round(getComplex().getHeightStream().get(realX_1, realZ)) < getComplex().getFluidHeight() || Math.round(getComplex().getHeightStream().get(realX, realZ1)) < getComplex().getFluidHeight() || Math.round(getComplex().getHeightStream().get(realX, realZ_1)) < getComplex().getFluidHeight() - ) - { + ) { IrisDecorator decorator = getDecorator(biome, realX, realZ); - if(decorator != null) - { - if(!decorator.isStacking()) - { - data.set(x, height+1, z, decorator.getBlockData100(biome, getRng(), realX, realZ, getData())); - } - else - { + if (decorator != null) { + if (!decorator.isStacking()) { + data.set(x, height + 1, z, decorator.getBlockData100(biome, getRng(), realX, realZ, getData())); + } else { int stack = decorator.getHeight(getRng().nextParallelRNG(Cache.key(realX, realZ)), realX, realZ, getData()); BlockData top = decorator.getBlockDataForTop(biome, getRng(), realX, realZ, getData()); BlockData fill = decorator.getBlockData100(biome, getRng(), realX, realZ, getData()); - for(int i = 0; i < stack; i++) - { - double threshold = ((double)i) / (stack - 1); - data.set(x, height+1+i, z, threshold >= decorator.getTopThreshold() ? top : fill); + for (int i = 0; i < stack; i++) { + double threshold = ((double) i) / (stack - 1); + data.set(x, height + 1 + i, z, threshold >= decorator.getTopThreshold() ? top : fill); } } } diff --git a/src/main/java/com/volmit/iris/generator/decorator/IrisSurfaceDecorator.java b/src/main/java/com/volmit/iris/generator/decorator/IrisSurfaceDecorator.java index ee45fbcac..97d121227 100644 --- a/src/main/java/com/volmit/iris/generator/decorator/IrisSurfaceDecorator.java +++ b/src/main/java/com/volmit/iris/generator/decorator/IrisSurfaceDecorator.java @@ -10,16 +10,14 @@ import com.volmit.iris.scaffold.hunk.Hunk; import org.bukkit.block.data.Bisected; import org.bukkit.block.data.BlockData; -public class IrisSurfaceDecorator extends IrisEngineDecorator -{ +public class IrisSurfaceDecorator extends IrisEngineDecorator { public IrisSurfaceDecorator(Engine engine) { super(engine, "Surface", DecorationPart.NONE); } @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(biome.getInferredType().equals(InferredType.SHORE) && height < getDimension().getFluidHeight()) - { + if (biome.getInferredType().equals(InferredType.SHORE) && height < getDimension().getFluidHeight()) { return; } @@ -28,44 +26,32 @@ public class IrisSurfaceDecorator extends IrisEngineDecorator bdx = data.get(x, height, z); boolean underwater = height < getDimension().getFluidHeight(); - if(decorator != null) - { - if(!decorator.isStacking()) - { + if (decorator != null) { + if (!decorator.isStacking()) { bd = decorator.getBlockData100(biome, getRng(), realX, realZ, getData()); - if(!underwater) - { - if(!canGoOn(bd, bdx)) - { + if (!underwater) { + if (!canGoOn(bd, bdx)) { return; } } - if(bd instanceof Bisected) - { + if (bd instanceof Bisected) { bd = bd.clone(); - ((Bisected)bd).setHalf(Bisected.Half.TOP); - try - { - data.set(x, height+2, z, bd); - } - - catch(Throwable e) - { + ((Bisected) bd).setHalf(Bisected.Half.TOP); + try { + data.set(x, height + 2, z, bd); + } catch (Throwable e) { } bd = bd.clone(); - ((Bisected)bd).setHalf(Bisected.Half.BOTTOM); + ((Bisected) bd).setHalf(Bisected.Half.BOTTOM); } - data.set(x, height+1, z, bd); + data.set(x, height + 1, z, bd); - } - else - { - if (height < getDimension().getFluidHeight()) - { + } else { + if (height < getDimension().getFluidHeight()) { max = getDimension().getFluidHeight() - height; } @@ -73,27 +59,23 @@ public class IrisSurfaceDecorator extends IrisEngineDecorator BlockData top = decorator.getBlockDataForTop(biome, getRng(), realX, realZ, getData()); BlockData fill = decorator.getBlockData100(biome, getRng(), realX, realZ, getData()); - for(int i = 0; i < stack; i++) - { - double threshold = ((double)i) / (stack - 1); + for (int i = 0; i < stack; i++) { + double threshold = ((double) i) / (stack - 1); bd = threshold >= decorator.getTopThreshold() ? top : fill; - if(bd == null) - { + if (bd == null) { break; } - if(i == 0 && !underwater && !canGoOn(bd, bdx)) - { + if (i == 0 && !underwater && !canGoOn(bd, bdx)) { break; } - if(underwater && height + 1 + i > getDimension().getFluidHeight()) - { + if (underwater && height + 1 + i > getDimension().getFluidHeight()) { break; } - data.set(x, height+1+i, z, bd); + data.set(x, height + 1 + i, z, bd); } } } diff --git a/src/main/java/com/volmit/iris/generator/modifier/IrisCaveModifier.java b/src/main/java/com/volmit/iris/generator/modifier/IrisCaveModifier.java index cf9fb1de1..076cc9af4 100644 --- a/src/main/java/com/volmit/iris/generator/modifier/IrisCaveModifier.java +++ b/src/main/java/com/volmit/iris/generator/modifier/IrisCaveModifier.java @@ -12,8 +12,7 @@ import org.bukkit.block.data.BlockData; import java.util.function.Function; -public class IrisCaveModifier extends EngineAssignedModifier -{ +public class IrisCaveModifier extends EngineAssignedModifier { public static final BlockData CAVE_AIR = B.get("CAVE_AIR"); public static final BlockData AIR = B.get("AIR"); private static final KList EMPTY = new KList<>(); @@ -28,31 +27,24 @@ public class IrisCaveModifier extends EngineAssignedModifier @Override public void onModify(int x, int z, Hunk a) { - if(!getDimension().isCaves()) - { + if (!getDimension().isCaves()) { return; } PrecisionStopwatch p = PrecisionStopwatch.start(); - for(int i = 0; i < a.getWidth(); i++) - { - for(int j = 0; j < a.getDepth(); j++) - { + for (int i = 0; i < a.getWidth(); i++) { + for (int j = 0; j < a.getDepth(); j++) { KList caves = genCaves(x + i, z + j, i, j, a); - int he = (int) Math.round(getComplex().getHeightStream().get(x+i, z+j)); - if(caves != null && caves.isNotEmpty()) - { + int he = (int) Math.round(getComplex().getHeightStream().get(x + i, z + j)); + if (caves != null && caves.isNotEmpty()) { IrisBiome cave = getComplex().getCaveBiomeStream().get(x + i, z + j); - if(cave == null) - { + if (cave == null) { continue; } - for(CaveResult cl : caves) - { - if(cl.getFloor() < 0 || cl.getFloor() > getEngine().getHeight() || cl.getCeiling() > getEngine().getHeight() || cl.getCeiling() < 0) - { + for (CaveResult cl : caves) { + if (cl.getFloor() < 0 || cl.getFloor() > getEngine().getHeight() || cl.getCeiling() > getEngine().getHeight() || cl.getCeiling() < 0) { continue; } @@ -61,13 +53,11 @@ public class IrisCaveModifier extends EngineAssignedModifier he - cl.getCeiling(), he - cl.getCeiling(), getData(), getComplex()); - for(int g = 0; g < floor.size(); g++) - { + for (int g = 0; g < floor.size(); g++) { a.set(i, cl.getFloor() - g, j, floor.get(g)); } - for(int g = ceiling.size() - 1; g > 0; g--) - { + for (int g = ceiling.size() - 1; g > 0; g--) { a.set(i, cl.getCeiling() + g, j, ceiling.get(g)); } } @@ -78,10 +68,8 @@ public class IrisCaveModifier extends EngineAssignedModifier getEngine().getMetrics().getCave().put(p.getMilliseconds()); } - public KList genCaves(double wxx, double wzz, int x, int z, Hunk data) - { - if(!getDimension().isCaves()) - { + public KList genCaves(double wxx, double wzz, int x, int z, Hunk data) { + if (!getDimension().isCaves()) { return EMPTY; } @@ -90,8 +78,7 @@ public class IrisCaveModifier extends EngineAssignedModifier gg.setCellularReturnType(FastNoiseDouble.CellularReturnType.Distance2Sub); gg.setCellularDistanceFunction(FastNoiseDouble.CellularDistanceFunction.Natural); - for(int i = 0; i < getDimension().getCaveLayers().size(); i++) - { + for (int i = 0; i < getDimension().getCaveLayers().size(); i++) { IrisCaveLayer layer = getDimension().getCaveLayers().get(i); generateCave(result, wxx, wzz, x, z, data, layer, i); } @@ -99,23 +86,17 @@ public class IrisCaveModifier extends EngineAssignedModifier return result; } - public void generateCave(KList result, double wxx, double wzz, int x, int z, Hunk data, IrisCaveLayer layer, int seed) - { + public void generateCave(KList result, double wxx, double wzz, int x, int z, Hunk data, IrisCaveLayer layer, int seed) { double scale = layer.getCaveZoom(); Function fluid = (height) -> { - if(!layer.getFluid().hasFluid(getData())) - { + if (!layer.getFluid().hasFluid(getData())) { return CAVE_AIR; } - if(layer.getFluid().isInverseHeight() && height >= layer.getFluid().getFluidHeight()) - { + if (layer.getFluid().isInverseHeight() && height >= layer.getFluid().getFluidHeight()) { return layer.getFluid().getFluid(getData()); - } - - else if(!layer.getFluid().isInverseHeight() && height <= layer.getFluid().getFluidHeight()) - { + } else if (!layer.getFluid().isInverseHeight() && height <= layer.getFluid().getFluidHeight()) { return layer.getFluid().getFluid(getData()); } @@ -130,8 +111,7 @@ public class IrisCaveModifier extends EngineAssignedModifier double distanceTake = 0.0022 * baseWidth; double caveHeightNoise = layer.getVerticalSlope().get(rng, wxx, wzz); - if(caveHeightNoise > 259 || caveHeightNoise < -1) - { + if (caveHeightNoise > 259 || caveHeightNoise < -1) { return; } @@ -139,62 +119,48 @@ public class IrisCaveModifier extends EngineAssignedModifier int ceiling = -256; int floor = 512; - for(double tunnelHeight = 1; tunnelHeight <= baseWidth; tunnelHeight++) - { + for (double tunnelHeight = 1; tunnelHeight <= baseWidth; tunnelHeight++) { double distance = (gg.GetCellular(((wx + (10000 * seed)) / layer.getCaveZoom()), ((wz - (10000 * seed)) / layer.getCaveZoom())) + 1D) / 2D; - if(distance < distanceCheck - (tunnelHeight * distanceTake)) - { + if (distance < distanceCheck - (tunnelHeight * distanceTake)) { int caveHeight = (int) Math.round(caveHeightNoise); int pu = (int) (caveHeight + tunnelHeight); int pd = (int) (caveHeight - tunnelHeight); - if(pd > surface + 1) - { + if (pd > surface + 1) { continue; } - if(!layer.isCanBreakSurface() && pu > surface - 3) - { + if (!layer.isCanBreakSurface() && pu > surface - 3) { continue; } - if((pu > 255 && pd > 255) || (pu < 0 && pd < 0)) - { + if ((pu > 255 && pd > 255) || (pu < 0 && pd < 0)) { continue; } - if(data == null) - { + if (data == null) { ceiling = Math.max(pu, ceiling); floor = Math.min(pu, floor); ceiling = Math.max(pd, ceiling); floor = Math.min(pd, floor); - if(tunnelHeight == 1) - { + if (tunnelHeight == 1) { ceiling = Math.max(caveHeight, ceiling); floor = Math.min(caveHeight, floor); } - } - - else - { - if(dig(x, pu, z, data, fluid)) - { + } else { + if (dig(x, pu, z, data, fluid)) { ceiling = Math.max(pu, ceiling); floor = Math.min(pu, floor); } - if(dig(x, pd, z, data, fluid)) - { + if (dig(x, pd, z, data, fluid)) { ceiling = Math.max(pd, ceiling); floor = Math.min(pd, floor); } - if(tunnelHeight == 1) - { - if(dig(x, caveHeight, z, data, fluid)) - { + if (tunnelHeight == 1) { + if (dig(x, caveHeight, z, data, fluid)) { ceiling = Math.max(caveHeight, ceiling); floor = Math.min(caveHeight, floor); } @@ -203,27 +169,23 @@ public class IrisCaveModifier extends EngineAssignedModifier } } - if(floor >= 0 && ceiling <= 255) - { + if (floor >= 0 && ceiling <= 255) { result.add(new CaveResult(floor, ceiling)); } } - private Material mat(int x, int y, int z, Hunk data) - { - BlockData d = data.get(Math.max(x, 0),Math.max(y, 0),Math.max(z,0)); + private Material mat(int x, int y, int z, Hunk data) { + BlockData d = data.get(Math.max(x, 0), Math.max(y, 0), Math.max(z, 0)); - if(d != null) - { + if (d != null) { return d.getMaterial(); } return Material.CAVE_AIR; } - public boolean dig(int x, int y, int z, Hunk data, Function caveFluid) - { - Material a = mat(x,y,z, data); + public boolean dig(int x, int y, int z, Hunk data, Function caveFluid) { + Material a = mat(x, y, z, data); Material c = mat(x, y + 1, z, data); Material d = mat(x, y + 2, z, data); Material e = mat(x, y + 3, z, data); @@ -231,8 +193,7 @@ public class IrisCaveModifier extends EngineAssignedModifier BlockData b = caveFluid.apply(y); BlockData b2 = caveFluid.apply(y + 1); - if(can(a) && canAir(c, b) && canAir(f, b) && canWater(d) && canWater(e)) - { + if (can(a) && canAir(c, b) && canAir(f, b) && canWater(d) && canWater(e)) { data.set(x, y, z, b); data.set(x, y + 1, z, b2); return true; @@ -241,8 +202,7 @@ public class IrisCaveModifier extends EngineAssignedModifier return false; } - public boolean canAir(Material m, BlockData caveFluid) - { + public boolean canAir(Material m, BlockData caveFluid) { return (B.isSolid(m) || (B.isDecorant(m.createBlockData())) || m.equals(Material.AIR) || m.equals(caveFluid.getMaterial()) || @@ -250,13 +210,11 @@ public class IrisCaveModifier extends EngineAssignedModifier && !m.equals(Material.BEDROCK); } - public boolean canWater(Material m) - { + public boolean canWater(Material m) { return !m.equals(Material.WATER); } - public boolean can(Material m) - { + public boolean can(Material m) { return B.isSolid(m) && !m.equals(Material.BEDROCK); } } diff --git a/src/main/java/com/volmit/iris/generator/modifier/IrisDepositModifier.java b/src/main/java/com/volmit/iris/generator/modifier/IrisDepositModifier.java index 79dd3da7d..607a03565 100644 --- a/src/main/java/com/volmit/iris/generator/modifier/IrisDepositModifier.java +++ b/src/main/java/com/volmit/iris/generator/modifier/IrisDepositModifier.java @@ -15,9 +15,10 @@ import org.bukkit.util.BlockVector; public class IrisDepositModifier extends EngineAssignedModifier { private final RNG rng; + public IrisDepositModifier(Engine engine) { super(engine, "Deposit"); - rng = new RNG(getEngine().getWorld().getSeed()+12938).nextParallelRNG(28348777); + rng = new RNG(getEngine().getWorld().getSeed() + 12938).nextParallelRNG(28348777); } @Override @@ -27,50 +28,40 @@ public class IrisDepositModifier extends EngineAssignedModifier { getEngine().getMetrics().getDeposit().put(p.getMilliseconds()); } - public void generateDeposits(RNG rx, Hunk terrain, int x, int z) - { + public void generateDeposits(RNG rx, Hunk terrain, int x, int z) { RNG ro = rx.nextParallelRNG(x * x).nextParallelRNG(z * z); IrisRegion region = getComplex().getRegionStream().get((x * 16) + 7, (z * 16) + 7); IrisBiome biome = getComplex().getTrueBiomeStream().get((x * 16) + 7, (z * 16) + 7); - for(IrisDepositGenerator k : getDimension().getDeposits()) - { + for (IrisDepositGenerator k : getDimension().getDeposits()) { generate(k, terrain, ro, x, z, false); } - for(IrisDepositGenerator k : region.getDeposits()) - { - for(int l = 0; l < ro.i(k.getMinPerChunk(), k.getMaxPerChunk()); l++) - { + for (IrisDepositGenerator k : region.getDeposits()) { + for (int l = 0; l < ro.i(k.getMinPerChunk(), k.getMaxPerChunk()); l++) { generate(k, terrain, ro, x, z, false); } } - for(IrisDepositGenerator k : biome.getDeposits()) - { - for(int l = 0; l < ro.i(k.getMinPerChunk(), k.getMaxPerChunk()); l++) - { + for (IrisDepositGenerator k : biome.getDeposits()) { + for (int l = 0; l < ro.i(k.getMinPerChunk(), k.getMaxPerChunk()); l++) { generate(k, terrain, ro, x, z, false); } } } - public void generate(IrisDepositGenerator k, Hunk data, RNG rng, int cx, int cz, boolean safe) - { + public void generate(IrisDepositGenerator k, Hunk data, RNG rng, int cx, int cz, boolean safe) { generate(k, data, rng, cx, cz, safe, null); } - public void generate(IrisDepositGenerator k, Hunk data, RNG rng, int cx, int cz, boolean safe, HeightMap he) - { - for(int l = 0; l < rng.i(k.getMinPerChunk(), k.getMaxPerChunk()); l++) - { + public void generate(IrisDepositGenerator k, Hunk data, RNG rng, int cx, int cz, boolean safe, HeightMap he) { + for (int l = 0; l < rng.i(k.getMinPerChunk(), k.getMaxPerChunk()); l++) { IrisObject clump = k.getClump(rng, getData()); int af = (int) Math.ceil(clump.getW() / 2D); int bf = (int) Math.floor(16D - (clump.getW() / 2D)); - if(af > bf || af < 0 || bf > 15 || af > 15 || bf < 0) - { + if (af > bf || af < 0 || bf > 15 || af > 15 || bf < 0) { af = 6; bf = 9; } @@ -81,8 +72,7 @@ public class IrisDepositModifier extends EngineAssignedModifier { getComplex().getHeightStream().get((cx << 4) + x, (cz << 4) + z) ))) - 7; - if(height <= 0) - { + if (height <= 0) { return; } @@ -90,33 +80,29 @@ public class IrisDepositModifier extends EngineAssignedModifier { // TODO: WARNING HEIGHT int a = Math.min(height, Math.min(256, k.getMaxHeight())); - if(i >= a) - { + if (i >= a) { return; } int h = rng.i(i, a); - if(h > k.getMaxHeight() || h < k.getMinHeight() || h > height - 2) - { + if (h > k.getMaxHeight() || h < k.getMinHeight() || h > height - 2) { return; } - for(BlockVector j : clump.getBlocks().keySet()) - { + for (BlockVector j : clump.getBlocks().keySet()) { int nx = j.getBlockX() + x; int ny = j.getBlockY() + h; int nz = j.getBlockZ() + z; - if(ny > height || nx > 15 || nx < 0 || ny > 255 || ny < 0 || nz < 0 || nz > 15) - { + if (ny > height || nx > 15 || nx < 0 || ny > 255 || ny < 0 || nz < 0 || nz > 15) { continue; } boolean allow = false; BlockData b = data.get(nx, ny, nz); - if(b != null) { + if (b != null) { for (BlockData f : getDimension().getRockPalette().getBlockData(getData())) { if (f.getMaterial().equals(b.getMaterial())) { allow = true; @@ -125,8 +111,7 @@ public class IrisDepositModifier extends EngineAssignedModifier { } } - if(allow) - { + if (allow) { data.set(nx, ny, nz, clump.getBlocks().get(j)); } } diff --git a/src/main/java/com/volmit/iris/generator/modifier/IrisPostModifier.java b/src/main/java/com/volmit/iris/generator/modifier/IrisPostModifier.java index 4d67b06c6..5674da8c5 100644 --- a/src/main/java/com/volmit/iris/generator/modifier/IrisPostModifier.java +++ b/src/main/java/com/volmit/iris/generator/modifier/IrisPostModifier.java @@ -23,7 +23,7 @@ public class IrisPostModifier extends EngineAssignedModifier { public IrisPostModifier(Engine engine) { super(engine, "Post"); - rng = new RNG(getEngine().getWorld().getSeed()+12938).nextParallelRNG(28348777); + rng = new RNG(getEngine().getWorld().getSeed() + 12938).nextParallelRNG(28348777); } @Override @@ -31,13 +31,11 @@ public class IrisPostModifier extends EngineAssignedModifier { PrecisionStopwatch p = PrecisionStopwatch.start(); BurstExecutor b = MultiBurst.burst.burst(output.getWidth() * output.getDepth()); int i, j; - for(i = 0; i < output.getWidth(); i++) - { + for (i = 0; i < output.getWidth(); i++) { int ii = i; - for(j = 0; j < output.getDepth(); j++) - { + for (j = 0; j < output.getDepth(); j++) { int jj = j; - b.queue(() -> post(ii, jj, output, ii+x, jj+z)); + b.queue(() -> post(ii, jj, output, ii + x, jj + z)); } } b.complete(); @@ -55,8 +53,7 @@ public class IrisPostModifier extends EngineAssignedModifier { // Floating Nibs int g = 0; - if(h < 1) - { + if (h < 1) { return; } @@ -65,14 +62,11 @@ public class IrisPostModifier extends EngineAssignedModifier { g += hc < h - 1 ? 1 : 0; g += hd < h - 1 ? 1 : 0; - if(g == 4 && isAir(x, h - 1, z, currentPostX, currentPostZ, currentData)) - { + if (g == 4 && isAir(x, h - 1, z, currentPostX, currentPostZ, currentData)) { setPostBlock(x, h, z, AIR, currentPostX, currentPostZ, currentData); - for(int i = h - 1; i > 0; i--) - { - if(!isAir(x, i, z, currentPostX, currentPostZ, currentData)) - { + for (int i = h - 1; i > 0; i--) { + if (!isAir(x, i, z, currentPostX, currentPostZ, currentData)) { h = i; break; } @@ -86,24 +80,18 @@ public class IrisPostModifier extends EngineAssignedModifier { g += hc == h - 1 ? 1 : 0; g += hd == h - 1 ? 1 : 0; - if(g >= 4) - { + if (g >= 4) { BlockData bc = getPostBlock(x, h, z, currentPostX, currentPostZ, currentData); BlockData b = getPostBlock(x, h + 1, z, currentPostX, currentPostZ, currentData); Material m = bc.getMaterial(); - if((b.getMaterial().isOccluding() && b.getMaterial().isSolid())) - { - if(m.isSolid()) - { + if ((b.getMaterial().isOccluding() && b.getMaterial().isSolid())) { + if (m.isSolid()) { setPostBlock(x, h, z, b, currentPostX, currentPostZ, currentData); h--; } } - } - - else - { + } else { // Potholes g = 0; g += ha == h + 1 ? 1 : 0; @@ -111,8 +99,7 @@ public class IrisPostModifier extends EngineAssignedModifier { g += hc == h + 1 ? 1 : 0; g += hd == h + 1 ? 1 : 0; - if(g >= 4) - { + if (g >= 4) { BlockData ba = getPostBlock(x, ha, z, currentPostX, currentPostZ, currentData); BlockData bb = getPostBlock(x, hb, z, currentPostX, currentPostZ, currentData); BlockData bc = getPostBlock(x, hc, z, currentPostX, currentPostZ, currentData); @@ -123,8 +110,7 @@ public class IrisPostModifier extends EngineAssignedModifier { g = B.isSolid(bc) ? g + 1 : g; g = B.isSolid(bd) ? g + 1 : g; - if(g >= 3) - { + if (g >= 3) { setPostBlock(x, h + 1, z, getPostBlock(x, h, z, currentPostX, currentPostZ, currentData), currentPostX, currentPostZ, currentData); h++; } @@ -132,27 +118,20 @@ public class IrisPostModifier extends EngineAssignedModifier { } // Wall Patcher - IrisBiome biome = getComplex().getTrueBiomeStream().get(x,z); + IrisBiome biome = getComplex().getTrueBiomeStream().get(x, z); - if(getDimension().isPostProcessingWalls()) - { - if(!biome.getWall().getPalette().isEmpty()) - { - if(ha < h - 2 || hb < h - 2 || hc < h - 2 || hd < h - 2) - { + if (getDimension().isPostProcessingWalls()) { + 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--) - { + for (int i = h; i > h - max; i--) { BlockData d = biome.getWall().get(rng, x + i, i + h, z + i, getData()); - if(d != null) - { - if(isAirOrWater(x, i, z, currentPostX, currentPostZ, currentData)) - { - if(brokeGround) - { + if (d != null) { + if (isAirOrWater(x, i, z, currentPostX, currentPostZ, currentData)) { + if (brokeGround) { break; } @@ -168,10 +147,9 @@ public class IrisPostModifier extends EngineAssignedModifier { } // Slab - if(getDimension().isPostProcessingSlabs()) - { + if (getDimension().isPostProcessingSlabs()) { //@builder - if((ha == h + 1 && isSolidNonSlab(x + 1, ha, z, currentPostX, currentPostZ, currentData)) + if ((ha == h + 1 && isSolidNonSlab(x + 1, ha, z, currentPostX, currentPostZ, currentData)) || (hb == h + 1 && isSolidNonSlab(x, hb, z + 1, currentPostX, currentPostZ, currentData)) || (hc == h + 1 && isSolidNonSlab(x - 1, hc, z, currentPostX, currentPostZ, currentData)) || (hd == h + 1 && isSolidNonSlab(x, hd, z - 1, currentPostX, currentPostZ, currentData))) @@ -179,27 +157,18 @@ public class IrisPostModifier extends EngineAssignedModifier { { BlockData d = biome.getSlab().get(rng, x, h, z, getData()); - if(d != null) - { - boolean cancel = false; + if (d != null) { + boolean cancel = B.isAir(d); - if(B.isAir(d)) - { + if (d.getMaterial().equals(Material.SNOW) && h + 1 <= getDimension().getFluidHeight()) { cancel = true; } - if(d.getMaterial().equals(Material.SNOW) && h + 1 <= getDimension().getFluidHeight()) - { + if (isSnowLayer(x, h, z, currentPostX, currentPostZ, currentData)) { cancel = true; } - if(isSnowLayer(x, h, z, currentPostX, currentPostZ, currentData)) - { - cancel = true; - } - - if(!cancel && isAirOrWater(x, h + 1, z, currentPostX, currentPostZ, currentData)) - { + if (!cancel && isAirOrWater(x, h + 1, z, currentPostX, currentPostZ, currentData)) { setPostBlock(x, h + 1, z, d, currentPostX, currentPostZ, currentData); h++; } @@ -210,34 +179,24 @@ public class IrisPostModifier extends EngineAssignedModifier { // Waterlogging BlockData b = getPostBlock(x, h, z, currentPostX, currentPostZ, currentData); - if(b instanceof Waterlogged) - { + if (b instanceof Waterlogged) { Waterlogged ww = (Waterlogged) b.clone(); boolean w = false; - if (h <= getDimension().getFluidHeight()+1) { - if(isWaterOrWaterlogged(x, h + 1, z, currentPostX, currentPostZ, currentData)) - { + if (h <= getDimension().getFluidHeight() + 1) { + if (isWaterOrWaterlogged(x, h + 1, z, currentPostX, currentPostZ, currentData)) { w = true; - } - - else if((isWaterOrWaterlogged(x + 1, h, z, currentPostX, currentPostZ, currentData) || isWaterOrWaterlogged(x - 1, h, z, currentPostX, currentPostZ, currentData) || isWaterOrWaterlogged(x, h, z + 1, currentPostX, currentPostZ, currentData) || isWaterOrWaterlogged(x, h, z - 1, currentPostX, currentPostZ, currentData))) - { + } else if ((isWaterOrWaterlogged(x + 1, h, z, currentPostX, currentPostZ, currentData) || isWaterOrWaterlogged(x - 1, h, z, currentPostX, currentPostZ, currentData) || isWaterOrWaterlogged(x, h, z + 1, currentPostX, currentPostZ, currentData) || isWaterOrWaterlogged(x, h, z - 1, currentPostX, currentPostZ, currentData))) { w = true; } } - if(w != ww.isWaterlogged()) - { + if (w != ww.isWaterlogged()) { ww.setWaterlogged(w); setPostBlock(x, h, z, ww, currentPostX, currentPostZ, currentData); } - } - - else if(b.getMaterial().equals(Material.AIR) && h <= getDimension().getFluidHeight()) - { - if((isWaterOrWaterlogged(x + 1, h, z, currentPostX, currentPostZ, currentData) || isWaterOrWaterlogged(x - 1, h, z, currentPostX, currentPostZ, currentData) || isWaterOrWaterlogged(x, h, z + 1, currentPostX, currentPostZ, currentData) || isWaterOrWaterlogged(x, h, z - 1, currentPostX, currentPostZ, currentData))) - { + } else if (b.getMaterial().equals(Material.AIR) && h <= getDimension().getFluidHeight()) { + if ((isWaterOrWaterlogged(x + 1, h, z, currentPostX, currentPostZ, currentData) || isWaterOrWaterlogged(x - 1, h, z, currentPostX, currentPostZ, currentData) || isWaterOrWaterlogged(x, h, z + 1, currentPostX, currentPostZ, currentData) || isWaterOrWaterlogged(x, h, z - 1, currentPostX, currentPostZ, currentData))) { setPostBlock(x, h, z, WATER, currentPostX, currentPostZ, currentData); } } @@ -245,26 +204,20 @@ public class IrisPostModifier extends EngineAssignedModifier { // Foliage b = getPostBlock(x, h + 1, z, currentPostX, currentPostZ, currentData); - if(B.isFoliage(b) || b.getMaterial().equals(Material.DEAD_BUSH)) - { + if (B.isFoliage(b) || b.getMaterial().equals(Material.DEAD_BUSH)) { Material onto = getPostBlock(x, h, z, currentPostX, currentPostZ, currentData).getMaterial(); - if(!B.canPlaceOnto(b.getMaterial(), onto)) - { + if (!B.canPlaceOnto(b.getMaterial(), onto)) { setPostBlock(x, h + 1, z, AIR, currentPostX, currentPostZ, currentData); } } - if(getDimension().isPostProcessCaves()) - { + if (getDimension().isPostProcessCaves()) { IrisBiome cave = getComplex().getCaveBiomeStream().get(x, z); - if(cave != null) - { - for(CaveResult i : ((IrisCaveModifier)getFramework().getCaveModifier()).genCaves(x, z, 0, 0, null)) - { - if(i.getCeiling() >= currentData.getMax2DParallelism() || i.getFloor() < 0) - { + if (cave != null) { + for (CaveResult i : ((IrisCaveModifier) getFramework().getCaveModifier()).genCaves(x, z, 0, 0, null)) { + if (i.getCeiling() >= currentData.getMax2DParallelism() || i.getFloor() < 0) { continue; } @@ -286,21 +239,16 @@ public class IrisPostModifier extends EngineAssignedModifier { g += fc == f - 1 ? 1 : 0; g += fd == f - 1 ? 1 : 0; - if(g >= 4) - { + if (g >= 4) { BlockData bc = getPostBlock(x, f, z, currentPostX, currentPostZ, currentData); b = getPostBlock(x, f + 1, z, currentPostX, currentPostZ, currentData); Material m = bc.getMaterial(); - if(m.isSolid()) - { + if (m.isSolid()) { setPostBlock(x, f, z, b, currentPostX, currentPostZ, currentData); h--; } - } - - else - { + } else { // Cave Potholes g = 0; g += fa == f + 1 ? 1 : 0; @@ -308,8 +256,7 @@ public class IrisPostModifier extends EngineAssignedModifier { g += fc == f + 1 ? 1 : 0; g += fd == f + 1 ? 1 : 0; - if(g >= 4) - { + if (g >= 4) { BlockData ba = getPostBlock(x, fa, z, currentPostX, currentPostZ, currentData); BlockData bb = getPostBlock(x, fb, z, currentPostX, currentPostZ, currentData); BlockData bc = getPostBlock(x, fc, z, currentPostX, currentPostZ, currentData); @@ -320,18 +267,16 @@ public class IrisPostModifier extends EngineAssignedModifier { g = B.isSolid(bc) ? g + 1 : g; g = B.isSolid(bd) ? g + 1 : g; - if(g >= 4) - { + if (g >= 4) { setPostBlock(x, f + 1, z, getPostBlock(x, f, z, currentPostX, currentPostZ, currentData), currentPostX, currentPostZ, currentData); h++; } } } - if(getDimension().isPostProcessingSlabs()) - { + if (getDimension().isPostProcessingSlabs()) { //@builder - if((fa == f + 1 && isSolidNonSlab(x + 1, fa, z, currentPostX, currentPostZ, currentData)) + if ((fa == f + 1 && isSolidNonSlab(x + 1, fa, z, currentPostX, currentPostZ, currentData)) || (fb == f + 1 && isSolidNonSlab(x, fb, z + 1, currentPostX, currentPostZ, currentData)) || (fc == f + 1 && isSolidNonSlab(x - 1, fc, z, currentPostX, currentPostZ, currentData)) || (fd == f + 1 && isSolidNonSlab(x, fd, z - 1, currentPostX, currentPostZ, currentData))) @@ -339,34 +284,25 @@ public class IrisPostModifier extends EngineAssignedModifier { { BlockData d = cave.getSlab().get(rng, x, f, z, getData()); - if(d != null) - { - boolean cancel = false; + if (d != null) { + boolean cancel = B.isAir(d); - if(B.isAir(d)) - { + if (d.getMaterial().equals(Material.SNOW) && f + 1 <= getDimension().getFluidHeight()) { cancel = true; } - if(d.getMaterial().equals(Material.SNOW) && f + 1 <= getDimension().getFluidHeight()) - { + if (isSnowLayer(x, f, z, currentPostX, currentPostZ, currentData)) { cancel = true; } - if(isSnowLayer(x, f, z, currentPostX, currentPostZ, currentData)) - { - cancel = true; - } - - if(!cancel && isAirOrWater(x, f + 1, z, currentPostX, currentPostZ, currentData)) - { + if (!cancel && isAirOrWater(x, f + 1, z, currentPostX, currentPostZ, currentData)) { setPostBlock(x, f + 1, z, d, currentPostX, currentPostZ, currentData); } } } //@builder - if((ca == c - 1 && isSolidNonSlab(x + 1, ca, z, currentPostX, currentPostZ, currentData)) + if ((ca == c - 1 && isSolidNonSlab(x + 1, ca, z, currentPostX, currentPostZ, currentData)) || (cb == c - 1 && isSolidNonSlab(x, cb, z + 1, currentPostX, currentPostZ, currentData)) || (cc == c - 1 && isSolidNonSlab(x - 1, cc, z, currentPostX, currentPostZ, currentData)) || (cd == c - 1 && isSolidNonSlab(x, cd, z - 1, currentPostX, currentPostZ, currentData))) @@ -374,27 +310,18 @@ public class IrisPostModifier extends EngineAssignedModifier { { BlockData d = cave.getSlab().get(rng, x, c, z, getData()); - if(d != null) - { - boolean cancel = false; + if (d != null) { + boolean cancel = B.isAir(d); - if(B.isAir(d)) - { + if (!(d instanceof Slab)) { cancel = true; } - if(!(d instanceof Slab)) - { + if (isSnowLayer(x, c, z, currentPostX, currentPostZ, currentData)) { cancel = true; } - if(isSnowLayer(x, c, z, currentPostX, currentPostZ, currentData)) - { - cancel = true; - } - - if(!cancel && isAirOrWater(x, c, z, currentPostX, currentPostZ, currentData)) - { + if (!cancel && isAirOrWater(x, c, z, currentPostX, currentPostZ, currentData)) { Slab slab = (Slab) d.clone(); slab.setType(Slab.Type.TOP); setPostBlock(x, c, z, slab, currentPostX, currentPostZ, currentData); @@ -407,29 +334,20 @@ public class IrisPostModifier extends EngineAssignedModifier { } } - private int nearestCaveFloor(int floor, int x, int z, int currentPostX, int currentPostZ, Hunk currentData) - { - if(floor >= currentData.getHeight()) - { - return currentData.getHeight()-1; + private int nearestCaveFloor(int floor, int x, int z, int currentPostX, int currentPostZ, Hunk currentData) { + if (floor >= currentData.getHeight()) { + return currentData.getHeight() - 1; } - if(B.isAir(getPostBlock(x, floor, z, currentPostX, currentPostZ, currentData))) - { - if(B.isAir(getPostBlock(x, floor - 1, z, currentPostX, currentPostZ, currentData))) - { + if (B.isAir(getPostBlock(x, floor, z, currentPostX, currentPostZ, currentData))) { + if (B.isAir(getPostBlock(x, floor - 1, z, currentPostX, currentPostZ, currentData))) { return floor - 2; } return floor - 1; - } - - else - { - if(!B.isAir(getPostBlock(x, floor + 1, z, currentPostX, currentPostZ, currentData))) - { - if(!B.isAir(getPostBlock(x, floor + 2, z, currentPostX, currentPostZ, currentData))) - { + } else { + if (!B.isAir(getPostBlock(x, floor + 1, z, currentPostX, currentPostZ, currentData))) { + if (!B.isAir(getPostBlock(x, floor + 2, z, currentPostX, currentPostZ, currentData))) { return floor + 2; } @@ -440,29 +358,20 @@ public class IrisPostModifier extends EngineAssignedModifier { } } - private int nearestCaveCeiling(int ceiling, int x, int z, int currentPostX, int currentPostZ, Hunk currentData) - { - if(ceiling >= currentData.getHeight()) - { - return currentData.getHeight()-1; + private int nearestCaveCeiling(int ceiling, int x, int z, int currentPostX, int currentPostZ, Hunk currentData) { + if (ceiling >= currentData.getHeight()) { + return currentData.getHeight() - 1; } - if(B.isAir(getPostBlock(x, ceiling, z, currentPostX, currentPostZ, currentData))) - { - if(B.isAir(getPostBlock(x, ceiling + 1, z, currentPostX, currentPostZ, currentData))) - { + if (B.isAir(getPostBlock(x, ceiling, z, currentPostX, currentPostZ, currentData))) { + if (B.isAir(getPostBlock(x, ceiling + 1, z, currentPostX, currentPostZ, currentData))) { return ceiling + 2; } return ceiling + 1; - } - - else - { - if(!B.isAir(getPostBlock(x, ceiling - 1, z, currentPostX, currentPostZ, currentData))) - { - if(!B.isAir(getPostBlock(x, ceiling - 2, z, currentPostX, currentPostZ, currentData))) - { + } else { + if (!B.isAir(getPostBlock(x, ceiling - 1, z, currentPostX, currentPostZ, currentData))) { + if (!B.isAir(getPostBlock(x, ceiling - 2, z, currentPostX, currentPostZ, currentData))) { return ceiling - 2; } @@ -473,77 +382,64 @@ public class IrisPostModifier extends EngineAssignedModifier { } } - public boolean isAir(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) - { + public boolean isAir(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) { BlockData d = getPostBlock(x, y, z, currentPostX, currentPostZ, currentData); return d.getMaterial().equals(Material.AIR) || d.getMaterial().equals(Material.CAVE_AIR); } - public boolean hasGravity(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) - { + public boolean hasGravity(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) { BlockData d = getPostBlock(x, y, z, currentPostX, currentPostZ, currentData); return d.getMaterial().equals(Material.SAND) || d.getMaterial().equals(Material.RED_SAND) || d.getMaterial().equals(Material.BLACK_CONCRETE_POWDER) || d.getMaterial().equals(Material.BLUE_CONCRETE_POWDER) || d.getMaterial().equals(Material.BROWN_CONCRETE_POWDER) || d.getMaterial().equals(Material.CYAN_CONCRETE_POWDER) || d.getMaterial().equals(Material.GRAY_CONCRETE_POWDER) || d.getMaterial().equals(Material.GREEN_CONCRETE_POWDER) || d.getMaterial().equals(Material.LIGHT_BLUE_CONCRETE_POWDER) || d.getMaterial().equals(Material.LIGHT_GRAY_CONCRETE_POWDER) || d.getMaterial().equals(Material.LIME_CONCRETE_POWDER) || d.getMaterial().equals(Material.MAGENTA_CONCRETE_POWDER) || d.getMaterial().equals(Material.ORANGE_CONCRETE_POWDER) || d.getMaterial().equals(Material.PINK_CONCRETE_POWDER) || d.getMaterial().equals(Material.PURPLE_CONCRETE_POWDER) || d.getMaterial().equals(Material.RED_CONCRETE_POWDER) || d.getMaterial().equals(Material.WHITE_CONCRETE_POWDER) || d.getMaterial().equals(Material.YELLOW_CONCRETE_POWDER); } - public boolean isSolid(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) - { + public boolean isSolid(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) { BlockData d = getPostBlock(x, y, z, currentPostX, currentPostZ, currentData); return d.getMaterial().isSolid(); } - public boolean isSolidNonSlab(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) - { + public boolean isSolidNonSlab(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) { BlockData d = getPostBlock(x, y, z, currentPostX, currentPostZ, currentData); return d.getMaterial().isSolid() && !(d instanceof Slab); } - public boolean isAirOrWater(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) - { + public boolean isAirOrWater(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) { BlockData d = getPostBlock(x, y, z, currentPostX, currentPostZ, currentData); return d.getMaterial().equals(Material.WATER) || d.getMaterial().equals(Material.AIR) || d.getMaterial().equals(Material.CAVE_AIR); } - public boolean isSlab(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) - { + public boolean isSlab(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) { BlockData d = getPostBlock(x, y, z, currentPostX, currentPostZ, currentData); return d instanceof Slab; } - public boolean isSnowLayer(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) - { + public boolean isSnowLayer(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) { BlockData d = getPostBlock(x, y, z, currentPostX, currentPostZ, currentData); return d.getMaterial().equals(Material.SNOW); } - public boolean isWater(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) - { + public boolean isWater(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) { BlockData d = getPostBlock(x, y, z, currentPostX, currentPostZ, currentData); return d.getMaterial().equals(Material.WATER); } - public boolean isWaterOrWaterlogged(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) - { + public boolean isWaterOrWaterlogged(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) { BlockData d = getPostBlock(x, y, z, currentPostX, currentPostZ, currentData); return d.getMaterial().equals(Material.WATER) || (d instanceof Waterlogged && ((Waterlogged) d).isWaterlogged()); } - public boolean isLiquid(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) - { + public boolean isLiquid(int x, int y, int z, int currentPostX, int currentPostZ, Hunk currentData) { BlockData d = getPostBlock(x, y, z, currentPostX, currentPostZ, currentData); return d instanceof Levelled; } - public void setPostBlock(int x, int y, int z, BlockData d, int currentPostX, int currentPostZ, Hunk currentData) - { - if(y < currentData.getHeight()) - { + public void setPostBlock(int x, int y, int z, BlockData d, int currentPostX, int currentPostZ, Hunk currentData) { + if (y < currentData.getHeight()) { currentData.set(x & 15, y, z & 15, d); } } - public BlockData getPostBlock(int x, int y, int z, int cpx, int cpz, Hunk h) - { + public BlockData getPostBlock(int x, int y, int z, int cpx, int cpz, Hunk h) { BlockData b = h.getClosest(x & 15, y, z & 15); return b == null ? AIR : b; diff --git a/src/main/java/com/volmit/iris/generator/modifier/IrisRavineModifier.java b/src/main/java/com/volmit/iris/generator/modifier/IrisRavineModifier.java index 1d5e36cb5..166e3b4d7 100644 --- a/src/main/java/com/volmit/iris/generator/modifier/IrisRavineModifier.java +++ b/src/main/java/com/volmit/iris/generator/modifier/IrisRavineModifier.java @@ -2,18 +2,18 @@ package com.volmit.iris.generator.modifier; import com.volmit.iris.generator.noise.CNG; import com.volmit.iris.object.NoiseStyle; -import com.volmit.iris.util.*; import com.volmit.iris.scaffold.engine.Engine; import com.volmit.iris.scaffold.engine.EngineAssignedModifier; import com.volmit.iris.scaffold.hunk.Hunk; +import com.volmit.iris.util.*; import org.bukkit.Material; import org.bukkit.block.data.BlockData; public class IrisRavineModifier extends EngineAssignedModifier { private static final BlockData CAVE_AIR = B.get("CAVE_AIR"); private static final BlockData LAVA = B.get("LAVA"); - private CNG cng; - private RNG rng; + private final CNG cng; + private final RNG rng; public IrisRavineModifier(Engine engine) { super(engine, "Ravine"); @@ -23,8 +23,7 @@ public class IrisRavineModifier extends EngineAssignedModifier { @Override public void onModify(int x, int z, Hunk output) { - if(!getDimension().isRavines()) - { + if (!getDimension().isRavines()) { return; } @@ -33,61 +32,51 @@ public class IrisRavineModifier extends EngineAssignedModifier { getEngine().getMetrics().getRavine().put(p.getMilliseconds()); } - private void set(Hunk pos, int x, int y, int z, BlockData b) - { + private void set(Hunk pos, int x, int y, int z, BlockData b) { pos.set(x, y, z, b); } - private BlockData get(Hunk pos, int x, int y, int z) - { - BlockData bb = pos.get(x, y, z); + private BlockData get(Hunk pos, int x, int y, int z) { + BlockData bb = pos.get(x, y, z); - if(bb == null) - { - bb = CAVE_AIR; + if (bb == null) { + bb = CAVE_AIR; } return bb; } - private BlockData getSurfaceBlock(int n6, int i, RNG rmg) - { - return getComplex().getTrueBiomeStream().get(n6,i).getSurfaceBlock(n6, i, rmg, getData()); + private BlockData getSurfaceBlock(int n6, int i, RNG rmg) { + return getComplex().getTrueBiomeStream().get(n6, i).getSurfaceBlock(n6, i, rmg, getData()); } - private float[] ravineCache = new float[1024]; + private final float[] ravineCache = new float[1024]; - private void doRavine(long seed, int tx, int tz, ChunkPosition pos, double sx, double sy, double sz, float f, float f2, float f3, int n3, int n4, double d4, RNG bbx, Hunk terrain) - { + private void doRavine(long seed, int tx, int tz, ChunkPosition pos, double sx, double sy, double sz, float f, float f2, float f3, int n3, int n4, double d4, RNG bbx, Hunk terrain) { int n5; RNG random = new RNG(seed); double x = tx * 16 + 8; double z = tz * 16 + 8; float f4 = 0.0f; float f5 = 0.0f; - if(n4 <= 0) - { + if (n4 <= 0) { n5 = 8 * 16 - 16; n4 = n5 - random.nextInt(n5 / 4); } n5 = 0; - if(n3 == -1) - { + if (n3 == -1) { n3 = n4 / 2; n5 = 1; } float f6 = 1.0f; // TODO: WARNING HEIGHT - for(int i = 0; i < 256; ++i) - { - if(i == 0 || random.nextInt(getDimension().getRavineRibRarity()) == 0) - { + for (int i = 0; i < 256; ++i) { + if (i == 0 || random.nextInt(getDimension().getRavineRibRarity()) == 0) { f6 = 1.0f + random.nextFloat() * random.nextFloat() * 1.0f; } this.ravineCache[i] = f6 * f6; } - while(n3 < n4) - { + while (n3 < n4) { double d7 = 1.5 + (double) (MathHelper.sin((float) n3 * 3.1415927f / (float) n4) * f * 1.0f); double d8 = d7 * d4; d7 *= (double) random.nextFloat() * 0.25 + 0.75; @@ -104,18 +93,15 @@ public class IrisRavineModifier extends EngineAssignedModifier { f4 *= 0.5f; f5 += (random.nextFloat() - random.nextFloat()) * random.nextFloat() * 2.0f; f4 += (random.nextFloat() - random.nextFloat()) * random.nextFloat() * 4.0f; - if(n5 != 0 || random.nextInt(4) != 0) - { + if (n5 != 0 || random.nextInt(4) != 0) { double d9 = sx - x; double d10 = sz - z; double d11 = n4 - n3; double d12 = f + 2.0f + 16.0f; - if(d9 * d9 + d10 * d10 - d11 * d11 > d12 * d12) - { + if (d9 * d9 + d10 * d10 - d11 * d11 > d12 * d12) { return; } - if(sx >= x - 16.0 - d7 * 2.0 && sz >= z - 16.0 - d7 * 2.0 && sx <= x + 16.0 + d7 * 2.0 && sz <= z + 16.0 + d7 * 2.0) - { + if (sx >= x - 16.0 - d7 * 2.0 && sz >= z - 16.0 - d7 * 2.0 && sx <= x + 16.0 + d7 * 2.0 && sz <= z + 16.0 + d7 * 2.0) { int n6; int n7 = MathHelper.floor(sx - d7) - tx * 16 - 1; int n8 = MathHelper.floor(sx + d7) - tx * 16 + 1; @@ -123,59 +109,47 @@ public class IrisRavineModifier extends EngineAssignedModifier { int n10 = MathHelper.floor(sy + d8) + 1; int n11 = MathHelper.floor(sz - d7) - tz * 16 - 1; int n12 = MathHelper.floor(sz + d7) - tz * 16 + 1; - if(n7 < 0) - { + if (n7 < 0) { n7 = 0; } - if(n8 > 16) - { + if (n8 > 16) { n8 = 16; } - if(n9 < 1) - { + if (n9 < 1) { n9 = 1; } - if(n10 > 248) - { + if (n10 > 248) { n10 = 248; } - if(n11 < 0) - { + if (n11 < 0) { n11 = 0; } - if(n12 > 16) - { + if (n12 > 16) { n12 = 16; } boolean bl = false; - for(int i = n7; !bl && i < n8; ++i) - { - for(n6 = n11; !bl && n6 < n12; ++n6) - { - for(int j = n10 + 1; !bl && j >= n9 - 1; --j) - { + for (int i = n7; !bl && i < n8; ++i) { + for (n6 = n11; !bl && n6 < n12; ++n6) { + for (int j = n10 + 1; !bl && j >= n9 - 1; --j) { // TODO: WARNING HEIGHT - if(j < 0 || j >= 256) - { + if (j < 0 || j >= 256) { continue; } BlockData bb = get(terrain, i, j, n6); - if(B.isWater(bb)) - { + if (B.isWater(bb)) { bl = true; } - if(j == n9 - 1 || i == n7 || i == n8 - 1 || n6 == n11 || n6 == n12 - 1) - { + if (j == n9 - 1 || i == n7 || i == n8 - 1 || n6 == n11 || n6 == n12 - 1) { continue; } j = n9; } } } - if(!bl) { + if (!bl) { BlockPosition bps = new BlockPosition(0, 0, 0); for (n6 = n7; n6 < n8; ++n6) { double d13 = ((double) (n6 + tx * 16) + 0.5 - sx) / d7; @@ -212,8 +186,7 @@ public class IrisRavineModifier extends EngineAssignedModifier { } } } - if (n5 != 0) - { + if (n5 != 0) { break; } } @@ -223,17 +196,15 @@ public class IrisRavineModifier extends EngineAssignedModifier { } } - private BlockPosition cSet(BlockPosition bb, double var0, double var2, double var4) - { - bb.setX(MathHelper.floor((double) var0)); - bb.setY(MathHelper.floor((double) var2)); - bb.setZ(MathHelper.floor((double) var4)); + private BlockPosition cSet(BlockPosition bb, double var0, double var2, double var4) { + bb.setX(MathHelper.floor(var0)); + bb.setY(MathHelper.floor(var2)); + bb.setZ(MathHelper.floor(var4)); return bb; } - private boolean isDirt(BlockData d) - { + private boolean isDirt(BlockData d) { //@builder Material m = d.getMaterial(); return m.equals(Material.DIRT) || @@ -242,8 +213,7 @@ public class IrisRavineModifier extends EngineAssignedModifier { //@done } - private boolean isSurface(BlockData d) - { + private boolean isSurface(BlockData d) { //@builder Material m = d.getMaterial(); return m.equals(Material.GRASS_BLOCK) || @@ -254,16 +224,13 @@ public class IrisRavineModifier extends EngineAssignedModifier { //@done } - public void genRavines(int n, int n2, ChunkPosition chunkSnapshot, RNG bbb, Hunk terrain) - { + public void genRavines(int n, int n2, ChunkPosition chunkSnapshot, RNG bbb, Hunk terrain) { RNG b = this.rng.nextParallelRNG(21949666); RNG bx = this.rng.nextParallelRNG(6676121); long l = b.nextLong(); long l2 = b.nextLong(); - for(int i = n - 8; i <= n + 8; ++i) - { - for(int j = n2 - 8; j <= n2 + 8; ++j) - { + for (int i = n - 8; i <= n + 8; ++i) { + for (int j = n2 - 8; j <= n2 + 8; ++j) { long l3 = (long) i * l; long l4 = (long) j * l2; bx = this.rng.nextParallelRNG((int) (l3 ^ l4 ^ 6676121)); @@ -272,10 +239,8 @@ public class IrisRavineModifier extends EngineAssignedModifier { } } - private void doRavines(int tx, int tz, int sx, int sz, ChunkPosition chunkSnapshot, RNG b, Hunk terrain) - { - if(b.nextInt(getDimension().getRavineRarity()) != 0) - { + private void doRavines(int tx, int tz, int sx, int sz, ChunkPosition chunkSnapshot, RNG b, Hunk terrain) { + if (b.nextInt(getDimension().getRavineRarity()) != 0) { return; } @@ -283,8 +248,7 @@ public class IrisRavineModifier extends EngineAssignedModifier { double d2 = b.nextInt(b.nextInt(40) + 8) + 20; double z = tz * 16 + b.nextInt(16); int n5 = 1; - for(int i = 0; i < n5; ++i) - { + for (int i = 0; i < n5; ++i) { float f = b.nextFloat() * 3.1415927f * 2.0f; float f2 = (b.nextFloat() - 0.5f) * 2.0f / 8.0f; float f3 = (b.nextFloat() * 2.0f + b.nextFloat()) * 2.0f; @@ -292,8 +256,7 @@ public class IrisRavineModifier extends EngineAssignedModifier { } } - public void generateRavines(RNG nextParallelRNG, int x, int z, Hunk terrain) - { + public void generateRavines(RNG nextParallelRNG, int x, int z, Hunk terrain) { genRavines(x, z, new ChunkPosition(x, z), nextParallelRNG.nextParallelRNG(x).nextParallelRNG(z), terrain); } } diff --git a/src/main/java/com/volmit/iris/generator/noise/CNG.java b/src/main/java/com/volmit/iris/generator/noise/CNG.java index fc9961c32..f88c2a108 100644 --- a/src/main/java/com/volmit/iris/generator/noise/CNG.java +++ b/src/main/java/com/volmit/iris/generator/noise/CNG.java @@ -9,457 +9,383 @@ import lombok.Data; import java.util.List; @Data -public class CNG -{ - public static long hits = 0; - public static long creates = 0; - public static final NoiseInjector ADD = (s, v) -> new double[] {s + v, 1}; - public static final NoiseInjector SRC_SUBTRACT = (s, v) -> new double[] {s - v < 0 ? 0 : s - v, -1}; - public static final NoiseInjector DST_SUBTRACT = (s, v) -> new double[] {v - s < 0 ? 0 : s - v, -1}; - public static final NoiseInjector MULTIPLY = (s, v) -> new double[] {s * v, 0}; - public static final NoiseInjector MAX = (s, v) -> new double[] {Math.max(s, v), 0}; - public static final NoiseInjector MIN = (s, v) -> new double[] {Math.min(s, v), 0}; - public static final NoiseInjector SRC_MOD = (s, v) -> new double[] {s % v, 0}; - public static final NoiseInjector SRC_POW = (s, v) -> new double[] {Math.pow(s, v), 0}; - public static final NoiseInjector DST_MOD = (s, v) -> new double[] {v % s, 0}; - public static final NoiseInjector DST_POW = (s, v) -> new double[] {Math.pow(v, s), 0}; - private double scale; - private double bakedScale; - private double fscale; - private boolean trueFracturing = false; - private KList children; - private CNG fracture; - private NoiseGenerator generator; - private final double opacity; - private NoiseInjector injector; - private RNG rng; - private boolean noscale; - private int oct; - private double patch; - private double up; - private double down; - private double power; - - public NoiseGenerator getGen() - { - return generator; - } - - public ProceduralStream stream() - { - return new CNGStream(this); - } - - public ProceduralStream stream(double min, double max) - { - return new FittedStream(stream(), min, max); - } - - public static CNG signature(RNG rng) - { - return signature(rng, NoiseType.SIMPLEX); - } - - public static CNG signatureHalf(RNG rng) - { - return signatureHalf(rng, NoiseType.SIMPLEX); - } - - public static CNG signatureThick(RNG rng) - { - return signatureThick(rng, NoiseType.SIMPLEX); - } - - public static CNG signatureDouble(RNG rng) - { - return signatureDouble(rng, NoiseType.SIMPLEX); - } - - public static CNG signatureDouble(RNG rng, NoiseType t) - { - return signatureThick(rng, t).fractureWith(signature(rng.nextParallelRNG(4956)), 93); - } - - - public static CNG signatureDoubleFast(RNG rng, NoiseType t, NoiseType f) - { - return signatureThickFast(rng, t, f) - .fractureWith(signatureFast(rng.nextParallelRNG(4956), t, f), 93); - } - - public static CNG signature(RNG rng, NoiseType t) - { - // @NoArgsConstructor - return new CNG(rng.nextParallelRNG(17), t, 1D, 1).fractureWith(new CNG(rng.nextParallelRNG(18), 1, 1).scale(0.9).fractureWith(new CNG(rng.nextParallelRNG(20), 1, 1).scale(0.21).fractureWith(new CNG(rng.nextParallelRNG(20), 1, 1).scale(0.9), 620), 145), 44).bake(); - // @done - } - - public static CNG signaturePerlin(RNG rng) - { - return signaturePerlin(rng, NoiseType.PERLIN); - } - - public static CNG signaturePerlin(RNG rng, NoiseType t) - { - // @NoArgsConstructor - return new CNG(rng.nextParallelRNG(124996), t, 1D, 1) - .fractureWith(new CNG(rng.nextParallelRNG(18), NoiseType.PERLIN, 1, 1).scale(1.25), 250) - .bake(); - // @done - } - - public static CNG signatureFast(RNG rng, NoiseType t, NoiseType f) - { - // @NoArgsConstructor - return new CNG(rng.nextParallelRNG(17), t, 1D, 1) - .fractureWith(new CNG(rng.nextParallelRNG(18), f, 1, 1) - .scale(0.9) - .fractureWith(new CNG(rng.nextParallelRNG(20), f, 1, 1) - .scale(0.21) - .fractureWith(new CNG(rng.nextParallelRNG(20), f, 1, 1).scale(0.9), 620), 145), 44) - .bake(); - // @done - } - - public static CNG signatureThick(RNG rng, NoiseType t) - { - // @NoArgsConstructor - return new CNG(rng.nextParallelRNG(133), t, 1D, 1).fractureWith(new CNG(rng.nextParallelRNG(18), 1, 1).scale(0.5).fractureWith(new CNG(rng.nextParallelRNG(20), 1, 1).scale(0.11).fractureWith(new CNG(rng.nextParallelRNG(20), 1, 1).scale(0.4), 620), 145), 44).bake(); - // @done - } - - public static CNG signatureThickFast(RNG rng, NoiseType t, NoiseType f) - { - // @NoArgsConstructor - return new CNG(rng.nextParallelRNG(133), t, 1D, 1) - .fractureWith(new CNG(rng.nextParallelRNG(18), f, 1, 1) - .scale(0.5).fractureWith(new CNG(rng.nextParallelRNG(20), f, 1, 1) - .scale(0.11).fractureWith(new CNG(rng.nextParallelRNG(20), f, 1, 1) - .scale(0.4), 620), 145), 44).bake(); - // @done - } - - public static CNG signatureHalf(RNG rng, NoiseType t) - { - // @NoArgsConstructor - return new CNG(rng.nextParallelRNG(127), t, 1D, 1).fractureWith(new CNG(rng.nextParallelRNG(18), 1, 1).scale(0.9).fractureWith(new CNG(rng.nextParallelRNG(20), 1, 1).scale(0.21).fractureWith(new CNG(rng.nextParallelRNG(20), 1, 1).scale(0.9), 420), 99), 22).bake(); - // @done - } - - public static CNG signatureHalfFast(RNG rng, NoiseType t, NoiseType f) - { - // @NoArgsConstructor - return new CNG(rng.nextParallelRNG(127), t, 1D, 1) - .fractureWith(new CNG(rng.nextParallelRNG(18),f, 1, 1).scale(0.9) - .fractureWith(new CNG(rng.nextParallelRNG(20), f, 1, 1).scale(0.21) - .fractureWith(new CNG(rng.nextParallelRNG(20), f, 1, 1).scale(0.9), 420), 99), 22).bake(); - // @done - } - - public CNG(RNG random) - { - this(random, 1); - } - - public CNG(RNG random, int octaves) - { - this(random, 1D, octaves); - } - - public CNG(RNG random, double opacity, int octaves) - { - this(random, NoiseType.SIMPLEX, opacity, octaves); - } - - public CNG(RNG random, NoiseType t, double opacity, int octaves) - { - creates++; - noscale = t.equals(NoiseType.WHITE); - this.oct = octaves; - this.rng = random; - power = 1; - scale = 1; - patch = 1; - bakedScale = 1; - fscale = 1; - down = 0; - up = 0; - fracture = null; - generator = t.create(random.nextParallelRNG(33).lmax()); - this.opacity = opacity; - this.injector = ADD; - - if(generator instanceof OctaveNoise) - { - ((OctaveNoise) generator).setOctaves(octaves); - } - } - - public CNG bake() - { - bakedScale *= scale; - scale = 1; - return this; - } - - public CNG child(CNG c) - { - if(children == null) - { - children = new KList<>(); - } - - children.add(c); - return this; - } - - public RNG getRNG() - { - return rng; - } - - public CNG fractureWith(CNG c, double scale) - { - fracture = c; - fscale = scale; - return this; - } - - public CNG scale(double c) - { - scale = c; - return this; - } - - public CNG patch(double c) - { - patch = c; - return this; - } - - public CNG up(double c) - { - up = c; - return this; - } - - public CNG down(double c) - { - down = c; - return this; - } - - public CNG injectWith(NoiseInjector i) - { - injector = i; - return this; - } - - public T fitRarity(KList b, double... dim) - { - if(b.size() == 0) - { - return null; - } - - if(b.size() == 1) - { - return b.get(0); - } - - KList rarityMapped = new KList<>(); - boolean o = false; - int max = 1; - for(T i : b) - { - if(i.getRarity() > max) - { - max = i.getRarity(); - } - } - - max++; - - for(T i : b) - { - for(int j = 0; j < max - i.getRarity(); j++) - { - if(o = !o) - { - rarityMapped.add(i); - } - - else - { - rarityMapped.add(0, i); - } - } - } - - if(rarityMapped.size() == 1) - { - return rarityMapped.get(0); - } - - if(rarityMapped.isEmpty()) - { - throw new RuntimeException("BAD RARITY MAP! RELATED TO: " + b.toString(", or possibly ")); - } - - return fit(rarityMapped, dim); - } - - public T fit(T[] v, double... dim) - { - if(v.length == 0) - { - return null; - } - - if(v.length == 1) - { - return v[0]; - } - - return v[fit(0, v.length - 1, dim)]; - } - - public T fit(List v, double... dim) - { - if(v.size() == 0) - { - return null; - } - - if(v.size() == 1) - { - return v.get(0); - } - - try - { - return v.get(fit(0, v.size() - 1, dim)); - } - - catch(Throwable e) - { - - } - - return v.get(0); - } - - public int fit(int min, int max, double... dim) - { - if(min == max) - { - return min; - } - - double noise = noise(dim); - - return (int) Math.round(IrisInterpolation.lerp(min, max, noise)); - } - - public int fit(double min, double max, double... dim) - { - if(min == max) - { - return (int) Math.round(min); - } - - double noise = noise(dim); - - return (int) Math.round(IrisInterpolation.lerp(min, max, noise)); - } - - public double fitDouble(double min, double max, double... dim) - { - if(min == max) - { - return min; - } - - double noise = noise(dim); - - return IrisInterpolation.lerp(min, max, noise); - } - - private double getNoise(double... dim) - { - if(isTrueFracturing()) - { - if(dim.length == 2) - { - double scale = noscale ? 1 : this.bakedScale * this.scale; - double f1 = noscale ? 0 : (fracture != null ? (fracture.noise(dim[0], dim[1]) - 0.5) * fscale : 0D); - double f2 = noscale ? 0 : (fracture != null ? (fracture.noise(dim[1], dim[0]) - 0.5) * fscale : 0D); - double x = dim[0] + f1; - double y = dim[1] + -f1; - double z = 0D; - return generator.noise(x * scale, y * scale, z * scale) * opacity; - } - - else if(dim.length == 3) - { - double scale = noscale ? 1 : this.bakedScale * this.scale; - double f1 = noscale ? 0 : (fracture != null ? (fracture.noise(dim[0], dim[2], dim[1]) - 0.5) * fscale : 0D); - double f2 = noscale ? 0 : (fracture != null ? (fracture.noise(dim[1], dim[0], dim[2]) - 0.5) * fscale : 0D); - double f3 = noscale ? 0 : (fracture != null ? (fracture.noise(dim[2], dim[1], dim[0]) - 0.5) * fscale : 0D); - double x = dim[0] + f1; - double y = dim[1] + f3; - double z = dim[2] + f2; - return generator.noise(x * scale, y * scale, z * scale) * opacity; - } - } - - double scale = noscale ? 1 : this.bakedScale * this.scale; - double f = noscale ? 0 : (fracture != null ? (fracture.noise(dim) - 0.5) * fscale : 0D); - double x = dim.length > 0 ? dim[0] + f : 0D; - double y = dim.length > 1 ? dim[1] + -f : 0D; - double z = dim.length > 2 ? dim[2] + -f : 0D; - return generator.noise(x * scale, y * scale, z * scale) * opacity; - } - - public double noise(double... dim) - { - double n = getNoise(dim); - n = power != 1D ? (n < 0 ? -Math.pow(Math.abs(n), power) : Math.pow(n, power)) : n; - double m = 1; - hits += oct; - if(children == null) - { - return (n - down + up) * patch; - } - - for(CNG i : children) - { - double[] r = injector.combine(n, i.noise(dim)); - n = r[0]; - m += r[1]; - } - - return ((n / m) - down + up) * patch; - } - - public CNG pow(double power) - { - this.power = power; - return this; - } - - public CNG oct(int octaves) - { - oct = octaves; - return this; - } - - public double getScale() - { - return scale; - } - - public boolean isStatic() { - return generator != null && generator.isStatic(); - } +public class CNG { + public static long hits = 0; + public static long creates = 0; + public static final NoiseInjector ADD = (s, v) -> new double[]{s + v, 1}; + public static final NoiseInjector SRC_SUBTRACT = (s, v) -> new double[]{s - v < 0 ? 0 : s - v, -1}; + public static final NoiseInjector DST_SUBTRACT = (s, v) -> new double[]{v - s < 0 ? 0 : s - v, -1}; + public static final NoiseInjector MULTIPLY = (s, v) -> new double[]{s * v, 0}; + public static final NoiseInjector MAX = (s, v) -> new double[]{Math.max(s, v), 0}; + public static final NoiseInjector MIN = (s, v) -> new double[]{Math.min(s, v), 0}; + public static final NoiseInjector SRC_MOD = (s, v) -> new double[]{s % v, 0}; + public static final NoiseInjector SRC_POW = (s, v) -> new double[]{Math.pow(s, v), 0}; + public static final NoiseInjector DST_MOD = (s, v) -> new double[]{v % s, 0}; + public static final NoiseInjector DST_POW = (s, v) -> new double[]{Math.pow(v, s), 0}; + private double scale; + private double bakedScale; + private double fscale; + private boolean trueFracturing = false; + private KList children; + private CNG fracture; + private NoiseGenerator generator; + private final double opacity; + private NoiseInjector injector; + private RNG rng; + private boolean noscale; + private int oct; + private double patch; + private double up; + private double down; + private double power; + + public NoiseGenerator getGen() { + return generator; + } + + public ProceduralStream stream() { + return new CNGStream(this); + } + + public ProceduralStream stream(double min, double max) { + return new FittedStream(stream(), min, max); + } + + public static CNG signature(RNG rng) { + return signature(rng, NoiseType.SIMPLEX); + } + + public static CNG signatureHalf(RNG rng) { + return signatureHalf(rng, NoiseType.SIMPLEX); + } + + public static CNG signatureThick(RNG rng) { + return signatureThick(rng, NoiseType.SIMPLEX); + } + + public static CNG signatureDouble(RNG rng) { + return signatureDouble(rng, NoiseType.SIMPLEX); + } + + public static CNG signatureDouble(RNG rng, NoiseType t) { + return signatureThick(rng, t).fractureWith(signature(rng.nextParallelRNG(4956)), 93); + } + + + public static CNG signatureDoubleFast(RNG rng, NoiseType t, NoiseType f) { + return signatureThickFast(rng, t, f) + .fractureWith(signatureFast(rng.nextParallelRNG(4956), t, f), 93); + } + + public static CNG signature(RNG rng, NoiseType t) { + // @NoArgsConstructor + return new CNG(rng.nextParallelRNG(17), t, 1D, 1).fractureWith(new CNG(rng.nextParallelRNG(18), 1, 1).scale(0.9).fractureWith(new CNG(rng.nextParallelRNG(20), 1, 1).scale(0.21).fractureWith(new CNG(rng.nextParallelRNG(20), 1, 1).scale(0.9), 620), 145), 44).bake(); + // @done + } + + public static CNG signaturePerlin(RNG rng) { + return signaturePerlin(rng, NoiseType.PERLIN); + } + + public static CNG signaturePerlin(RNG rng, NoiseType t) { + // @NoArgsConstructor + return new CNG(rng.nextParallelRNG(124996), t, 1D, 1) + .fractureWith(new CNG(rng.nextParallelRNG(18), NoiseType.PERLIN, 1, 1).scale(1.25), 250) + .bake(); + // @done + } + + public static CNG signatureFast(RNG rng, NoiseType t, NoiseType f) { + // @NoArgsConstructor + return new CNG(rng.nextParallelRNG(17), t, 1D, 1) + .fractureWith(new CNG(rng.nextParallelRNG(18), f, 1, 1) + .scale(0.9) + .fractureWith(new CNG(rng.nextParallelRNG(20), f, 1, 1) + .scale(0.21) + .fractureWith(new CNG(rng.nextParallelRNG(20), f, 1, 1).scale(0.9), 620), 145), 44) + .bake(); + // @done + } + + public static CNG signatureThick(RNG rng, NoiseType t) { + // @NoArgsConstructor + return new CNG(rng.nextParallelRNG(133), t, 1D, 1).fractureWith(new CNG(rng.nextParallelRNG(18), 1, 1).scale(0.5).fractureWith(new CNG(rng.nextParallelRNG(20), 1, 1).scale(0.11).fractureWith(new CNG(rng.nextParallelRNG(20), 1, 1).scale(0.4), 620), 145), 44).bake(); + // @done + } + + public static CNG signatureThickFast(RNG rng, NoiseType t, NoiseType f) { + // @NoArgsConstructor + return new CNG(rng.nextParallelRNG(133), t, 1D, 1) + .fractureWith(new CNG(rng.nextParallelRNG(18), f, 1, 1) + .scale(0.5).fractureWith(new CNG(rng.nextParallelRNG(20), f, 1, 1) + .scale(0.11).fractureWith(new CNG(rng.nextParallelRNG(20), f, 1, 1) + .scale(0.4), 620), 145), 44).bake(); + // @done + } + + public static CNG signatureHalf(RNG rng, NoiseType t) { + // @NoArgsConstructor + return new CNG(rng.nextParallelRNG(127), t, 1D, 1).fractureWith(new CNG(rng.nextParallelRNG(18), 1, 1).scale(0.9).fractureWith(new CNG(rng.nextParallelRNG(20), 1, 1).scale(0.21).fractureWith(new CNG(rng.nextParallelRNG(20), 1, 1).scale(0.9), 420), 99), 22).bake(); + // @done + } + + public static CNG signatureHalfFast(RNG rng, NoiseType t, NoiseType f) { + // @NoArgsConstructor + return new CNG(rng.nextParallelRNG(127), t, 1D, 1) + .fractureWith(new CNG(rng.nextParallelRNG(18), f, 1, 1).scale(0.9) + .fractureWith(new CNG(rng.nextParallelRNG(20), f, 1, 1).scale(0.21) + .fractureWith(new CNG(rng.nextParallelRNG(20), f, 1, 1).scale(0.9), 420), 99), 22).bake(); + // @done + } + + public CNG(RNG random) { + this(random, 1); + } + + public CNG(RNG random, int octaves) { + this(random, 1D, octaves); + } + + public CNG(RNG random, double opacity, int octaves) { + this(random, NoiseType.SIMPLEX, opacity, octaves); + } + + public CNG(RNG random, NoiseType t, double opacity, int octaves) { + creates++; + noscale = t.equals(NoiseType.WHITE); + this.oct = octaves; + this.rng = random; + power = 1; + scale = 1; + patch = 1; + bakedScale = 1; + fscale = 1; + down = 0; + up = 0; + fracture = null; + generator = t.create(random.nextParallelRNG(33).lmax()); + this.opacity = opacity; + this.injector = ADD; + + if (generator instanceof OctaveNoise) { + ((OctaveNoise) generator).setOctaves(octaves); + } + } + + public CNG bake() { + bakedScale *= scale; + scale = 1; + return this; + } + + public CNG child(CNG c) { + if (children == null) { + children = new KList<>(); + } + + children.add(c); + return this; + } + + public RNG getRNG() { + return rng; + } + + public CNG fractureWith(CNG c, double scale) { + fracture = c; + fscale = scale; + return this; + } + + public CNG scale(double c) { + scale = c; + return this; + } + + public CNG patch(double c) { + patch = c; + return this; + } + + public CNG up(double c) { + up = c; + return this; + } + + public CNG down(double c) { + down = c; + return this; + } + + public CNG injectWith(NoiseInjector i) { + injector = i; + return this; + } + + public T fitRarity(KList b, double... dim) { + if (b.size() == 0) { + return null; + } + + if (b.size() == 1) { + return b.get(0); + } + + KList rarityMapped = new KList<>(); + boolean o = false; + int max = 1; + for (T i : b) { + if (i.getRarity() > max) { + max = i.getRarity(); + } + } + + max++; + + for (T i : b) { + for (int j = 0; j < max - i.getRarity(); j++) { + if (o = !o) { + rarityMapped.add(i); + } else { + rarityMapped.add(0, i); + } + } + } + + if (rarityMapped.size() == 1) { + return rarityMapped.get(0); + } + + if (rarityMapped.isEmpty()) { + throw new RuntimeException("BAD RARITY MAP! RELATED TO: " + b.toString(", or possibly ")); + } + + return fit(rarityMapped, dim); + } + + public T fit(T[] v, double... dim) { + if (v.length == 0) { + return null; + } + + if (v.length == 1) { + return v[0]; + } + + return v[fit(0, v.length - 1, dim)]; + } + + public T fit(List v, double... dim) { + if (v.size() == 0) { + return null; + } + + if (v.size() == 1) { + return v.get(0); + } + + try { + return v.get(fit(0, v.size() - 1, dim)); + } catch (Throwable e) { + + } + + return v.get(0); + } + + public int fit(int min, int max, double... dim) { + if (min == max) { + return min; + } + + double noise = noise(dim); + + return (int) Math.round(IrisInterpolation.lerp(min, max, noise)); + } + + public int fit(double min, double max, double... dim) { + if (min == max) { + return (int) Math.round(min); + } + + double noise = noise(dim); + + return (int) Math.round(IrisInterpolation.lerp(min, max, noise)); + } + + public double fitDouble(double min, double max, double... dim) { + if (min == max) { + return min; + } + + double noise = noise(dim); + + return IrisInterpolation.lerp(min, max, noise); + } + + private double getNoise(double... dim) { + if (isTrueFracturing()) { + if (dim.length == 2) { + double scale = noscale ? 1 : this.bakedScale * this.scale; + double f1 = noscale ? 0 : (fracture != null ? (fracture.noise(dim[0], dim[1]) - 0.5) * fscale : 0D); + double f2 = noscale ? 0 : (fracture != null ? (fracture.noise(dim[1], dim[0]) - 0.5) * fscale : 0D); + double x = dim[0] + f1; + double y = dim[1] + -f1; + double z = 0D; + return generator.noise(x * scale, y * scale, z * scale) * opacity; + } else if (dim.length == 3) { + double scale = noscale ? 1 : this.bakedScale * this.scale; + double f1 = noscale ? 0 : (fracture != null ? (fracture.noise(dim[0], dim[2], dim[1]) - 0.5) * fscale : 0D); + double f2 = noscale ? 0 : (fracture != null ? (fracture.noise(dim[1], dim[0], dim[2]) - 0.5) * fscale : 0D); + double f3 = noscale ? 0 : (fracture != null ? (fracture.noise(dim[2], dim[1], dim[0]) - 0.5) * fscale : 0D); + double x = dim[0] + f1; + double y = dim[1] + f3; + double z = dim[2] + f2; + return generator.noise(x * scale, y * scale, z * scale) * opacity; + } + } + + double scale = noscale ? 1 : this.bakedScale * this.scale; + double f = noscale ? 0 : (fracture != null ? (fracture.noise(dim) - 0.5) * fscale : 0D); + double x = dim.length > 0 ? dim[0] + f : 0D; + double y = dim.length > 1 ? dim[1] + -f : 0D; + double z = dim.length > 2 ? dim[2] + -f : 0D; + return generator.noise(x * scale, y * scale, z * scale) * opacity; + } + + public double noise(double... dim) { + double n = getNoise(dim); + n = power != 1D ? (n < 0 ? -Math.pow(Math.abs(n), power) : Math.pow(n, power)) : n; + double m = 1; + hits += oct; + if (children == null) { + return (n - down + up) * patch; + } + + for (CNG i : children) { + double[] r = injector.combine(n, i.noise(dim)); + n = r[0]; + m += r[1]; + } + + return ((n / m) - down + up) * patch; + } + + public CNG pow(double power) { + this.power = power; + return this; + } + + public CNG oct(int octaves) { + oct = octaves; + return this; + } + + public double getScale() { + return scale; + } + + public boolean isStatic() { + return generator != null && generator.isStatic(); + } } diff --git a/src/main/java/com/volmit/iris/generator/noise/CNGFactory.java b/src/main/java/com/volmit/iris/generator/noise/CNGFactory.java index ce9aef9e8..4f2eca08a 100644 --- a/src/main/java/com/volmit/iris/generator/noise/CNGFactory.java +++ b/src/main/java/com/volmit/iris/generator/noise/CNGFactory.java @@ -3,7 +3,6 @@ package com.volmit.iris.generator.noise; import com.volmit.iris.util.RNG; @FunctionalInterface -public interface CNGFactory -{ - CNG create(RNG seed); +public interface CNGFactory { + CNG create(RNG seed); } diff --git a/src/main/java/com/volmit/iris/generator/noise/CellGenerator.java b/src/main/java/com/volmit/iris/generator/noise/CellGenerator.java index 0beba98b6..2265c551c 100644 --- a/src/main/java/com/volmit/iris/generator/noise/CellGenerator.java +++ b/src/main/java/com/volmit/iris/generator/noise/CellGenerator.java @@ -1,88 +1,75 @@ package com.volmit.iris.generator.noise; import com.volmit.iris.util.RNG; - import lombok.Getter; import lombok.Setter; -public class CellGenerator -{ - private FastNoiseDouble fn; - private FastNoiseDouble fd; - private CNG cng; +public class CellGenerator { + private final FastNoiseDouble fn; + private final FastNoiseDouble fd; + private final CNG cng; - @Getter - @Setter - private double cellScale; + @Getter + @Setter + private double cellScale; - @Getter - @Setter - private double shuffle; + @Getter + @Setter + private double shuffle; - public CellGenerator(RNG rng) - { - shuffle = 128; - cellScale = 0.73; - cng = CNG.signature(rng.nextParallelRNG(3204)); - RNG rx = rng.nextParallelRNG(8735652); - long s = rx.lmax(); - fn = new FastNoiseDouble(s); - fn.setNoiseType(FastNoiseDouble.NoiseType.Cellular); - fn.setCellularReturnType(FastNoiseDouble.CellularReturnType.CellValue); - fn.setCellularDistanceFunction(FastNoiseDouble.CellularDistanceFunction.Natural); - fd = new FastNoiseDouble(s); - fd.setNoiseType(FastNoiseDouble.NoiseType.Cellular); - fd.setCellularReturnType(FastNoiseDouble.CellularReturnType.Distance2Sub); - fd.setCellularDistanceFunction(FastNoiseDouble.CellularDistanceFunction.Natural); - } + public CellGenerator(RNG rng) { + shuffle = 128; + cellScale = 0.73; + cng = CNG.signature(rng.nextParallelRNG(3204)); + RNG rx = rng.nextParallelRNG(8735652); + long s = rx.lmax(); + fn = new FastNoiseDouble(s); + fn.setNoiseType(FastNoiseDouble.NoiseType.Cellular); + fn.setCellularReturnType(FastNoiseDouble.CellularReturnType.CellValue); + fn.setCellularDistanceFunction(FastNoiseDouble.CellularDistanceFunction.Natural); + fd = new FastNoiseDouble(s); + fd.setNoiseType(FastNoiseDouble.NoiseType.Cellular); + fd.setCellularReturnType(FastNoiseDouble.CellularReturnType.Distance2Sub); + fd.setCellularDistanceFunction(FastNoiseDouble.CellularDistanceFunction.Natural); + } - public double getDistance(double x, double z) - { - return ((fd.GetCellular(((x * cellScale) + (cng.noise(x, z) * shuffle)), ((z * cellScale) + (cng.noise(z, x) * shuffle)))) + 1f) / 2f; - } + public double getDistance(double x, double z) { + return ((fd.GetCellular(((x * cellScale) + (cng.noise(x, z) * shuffle)), ((z * cellScale) + (cng.noise(z, x) * shuffle)))) + 1f) / 2f; + } - public double getDistance(double x, double y, double z) - { - return ((fd.GetCellular(((x * cellScale) + (cng.noise(x, y, z) * shuffle)), ((y * cellScale) + (cng.noise(x, y, z) * shuffle)), ((z * cellScale) + (cng.noise(z, y, x) * shuffle)))) + 1f) / 2f; - } + public double getDistance(double x, double y, double z) { + return ((fd.GetCellular(((x * cellScale) + (cng.noise(x, y, z) * shuffle)), ((y * cellScale) + (cng.noise(x, y, z) * shuffle)), ((z * cellScale) + (cng.noise(z, y, x) * shuffle)))) + 1f) / 2f; + } - public double getValue(double x, double z, int possibilities) - { - if(possibilities == 1) - { - return 0; - } + public double getValue(double x, double z, int possibilities) { + if (possibilities == 1) { + return 0; + } - return ((fn.GetCellular(((x * cellScale) + (cng.noise(x, z) * shuffle)), ((z * cellScale) + (cng.noise(z, x) * shuffle))) + 1f) / 2f) * (possibilities - 1); - } + return ((fn.GetCellular(((x * cellScale) + (cng.noise(x, z) * shuffle)), ((z * cellScale) + (cng.noise(z, x) * shuffle))) + 1f) / 2f) * (possibilities - 1); + } - public double getValue(double x, double y, double z, int possibilities) - { - if(possibilities == 1) - { - return 0; - } + public double getValue(double x, double y, double z, int possibilities) { + if (possibilities == 1) { + return 0; + } - return ((fn.GetCellular(((x * cellScale) + (cng.noise(x, z) * shuffle)), ((y * 8 * cellScale) + (cng.noise(x, y * 8) * shuffle)), ((z * cellScale) + (cng.noise(z, x) * shuffle))) + 1f) / 2f) * (possibilities - 1); - } + return ((fn.GetCellular(((x * cellScale) + (cng.noise(x, z) * shuffle)), ((y * 8 * cellScale) + (cng.noise(x, y * 8) * shuffle)), ((z * cellScale) + (cng.noise(z, x) * shuffle))) + 1f) / 2f) * (possibilities - 1); + } - public int getIndex(double x, double z, int possibilities) - { - if(possibilities == 1) - { - return 0; - } + public int getIndex(double x, double z, int possibilities) { + if (possibilities == 1) { + return 0; + } - return (int) Math.round(getValue(x, z, possibilities)); - } + return (int) Math.round(getValue(x, z, possibilities)); + } - public int getIndex(double x, double y, double z, int possibilities) - { - if(possibilities == 1) - { - return 0; - } + public int getIndex(double x, double y, double z, int possibilities) { + if (possibilities == 1) { + return 0; + } - return (int) Math.round(getValue(x, y, z, possibilities)); - } + return (int) Math.round(getValue(x, y, z, possibilities)); + } } diff --git a/src/main/java/com/volmit/iris/generator/noise/CellHeightNoise.java b/src/main/java/com/volmit/iris/generator/noise/CellHeightNoise.java index fc94ae512..ec7565b21 100644 --- a/src/main/java/com/volmit/iris/generator/noise/CellHeightNoise.java +++ b/src/main/java/com/volmit/iris/generator/noise/CellHeightNoise.java @@ -3,38 +3,32 @@ package com.volmit.iris.generator.noise; import com.volmit.iris.util.M; import com.volmit.iris.util.RNG; -public class CellHeightNoise implements NoiseGenerator -{ - private final FastNoiseDouble n; +public class CellHeightNoise implements NoiseGenerator { + private final FastNoiseDouble n; - public CellHeightNoise(long seed) - { - this.n = new FastNoiseDouble(new RNG(seed).lmax()); - n.setNoiseType(FastNoiseDouble.NoiseType.Cellular); - n.setCellularReturnType(FastNoiseDouble.CellularReturnType.Distance2Sub); - n.setCellularDistanceFunction(FastNoiseDouble.CellularDistanceFunction.Natural); - } + public CellHeightNoise(long seed) { + this.n = new FastNoiseDouble(new RNG(seed).lmax()); + n.setNoiseType(FastNoiseDouble.NoiseType.Cellular); + n.setCellularReturnType(FastNoiseDouble.CellularReturnType.Distance2Sub); + n.setCellularDistanceFunction(FastNoiseDouble.CellularDistanceFunction.Natural); + } - private double filter(double noise) - { - return M.clip(1D - ((noise / 2D) + 0.5D), 0D, 1D); - } + private double filter(double noise) { + return M.clip(1D - ((noise / 2D) + 0.5D), 0D, 1D); + } - @Override - public double noise(double x) - { - return filter(n.GetCellular(x, 0)); - } + @Override + public double noise(double x) { + return filter(n.GetCellular(x, 0)); + } - @Override - public double noise(double x, double z) - { - return filter(n.GetCellular(x, z)); - } + @Override + public double noise(double x, double z) { + return filter(n.GetCellular(x, z)); + } - @Override - public double noise(double x, double y, double z) - { - return filter(n.GetCellular(x, y, z)); - } + @Override + public double noise(double x, double y, double z) { + return filter(n.GetCellular(x, y, z)); + } } diff --git a/src/main/java/com/volmit/iris/generator/noise/CellularNoise.java b/src/main/java/com/volmit/iris/generator/noise/CellularNoise.java index 1db837397..ee8fab770 100644 --- a/src/main/java/com/volmit/iris/generator/noise/CellularNoise.java +++ b/src/main/java/com/volmit/iris/generator/noise/CellularNoise.java @@ -2,33 +2,28 @@ package com.volmit.iris.generator.noise; import com.volmit.iris.util.RNG; -public class CellularNoise implements NoiseGenerator -{ - private final FastNoise n; +public class CellularNoise implements NoiseGenerator { + private final FastNoise n; - public CellularNoise(long seed) - { - this.n = new FastNoise(new RNG(seed).imax()); - n.SetNoiseType(FastNoise.NoiseType.Cellular); - n.SetCellularReturnType(FastNoise.CellularReturnType.CellValue); - n.SetCellularDistanceFunction(FastNoise.CellularDistanceFunction.Natural); - } + public CellularNoise(long seed) { + this.n = new FastNoise(new RNG(seed).imax()); + n.SetNoiseType(FastNoise.NoiseType.Cellular); + n.SetCellularReturnType(FastNoise.CellularReturnType.CellValue); + n.SetCellularDistanceFunction(FastNoise.CellularDistanceFunction.Natural); + } - @Override - public double noise(double x) - { - return (n.GetCellular((float) x, 0) / 2D) + 0.5D; - } + @Override + public double noise(double x) { + return (n.GetCellular((float) x, 0) / 2D) + 0.5D; + } - @Override - public double noise(double x, double z) - { - return (n.GetCellular((float)x, (float)z) / 2D) + 0.5D; - } + @Override + public double noise(double x, double z) { + return (n.GetCellular((float) x, (float) z) / 2D) + 0.5D; + } - @Override - public double noise(double x, double y, double z) - { - return (n.GetCellular((float)x, (float)y, (float)z) / 2D) + 0.5D; - } + @Override + public double noise(double x, double y, double z) { + return (n.GetCellular((float) x, (float) y, (float) z) / 2D) + 0.5D; + } } diff --git a/src/main/java/com/volmit/iris/generator/noise/CubicNoise.java b/src/main/java/com/volmit/iris/generator/noise/CubicNoise.java index 57e55339f..a34b69081 100644 --- a/src/main/java/com/volmit/iris/generator/noise/CubicNoise.java +++ b/src/main/java/com/volmit/iris/generator/noise/CubicNoise.java @@ -2,35 +2,29 @@ package com.volmit.iris.generator.noise; import com.volmit.iris.util.RNG; -public class CubicNoise implements NoiseGenerator -{ - private final FastNoiseDouble n; +public class CubicNoise implements NoiseGenerator { + private final FastNoiseDouble n; - public CubicNoise(long seed) - { - this.n = new FastNoiseDouble(new RNG(seed).lmax()); - } + public CubicNoise(long seed) { + this.n = new FastNoiseDouble(new RNG(seed).lmax()); + } - private double f(double n) - { - return (n / 2D) + 0.5D; - } + private double f(double n) { + return (n / 2D) + 0.5D; + } - @Override - public double noise(double x) - { - return f(n.GetCubic(x, 0)); - } + @Override + public double noise(double x) { + return f(n.GetCubic(x, 0)); + } - @Override - public double noise(double x, double z) - { - return f(n.GetCubic(x, z)); - } + @Override + public double noise(double x, double z) { + return f(n.GetCubic(x, z)); + } - @Override - public double noise(double x, double y, double z) - { - return f(n.GetCubic(x, y, z)); - } + @Override + public double noise(double x, double y, double z) { + return f(n.GetCubic(x, y, z)); + } } diff --git a/src/main/java/com/volmit/iris/generator/noise/FastNoise.java b/src/main/java/com/volmit/iris/generator/noise/FastNoise.java index 4dc06e187..dcffbf8e5 100644 --- a/src/main/java/com/volmit/iris/generator/noise/FastNoise.java +++ b/src/main/java/com/volmit/iris/generator/noise/FastNoise.java @@ -31,2339 +31,2101 @@ package com.volmit.iris.generator.noise; import com.volmit.iris.util.Vector2f; import com.volmit.iris.util.Vector3f; -public class FastNoise -{ - public enum NoiseType - { - Value, - ValueFractal, - Perlin, - PerlinFractal, - Simplex, - SimplexFractal, - Cellular, - WhiteNoise, - Cubic, - CubicFractal - } - - public enum Interp - { - Linear, - Hermite, - Quintic - } - - public enum FractalType - { - FBM, - Billow, - RigidMulti - } - - public enum CellularDistanceFunction - { - Euclidean, - Manhattan, - Natural - } - - public enum CellularReturnType - { - CellValue, - NoiseLookup, - Distance, - Distance2, - Distance2Add, - Distance2Sub, - Distance2Mul, - Distance2Div - } - - private int m_seed = 1337; - private float m_frequency = (float) 0.01; - private Interp m_interp = Interp.Quintic; - private NoiseType m_noiseType = NoiseType.Simplex; - - private int m_octaves = 3; - private float m_lacunarity = (float) 2.0; - private float m_gain = (float) 0.5; - private FractalType m_fractalType = FractalType.FBM; - - private float m_fractalBounding; - - private CellularDistanceFunction m_cellularDistanceFunction = CellularDistanceFunction.Euclidean; - private CellularReturnType m_cellularReturnType = CellularReturnType.CellValue; - private FastNoise m_cellularNoiseLookup = null; - - private float m_gradientPerturbAmp = (float) (1.0 / 0.45); - - public FastNoise() - { - this(1337); - } - - public FastNoise(int seed) - { - m_seed = seed; - CalculateFractalBounding(); - } - - // Returns a 0 float/double - public static float GetDecimalType() - { - return 0; - } - - // Returns the seed used by this object - public int GetSeed() - { - return m_seed; - } - - // Sets seed used for all noise types - // Default: 1337 - public void SetSeed(int seed) - { - m_seed = seed; - } - - // Sets frequency for all noise types - // Default: 0.01 - public void SetFrequency(float frequency) - { - m_frequency = frequency; - } - - // Changes the interpolation method used to smooth between noise values - // Possible interpolation methods (lowest to highest quality) : - // - Linear - // - Hermite - // - Quintic - // Used in Value, Gradient Noise and Position Perturbing - // Default: Quintic - public void SetInterp(Interp interp) - { - m_interp = interp; - } - - // Sets noise return type of GetNoise(...) - // Default: Simplex - public void SetNoiseType(NoiseType noiseType) - { - m_noiseType = noiseType; - } - - // Sets octave count for all fractal noise types - // Default: 3 - public void SetFractalOctaves(int octaves) - { - m_octaves = octaves; - CalculateFractalBounding(); - } - - // Sets octave lacunarity for all fractal noise types - // Default: 2.0 - public void SetFractalLacunarity(float lacunarity) - { - m_lacunarity = lacunarity; - } - - // Sets octave gain for all fractal noise types - // Default: 0.5 - public void SetFractalGain(float gain) - { - m_gain = gain; - CalculateFractalBounding(); - } - - // Sets method for combining octaves in all fractal noise types - // Default: FBM - public void SetFractalType(FractalType fractalType) - { - m_fractalType = fractalType; - } - - // Sets return type from cellular noise calculations - // Note: NoiseLookup requires another FastNoise object be set with - // SetCellularNoiseLookup() to function - // Default: CellValue - public void SetCellularDistanceFunction(CellularDistanceFunction cellularDistanceFunction) - { - m_cellularDistanceFunction = cellularDistanceFunction; - } - - // Sets distance function used in cellular noise calculations - // Default: Euclidean - public void SetCellularReturnType(CellularReturnType cellularReturnType) - { - m_cellularReturnType = cellularReturnType; - } - - // Noise used to calculate a cell value if cellular return type is NoiseLookup - // The lookup value is acquired through GetNoise() so ensure you SetNoiseType() - // on the noise lookup, value, gradient or simplex is recommended - public void SetCellularNoiseLookup(FastNoise noise) - { - m_cellularNoiseLookup = noise; - } - - // Sets the maximum perturb distance from original location when using - // GradientPerturb{Fractal}(...) - // Default: 1.0 - public void SetGradientPerturbAmp(float gradientPerturbAmp) - { - m_gradientPerturbAmp = gradientPerturbAmp / (float) 0.45; - } - - private static class Float2 - { - public final float x, y; - - public Float2(float x, float y) - { - this.x = x; - this.y = y; - } - } - - private static class Float3 - { - public final float x, y, z; - - public Float3(float x, float y, float z) - { - this.x = x; - this.y = y; - this.z = z; - } - } - - private static final Float2[] GRAD_2D = {new Float2(-1, -1), new Float2(1, -1), new Float2(-1, 1), new Float2(1, 1), new Float2(0, -1), new Float2(-1, 0), new Float2(0, 1), new Float2(1, 0), - }; - - private static final Float3[] GRAD_3D = {new Float3(1, 1, 0), new Float3(-1, 1, 0), new Float3(1, -1, 0), new Float3(-1, -1, 0), new Float3(1, 0, 1), new Float3(-1, 0, 1), new Float3(1, 0, -1), new Float3(-1, 0, -1), new Float3(0, 1, 1), new Float3(0, -1, 1), new Float3(0, 1, -1), new Float3(0, -1, -1), new Float3(1, 1, 0), new Float3(0, -1, 1), new Float3(-1, 1, 0), new Float3(0, -1, -1), - }; - - private static final Float2[] CELL_2D = {new Float2(-0.4313539279f, 0.1281943404f), new Float2(-0.1733316799f, 0.415278375f), new Float2(-0.2821957395f, -0.3505218461f), new Float2(-0.2806473808f, 0.3517627718f), new Float2(0.3125508975f, -0.3237467165f), new Float2(0.3383018443f, -0.2967353402f), new Float2(-0.4393982022f, -0.09710417025f), new Float2(-0.4460443703f, -0.05953502905f), new Float2(-0.302223039f, 0.3334085102f), new Float2(-0.212681052f, -0.3965687458f), new Float2(-0.2991156529f, 0.3361990872f), new Float2(0.2293323691f, 0.3871778202f), new Float2(0.4475439151f, -0.04695150755f), new Float2(0.1777518f, 0.41340573f), new Float2(0.1688522499f, -0.4171197882f), new Float2(-0.0976597166f, 0.4392750616f), new Float2(0.08450188373f, 0.4419948321f), new Float2(-0.4098760448f, -0.1857461384f), new Float2(0.3476585782f, -0.2857157906f), new Float2(-0.3350670039f, -0.30038326f), new Float2(0.2298190031f, -0.3868891648f), new Float2(-0.01069924099f, 0.449872789f), new Float2(-0.4460141246f, -0.05976119672f), new Float2(0.3650293864f, 0.2631606867f), new Float2(-0.349479423f, 0.2834856838f), new Float2(-0.4122720642f, 0.1803655873f), new Float2(-0.267327811f, 0.3619887311f), new Float2(0.322124041f, -0.3142230135f), new Float2(0.2880445931f, -0.3457315612f), new Float2(0.3892170926f, -0.2258540565f), new Float2(0.4492085018f, -0.02667811596f), new Float2(-0.4497724772f, 0.01430799601f), new Float2(0.1278175387f, -0.4314657307f), new Float2(-0.03572100503f, 0.4485799926f), new Float2(-0.4297407068f, -0.1335025276f), new Float2(-0.3217817723f, 0.3145735065f), new Float2(-0.3057158873f, 0.3302087162f), new Float2(-0.414503978f, 0.1751754899f), new Float2(-0.3738139881f, 0.2505256519f), new Float2(0.2236891408f, -0.3904653228f), new Float2(0.002967775577f, -0.4499902136f), new Float2(0.1747128327f, -0.4146991995f), new Float2(-0.4423772489f, -0.08247647938f), new Float2(-0.2763960987f, -0.355112935f), new Float2(-0.4019385906f, -0.2023496216f), new Float2(0.3871414161f, -0.2293938184f), new Float2(-0.430008727f, 0.1326367019f), new Float2(-0.03037574274f, -0.4489736231f), new Float2(-0.3486181573f, 0.2845441624f), new Float2(0.04553517144f, -0.4476902368f), new Float2(-0.0375802926f, 0.4484280562f), new Float2(0.3266408905f, 0.3095250049f), new Float2(0.06540017593f, -0.4452222108f), new Float2(0.03409025829f, 0.448706869f), new Float2(-0.4449193635f, 0.06742966669f), new Float2(-0.4255936157f, -0.1461850686f), new Float2(0.449917292f, 0.008627302568f), new Float2(0.05242606404f, 0.4469356864f), new Float2(-0.4495305179f, -0.02055026661f), new Float2(-0.1204775703f, 0.4335725488f), new Float2(-0.341986385f, -0.2924813028f), new Float2(0.3865320182f, 0.2304191809f), new Float2(0.04506097811f, -0.447738214f), new Float2(-0.06283465979f, 0.4455915232f), new Float2(0.3932600341f, -0.2187385324f), new Float2(0.4472261803f, -0.04988730975f), new Float2(0.3753571011f, -0.2482076684f), new Float2(-0.273662295f, 0.357223947f), new Float2(0.1700461538f, 0.4166344988f), new Float2(0.4102692229f, 0.1848760794f), new Float2(0.323227187f, -0.3130881435f), new Float2(-0.2882310238f, -0.3455761521f), new Float2(0.2050972664f, 0.4005435199f), new Float2(0.4414085979f, -0.08751256895f), new Float2(-0.1684700334f, 0.4172743077f), new Float2(-0.003978032396f, 0.4499824166f), new Float2(-0.2055133639f, 0.4003301853f), new Float2(-0.006095674897f, -0.4499587123f), new Float2(-0.1196228124f, -0.4338091548f), new Float2(0.3901528491f, -0.2242337048f), new Float2(0.01723531752f, 0.4496698165f), new Float2(-0.3015070339f, 0.3340561458f), new Float2(-0.01514262423f, -0.4497451511f), new Float2(-0.4142574071f, -0.1757577897f), new Float2(-0.1916377265f, -0.4071547394f), new Float2(0.3749248747f, 0.2488600778f), new Float2(-0.2237774255f, 0.3904147331f), new Float2(-0.4166343106f, -0.1700466149f), new Float2(0.3619171625f, 0.267424695f), new Float2(0.1891126846f, -0.4083336779f), new Float2(-0.3127425077f, 0.323561623f), new Float2(-0.3281807787f, 0.307891826f), new Float2(-0.2294806661f, 0.3870899429f), new Float2(-0.3445266136f, 0.2894847362f), new Float2(-0.4167095422f, -0.1698621719f), new Float2(-0.257890321f, -0.3687717212f), new Float2(-0.3612037825f, 0.2683874578f), new Float2(0.2267996491f, 0.3886668486f), new Float2(0.207157062f, 0.3994821043f), new Float2(0.08355176718f, -0.4421754202f), new Float2(-0.4312233307f, 0.1286329626f), new Float2(0.3257055497f, 0.3105090899f), new Float2(0.177701095f, -0.4134275279f), new Float2(-0.445182522f, 0.06566979625f), new Float2(0.3955143435f, 0.2146355146f), new Float2(-0.4264613988f, 0.1436338239f), new Float2(-0.3793799665f, -0.2420141339f), new Float2(0.04617599081f, -0.4476245948f), new Float2(-0.371405428f, -0.2540826796f), new Float2(0.2563570295f, -0.3698392535f), new Float2(0.03476646309f, 0.4486549822f), new Float2(-0.3065454405f, 0.3294387544f), new Float2(-0.2256979823f, 0.3893076172f), new Float2(0.4116448463f, -0.1817925206f), new Float2(-0.2907745828f, -0.3434387019f), new Float2(0.2842278468f, -0.348876097f), new Float2(0.3114589359f, -0.3247973695f), new Float2(0.4464155859f, -0.0566844308f), new Float2(-0.3037334033f, -0.3320331606f), new Float2(0.4079607166f, 0.1899159123f), new Float2(-0.3486948919f, -0.2844501228f), new Float2(0.3264821436f, 0.3096924441f), new Float2(0.3211142406f, 0.3152548881f), new Float2(0.01183382662f, 0.4498443737f), new Float2(0.4333844092f, 0.1211526057f), new Float2(0.3118668416f, 0.324405723f), new Float2(-0.272753471f, 0.3579183483f), new Float2(-0.422228622f, -0.1556373694f), new Float2(-0.1009700099f, -0.4385260051f), new Float2(-0.2741171231f, -0.3568750521f), new Float2(-0.1465125133f, 0.4254810025f), new Float2(0.2302279044f, -0.3866459777f), new Float2(-0.3699435608f, 0.2562064828f), new Float2(0.105700352f, -0.4374099171f), new Float2(-0.2646713633f, 0.3639355292f), new Float2(0.3521828122f, 0.2801200935f), new Float2(-0.1864187807f, -0.4095705534f), new Float2(0.1994492955f, -0.4033856449f), new Float2(0.3937065066f, 0.2179339044f), new Float2(-0.3226158377f, 0.3137180602f), new Float2(0.3796235338f, 0.2416318948f), new Float2(0.1482921929f, 0.4248640083f), new Float2(-0.407400394f, 0.1911149365f), new Float2(0.4212853031f, 0.1581729856f), new Float2(-0.2621297173f, 0.3657704353f), new Float2(-0.2536986953f, -0.3716678248f), new Float2(-0.2100236383f, 0.3979825013f), new Float2(0.3624152444f, 0.2667493029f), new Float2(-0.3645038479f, -0.2638881295f), new Float2(0.2318486784f, 0.3856762766f), new Float2(-0.3260457004f, 0.3101519002f), new Float2(-0.2130045332f, -0.3963950918f), new Float2(0.3814998766f, -0.2386584257f), new Float2(-0.342977305f, 0.2913186713f), new Float2(-0.4355865605f, 0.1129794154f), new Float2(-0.2104679605f, 0.3977477059f), new Float2(0.3348364681f, -0.3006402163f), new Float2(0.3430468811f, 0.2912367377f), new Float2(-0.2291836801f, -0.3872658529f), new Float2(0.2547707298f, -0.3709337882f), new Float2(0.4236174945f, -0.151816397f), new Float2(-0.15387742f, 0.4228731957f), new Float2(-0.4407449312f, 0.09079595574f), new Float2(-0.06805276192f, -0.444824484f), new Float2(0.4453517192f, -0.06451237284f), new Float2(0.2562464609f, -0.3699158705f), new Float2(0.3278198355f, -0.3082761026f), new Float2(-0.4122774207f, -0.1803533432f), new Float2(0.3354090914f, -0.3000012356f), new Float2(0.446632869f, -0.05494615882f), new Float2(-0.1608953296f, 0.4202531296f), new Float2(-0.09463954939f, 0.4399356268f), new Float2(-0.02637688324f, -0.4492262904f), new Float2(0.447102804f, -0.05098119915f), new Float2(-0.4365670908f, 0.1091291678f), new Float2(-0.3959858651f, 0.2137643437f), new Float2(-0.4240048207f, -0.1507312575f), new Float2(-0.3882794568f, 0.2274622243f), new Float2(-0.4283652566f, -0.1378521198f), new Float2(0.3303888091f, 0.305521251f), new Float2(0.3321434919f, -0.3036127481f), new Float2(-0.413021046f, -0.1786438231f), new Float2(0.08403060337f, -0.4420846725f), new Float2(-0.3822882919f, 0.2373934748f), new Float2(-0.3712395594f, -0.2543249683f), new Float2(0.4472363971f, -0.04979563372f), new Float2(-0.4466591209f, 0.05473234629f), new Float2(0.0486272539f, -0.4473649407f), new Float2(-0.4203101295f, -0.1607463688f), new Float2(0.2205360833f, 0.39225481f), new Float2(-0.3624900666f, 0.2666476169f), new Float2(-0.4036086833f, -0.1989975647f), new Float2(0.2152727807f, 0.3951678503f), new Float2(-0.4359392962f, -0.1116106179f), new Float2(0.4178354266f, 0.1670735057f), new Float2(0.2007630161f, 0.4027334247f), new Float2(-0.07278067175f, -0.4440754146f), new Float2(0.3644748615f, -0.2639281632f), new Float2(-0.4317451775f, 0.126870413f), new Float2(-0.297436456f, 0.3376855855f), new Float2(-0.2998672222f, 0.3355289094f), new Float2(-0.2673674124f, 0.3619594822f), new Float2(0.2808423357f, 0.3516071423f), new Float2(0.3498946567f, 0.2829730186f), new Float2(-0.2229685561f, 0.390877248f), new Float2(0.3305823267f, 0.3053118493f), new Float2(-0.2436681211f, -0.3783197679f), new Float2(-0.03402776529f, 0.4487116125f), new Float2(-0.319358823f, 0.3170330301f), new Float2(0.4454633477f, -0.06373700535f), new Float2(0.4483504221f, 0.03849544189f), new Float2(-0.4427358436f, -0.08052932871f), new Float2(0.05452298565f, 0.4466847255f), new Float2(-0.2812560807f, 0.3512762688f), new Float2(0.1266696921f, 0.4318041097f), new Float2(-0.3735981243f, 0.2508474468f), new Float2(0.2959708351f, -0.3389708908f), new Float2(-0.3714377181f, 0.254035473f), new Float2(-0.404467102f, -0.1972469604f), new Float2(0.1636165687f, -0.419201167f), new Float2(0.3289185495f, -0.3071035458f), new Float2(-0.2494824991f, -0.3745109914f), new Float2(0.03283133272f, 0.4488007393f), new Float2(-0.166306057f, -0.4181414777f), new Float2(-0.106833179f, 0.4371346153f), new Float2(0.06440260376f, -0.4453676062f), new Float2(-0.4483230967f, 0.03881238203f), new Float2(-0.421377757f, -0.1579265206f), new Float2(0.05097920662f, -0.4471030312f), new Float2(0.2050584153f, -0.4005634111f), new Float2(0.4178098529f, -0.167137449f), new Float2(-0.3565189504f, -0.2745801121f), new Float2(0.4478398129f, 0.04403977727f), new Float2(-0.3399999602f, -0.2947881053f), new Float2(0.3767121994f, 0.2461461331f), new Float2(-0.3138934434f, 0.3224451987f), new Float2(-0.1462001792f, -0.4255884251f), new Float2(0.3970290489f, -0.2118205239f), new Float2(0.4459149305f, -0.06049689889f), new Float2(-0.4104889426f, -0.1843877112f), new Float2(0.1475103971f, -0.4251360756f), new Float2(0.09258030352f, 0.4403735771f), new Float2(-0.1589664637f, -0.4209865359f), new Float2(0.2482445008f, 0.3753327428f), new Float2(0.4383624232f, -0.1016778537f), new Float2(0.06242802956f, 0.4456486745f), new Float2(0.2846591015f, -0.3485243118f), new Float2(-0.344202744f, -0.2898697484f), new Float2(0.1198188883f, -0.4337550392f), new Float2(-0.243590703f, 0.3783696201f), new Float2(0.2958191174f, -0.3391033025f), new Float2(-0.1164007991f, 0.4346847754f), new Float2(0.1274037151f, -0.4315881062f), new Float2(0.368047306f, 0.2589231171f), new Float2(0.2451436949f, 0.3773652989f), new Float2(-0.4314509715f, 0.12786735f), - }; - - private static final Float3[] CELL_3D = {new Float3(0.1453787434f, -0.4149781685f, -0.0956981749f), new Float3(-0.01242829687f, -0.1457918398f, -0.4255470325f), new Float3(0.2877979582f, -0.02606483451f, -0.3449535616f), new Float3(-0.07732986802f, 0.2377094325f, 0.3741848704f), new Float3(0.1107205875f, -0.3552302079f, -0.2530858567f), new Float3(0.2755209141f, 0.2640521179f, -0.238463215f), new Float3(0.294168941f, 0.1526064594f, 0.3044271714f), new Float3(0.4000921098f, -0.2034056362f, 0.03244149937f), new Float3(-0.1697304074f, 0.3970864695f, -0.1265461359f), new Float3(-0.1483224484f, -0.3859694688f, 0.1775613147f), new Float3(0.2623596946f, -0.2354852944f, 0.2796677792f), new Float3(-0.2709003183f, 0.3505271138f, -0.07901746678f), new Float3(-0.03516550699f, 0.3885234328f, 0.2243054374f), new Float3(-0.1267712655f, 0.1920044036f, 0.3867342179f), new Float3(0.02952021915f, 0.4409685861f, 0.08470692262f), new Float3(-0.2806854217f, -0.266996757f, 0.2289725438f), new Float3(-0.171159547f, 0.2141185563f, 0.3568720405f), new Float3(0.2113227183f, 0.3902405947f, -0.07453178509f), new Float3(-0.1024352839f, 0.2128044156f, -0.3830421561f), new Float3(-0.3304249877f, -0.1566986703f, 0.2622305365f), new Float3(0.2091111325f, 0.3133278055f, -0.2461670583f), new Float3(0.344678154f, -0.1944240454f, -0.2142341261f), new Float3(0.1984478035f, -0.3214342325f, -0.2445373252f), new Float3(-0.2929008603f, 0.2262915116f, 0.2559320961f), new Float3(-0.1617332831f, 0.006314769776f, -0.4198838754f), new Float3(-0.3582060271f, -0.148303178f, -0.2284613961f), new Float3(-0.1852067326f, -0.3454119342f, -0.2211087107f), new Float3(0.3046301062f, 0.1026310383f, 0.314908508f), new Float3(-0.03816768434f, -0.2551766358f, -0.3686842991f), new Float3(-0.4084952196f, 0.1805950793f, 0.05492788837f), new Float3(-0.02687443361f, -0.2749741471f, 0.3551999201f), new Float3(-0.03801098351f, 0.3277859044f, 0.3059600725f), new Float3(0.2371120802f, 0.2900386767f, -0.2493099024f), new Float3(0.4447660503f, 0.03946930643f, 0.05590469027f), new Float3(0.01985147278f, -0.01503183293f, -0.4493105419f), new Float3(0.4274339143f, 0.03345994256f, -0.1366772882f), new Float3(-0.2072988631f, 0.2871414597f, -0.2776273824f), new Float3(-0.3791240978f, 0.1281177671f, 0.2057929936f), new Float3(-0.2098721267f, -0.1007087278f, -0.3851122467f), new Float3(0.01582798878f, 0.4263894424f, 0.1429738373f), new Float3(-0.1888129464f, -0.3160996813f, -0.2587096108f), new Float3(0.1612988974f, -0.1974805082f, -0.3707885038f), new Float3(-0.08974491322f, 0.229148752f, -0.3767448739f), new Float3(0.07041229526f, 0.4150230285f, -0.1590534329f), new Float3(-0.1082925611f, -0.1586061639f, 0.4069604477f), new Float3(0.2474100658f, -0.3309414609f, 0.1782302128f), new Float3(-0.1068836661f, -0.2701644537f, -0.3436379634f), new Float3(0.2396452163f, 0.06803600538f, -0.3747549496f), new Float3(-0.3063886072f, 0.2597428179f, 0.2028785103f), new Float3(0.1593342891f, -0.3114350249f, -0.2830561951f), new Float3(0.2709690528f, 0.1412648683f, -0.3303331794f), new Float3(-0.1519780427f, 0.3623355133f, 0.2193527988f), new Float3(0.1699773681f, 0.3456012883f, 0.2327390037f), new Float3(-0.1986155616f, 0.3836276443f, -0.1260225743f), new Float3(-0.1887482106f, -0.2050154888f, -0.353330953f), new Float3(0.2659103394f, 0.3015631259f, -0.2021172246f), new Float3(-0.08838976154f, -0.4288819642f, -0.1036702021f), new Float3(-0.04201869311f, 0.3099592485f, 0.3235115047f), new Float3(-0.3230334656f, 0.201549922f, -0.2398478873f), new Float3(0.2612720941f, 0.2759854499f, -0.2409749453f), new Float3(0.385713046f, 0.2193460345f, 0.07491837764f), new Float3(0.07654967953f, 0.3721732183f, 0.241095919f), new Float3(0.4317038818f, -0.02577753072f, 0.1243675091f), new Float3(-0.2890436293f, -0.3418179959f, -0.04598084447f), new Float3(-0.2201947582f, 0.383023377f, -0.08548310451f), new Float3(0.4161322773f, -0.1669634289f, -0.03817251927f), new Float3(0.2204718095f, 0.02654238946f, -0.391391981f), new Float3(-0.1040307469f, 0.3890079625f, -0.2008741118f), new Float3(-0.1432122615f, 0.371614387f, -0.2095065525f), new Float3(0.3978380468f, -0.06206669342f, 0.2009293758f), new Float3(-0.2599274663f, 0.2616724959f, -0.2578084893f), new Float3(0.4032618332f, -0.1124593585f, 0.1650235939f), new Float3(-0.08953470255f, -0.3048244735f, 0.3186935478f), new Float3(0.118937202f, -0.2875221847f, 0.325092195f), new Float3(0.02167047076f, -0.03284630549f, -0.4482761547f), new Float3(-0.3411343612f, 0.2500031105f, 0.1537068389f), new Float3(0.3162964612f, 0.3082064153f, -0.08640228117f), new Float3(0.2355138889f, -0.3439334267f, -0.1695376245f), new Float3(-0.02874541518f, -0.3955933019f, 0.2125550295f), new Float3(-0.2461455173f, 0.02020282325f, -0.3761704803f), new Float3(0.04208029445f, -0.4470439576f, 0.02968078139f), new Float3(0.2727458746f, 0.2288471896f, -0.2752065618f), new Float3(-0.1347522818f, -0.02720848277f, -0.4284874806f), new Float3(0.3829624424f, 0.1231931484f, -0.2016512234f), new Float3(-0.3547613644f, 0.1271702173f, 0.2459107769f), new Float3(0.2305790207f, 0.3063895591f, 0.2354968222f), new Float3(-0.08323845599f, -0.1922245118f, 0.3982726409f), new Float3(0.2993663085f, -0.2619918095f, -0.2103333191f), new Float3(-0.2154865723f, 0.2706747713f, 0.287751117f), new Float3(0.01683355354f, -0.2680655787f, -0.3610505186f), new Float3(0.05240429123f, 0.4335128183f, -0.1087217856f), new Float3(0.00940104872f, -0.4472890582f, 0.04841609928f), new Float3(0.3465688735f, 0.01141914583f, -0.2868093776f), new Float3(-0.3706867948f, -0.2551104378f, 0.003156692623f), new Float3(0.2741169781f, 0.2139972417f, -0.2855959784f), new Float3(0.06413433865f, 0.1708718512f, 0.4113266307f), new Float3(-0.388187972f, -0.03973280434f, -0.2241236325f), new Float3(0.06419469312f, -0.2803682491f, 0.3460819069f), new Float3(-0.1986120739f, -0.3391173584f, 0.2192091725f), new Float3(-0.203203009f, -0.3871641506f, 0.1063600375f), new Float3(-0.1389736354f, -0.2775901578f, -0.3257760473f), new Float3(-0.06555641638f, 0.342253257f, -0.2847192729f), new Float3(-0.2529246486f, -0.2904227915f, 0.2327739768f), new Float3(0.1444476522f, 0.1069184044f, 0.4125570634f), new Float3(-0.3643780054f, -0.2447099973f, -0.09922543227f), new Float3(0.4286142488f, -0.1358496089f, -0.01829506817f), new Float3(0.165872923f, -0.3136808464f, -0.2767498872f), new Float3(0.2219610524f, -0.3658139958f, 0.1393320198f), new Float3(0.04322940318f, -0.3832730794f, 0.2318037215f), new Float3(-0.08481269795f, -0.4404869674f, -0.03574965489f), new Float3(0.1822082075f, -0.3953259299f, 0.1140946023f), new Float3(-0.3269323334f, 0.3036542563f, 0.05838957105f), new Float3(-0.4080485344f, 0.04227858267f, -0.184956522f), new Float3(0.2676025294f, -0.01299671652f, 0.36155217f), new Float3(0.3024892441f, -0.1009990293f, -0.3174892964f), new Float3(0.1448494052f, 0.425921681f, -0.0104580805f), new Float3(0.4198402157f, 0.08062320474f, 0.1404780841f), new Float3(-0.3008872161f, -0.333040905f, -0.03241355801f), new Float3(0.3639310428f, -0.1291284382f, -0.2310412139f), new Float3(0.3295806598f, 0.0184175994f, -0.3058388149f), new Float3(0.2776259487f, -0.2974929052f, -0.1921504723f), new Float3(0.4149000507f, -0.144793182f, -0.09691688386f), new Float3(0.145016715f, -0.0398992945f, 0.4241205002f), new Float3(0.09299023471f, -0.299732164f, -0.3225111565f), new Float3(0.1028907093f, -0.361266869f, 0.247789732f), new Float3(0.2683057049f, -0.07076041213f, -0.3542668666f), new Float3(-0.4227307273f, -0.07933161816f, -0.1323073187f), new Float3(-0.1781224702f, 0.1806857196f, -0.3716517945f), new Float3(0.4390788626f, -0.02841848598f, -0.09435116353f), new Float3(0.2972583585f, 0.2382799621f, -0.2394997452f), new Float3(-0.1707002821f, 0.2215845691f, 0.3525077196f), new Float3(0.3806686614f, 0.1471852559f, -0.1895464869f), new Float3(-0.1751445661f, -0.274887877f, 0.3102596268f), new Float3(-0.2227237566f, -0.2316778837f, 0.3149912482f), new Float3(0.1369633021f, 0.1341343041f, -0.4071228836f), new Float3(-0.3529503428f, -0.2472893463f, -0.129514612f), new Float3(-0.2590744185f, -0.2985577559f, -0.2150435121f), new Float3(-0.3784019401f, 0.2199816631f, -0.1044989934f), new Float3(-0.05635805671f, 0.1485737441f, 0.4210102279f), new Float3(0.3251428613f, 0.09666046873f, -0.2957006485f), new Float3(-0.4190995804f, 0.1406751354f, -0.08405978803f), new Float3(-0.3253150961f, -0.3080335042f, -0.04225456877f), new Float3(0.2857945863f, -0.05796152095f, 0.3427271751f), new Float3(-0.2733604046f, 0.1973770973f, -0.2980207554f), new Float3(0.219003657f, 0.2410037886f, -0.3105713639f), new Float3(0.3182767252f, -0.271342949f, 0.1660509868f), new Float3(-0.03222023115f, -0.3331161506f, -0.300824678f), new Float3(-0.3087780231f, 0.1992794134f, -0.2596995338f), new Float3(-0.06487611647f, -0.4311322747f, 0.1114273361f), new Float3(0.3921171432f, -0.06294284106f, -0.2116183942f), new Float3(-0.1606404506f, -0.358928121f, -0.2187812825f), new Float3(-0.03767771199f, -0.2290351443f, 0.3855169162f), new Float3(0.1394866832f, -0.3602213994f, 0.2308332918f), new Float3(-0.4345093872f, 0.005751117145f, 0.1169124335f), new Float3(-0.1044637494f, 0.4168128432f, -0.1336202785f), new Float3(0.2658727501f, 0.2551943237f, 0.2582393035f), new Float3(0.2051461999f, 0.1975390727f, 0.3484154868f), new Float3(-0.266085566f, 0.23483312f, 0.2766800993f), new Float3(0.07849405464f, -0.3300346342f, -0.2956616708f), new Float3(-0.2160686338f, 0.05376451292f, -0.3910546287f), new Float3(-0.185779186f, 0.2148499206f, 0.3490352499f), new Float3(0.02492421743f, -0.3229954284f, -0.3123343347f), new Float3(-0.120167831f, 0.4017266681f, 0.1633259825f), new Float3(-0.02160084693f, -0.06885389554f, 0.4441762538f), new Float3(0.2597670064f, 0.3096300784f, 0.1978643903f), new Float3(-0.1611553854f, -0.09823036005f, 0.4085091653f), new Float3(-0.3278896792f, 0.1461670309f, 0.2713366126f), new Float3(0.2822734956f, 0.03754421121f, -0.3484423997f), new Float3(0.03169341113f, 0.347405252f, -0.2842624114f), new Float3(0.2202613604f, -0.3460788041f, -0.1849713341f), new Float3(0.2933396046f, 0.3031973659f, 0.1565989581f), new Float3(-0.3194922995f, 0.2453752201f, -0.200538455f), new Float3(-0.3441586045f, -0.1698856132f, -0.2349334659f), new Float3(0.2703645948f, -0.3574277231f, 0.04060059933f), new Float3(0.2298568861f, 0.3744156221f, 0.0973588921f), new Float3(0.09326603877f, -0.3170108894f, 0.3054595587f), new Float3(-0.1116165319f, -0.2985018719f, 0.3177080142f), new Float3(0.2172907365f, -0.3460005203f, -0.1885958001f), new Float3(0.1991339479f, 0.3820341668f, -0.1299829458f), new Float3(-0.0541918155f, -0.2103145071f, 0.39412061f), new Float3(0.08871336998f, 0.2012117383f, 0.3926114802f), new Float3(0.2787673278f, 0.3505404674f, 0.04370535101f), new Float3(-0.322166438f, 0.3067213525f, 0.06804996813f), new Float3(-0.4277366384f, 0.132066775f, 0.04582286686f), new Float3(0.240131882f, -0.1612516055f, 0.344723946f), new Float3(0.1448607981f, -0.2387819045f, 0.3528435224f), new Float3(-0.3837065682f, -0.2206398454f, 0.08116235683f), new Float3(-0.4382627882f, -0.09082753406f, -0.04664855374f), new Float3(-0.37728353f, 0.05445141085f, 0.2391488697f), new Float3(0.1259579313f, 0.348394558f, 0.2554522098f), new Float3(-0.1406285511f, -0.270877371f, -0.3306796947f), new Float3(-0.1580694418f, 0.4162931958f, -0.06491553533f), new Float3(0.2477612106f, -0.2927867412f, -0.2353514536f), new Float3(0.2916132853f, 0.3312535401f, 0.08793624968f), new Float3(0.07365265219f, -0.1666159848f, 0.411478311f), new Float3(-0.26126526f, -0.2422237692f, 0.2748965434f), new Float3(-0.3721862032f, 0.252790166f, 0.008634938242f), new Float3(-0.3691191571f, -0.255281188f, 0.03290232422f), new Float3(0.2278441737f, -0.3358364886f, 0.1944244981f), new Float3(0.363398169f, -0.2310190248f, 0.1306597909f), new Float3(-0.304231482f, -0.2698452035f, 0.1926830856f), new Float3(-0.3199312232f, 0.316332536f, -0.008816977938f), new Float3(0.2874852279f, 0.1642275508f, -0.304764754f), new Float3(-0.1451096801f, 0.3277541114f, -0.2720669462f), new Float3(0.3220090754f, 0.0511344108f, 0.3101538769f), new Float3(-0.1247400865f, -0.04333605335f, -0.4301882115f), new Float3(-0.2829555867f, -0.3056190617f, -0.1703910946f), new Float3(0.1069384374f, 0.3491024667f, -0.2630430352f), new Float3(-0.1420661144f, -0.3055376754f, -0.2982682484f), new Float3(-0.250548338f, 0.3156466809f, -0.2002316239f), new Float3(0.3265787872f, 0.1871229129f, 0.2466400438f), new Float3(0.07646097258f, -0.3026690852f, 0.324106687f), new Float3(0.3451771584f, 0.2757120714f, -0.0856480183f), new Float3(0.298137964f, 0.2852657134f, 0.179547284f), new Float3(0.2812250376f, 0.3466716415f, 0.05684409612f), new Float3(0.4390345476f, -0.09790429955f, -0.01278335452f), new Float3(0.2148373234f, 0.1850172527f, 0.3494474791f), new Float3(0.2595421179f, -0.07946825393f, 0.3589187731f), new Float3(0.3182823114f, -0.307355516f, -0.08203022006f), new Float3(-0.4089859285f, -0.04647718411f, 0.1818526372f), new Float3(-0.2826749061f, 0.07417482322f, 0.3421885344f), new Float3(0.3483864637f, 0.225442246f, -0.1740766085f), new Float3(-0.3226415069f, -0.1420585388f, -0.2796816575f), new Float3(0.4330734858f, -0.118868561f, -0.02859407492f), new Float3(-0.08717822568f, -0.3909896417f, -0.2050050172f), new Float3(-0.2149678299f, 0.3939973956f, -0.03247898316f), new Float3(-0.2687330705f, 0.322686276f, -0.1617284888f), new Float3(0.2105665099f, -0.1961317136f, -0.3459683451f), new Float3(0.4361845915f, -0.1105517485f, 0.004616608544f), new Float3(0.05333333359f, -0.313639498f, -0.3182543336f), new Float3(-0.05986216652f, 0.1361029153f, -0.4247264031f), new Float3(0.3664988455f, 0.2550543014f, -0.05590974511f), new Float3(-0.2341015558f, -0.182405731f, 0.3382670703f), new Float3(-0.04730947785f, -0.4222150243f, -0.1483114513f), new Float3(-0.2391566239f, -0.2577696514f, -0.2808182972f), new Float3(-0.1242081035f, 0.4256953395f, -0.07652336246f), new Float3(0.2614832715f, -0.3650179274f, 0.02980623099f), new Float3(-0.2728794681f, -0.3499628774f, 0.07458404908f), new Float3(0.007892900508f, -0.1672771315f, 0.4176793787f), new Float3(-0.01730330376f, 0.2978486637f, -0.3368779738f), new Float3(0.2054835762f, -0.3252600376f, -0.2334146693f), new Float3(-0.3231994983f, 0.1564282844f, -0.2712420987f), new Float3(-0.2669545963f, 0.2599343665f, -0.2523278991f), new Float3(-0.05554372779f, 0.3170813944f, -0.3144428146f), new Float3(-0.2083935713f, -0.310922837f, -0.2497981362f), new Float3(0.06989323478f, -0.3156141536f, 0.3130537363f), new Float3(0.3847566193f, -0.1605309138f, -0.1693876312f), new Float3(-0.3026215288f, -0.3001537679f, -0.1443188342f), new Float3(0.3450735512f, 0.08611519592f, 0.2756962409f), new Float3(0.1814473292f, -0.2788782453f, -0.3029914042f), new Float3(-0.03855010448f, 0.09795110726f, 0.4375151083f), new Float3(0.3533670318f, 0.2665752752f, 0.08105160988f), new Float3(-0.007945601311f, 0.140359426f, -0.4274764309f), new Float3(0.4063099273f, -0.1491768253f, -0.1231199324f), new Float3(-0.2016773589f, 0.008816271194f, -0.4021797064f), new Float3(-0.07527055435f, -0.425643481f, -0.1251477955f), - }; - - private static int FastFloor(float f) - { - return (f >= 0 ? (int) f : (int) f - 1); - } - - private static int FastRound(float f) - { - return (f >= 0) ? (int) (f + (float) 0.5) : (int) (f - (float) 0.5); - } - - private static float Lerp(float a, float b, float t) - { - return a + t * (b - a); - } - - private static float InterpHermiteFunc(float t) - { - return t * t * (3 - 2 * t); - } - - private static float InterpQuinticFunc(float t) - { - return t * t * t * (t * (t * 6 - 15) + 10); - } - - private static float CubicLerp(float a, float b, float c, float d, float t) - { - float p = (d - c) - (a - b); - return t * t * t * p + t * t * ((a - b) - p) + t * (c - a) + b; - } - - private void CalculateFractalBounding() - { - float amp = m_gain; - float ampFractal = 1; - for(int i = 1; i < m_octaves; i++) - { - ampFractal += amp; - amp *= m_gain; - } - m_fractalBounding = 1 / ampFractal; - } - - // Hashing - private final static int X_PRIME = 1619; - private final static int Y_PRIME = 31337; - private final static int Z_PRIME = 6971; - private final static int W_PRIME = 1013; - - private static int Hash2D(int seed, int x, int y) - { - int hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - return hash; - } - - private static int Hash3D(int seed, int x, int y, int z) - { - int hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - hash ^= Z_PRIME * z; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - return hash; - } - - public static int Hash4D(int seed, int x, int y, int z, int w) - { - int hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - hash ^= Z_PRIME * z; - hash ^= W_PRIME * w; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - return hash; - } - - private static float ValCoord2D(int seed, int x, int y) - { - int n = seed; - n ^= X_PRIME * x; - n ^= Y_PRIME * y; - - return (n * n * n * 60493) / (float) 2147483648.0; - } - - private static float ValCoord3D(int seed, int x, int y, int z) - { - int n = seed; - n ^= X_PRIME * x; - n ^= Y_PRIME * y; - n ^= Z_PRIME * z; - - return (n * n * n * 60493) / (float) 2147483648.0; - } - - private static float ValCoord4D(int seed, int x, int y, int z, int w) - { - int n = seed; - n ^= X_PRIME * x; - n ^= Y_PRIME * y; - n ^= Z_PRIME * z; - n ^= W_PRIME * w; - - return (n * n * n * 60493) / (float) 2147483648.0; - } - - private static float GradCoord2D(int seed, int x, int y, float xd, float yd) - { - int hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - Float2 g = GRAD_2D[hash & 7]; - - return xd * g.x + yd * g.y; - } - - private static float GradCoord3D(int seed, int x, int y, int z, float xd, float yd, float zd) - { - int hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - hash ^= Z_PRIME * z; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - Float3 g = GRAD_3D[hash & 15]; - - return xd * g.x + yd * g.y + zd * g.z; - } - - private static float GradCoord4D(int seed, int x, int y, int z, int w, float xd, float yd, float zd, float wd) - { - int hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - hash ^= Z_PRIME * z; - hash ^= W_PRIME * w; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - hash &= 31; - float a = yd, b = zd, c = wd; // X,Y,Z - switch(hash >> 3) - { // OR, DEPENDING ON HIGH ORDER 2 BITS: - case 1: - a = wd; - b = xd; - c = yd; - break; // W,X,Y - case 2: - a = zd; - b = wd; - c = xd; - break; // Z,W,X - case 3: - a = yd; - b = zd; - c = wd; - break; // Y,Z,W - } - return ((hash & 4) == 0 ? -a : a) + ((hash & 2) == 0 ? -b : b) + ((hash & 1) == 0 ? -c : c); - } - - public float GetNoise(float x, float y, float z) - { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - switch(m_noiseType) - { - case Value: - return SingleValue(m_seed, x, y, z); - case ValueFractal: - switch(m_fractalType) - { - case FBM: - return SingleValueFractalFBM(x, y, z); - case Billow: - return SingleValueFractalBillow(x, y, z); - case RigidMulti: - return SingleValueFractalRigidMulti(x, y, z); - default: - return 0; - } - case Perlin: - return SinglePerlin(m_seed, x, y, z); - case PerlinFractal: - switch(m_fractalType) - { - case FBM: - return SinglePerlinFractalFBM(x, y, z); - case Billow: - return SinglePerlinFractalBillow(x, y, z); - case RigidMulti: - return SinglePerlinFractalRigidMulti(x, y, z); - default: - return 0; - } - case Simplex: - return SingleSimplex(m_seed, x, y, z); - case SimplexFractal: - switch(m_fractalType) - { - case FBM: - return SingleSimplexFractalFBM(x, y, z); - case Billow: - return SingleSimplexFractalBillow(x, y, z); - case RigidMulti: - return SingleSimplexFractalRigidMulti(x, y, z); - default: - return 0; - } - case Cellular: - switch(m_cellularReturnType) - { - case CellValue: - case NoiseLookup: - case Distance: - return SingleCellular(x, y, z); - default: - return SingleCellular2Edge(x, y, z); - } - case WhiteNoise: - return GetWhiteNoise(x, y, z); - case Cubic: - return SingleCubic(m_seed, x, y, z); - case CubicFractal: - switch(m_fractalType) - { - case FBM: - return SingleCubicFractalFBM(x, y, z); - case Billow: - return SingleCubicFractalBillow(x, y, z); - case RigidMulti: - return SingleCubicFractalRigidMulti(x, y, z); - default: - return 0; - } - default: - return 0; - } - } - - public float GetNoise(float x, float y) - { - x *= m_frequency; - y *= m_frequency; - - switch(m_noiseType) - { - case Value: - return SingleValue(m_seed, x, y); - case ValueFractal: - switch(m_fractalType) - { - case FBM: - return SingleValueFractalFBM(x, y); - case Billow: - return SingleValueFractalBillow(x, y); - case RigidMulti: - return SingleValueFractalRigidMulti(x, y); - default: - return 0; - } - case Perlin: - return SinglePerlin(m_seed, x, y); - case PerlinFractal: - switch(m_fractalType) - { - case FBM: - return SinglePerlinFractalFBM(x, y); - case Billow: - return SinglePerlinFractalBillow(x, y); - case RigidMulti: - return SinglePerlinFractalRigidMulti(x, y); - default: - return 0; - } - case Simplex: - return SingleSimplex(m_seed, x, y); - case SimplexFractal: - switch(m_fractalType) - { - case FBM: - return SingleSimplexFractalFBM(x, y); - case Billow: - return SingleSimplexFractalBillow(x, y); - case RigidMulti: - return SingleSimplexFractalRigidMulti(x, y); - default: - return 0; - } - case Cellular: - switch(m_cellularReturnType) - { - case CellValue: - case NoiseLookup: - case Distance: - return SingleCellular(x, y); - default: - return SingleCellular2Edge(x, y); - } - case WhiteNoise: - return GetWhiteNoise(x, y); - case Cubic: - return SingleCubic(m_seed, x, y); - case CubicFractal: - switch(m_fractalType) - { - case FBM: - return SingleCubicFractalFBM(x, y); - case Billow: - return SingleCubicFractalBillow(x, y); - case RigidMulti: - return SingleCubicFractalRigidMulti(x, y); - default: - return 0; - } - default: - return 0; - } - } - - // White Noise - - private int FloatCast2Int(float f) - { - int i = Float.floatToRawIntBits(f); - - return i ^ (i >> 16); - } - - public float GetWhiteNoise(float x, float y, float z, float w) - { - int xi = FloatCast2Int(x); - int yi = FloatCast2Int(y); - int zi = FloatCast2Int(z); - int wi = FloatCast2Int(w); - - return ValCoord4D(m_seed, xi, yi, zi, wi); - } - - public float GetWhiteNoise(double x, double y, double z) - { - int xi = FloatCast2Int((float) x); - int yi = FloatCast2Int((float) y); - int zi = FloatCast2Int((float) z); - - return ValCoord3D(m_seed, xi, yi, zi); - } - - public float GetWhiteNoise(double x, double y) - { - int xi = FloatCast2Int((float) x); - int yi = FloatCast2Int((float) y); - - return ValCoord2D(m_seed, xi, yi); - } - - public float GetWhiteNoiseInt(int x, int y, int z, int w) - { - return ValCoord4D(m_seed, x, y, z, w); - } - - public float GetWhiteNoiseInt(int x, int y, int z) - { - return ValCoord3D(m_seed, x, y, z); - } - - public float GetWhiteNoiseInt(int x, int y) - { - return ValCoord2D(m_seed, x, y); - } - - // Value Noise - public float GetValueFractal(float x, float y, float z) - { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - switch(m_fractalType) - { - case FBM: - return SingleValueFractalFBM(x, y, z); - case Billow: - return SingleValueFractalBillow(x, y, z); - case RigidMulti: - return SingleValueFractalRigidMulti(x, y, z); - default: - return 0; - } - } - - private float SingleValueFractalFBM(float x, float y, float z) - { - int seed = m_seed; - float sum = SingleValue(seed, x, y, z); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += SingleValue(++seed, x, y, z) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleValueFractalBillow(float x, float y, float z) - { - int seed = m_seed; - float sum = Math.abs(SingleValue(seed, x, y, z)) * 2 - 1; - float amp = 1; - - for(int i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SingleValue(++seed, x, y, z)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleValueFractalRigidMulti(float x, float y, float z) - { - int seed = m_seed; - float sum = 1 - Math.abs(SingleValue(seed, x, y, z)); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleValue(++seed, x, y, z))) * amp; - } - - return sum; - } - - public float GetValue(float x, float y, float z) - { - return SingleValue(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); - } - - private float SingleValue(int seed, float x, float y, float z) - { - int x0 = FastFloor(x); - int y0 = FastFloor(y); - int z0 = FastFloor(z); - int x1 = x0 + 1; - int y1 = y0 + 1; - int z1 = z0 + 1; - - float xs, ys, zs; - switch(m_interp) - { - default: - case Linear: - xs = x - x0; - ys = y - y0; - zs = z - z0; - break; - case Hermite: - xs = InterpHermiteFunc(x - x0); - ys = InterpHermiteFunc(y - y0); - zs = InterpHermiteFunc(z - z0); - break; - case Quintic: - xs = InterpQuinticFunc(x - x0); - ys = InterpQuinticFunc(y - y0); - zs = InterpQuinticFunc(z - z0); - break; - } - - float xf00 = Lerp(ValCoord3D(seed, x0, y0, z0), ValCoord3D(seed, x1, y0, z0), xs); - float xf10 = Lerp(ValCoord3D(seed, x0, y1, z0), ValCoord3D(seed, x1, y1, z0), xs); - float xf01 = Lerp(ValCoord3D(seed, x0, y0, z1), ValCoord3D(seed, x1, y0, z1), xs); - float xf11 = Lerp(ValCoord3D(seed, x0, y1, z1), ValCoord3D(seed, x1, y1, z1), xs); - - float yf0 = Lerp(xf00, xf10, ys); - float yf1 = Lerp(xf01, xf11, ys); - - return Lerp(yf0, yf1, zs); - } - - public float GetValueFractal(float x, float y) - { - x *= m_frequency; - y *= m_frequency; - - switch(m_fractalType) - { - case FBM: - return SingleValueFractalFBM(x, y); - case Billow: - return SingleValueFractalBillow(x, y); - case RigidMulti: - return SingleValueFractalRigidMulti(x, y); - default: - return 0; - } - } - - private float SingleValueFractalFBM(float x, float y) - { - int seed = m_seed; - float sum = SingleValue(seed, x, y); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += SingleValue(++seed, x, y) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleValueFractalBillow(float x, float y) - { - int seed = m_seed; - float sum = Math.abs(SingleValue(seed, x, y)) * 2 - 1; - float amp = 1; - - for(int i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - amp *= m_gain; - sum += (Math.abs(SingleValue(++seed, x, y)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleValueFractalRigidMulti(float x, float y) - { - int seed = m_seed; - float sum = 1 - Math.abs(SingleValue(seed, x, y)); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleValue(++seed, x, y))) * amp; - } - - return sum; - } - - public float GetValue(float x, float y) - { - return SingleValue(m_seed, x * m_frequency, y * m_frequency); - } - - private float SingleValue(int seed, float x, float y) - { - int x0 = FastFloor(x); - int y0 = FastFloor(y); - int x1 = x0 + 1; - int y1 = y0 + 1; - - float xs, ys; - switch(m_interp) - { - default: - case Linear: - xs = x - x0; - ys = y - y0; - break; - case Hermite: - xs = InterpHermiteFunc(x - x0); - ys = InterpHermiteFunc(y - y0); - break; - case Quintic: - xs = InterpQuinticFunc(x - x0); - ys = InterpQuinticFunc(y - y0); - break; - } - - float xf0 = Lerp(ValCoord2D(seed, x0, y0), ValCoord2D(seed, x1, y0), xs); - float xf1 = Lerp(ValCoord2D(seed, x0, y1), ValCoord2D(seed, x1, y1), xs); - - return Lerp(xf0, xf1, ys); - } - - // Gradient Noise - public float GetPerlinFractal(float x, float y, float z) - { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - switch(m_fractalType) - { - case FBM: - return SinglePerlinFractalFBM(x, y, z); - case Billow: - return SinglePerlinFractalBillow(x, y, z); - case RigidMulti: - return SinglePerlinFractalRigidMulti(x, y, z); - default: - return 0; - } - } - - private float SinglePerlinFractalFBM(float x, float y, float z) - { - int seed = m_seed; - float sum = SinglePerlin(seed, x, y, z); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += SinglePerlin(++seed, x, y, z) * amp; - } - - return sum * m_fractalBounding; - } - - private float SinglePerlinFractalBillow(float x, float y, float z) - { - int seed = m_seed; - float sum = Math.abs(SinglePerlin(seed, x, y, z)) * 2 - 1; - float amp = 1; - - for(int i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SinglePerlin(++seed, x, y, z)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private float SinglePerlinFractalRigidMulti(float x, float y, float z) - { - int seed = m_seed; - float sum = 1 - Math.abs(SinglePerlin(seed, x, y, z)); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SinglePerlin(++seed, x, y, z))) * amp; - } - - return sum; - } - - public float GetPerlin(float x, float y, float z) - { - return SinglePerlin(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); - } - - private float SinglePerlin(int seed, float x, float y, float z) - { - int x0 = FastFloor(x); - int y0 = FastFloor(y); - int z0 = FastFloor(z); - int x1 = x0 + 1; - int y1 = y0 + 1; - int z1 = z0 + 1; - - float xs, ys, zs; - switch(m_interp) - { - default: - case Linear: - xs = x - x0; - ys = y - y0; - zs = z - z0; - break; - case Hermite: - xs = InterpHermiteFunc(x - x0); - ys = InterpHermiteFunc(y - y0); - zs = InterpHermiteFunc(z - z0); - break; - case Quintic: - xs = InterpQuinticFunc(x - x0); - ys = InterpQuinticFunc(y - y0); - zs = InterpQuinticFunc(z - z0); - break; - } - - float xd0 = x - x0; - float yd0 = y - y0; - float zd0 = z - z0; - float xd1 = xd0 - 1; - float yd1 = yd0 - 1; - float zd1 = zd0 - 1; - - float xf00 = Lerp(GradCoord3D(seed, x0, y0, z0, xd0, yd0, zd0), GradCoord3D(seed, x1, y0, z0, xd1, yd0, zd0), xs); - float xf10 = Lerp(GradCoord3D(seed, x0, y1, z0, xd0, yd1, zd0), GradCoord3D(seed, x1, y1, z0, xd1, yd1, zd0), xs); - float xf01 = Lerp(GradCoord3D(seed, x0, y0, z1, xd0, yd0, zd1), GradCoord3D(seed, x1, y0, z1, xd1, yd0, zd1), xs); - float xf11 = Lerp(GradCoord3D(seed, x0, y1, z1, xd0, yd1, zd1), GradCoord3D(seed, x1, y1, z1, xd1, yd1, zd1), xs); - - float yf0 = Lerp(xf00, xf10, ys); - float yf1 = Lerp(xf01, xf11, ys); - - return Lerp(yf0, yf1, zs); - } - - public float GetPerlinFractal(float x, float y) - { - x *= m_frequency; - y *= m_frequency; - - switch(m_fractalType) - { - case FBM: - return SinglePerlinFractalFBM(x, y); - case Billow: - return SinglePerlinFractalBillow(x, y); - case RigidMulti: - return SinglePerlinFractalRigidMulti(x, y); - default: - return 0; - } - } - - private float SinglePerlinFractalFBM(float x, float y) - { - int seed = m_seed; - float sum = SinglePerlin(seed, x, y); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += SinglePerlin(++seed, x, y) * amp; - } - - return sum * m_fractalBounding; - } - - private float SinglePerlinFractalBillow(float x, float y) - { - int seed = m_seed; - float sum = Math.abs(SinglePerlin(seed, x, y)) * 2 - 1; - float amp = 1; - - for(int i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SinglePerlin(++seed, x, y)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private float SinglePerlinFractalRigidMulti(float x, float y) - { - int seed = m_seed; - float sum = 1 - Math.abs(SinglePerlin(seed, x, y)); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SinglePerlin(++seed, x, y))) * amp; - } - - return sum; - } - - public float GetPerlin(float x, float y) - { - return SinglePerlin(m_seed, x * m_frequency, y * m_frequency); - } - - private float SinglePerlin(int seed, float x, float y) - { - int x0 = FastFloor(x); - int y0 = FastFloor(y); - int x1 = x0 + 1; - int y1 = y0 + 1; - - float xs, ys; - switch(m_interp) - { - default: - case Linear: - xs = x - x0; - ys = y - y0; - break; - case Hermite: - xs = InterpHermiteFunc(x - x0); - ys = InterpHermiteFunc(y - y0); - break; - case Quintic: - xs = InterpQuinticFunc(x - x0); - ys = InterpQuinticFunc(y - y0); - break; - } - - float xd0 = x - x0; - float yd0 = y - y0; - float xd1 = xd0 - 1; - float yd1 = yd0 - 1; - - float xf0 = Lerp(GradCoord2D(seed, x0, y0, xd0, yd0), GradCoord2D(seed, x1, y0, xd1, yd0), xs); - float xf1 = Lerp(GradCoord2D(seed, x0, y1, xd0, yd1), GradCoord2D(seed, x1, y1, xd1, yd1), xs); - - return Lerp(xf0, xf1, ys); - } - - // Simplex Noise - public float GetSimplexFractal(float x, float y, float z) - { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - switch(m_fractalType) - { - case FBM: - return SingleSimplexFractalFBM(x, y, z); - case Billow: - return SingleSimplexFractalBillow(x, y, z); - case RigidMulti: - return SingleSimplexFractalRigidMulti(x, y, z); - default: - return 0; - } - } - - private float SingleSimplexFractalFBM(float x, float y, float z) - { - int seed = m_seed; - float sum = SingleSimplex(seed, x, y, z); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += SingleSimplex(++seed, x, y, z) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleSimplexFractalBillow(float x, float y, float z) - { - int seed = m_seed; - float sum = Math.abs(SingleSimplex(seed, x, y, z)) * 2 - 1; - float amp = 1; - - for(int i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SingleSimplex(++seed, x, y, z)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleSimplexFractalRigidMulti(float x, float y, float z) - { - int seed = m_seed; - float sum = 1 - Math.abs(SingleSimplex(seed, x, y, z)); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleSimplex(++seed, x, y, z))) * amp; - } - - return sum; - } - - public float GetSimplex(float x, float y, float z) - { - return SingleSimplex(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); - } - - private final static float F3 = (float) (1.0 / 3.0); - private final static float G3 = (float) (1.0 / 6.0); - private final static float G33 = G3 * 3 - 1; - - private float SingleSimplex(int seed, float x, float y, float z) - { - float t = (x + y + z) * F3; - int i = FastFloor(x + t); - int j = FastFloor(y + t); - int k = FastFloor(z + t); - - t = (i + j + k) * G3; - float x0 = x - (i - t); - float y0 = y - (j - t); - float z0 = z - (k - t); - - int i1, j1, k1; - int i2, j2, k2; - - if(x0 >= y0) - { - if(y0 >= z0) - { - i1 = 1; - j1 = 0; - k1 = 0; - i2 = 1; - j2 = 1; - k2 = 0; - } - else if(x0 >= z0) - { - i1 = 1; - j1 = 0; - k1 = 0; - i2 = 1; - j2 = 0; - k2 = 1; - } - else // x0 < z0 - { - i1 = 0; - j1 = 0; - k1 = 1; - i2 = 1; - j2 = 0; - k2 = 1; - } - } - else // x0 < y0 - { - if(y0 < z0) - { - i1 = 0; - j1 = 0; - k1 = 1; - i2 = 0; - j2 = 1; - k2 = 1; - } - else if(x0 < z0) - { - i1 = 0; - j1 = 1; - k1 = 0; - i2 = 0; - j2 = 1; - k2 = 1; - } - else // x0 >= z0 - { - i1 = 0; - j1 = 1; - k1 = 0; - i2 = 1; - j2 = 1; - k2 = 0; - } - } - - float x1 = x0 - i1 + G3; - float y1 = y0 - j1 + G3; - float z1 = z0 - k1 + G3; - float x2 = x0 - i2 + F3; - float y2 = y0 - j2 + F3; - float z2 = z0 - k2 + F3; - float x3 = x0 + G33; - float y3 = y0 + G33; - float z3 = z0 + G33; - - float n0, n1, n2, n3; - - t = (float) 0.6 - x0 * x0 - y0 * y0 - z0 * z0; - if(t < 0) - n0 = 0; - else - { - t *= t; - n0 = t * t * GradCoord3D(seed, i, j, k, x0, y0, z0); - } - - t = (float) 0.6 - x1 * x1 - y1 * y1 - z1 * z1; - if(t < 0) - n1 = 0; - else - { - t *= t; - n1 = t * t * GradCoord3D(seed, i + i1, j + j1, k + k1, x1, y1, z1); - } - - t = (float) 0.6 - x2 * x2 - y2 * y2 - z2 * z2; - if(t < 0) - n2 = 0; - else - { - t *= t; - n2 = t * t * GradCoord3D(seed, i + i2, j + j2, k + k2, x2, y2, z2); - } - - t = (float) 0.6 - x3 * x3 - y3 * y3 - z3 * z3; - if(t < 0) - n3 = 0; - else - { - t *= t; - n3 = t * t * GradCoord3D(seed, i + 1, j + 1, k + 1, x3, y3, z3); - } - - return 32 * (n0 + n1 + n2 + n3); - } - - public float GetSimplexFractal(float x, float y) - { - x *= m_frequency; - y *= m_frequency; - - switch(m_fractalType) - { - case FBM: - return SingleSimplexFractalFBM(x, y); - case Billow: - return SingleSimplexFractalBillow(x, y); - case RigidMulti: - return SingleSimplexFractalRigidMulti(x, y); - default: - return 0; - } - } - - private float SingleSimplexFractalFBM(float x, float y) - { - int seed = m_seed; - float sum = SingleSimplex(seed, x, y); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += SingleSimplex(++seed, x, y) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleSimplexFractalBillow(float x, float y) - { - int seed = m_seed; - float sum = Math.abs(SingleSimplex(seed, x, y)) * 2 - 1; - float amp = 1; - - for(int i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SingleSimplex(++seed, x, y)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleSimplexFractalRigidMulti(float x, float y) - { - int seed = m_seed; - float sum = 1 - Math.abs(SingleSimplex(seed, x, y)); - float amp = 1; - - for(int i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleSimplex(++seed, x, y))) * amp; - } - - return sum; - } - - public float GetSimplex(float x, float y) - { - return SingleSimplex(m_seed, x * m_frequency, y * m_frequency); - } - - // private final static float F2 = (float) (1.0 / 2.0); - // private final static float G2 = (float) (1.0 / 4.0); - - private final static float SQRT3 = (float) 1.7320508075688772935274463415059; - private final static float F2 = 0.5f * (SQRT3 - 1.0f); - private final static float G2 = (3.0f - SQRT3) / 6.0f; - - private float SingleSimplex(int seed, float x, float y) - { - float t = (x + y) * F2; - int i = FastFloor(x + t); - int j = FastFloor(y + t); - - t = (i + j) * G2; - float X0 = i - t; - float Y0 = j - t; - - float x0 = x - X0; - float y0 = y - Y0; - - int i1, j1; - if(x0 > y0) - { - i1 = 1; - j1 = 0; - } - else - { - i1 = 0; - j1 = 1; - } - - float x1 = x0 - i1 + G2; - float y1 = y0 - j1 + G2; - float x2 = x0 - 1 + 2 * G2; - float y2 = y0 - 1 + 2 * G2; - - float n0, n1, n2; - - t = (float) 0.5 - x0 * x0 - y0 * y0; - if(t < 0) - n0 = 0; - else - { - t *= t; - n0 = t * t * GradCoord2D(seed, i, j, x0, y0); - } - - t = (float) 0.5 - x1 * x1 - y1 * y1; - if(t < 0) - n1 = 0; - else - { - t *= t; - n1 = t * t * GradCoord2D(seed, i + i1, j + j1, x1, y1); - } - - t = (float) 0.5 - x2 * x2 - y2 * y2; - if(t < 0) - n2 = 0; - else - { - t *= t; - n2 = t * t * GradCoord2D(seed, i + 1, j + 1, x2, y2); - } - - return 50 * (n0 + n1 + n2); - } - - public float GetSimplex(float x, float y, float z, float w) - { - return SingleSimplex(m_seed, x * m_frequency, y * m_frequency, z * m_frequency, w * m_frequency); - } - - private static final byte[] SIMPLEX_4D = {0, 1, 2, 3, 0, 1, 3, 2, 0, 0, 0, 0, 0, 2, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 0, 2, 1, 3, 0, 0, 0, 0, 0, 3, 1, 2, 0, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 3, 0, 0, 0, 0, 1, 3, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 0, 1, 2, 3, 1, 0, 1, 0, 2, 3, 1, 0, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 1, 0, 0, 0, 0, 2, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 1, 2, 3, 0, 2, 1, 0, 0, 0, 0, 3, 1, 2, 0, 2, 1, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 1, 0, 2, 0, 0, 0, 0, 3, 2, 0, 1, 3, 2, 1, 0 - }; - - private final static float F4 = (float) ((2.23606797 - 1.0) / 4.0); - private final static float G4 = (float) ((5.0 - 2.23606797) / 20.0); - - private float SingleSimplex(int seed, float x, float y, float z, float w) - { - float n0, n1, n2, n3, n4; - float t = (x + y + z + w) * F4; - int i = FastFloor(x + t); - int j = FastFloor(y + t); - int k = FastFloor(z + t); - int l = FastFloor(w + t); - t = (i + j + k + l) * G4; - float X0 = i - t; - float Y0 = j - t; - float Z0 = k - t; - float W0 = l - t; - float x0 = x - X0; - float y0 = y - Y0; - float z0 = z - Z0; - float w0 = w - W0; - - int c = (x0 > y0) ? 32 : 0; - c += (x0 > z0) ? 16 : 0; - c += (y0 > z0) ? 8 : 0; - c += (x0 > w0) ? 4 : 0; - c += (y0 > w0) ? 2 : 0; - c += (z0 > w0) ? 1 : 0; - c <<= 2; - - int i1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; - int i2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; - int i3 = SIMPLEX_4D[c++] >= 1 ? 1 : 0; - int j1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; - int j2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; - int j3 = SIMPLEX_4D[c++] >= 1 ? 1 : 0; - int k1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; - int k2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; - int k3 = SIMPLEX_4D[c++] >= 1 ? 1 : 0; - int l1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; - int l2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; - int l3 = SIMPLEX_4D[c] >= 1 ? 1 : 0; - - float x1 = x0 - i1 + G4; - float y1 = y0 - j1 + G4; - float z1 = z0 - k1 + G4; - float w1 = w0 - l1 + G4; - float x2 = x0 - i2 + 2 * G4; - float y2 = y0 - j2 + 2 * G4; - float z2 = z0 - k2 + 2 * G4; - float w2 = w0 - l2 + 2 * G4; - float x3 = x0 - i3 + 3 * G4; - float y3 = y0 - j3 + 3 * G4; - float z3 = z0 - k3 + 3 * G4; - float w3 = w0 - l3 + 3 * G4; - float x4 = x0 - 1 + 4 * G4; - float y4 = y0 - 1 + 4 * G4; - float z4 = z0 - 1 + 4 * G4; - float w4 = w0 - 1 + 4 * G4; - - t = (float) 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0; - if(t < 0) - n0 = 0; - else - { - t *= t; - n0 = t * t * GradCoord4D(seed, i, j, k, l, x0, y0, z0, w0); - } - t = (float) 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1; - if(t < 0) - n1 = 0; - else - { - t *= t; - n1 = t * t * GradCoord4D(seed, i + i1, j + j1, k + k1, l + l1, x1, y1, z1, w1); - } - t = (float) 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2; - if(t < 0) - n2 = 0; - else - { - t *= t; - n2 = t * t * GradCoord4D(seed, i + i2, j + j2, k + k2, l + l2, x2, y2, z2, w2); - } - t = (float) 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3; - if(t < 0) - n3 = 0; - else - { - t *= t; - n3 = t * t * GradCoord4D(seed, i + i3, j + j3, k + k3, l + l3, x3, y3, z3, w3); - } - t = (float) 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4; - if(t < 0) - n4 = 0; - else - { - t *= t; - n4 = t * t * GradCoord4D(seed, i + 1, j + 1, k + 1, l + 1, x4, y4, z4, w4); - } - - return 27 * (n0 + n1 + n2 + n3 + n4); - } - - // Cubic Noise - public float GetCubicFractal(float x, float y, float z) - { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - switch(m_fractalType) - { - case FBM: - return SingleCubicFractalFBM(x, y, z); - case Billow: - return SingleCubicFractalBillow(x, y, z); - case RigidMulti: - return SingleCubicFractalRigidMulti(x, y, z); - default: - return 0; - } - } - - private float SingleCubicFractalFBM(float x, float y, float z) - { - int seed = m_seed; - float sum = SingleCubic(seed, x, y, z); - float amp = 1; - int i = 0; - - while(++i < m_octaves) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += SingleCubic(++seed, x, y, z) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleCubicFractalBillow(float x, float y, float z) - { - int seed = m_seed; - float sum = Math.abs(SingleCubic(seed, x, y, z)) * 2 - 1; - float amp = 1; - int i = 0; - - while(++i < m_octaves) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SingleCubic(++seed, x, y, z)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleCubicFractalRigidMulti(float x, float y, float z) - { - int seed = m_seed; - float sum = 1 - Math.abs(SingleCubic(seed, x, y, z)); - float amp = 1; - int i = 0; - - while(++i < m_octaves) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleCubic(++seed, x, y, z))) * amp; - } - - return sum; - } - - public float GetCubic(float x, float y, float z) - { - return SingleCubic(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); - } - - private final static float CUBIC_3D_BOUNDING = 1 / (float) (1.5 * 1.5 * 1.5); - - private float SingleCubic(int seed, float x, float y, float z) - { - int x1 = FastFloor(x); - int y1 = FastFloor(y); - int z1 = FastFloor(z); - - int x0 = x1 - 1; - int y0 = y1 - 1; - int z0 = z1 - 1; - int x2 = x1 + 1; - int y2 = y1 + 1; - int z2 = z1 + 1; - int x3 = x1 + 2; - int y3 = y1 + 2; - int z3 = z1 + 2; - - float xs = x - (float) x1; - float ys = y - (float) y1; - float zs = z - (float) z1; - - return CubicLerp(CubicLerp(CubicLerp(ValCoord3D(seed, x0, y0, z0), ValCoord3D(seed, x1, y0, z0), ValCoord3D(seed, x2, y0, z0), ValCoord3D(seed, x3, y0, z0), xs), CubicLerp(ValCoord3D(seed, x0, y1, z0), ValCoord3D(seed, x1, y1, z0), ValCoord3D(seed, x2, y1, z0), ValCoord3D(seed, x3, y1, z0), xs), CubicLerp(ValCoord3D(seed, x0, y2, z0), ValCoord3D(seed, x1, y2, z0), ValCoord3D(seed, x2, y2, z0), ValCoord3D(seed, x3, y2, z0), xs), CubicLerp(ValCoord3D(seed, x0, y3, z0), ValCoord3D(seed, x1, y3, z0), ValCoord3D(seed, x2, y3, z0), ValCoord3D(seed, x3, y3, z0), xs), ys), CubicLerp(CubicLerp(ValCoord3D(seed, x0, y0, z1), ValCoord3D(seed, x1, y0, z1), ValCoord3D(seed, x2, y0, z1), ValCoord3D(seed, x3, y0, z1), xs), CubicLerp(ValCoord3D(seed, x0, y1, z1), ValCoord3D(seed, x1, y1, z1), ValCoord3D(seed, x2, y1, z1), ValCoord3D(seed, x3, y1, z1), xs), CubicLerp(ValCoord3D(seed, x0, y2, z1), ValCoord3D(seed, x1, y2, z1), ValCoord3D(seed, x2, y2, z1), ValCoord3D(seed, x3, y2, z1), xs), CubicLerp(ValCoord3D(seed, x0, y3, z1), ValCoord3D(seed, x1, y3, z1), ValCoord3D(seed, x2, y3, z1), ValCoord3D(seed, x3, y3, z1), xs), ys), CubicLerp(CubicLerp(ValCoord3D(seed, x0, y0, z2), ValCoord3D(seed, x1, y0, z2), ValCoord3D(seed, x2, y0, z2), ValCoord3D(seed, x3, y0, z2), xs), CubicLerp(ValCoord3D(seed, x0, y1, z2), ValCoord3D(seed, x1, y1, z2), ValCoord3D(seed, x2, y1, z2), ValCoord3D(seed, x3, y1, z2), xs), CubicLerp(ValCoord3D(seed, x0, y2, z2), ValCoord3D(seed, x1, y2, z2), ValCoord3D(seed, x2, y2, z2), ValCoord3D(seed, x3, y2, z2), xs), CubicLerp(ValCoord3D(seed, x0, y3, z2), ValCoord3D(seed, x1, y3, z2), ValCoord3D(seed, x2, y3, z2), ValCoord3D(seed, x3, y3, z2), xs), ys), CubicLerp(CubicLerp(ValCoord3D(seed, x0, y0, z3), ValCoord3D(seed, x1, y0, z3), ValCoord3D(seed, x2, y0, z3), ValCoord3D(seed, x3, y0, z3), xs), CubicLerp(ValCoord3D(seed, x0, y1, z3), ValCoord3D(seed, x1, y1, z3), ValCoord3D(seed, x2, y1, z3), ValCoord3D(seed, x3, y1, z3), xs), CubicLerp(ValCoord3D(seed, x0, y2, z3), ValCoord3D(seed, x1, y2, z3), ValCoord3D(seed, x2, y2, z3), ValCoord3D(seed, x3, y2, z3), xs), CubicLerp(ValCoord3D(seed, x0, y3, z3), ValCoord3D(seed, x1, y3, z3), ValCoord3D(seed, x2, y3, z3), ValCoord3D(seed, x3, y3, z3), xs), ys), zs) * CUBIC_3D_BOUNDING; - } - - public float GetCubicFractal(float x, float y) - { - x *= m_frequency; - y *= m_frequency; - - switch(m_fractalType) - { - case FBM: - return SingleCubicFractalFBM(x, y); - case Billow: - return SingleCubicFractalBillow(x, y); - case RigidMulti: - return SingleCubicFractalRigidMulti(x, y); - default: - return 0; - } - } - - private float SingleCubicFractalFBM(float x, float y) - { - int seed = m_seed; - float sum = SingleCubic(seed, x, y); - float amp = 1; - int i = 0; - - while(++i < m_octaves) - { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += SingleCubic(++seed, x, y) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleCubicFractalBillow(float x, float y) - { - int seed = m_seed; - float sum = Math.abs(SingleCubic(seed, x, y)) * 2 - 1; - float amp = 1; - int i = 0; - - while(++i < m_octaves) - { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SingleCubic(++seed, x, y)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private float SingleCubicFractalRigidMulti(float x, float y) - { - int seed = m_seed; - float sum = 1 - Math.abs(SingleCubic(seed, x, y)); - float amp = 1; - int i = 0; - - while(++i < m_octaves) - { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleCubic(++seed, x, y))) * amp; - } - - return sum; - } - - public float GetCubic(float x, float y) - { - x *= m_frequency; - y *= m_frequency; - - return SingleCubic(0, x, y); - } - - private final static float CUBIC_2D_BOUNDING = 1 / (float) (1.5 * 1.5); - - private float SingleCubic(int seed, float x, float y) - { - int x1 = FastFloor(x); - int y1 = FastFloor(y); - - int x0 = x1 - 1; - int y0 = y1 - 1; - int x2 = x1 + 1; - int y2 = y1 + 1; - int x3 = x1 + 2; - int y3 = y1 + 2; - - float xs = x - (float) x1; - float ys = y - (float) y1; - - return CubicLerp(CubicLerp(ValCoord2D(seed, x0, y0), ValCoord2D(seed, x1, y0), ValCoord2D(seed, x2, y0), ValCoord2D(seed, x3, y0), xs), CubicLerp(ValCoord2D(seed, x0, y1), ValCoord2D(seed, x1, y1), ValCoord2D(seed, x2, y1), ValCoord2D(seed, x3, y1), xs), CubicLerp(ValCoord2D(seed, x0, y2), ValCoord2D(seed, x1, y2), ValCoord2D(seed, x2, y2), ValCoord2D(seed, x3, y2), xs), CubicLerp(ValCoord2D(seed, x0, y3), ValCoord2D(seed, x1, y3), ValCoord2D(seed, x2, y3), ValCoord2D(seed, x3, y3), xs), ys) * CUBIC_2D_BOUNDING; - } - - // Cellular Noise - public float GetCellular(float x, float y, float z) - { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - switch(m_cellularReturnType) - { - case CellValue: - case NoiseLookup: - case Distance: - return SingleCellular(x, y, z); - default: - return SingleCellular2Edge(x, y, z); - } - } - - private float SingleCellular(float x, float y, float z) - { - int xr = FastRound(x); - int yr = FastRound(y); - int zr = FastRound(z); - - float distance = 999999; - int xc = 0, yc = 0, zc = 0; - - switch(m_cellularDistanceFunction) - { - case Euclidean: - for(int xi = xr - 1; xi <= xr + 1; xi++) - { - for(int yi = yr - 1; yi <= yr + 1; yi++) - { - for(int zi = zr - 1; zi <= zr + 1; zi++) - { - Float3 vec = CELL_3D[Hash3D(m_seed, xi, yi, zi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - float vecZ = zi - z + vec.z; - - float newDistance = vecX * vecX + vecY * vecY + vecZ * vecZ; - - if(newDistance < distance) - { - distance = newDistance; - xc = xi; - yc = yi; - zc = zi; - } - } - } - } - break; - case Manhattan: - for(int xi = xr - 1; xi <= xr + 1; xi++) - { - for(int yi = yr - 1; yi <= yr + 1; yi++) - { - for(int zi = zr - 1; zi <= zr + 1; zi++) - { - Float3 vec = CELL_3D[Hash3D(m_seed, xi, yi, zi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - float vecZ = zi - z + vec.z; - - float newDistance = Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ); - - if(newDistance < distance) - { - distance = newDistance; - xc = xi; - yc = yi; - zc = zi; - } - } - } - } - break; - case Natural: - for(int xi = xr - 1; xi <= xr + 1; xi++) - { - for(int yi = yr - 1; yi <= yr + 1; yi++) - { - for(int zi = zr - 1; zi <= zr + 1; zi++) - { - Float3 vec = CELL_3D[Hash3D(m_seed, xi, yi, zi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - float vecZ = zi - z + vec.z; - - float newDistance = (Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ)) + (vecX * vecX + vecY * vecY + vecZ * vecZ); - - if(newDistance < distance) - { - distance = newDistance; - xc = xi; - yc = yi; - zc = zi; - } - } - } - } - break; - } - - switch(m_cellularReturnType) - { - case CellValue: - return ValCoord3D(0, xc, yc, zc); - - case NoiseLookup: - Float3 vec = CELL_3D[Hash3D(m_seed, xc, yc, zc) & 255]; - return m_cellularNoiseLookup.GetNoise(xc + vec.x, yc + vec.y, zc + vec.z); - - case Distance: - return distance - 1; - default: - return 0; - } - } - - private float SingleCellular2Edge(float x, float y, float z) - { - int xr = FastRound(x); - int yr = FastRound(y); - int zr = FastRound(z); - - float distance = 999999; - float distance2 = 999999; - - switch(m_cellularDistanceFunction) - { - case Euclidean: - for(int xi = xr - 1; xi <= xr + 1; xi++) - { - for(int yi = yr - 1; yi <= yr + 1; yi++) - { - for(int zi = zr - 1; zi <= zr + 1; zi++) - { - Float3 vec = CELL_3D[Hash3D(m_seed, xi, yi, zi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - float vecZ = zi - z + vec.z; - - float newDistance = vecX * vecX + vecY * vecY + vecZ * vecZ; - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - } - break; - case Manhattan: - for(int xi = xr - 1; xi <= xr + 1; xi++) - { - for(int yi = yr - 1; yi <= yr + 1; yi++) - { - for(int zi = zr - 1; zi <= zr + 1; zi++) - { - Float3 vec = CELL_3D[Hash3D(m_seed, xi, yi, zi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - float vecZ = zi - z + vec.z; - - float newDistance = Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ); - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - } - break; - case Natural: - for(int xi = xr - 1; xi <= xr + 1; xi++) - { - for(int yi = yr - 1; yi <= yr + 1; yi++) - { - for(int zi = zr - 1; zi <= zr + 1; zi++) - { - Float3 vec = CELL_3D[Hash3D(m_seed, xi, yi, zi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - float vecZ = zi - z + vec.z; - - float newDistance = (Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ)) + (vecX * vecX + vecY * vecY + vecZ * vecZ); - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - } - break; - default: - break; - } - - switch(m_cellularReturnType) - { - case Distance2: - return distance2 - 1; - case Distance2Add: - return distance2 + distance - 1; - case Distance2Sub: - return distance2 - distance - 1; - case Distance2Mul: - return distance2 * distance - 1; - case Distance2Div: - return distance / distance2 - 1; - default: - return 0; - } - } - - public float GetCellular(float x, float y) - { - x *= m_frequency; - y *= m_frequency; - - switch(m_cellularReturnType) - { - case CellValue: - case NoiseLookup: - case Distance: - return SingleCellular(x, y); - default: - return SingleCellular2Edge(x, y); - } - } - - private float SingleCellular(float x, float y) - { - int xr = FastRound(x); - int yr = FastRound(y); - - float distance = 999999; - int xc = 0, yc = 0; - - switch(m_cellularDistanceFunction) - { - default: - case Euclidean: - for(int xi = xr - 1; xi <= xr + 1; xi++) - { - for(int yi = yr - 1; yi <= yr + 1; yi++) - { - Float2 vec = CELL_2D[Hash2D(m_seed, xi, yi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - - float newDistance = vecX * vecX + vecY * vecY; - - if(newDistance < distance) - { - distance = newDistance; - xc = xi; - yc = yi; - } - } - } - break; - case Manhattan: - for(int xi = xr - 1; xi <= xr + 1; xi++) - { - for(int yi = yr - 1; yi <= yr + 1; yi++) - { - Float2 vec = CELL_2D[Hash2D(m_seed, xi, yi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - - float newDistance = (Math.abs(vecX) + Math.abs(vecY)); - - if(newDistance < distance) - { - distance = newDistance; - xc = xi; - yc = yi; - } - } - } - break; - case Natural: - for(int xi = xr - 1; xi <= xr + 1; xi++) - { - for(int yi = yr - 1; yi <= yr + 1; yi++) - { - Float2 vec = CELL_2D[Hash2D(m_seed, xi, yi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - - float newDistance = (Math.abs(vecX) + Math.abs(vecY)) + (vecX * vecX + vecY * vecY); - - if(newDistance < distance) - { - distance = newDistance; - xc = xi; - yc = yi; - } - } - } - break; - } - - switch(m_cellularReturnType) - { - case CellValue: - return ValCoord2D(0, xc, yc); - - case NoiseLookup: - Float2 vec = CELL_2D[Hash2D(m_seed, xc, yc) & 255]; - return m_cellularNoiseLookup.GetNoise(xc + vec.x, yc + vec.y); - - case Distance: - return distance - 1; - default: - return 0; - } - } - - private float SingleCellular2Edge(float x, float y) - { - int xr = FastRound(x); - int yr = FastRound(y); - - float distance = 999999; - float distance2 = 999999; - - switch(m_cellularDistanceFunction) - { - default: - case Euclidean: - for(int xi = xr - 1; xi <= xr + 1; xi++) - { - for(int yi = yr - 1; yi <= yr + 1; yi++) - { - Float2 vec = CELL_2D[Hash2D(m_seed, xi, yi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - - float newDistance = vecX * vecX + vecY * vecY; - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - break; - case Manhattan: - for(int xi = xr - 1; xi <= xr + 1; xi++) - { - for(int yi = yr - 1; yi <= yr + 1; yi++) - { - Float2 vec = CELL_2D[Hash2D(m_seed, xi, yi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - - float newDistance = Math.abs(vecX) + Math.abs(vecY); - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - break; - case Natural: - for(int xi = xr - 1; xi <= xr + 1; xi++) - { - for(int yi = yr - 1; yi <= yr + 1; yi++) - { - Float2 vec = CELL_2D[Hash2D(m_seed, xi, yi) & 255]; - - float vecX = xi - x + vec.x; - float vecY = yi - y + vec.y; - - float newDistance = (Math.abs(vecX) + Math.abs(vecY)) + (vecX * vecX + vecY * vecY); - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - break; - } - - switch(m_cellularReturnType) - { - case Distance2: - return distance2 - 1; - case Distance2Add: - return distance2 + distance - 1; - case Distance2Sub: - return distance2 - distance - 1; - case Distance2Mul: - return distance2 * distance - 1; - case Distance2Div: - return distance / distance2 - 1; - default: - return 0; - } - } - - public void GradientPerturb(Vector3f v3) - { - SingleGradientPerturb(m_seed, m_gradientPerturbAmp, m_frequency, v3); - } - - public void GradientPerturbFractal(Vector3f v3) - { - int seed = m_seed; - float amp = m_gradientPerturbAmp * m_fractalBounding; - float freq = m_frequency; - - SingleGradientPerturb(seed, amp, m_frequency, v3); - - for(int i = 1; i < m_octaves; i++) - { - freq *= m_lacunarity; - amp *= m_gain; - SingleGradientPerturb(++seed, amp, freq, v3); - } - } - - private void SingleGradientPerturb(int seed, float perturbAmp, float frequency, Vector3f v3) - { - float xf = v3.x * frequency; - float yf = v3.y * frequency; - float zf = v3.z * frequency; - - int x0 = FastFloor(xf); - int y0 = FastFloor(yf); - int z0 = FastFloor(zf); - int x1 = x0 + 1; - int y1 = y0 + 1; - int z1 = z0 + 1; - - float xs, ys, zs; - switch(m_interp) - { - default: - case Linear: - xs = xf - x0; - ys = yf - y0; - zs = zf - z0; - break; - case Hermite: - xs = InterpHermiteFunc(xf - x0); - ys = InterpHermiteFunc(yf - y0); - zs = InterpHermiteFunc(zf - z0); - break; - case Quintic: - xs = InterpQuinticFunc(xf - x0); - ys = InterpQuinticFunc(yf - y0); - zs = InterpQuinticFunc(zf - z0); - break; - } - - Float3 vec0 = CELL_3D[Hash3D(seed, x0, y0, z0) & 255]; - Float3 vec1 = CELL_3D[Hash3D(seed, x1, y0, z0) & 255]; - - float lx0x = Lerp(vec0.x, vec1.x, xs); - float ly0x = Lerp(vec0.y, vec1.y, xs); - float lz0x = Lerp(vec0.z, vec1.z, xs); - - vec0 = CELL_3D[Hash3D(seed, x0, y1, z0) & 255]; - vec1 = CELL_3D[Hash3D(seed, x1, y1, z0) & 255]; - - float lx1x = Lerp(vec0.x, vec1.x, xs); - float ly1x = Lerp(vec0.y, vec1.y, xs); - float lz1x = Lerp(vec0.z, vec1.z, xs); - - float lx0y = Lerp(lx0x, lx1x, ys); - float ly0y = Lerp(ly0x, ly1x, ys); - float lz0y = Lerp(lz0x, lz1x, ys); - - vec0 = CELL_3D[Hash3D(seed, x0, y0, z1) & 255]; - vec1 = CELL_3D[Hash3D(seed, x1, y0, z1) & 255]; - - lx0x = Lerp(vec0.x, vec1.x, xs); - ly0x = Lerp(vec0.y, vec1.y, xs); - lz0x = Lerp(vec0.z, vec1.z, xs); - - vec0 = CELL_3D[Hash3D(seed, x0, y1, z1) & 255]; - vec1 = CELL_3D[Hash3D(seed, x1, y1, z1) & 255]; - - lx1x = Lerp(vec0.x, vec1.x, xs); - ly1x = Lerp(vec0.y, vec1.y, xs); - lz1x = Lerp(vec0.z, vec1.z, xs); - - v3.x += Lerp(lx0y, Lerp(lx0x, lx1x, ys), zs) * perturbAmp; - v3.y += Lerp(ly0y, Lerp(ly0x, ly1x, ys), zs) * perturbAmp; - v3.z += Lerp(lz0y, Lerp(lz0x, lz1x, ys), zs) * perturbAmp; - } - - public void GradientPerturb(Vector2f v2) - { - SingleGradientPerturb(m_seed, m_gradientPerturbAmp, m_frequency, v2); - } - - public void GradientPerturbFractal(Vector2f v2) - { - int seed = m_seed; - float amp = m_gradientPerturbAmp * m_fractalBounding; - float freq = m_frequency; - - SingleGradientPerturb(seed, amp, m_frequency, v2); - - for(int i = 1; i < m_octaves; i++) - { - freq *= m_lacunarity; - amp *= m_gain; - SingleGradientPerturb(++seed, amp, freq, v2); - } - } - - private void SingleGradientPerturb(int seed, float perturbAmp, float frequency, Vector2f v2) - { - float xf = v2.x * frequency; - float yf = v2.y * frequency; - - int x0 = FastFloor(xf); - int y0 = FastFloor(yf); - int x1 = x0 + 1; - int y1 = y0 + 1; - - float xs, ys; - switch(m_interp) - { - default: - case Linear: - xs = xf - x0; - ys = yf - y0; - break; - case Hermite: - xs = InterpHermiteFunc(xf - x0); - ys = InterpHermiteFunc(yf - y0); - break; - case Quintic: - xs = InterpQuinticFunc(xf - x0); - ys = InterpQuinticFunc(yf - y0); - break; - } - - Float2 vec0 = CELL_2D[Hash2D(seed, x0, y0) & 255]; - Float2 vec1 = CELL_2D[Hash2D(seed, x1, y0) & 255]; - - float lx0x = Lerp(vec0.x, vec1.x, xs); - float ly0x = Lerp(vec0.y, vec1.y, xs); - - vec0 = CELL_2D[Hash2D(seed, x0, y1) & 255]; - vec1 = CELL_2D[Hash2D(seed, x1, y1) & 255]; - - float lx1x = Lerp(vec0.x, vec1.x, xs); - float ly1x = Lerp(vec0.y, vec1.y, xs); - - v2.x += Lerp(lx0x, lx1x, ys) * perturbAmp; - v2.y += Lerp(ly0x, ly1x, ys) * perturbAmp; - } +public class FastNoise { + public enum NoiseType { + Value, + ValueFractal, + Perlin, + PerlinFractal, + Simplex, + SimplexFractal, + Cellular, + WhiteNoise, + Cubic, + CubicFractal + } + + public enum Interp { + Linear, + Hermite, + Quintic + } + + public enum FractalType { + FBM, + Billow, + RigidMulti + } + + public enum CellularDistanceFunction { + Euclidean, + Manhattan, + Natural + } + + public enum CellularReturnType { + CellValue, + NoiseLookup, + Distance, + Distance2, + Distance2Add, + Distance2Sub, + Distance2Mul, + Distance2Div + } + + private int m_seed = 1337; + private float m_frequency = (float) 0.01; + private Interp m_interp = Interp.Quintic; + private NoiseType m_noiseType = NoiseType.Simplex; + + private int m_octaves = 3; + private float m_lacunarity = (float) 2.0; + private float m_gain = (float) 0.5; + private FractalType m_fractalType = FractalType.FBM; + + private float m_fractalBounding; + + private CellularDistanceFunction m_cellularDistanceFunction = CellularDistanceFunction.Euclidean; + private CellularReturnType m_cellularReturnType = CellularReturnType.CellValue; + private FastNoise m_cellularNoiseLookup = null; + + private float m_gradientPerturbAmp = (float) (1.0 / 0.45); + + public FastNoise() { + this(1337); + } + + public FastNoise(int seed) { + m_seed = seed; + CalculateFractalBounding(); + } + + // Returns a 0 float/double + public static float GetDecimalType() { + return 0; + } + + // Returns the seed used by this object + public int GetSeed() { + return m_seed; + } + + // Sets seed used for all noise types + // Default: 1337 + public void SetSeed(int seed) { + m_seed = seed; + } + + // Sets frequency for all noise types + // Default: 0.01 + public void SetFrequency(float frequency) { + m_frequency = frequency; + } + + // Changes the interpolation method used to smooth between noise values + // Possible interpolation methods (lowest to highest quality) : + // - Linear + // - Hermite + // - Quintic + // Used in Value, Gradient Noise and Position Perturbing + // Default: Quintic + public void SetInterp(Interp interp) { + m_interp = interp; + } + + // Sets noise return type of GetNoise(...) + // Default: Simplex + public void SetNoiseType(NoiseType noiseType) { + m_noiseType = noiseType; + } + + // Sets octave count for all fractal noise types + // Default: 3 + public void SetFractalOctaves(int octaves) { + m_octaves = octaves; + CalculateFractalBounding(); + } + + // Sets octave lacunarity for all fractal noise types + // Default: 2.0 + public void SetFractalLacunarity(float lacunarity) { + m_lacunarity = lacunarity; + } + + // Sets octave gain for all fractal noise types + // Default: 0.5 + public void SetFractalGain(float gain) { + m_gain = gain; + CalculateFractalBounding(); + } + + // Sets method for combining octaves in all fractal noise types + // Default: FBM + public void SetFractalType(FractalType fractalType) { + m_fractalType = fractalType; + } + + // Sets return type from cellular noise calculations + // Note: NoiseLookup requires another FastNoise object be set with + // SetCellularNoiseLookup() to function + // Default: CellValue + public void SetCellularDistanceFunction(CellularDistanceFunction cellularDistanceFunction) { + m_cellularDistanceFunction = cellularDistanceFunction; + } + + // Sets distance function used in cellular noise calculations + // Default: Euclidean + public void SetCellularReturnType(CellularReturnType cellularReturnType) { + m_cellularReturnType = cellularReturnType; + } + + // Noise used to calculate a cell value if cellular return type is NoiseLookup + // The lookup value is acquired through GetNoise() so ensure you SetNoiseType() + // on the noise lookup, value, gradient or simplex is recommended + public void SetCellularNoiseLookup(FastNoise noise) { + m_cellularNoiseLookup = noise; + } + + // Sets the maximum perturb distance from original location when using + // GradientPerturb{Fractal}(...) + // Default: 1.0 + public void SetGradientPerturbAmp(float gradientPerturbAmp) { + m_gradientPerturbAmp = gradientPerturbAmp / (float) 0.45; + } + + private static class Float2 { + public final float x, y; + + public Float2(float x, float y) { + this.x = x; + this.y = y; + } + } + + private static class Float3 { + public final float x, y, z; + + public Float3(float x, float y, float z) { + this.x = x; + this.y = y; + this.z = z; + } + } + + private static final Float2[] GRAD_2D = {new Float2(-1, -1), new Float2(1, -1), new Float2(-1, 1), new Float2(1, 1), new Float2(0, -1), new Float2(-1, 0), new Float2(0, 1), new Float2(1, 0), + }; + + private static final Float3[] GRAD_3D = {new Float3(1, 1, 0), new Float3(-1, 1, 0), new Float3(1, -1, 0), new Float3(-1, -1, 0), new Float3(1, 0, 1), new Float3(-1, 0, 1), new Float3(1, 0, -1), new Float3(-1, 0, -1), new Float3(0, 1, 1), new Float3(0, -1, 1), new Float3(0, 1, -1), new Float3(0, -1, -1), new Float3(1, 1, 0), new Float3(0, -1, 1), new Float3(-1, 1, 0), new Float3(0, -1, -1), + }; + + private static final Float2[] CELL_2D = {new Float2(-0.4313539279f, 0.1281943404f), new Float2(-0.1733316799f, 0.415278375f), new Float2(-0.2821957395f, -0.3505218461f), new Float2(-0.2806473808f, 0.3517627718f), new Float2(0.3125508975f, -0.3237467165f), new Float2(0.3383018443f, -0.2967353402f), new Float2(-0.4393982022f, -0.09710417025f), new Float2(-0.4460443703f, -0.05953502905f), new Float2(-0.302223039f, 0.3334085102f), new Float2(-0.212681052f, -0.3965687458f), new Float2(-0.2991156529f, 0.3361990872f), new Float2(0.2293323691f, 0.3871778202f), new Float2(0.4475439151f, -0.04695150755f), new Float2(0.1777518f, 0.41340573f), new Float2(0.1688522499f, -0.4171197882f), new Float2(-0.0976597166f, 0.4392750616f), new Float2(0.08450188373f, 0.4419948321f), new Float2(-0.4098760448f, -0.1857461384f), new Float2(0.3476585782f, -0.2857157906f), new Float2(-0.3350670039f, -0.30038326f), new Float2(0.2298190031f, -0.3868891648f), new Float2(-0.01069924099f, 0.449872789f), new Float2(-0.4460141246f, -0.05976119672f), new Float2(0.3650293864f, 0.2631606867f), new Float2(-0.349479423f, 0.2834856838f), new Float2(-0.4122720642f, 0.1803655873f), new Float2(-0.267327811f, 0.3619887311f), new Float2(0.322124041f, -0.3142230135f), new Float2(0.2880445931f, -0.3457315612f), new Float2(0.3892170926f, -0.2258540565f), new Float2(0.4492085018f, -0.02667811596f), new Float2(-0.4497724772f, 0.01430799601f), new Float2(0.1278175387f, -0.4314657307f), new Float2(-0.03572100503f, 0.4485799926f), new Float2(-0.4297407068f, -0.1335025276f), new Float2(-0.3217817723f, 0.3145735065f), new Float2(-0.3057158873f, 0.3302087162f), new Float2(-0.414503978f, 0.1751754899f), new Float2(-0.3738139881f, 0.2505256519f), new Float2(0.2236891408f, -0.3904653228f), new Float2(0.002967775577f, -0.4499902136f), new Float2(0.1747128327f, -0.4146991995f), new Float2(-0.4423772489f, -0.08247647938f), new Float2(-0.2763960987f, -0.355112935f), new Float2(-0.4019385906f, -0.2023496216f), new Float2(0.3871414161f, -0.2293938184f), new Float2(-0.430008727f, 0.1326367019f), new Float2(-0.03037574274f, -0.4489736231f), new Float2(-0.3486181573f, 0.2845441624f), new Float2(0.04553517144f, -0.4476902368f), new Float2(-0.0375802926f, 0.4484280562f), new Float2(0.3266408905f, 0.3095250049f), new Float2(0.06540017593f, -0.4452222108f), new Float2(0.03409025829f, 0.448706869f), new Float2(-0.4449193635f, 0.06742966669f), new Float2(-0.4255936157f, -0.1461850686f), new Float2(0.449917292f, 0.008627302568f), new Float2(0.05242606404f, 0.4469356864f), new Float2(-0.4495305179f, -0.02055026661f), new Float2(-0.1204775703f, 0.4335725488f), new Float2(-0.341986385f, -0.2924813028f), new Float2(0.3865320182f, 0.2304191809f), new Float2(0.04506097811f, -0.447738214f), new Float2(-0.06283465979f, 0.4455915232f), new Float2(0.3932600341f, -0.2187385324f), new Float2(0.4472261803f, -0.04988730975f), new Float2(0.3753571011f, -0.2482076684f), new Float2(-0.273662295f, 0.357223947f), new Float2(0.1700461538f, 0.4166344988f), new Float2(0.4102692229f, 0.1848760794f), new Float2(0.323227187f, -0.3130881435f), new Float2(-0.2882310238f, -0.3455761521f), new Float2(0.2050972664f, 0.4005435199f), new Float2(0.4414085979f, -0.08751256895f), new Float2(-0.1684700334f, 0.4172743077f), new Float2(-0.003978032396f, 0.4499824166f), new Float2(-0.2055133639f, 0.4003301853f), new Float2(-0.006095674897f, -0.4499587123f), new Float2(-0.1196228124f, -0.4338091548f), new Float2(0.3901528491f, -0.2242337048f), new Float2(0.01723531752f, 0.4496698165f), new Float2(-0.3015070339f, 0.3340561458f), new Float2(-0.01514262423f, -0.4497451511f), new Float2(-0.4142574071f, -0.1757577897f), new Float2(-0.1916377265f, -0.4071547394f), new Float2(0.3749248747f, 0.2488600778f), new Float2(-0.2237774255f, 0.3904147331f), new Float2(-0.4166343106f, -0.1700466149f), new Float2(0.3619171625f, 0.267424695f), new Float2(0.1891126846f, -0.4083336779f), new Float2(-0.3127425077f, 0.323561623f), new Float2(-0.3281807787f, 0.307891826f), new Float2(-0.2294806661f, 0.3870899429f), new Float2(-0.3445266136f, 0.2894847362f), new Float2(-0.4167095422f, -0.1698621719f), new Float2(-0.257890321f, -0.3687717212f), new Float2(-0.3612037825f, 0.2683874578f), new Float2(0.2267996491f, 0.3886668486f), new Float2(0.207157062f, 0.3994821043f), new Float2(0.08355176718f, -0.4421754202f), new Float2(-0.4312233307f, 0.1286329626f), new Float2(0.3257055497f, 0.3105090899f), new Float2(0.177701095f, -0.4134275279f), new Float2(-0.445182522f, 0.06566979625f), new Float2(0.3955143435f, 0.2146355146f), new Float2(-0.4264613988f, 0.1436338239f), new Float2(-0.3793799665f, -0.2420141339f), new Float2(0.04617599081f, -0.4476245948f), new Float2(-0.371405428f, -0.2540826796f), new Float2(0.2563570295f, -0.3698392535f), new Float2(0.03476646309f, 0.4486549822f), new Float2(-0.3065454405f, 0.3294387544f), new Float2(-0.2256979823f, 0.3893076172f), new Float2(0.4116448463f, -0.1817925206f), new Float2(-0.2907745828f, -0.3434387019f), new Float2(0.2842278468f, -0.348876097f), new Float2(0.3114589359f, -0.3247973695f), new Float2(0.4464155859f, -0.0566844308f), new Float2(-0.3037334033f, -0.3320331606f), new Float2(0.4079607166f, 0.1899159123f), new Float2(-0.3486948919f, -0.2844501228f), new Float2(0.3264821436f, 0.3096924441f), new Float2(0.3211142406f, 0.3152548881f), new Float2(0.01183382662f, 0.4498443737f), new Float2(0.4333844092f, 0.1211526057f), new Float2(0.3118668416f, 0.324405723f), new Float2(-0.272753471f, 0.3579183483f), new Float2(-0.422228622f, -0.1556373694f), new Float2(-0.1009700099f, -0.4385260051f), new Float2(-0.2741171231f, -0.3568750521f), new Float2(-0.1465125133f, 0.4254810025f), new Float2(0.2302279044f, -0.3866459777f), new Float2(-0.3699435608f, 0.2562064828f), new Float2(0.105700352f, -0.4374099171f), new Float2(-0.2646713633f, 0.3639355292f), new Float2(0.3521828122f, 0.2801200935f), new Float2(-0.1864187807f, -0.4095705534f), new Float2(0.1994492955f, -0.4033856449f), new Float2(0.3937065066f, 0.2179339044f), new Float2(-0.3226158377f, 0.3137180602f), new Float2(0.3796235338f, 0.2416318948f), new Float2(0.1482921929f, 0.4248640083f), new Float2(-0.407400394f, 0.1911149365f), new Float2(0.4212853031f, 0.1581729856f), new Float2(-0.2621297173f, 0.3657704353f), new Float2(-0.2536986953f, -0.3716678248f), new Float2(-0.2100236383f, 0.3979825013f), new Float2(0.3624152444f, 0.2667493029f), new Float2(-0.3645038479f, -0.2638881295f), new Float2(0.2318486784f, 0.3856762766f), new Float2(-0.3260457004f, 0.3101519002f), new Float2(-0.2130045332f, -0.3963950918f), new Float2(0.3814998766f, -0.2386584257f), new Float2(-0.342977305f, 0.2913186713f), new Float2(-0.4355865605f, 0.1129794154f), new Float2(-0.2104679605f, 0.3977477059f), new Float2(0.3348364681f, -0.3006402163f), new Float2(0.3430468811f, 0.2912367377f), new Float2(-0.2291836801f, -0.3872658529f), new Float2(0.2547707298f, -0.3709337882f), new Float2(0.4236174945f, -0.151816397f), new Float2(-0.15387742f, 0.4228731957f), new Float2(-0.4407449312f, 0.09079595574f), new Float2(-0.06805276192f, -0.444824484f), new Float2(0.4453517192f, -0.06451237284f), new Float2(0.2562464609f, -0.3699158705f), new Float2(0.3278198355f, -0.3082761026f), new Float2(-0.4122774207f, -0.1803533432f), new Float2(0.3354090914f, -0.3000012356f), new Float2(0.446632869f, -0.05494615882f), new Float2(-0.1608953296f, 0.4202531296f), new Float2(-0.09463954939f, 0.4399356268f), new Float2(-0.02637688324f, -0.4492262904f), new Float2(0.447102804f, -0.05098119915f), new Float2(-0.4365670908f, 0.1091291678f), new Float2(-0.3959858651f, 0.2137643437f), new Float2(-0.4240048207f, -0.1507312575f), new Float2(-0.3882794568f, 0.2274622243f), new Float2(-0.4283652566f, -0.1378521198f), new Float2(0.3303888091f, 0.305521251f), new Float2(0.3321434919f, -0.3036127481f), new Float2(-0.413021046f, -0.1786438231f), new Float2(0.08403060337f, -0.4420846725f), new Float2(-0.3822882919f, 0.2373934748f), new Float2(-0.3712395594f, -0.2543249683f), new Float2(0.4472363971f, -0.04979563372f), new Float2(-0.4466591209f, 0.05473234629f), new Float2(0.0486272539f, -0.4473649407f), new Float2(-0.4203101295f, -0.1607463688f), new Float2(0.2205360833f, 0.39225481f), new Float2(-0.3624900666f, 0.2666476169f), new Float2(-0.4036086833f, -0.1989975647f), new Float2(0.2152727807f, 0.3951678503f), new Float2(-0.4359392962f, -0.1116106179f), new Float2(0.4178354266f, 0.1670735057f), new Float2(0.2007630161f, 0.4027334247f), new Float2(-0.07278067175f, -0.4440754146f), new Float2(0.3644748615f, -0.2639281632f), new Float2(-0.4317451775f, 0.126870413f), new Float2(-0.297436456f, 0.3376855855f), new Float2(-0.2998672222f, 0.3355289094f), new Float2(-0.2673674124f, 0.3619594822f), new Float2(0.2808423357f, 0.3516071423f), new Float2(0.3498946567f, 0.2829730186f), new Float2(-0.2229685561f, 0.390877248f), new Float2(0.3305823267f, 0.3053118493f), new Float2(-0.2436681211f, -0.3783197679f), new Float2(-0.03402776529f, 0.4487116125f), new Float2(-0.319358823f, 0.3170330301f), new Float2(0.4454633477f, -0.06373700535f), new Float2(0.4483504221f, 0.03849544189f), new Float2(-0.4427358436f, -0.08052932871f), new Float2(0.05452298565f, 0.4466847255f), new Float2(-0.2812560807f, 0.3512762688f), new Float2(0.1266696921f, 0.4318041097f), new Float2(-0.3735981243f, 0.2508474468f), new Float2(0.2959708351f, -0.3389708908f), new Float2(-0.3714377181f, 0.254035473f), new Float2(-0.404467102f, -0.1972469604f), new Float2(0.1636165687f, -0.419201167f), new Float2(0.3289185495f, -0.3071035458f), new Float2(-0.2494824991f, -0.3745109914f), new Float2(0.03283133272f, 0.4488007393f), new Float2(-0.166306057f, -0.4181414777f), new Float2(-0.106833179f, 0.4371346153f), new Float2(0.06440260376f, -0.4453676062f), new Float2(-0.4483230967f, 0.03881238203f), new Float2(-0.421377757f, -0.1579265206f), new Float2(0.05097920662f, -0.4471030312f), new Float2(0.2050584153f, -0.4005634111f), new Float2(0.4178098529f, -0.167137449f), new Float2(-0.3565189504f, -0.2745801121f), new Float2(0.4478398129f, 0.04403977727f), new Float2(-0.3399999602f, -0.2947881053f), new Float2(0.3767121994f, 0.2461461331f), new Float2(-0.3138934434f, 0.3224451987f), new Float2(-0.1462001792f, -0.4255884251f), new Float2(0.3970290489f, -0.2118205239f), new Float2(0.4459149305f, -0.06049689889f), new Float2(-0.4104889426f, -0.1843877112f), new Float2(0.1475103971f, -0.4251360756f), new Float2(0.09258030352f, 0.4403735771f), new Float2(-0.1589664637f, -0.4209865359f), new Float2(0.2482445008f, 0.3753327428f), new Float2(0.4383624232f, -0.1016778537f), new Float2(0.06242802956f, 0.4456486745f), new Float2(0.2846591015f, -0.3485243118f), new Float2(-0.344202744f, -0.2898697484f), new Float2(0.1198188883f, -0.4337550392f), new Float2(-0.243590703f, 0.3783696201f), new Float2(0.2958191174f, -0.3391033025f), new Float2(-0.1164007991f, 0.4346847754f), new Float2(0.1274037151f, -0.4315881062f), new Float2(0.368047306f, 0.2589231171f), new Float2(0.2451436949f, 0.3773652989f), new Float2(-0.4314509715f, 0.12786735f), + }; + + private static final Float3[] CELL_3D = {new Float3(0.1453787434f, -0.4149781685f, -0.0956981749f), new Float3(-0.01242829687f, -0.1457918398f, -0.4255470325f), new Float3(0.2877979582f, -0.02606483451f, -0.3449535616f), new Float3(-0.07732986802f, 0.2377094325f, 0.3741848704f), new Float3(0.1107205875f, -0.3552302079f, -0.2530858567f), new Float3(0.2755209141f, 0.2640521179f, -0.238463215f), new Float3(0.294168941f, 0.1526064594f, 0.3044271714f), new Float3(0.4000921098f, -0.2034056362f, 0.03244149937f), new Float3(-0.1697304074f, 0.3970864695f, -0.1265461359f), new Float3(-0.1483224484f, -0.3859694688f, 0.1775613147f), new Float3(0.2623596946f, -0.2354852944f, 0.2796677792f), new Float3(-0.2709003183f, 0.3505271138f, -0.07901746678f), new Float3(-0.03516550699f, 0.3885234328f, 0.2243054374f), new Float3(-0.1267712655f, 0.1920044036f, 0.3867342179f), new Float3(0.02952021915f, 0.4409685861f, 0.08470692262f), new Float3(-0.2806854217f, -0.266996757f, 0.2289725438f), new Float3(-0.171159547f, 0.2141185563f, 0.3568720405f), new Float3(0.2113227183f, 0.3902405947f, -0.07453178509f), new Float3(-0.1024352839f, 0.2128044156f, -0.3830421561f), new Float3(-0.3304249877f, -0.1566986703f, 0.2622305365f), new Float3(0.2091111325f, 0.3133278055f, -0.2461670583f), new Float3(0.344678154f, -0.1944240454f, -0.2142341261f), new Float3(0.1984478035f, -0.3214342325f, -0.2445373252f), new Float3(-0.2929008603f, 0.2262915116f, 0.2559320961f), new Float3(-0.1617332831f, 0.006314769776f, -0.4198838754f), new Float3(-0.3582060271f, -0.148303178f, -0.2284613961f), new Float3(-0.1852067326f, -0.3454119342f, -0.2211087107f), new Float3(0.3046301062f, 0.1026310383f, 0.314908508f), new Float3(-0.03816768434f, -0.2551766358f, -0.3686842991f), new Float3(-0.4084952196f, 0.1805950793f, 0.05492788837f), new Float3(-0.02687443361f, -0.2749741471f, 0.3551999201f), new Float3(-0.03801098351f, 0.3277859044f, 0.3059600725f), new Float3(0.2371120802f, 0.2900386767f, -0.2493099024f), new Float3(0.4447660503f, 0.03946930643f, 0.05590469027f), new Float3(0.01985147278f, -0.01503183293f, -0.4493105419f), new Float3(0.4274339143f, 0.03345994256f, -0.1366772882f), new Float3(-0.2072988631f, 0.2871414597f, -0.2776273824f), new Float3(-0.3791240978f, 0.1281177671f, 0.2057929936f), new Float3(-0.2098721267f, -0.1007087278f, -0.3851122467f), new Float3(0.01582798878f, 0.4263894424f, 0.1429738373f), new Float3(-0.1888129464f, -0.3160996813f, -0.2587096108f), new Float3(0.1612988974f, -0.1974805082f, -0.3707885038f), new Float3(-0.08974491322f, 0.229148752f, -0.3767448739f), new Float3(0.07041229526f, 0.4150230285f, -0.1590534329f), new Float3(-0.1082925611f, -0.1586061639f, 0.4069604477f), new Float3(0.2474100658f, -0.3309414609f, 0.1782302128f), new Float3(-0.1068836661f, -0.2701644537f, -0.3436379634f), new Float3(0.2396452163f, 0.06803600538f, -0.3747549496f), new Float3(-0.3063886072f, 0.2597428179f, 0.2028785103f), new Float3(0.1593342891f, -0.3114350249f, -0.2830561951f), new Float3(0.2709690528f, 0.1412648683f, -0.3303331794f), new Float3(-0.1519780427f, 0.3623355133f, 0.2193527988f), new Float3(0.1699773681f, 0.3456012883f, 0.2327390037f), new Float3(-0.1986155616f, 0.3836276443f, -0.1260225743f), new Float3(-0.1887482106f, -0.2050154888f, -0.353330953f), new Float3(0.2659103394f, 0.3015631259f, -0.2021172246f), new Float3(-0.08838976154f, -0.4288819642f, -0.1036702021f), new Float3(-0.04201869311f, 0.3099592485f, 0.3235115047f), new Float3(-0.3230334656f, 0.201549922f, -0.2398478873f), new Float3(0.2612720941f, 0.2759854499f, -0.2409749453f), new Float3(0.385713046f, 0.2193460345f, 0.07491837764f), new Float3(0.07654967953f, 0.3721732183f, 0.241095919f), new Float3(0.4317038818f, -0.02577753072f, 0.1243675091f), new Float3(-0.2890436293f, -0.3418179959f, -0.04598084447f), new Float3(-0.2201947582f, 0.383023377f, -0.08548310451f), new Float3(0.4161322773f, -0.1669634289f, -0.03817251927f), new Float3(0.2204718095f, 0.02654238946f, -0.391391981f), new Float3(-0.1040307469f, 0.3890079625f, -0.2008741118f), new Float3(-0.1432122615f, 0.371614387f, -0.2095065525f), new Float3(0.3978380468f, -0.06206669342f, 0.2009293758f), new Float3(-0.2599274663f, 0.2616724959f, -0.2578084893f), new Float3(0.4032618332f, -0.1124593585f, 0.1650235939f), new Float3(-0.08953470255f, -0.3048244735f, 0.3186935478f), new Float3(0.118937202f, -0.2875221847f, 0.325092195f), new Float3(0.02167047076f, -0.03284630549f, -0.4482761547f), new Float3(-0.3411343612f, 0.2500031105f, 0.1537068389f), new Float3(0.3162964612f, 0.3082064153f, -0.08640228117f), new Float3(0.2355138889f, -0.3439334267f, -0.1695376245f), new Float3(-0.02874541518f, -0.3955933019f, 0.2125550295f), new Float3(-0.2461455173f, 0.02020282325f, -0.3761704803f), new Float3(0.04208029445f, -0.4470439576f, 0.02968078139f), new Float3(0.2727458746f, 0.2288471896f, -0.2752065618f), new Float3(-0.1347522818f, -0.02720848277f, -0.4284874806f), new Float3(0.3829624424f, 0.1231931484f, -0.2016512234f), new Float3(-0.3547613644f, 0.1271702173f, 0.2459107769f), new Float3(0.2305790207f, 0.3063895591f, 0.2354968222f), new Float3(-0.08323845599f, -0.1922245118f, 0.3982726409f), new Float3(0.2993663085f, -0.2619918095f, -0.2103333191f), new Float3(-0.2154865723f, 0.2706747713f, 0.287751117f), new Float3(0.01683355354f, -0.2680655787f, -0.3610505186f), new Float3(0.05240429123f, 0.4335128183f, -0.1087217856f), new Float3(0.00940104872f, -0.4472890582f, 0.04841609928f), new Float3(0.3465688735f, 0.01141914583f, -0.2868093776f), new Float3(-0.3706867948f, -0.2551104378f, 0.003156692623f), new Float3(0.2741169781f, 0.2139972417f, -0.2855959784f), new Float3(0.06413433865f, 0.1708718512f, 0.4113266307f), new Float3(-0.388187972f, -0.03973280434f, -0.2241236325f), new Float3(0.06419469312f, -0.2803682491f, 0.3460819069f), new Float3(-0.1986120739f, -0.3391173584f, 0.2192091725f), new Float3(-0.203203009f, -0.3871641506f, 0.1063600375f), new Float3(-0.1389736354f, -0.2775901578f, -0.3257760473f), new Float3(-0.06555641638f, 0.342253257f, -0.2847192729f), new Float3(-0.2529246486f, -0.2904227915f, 0.2327739768f), new Float3(0.1444476522f, 0.1069184044f, 0.4125570634f), new Float3(-0.3643780054f, -0.2447099973f, -0.09922543227f), new Float3(0.4286142488f, -0.1358496089f, -0.01829506817f), new Float3(0.165872923f, -0.3136808464f, -0.2767498872f), new Float3(0.2219610524f, -0.3658139958f, 0.1393320198f), new Float3(0.04322940318f, -0.3832730794f, 0.2318037215f), new Float3(-0.08481269795f, -0.4404869674f, -0.03574965489f), new Float3(0.1822082075f, -0.3953259299f, 0.1140946023f), new Float3(-0.3269323334f, 0.3036542563f, 0.05838957105f), new Float3(-0.4080485344f, 0.04227858267f, -0.184956522f), new Float3(0.2676025294f, -0.01299671652f, 0.36155217f), new Float3(0.3024892441f, -0.1009990293f, -0.3174892964f), new Float3(0.1448494052f, 0.425921681f, -0.0104580805f), new Float3(0.4198402157f, 0.08062320474f, 0.1404780841f), new Float3(-0.3008872161f, -0.333040905f, -0.03241355801f), new Float3(0.3639310428f, -0.1291284382f, -0.2310412139f), new Float3(0.3295806598f, 0.0184175994f, -0.3058388149f), new Float3(0.2776259487f, -0.2974929052f, -0.1921504723f), new Float3(0.4149000507f, -0.144793182f, -0.09691688386f), new Float3(0.145016715f, -0.0398992945f, 0.4241205002f), new Float3(0.09299023471f, -0.299732164f, -0.3225111565f), new Float3(0.1028907093f, -0.361266869f, 0.247789732f), new Float3(0.2683057049f, -0.07076041213f, -0.3542668666f), new Float3(-0.4227307273f, -0.07933161816f, -0.1323073187f), new Float3(-0.1781224702f, 0.1806857196f, -0.3716517945f), new Float3(0.4390788626f, -0.02841848598f, -0.09435116353f), new Float3(0.2972583585f, 0.2382799621f, -0.2394997452f), new Float3(-0.1707002821f, 0.2215845691f, 0.3525077196f), new Float3(0.3806686614f, 0.1471852559f, -0.1895464869f), new Float3(-0.1751445661f, -0.274887877f, 0.3102596268f), new Float3(-0.2227237566f, -0.2316778837f, 0.3149912482f), new Float3(0.1369633021f, 0.1341343041f, -0.4071228836f), new Float3(-0.3529503428f, -0.2472893463f, -0.129514612f), new Float3(-0.2590744185f, -0.2985577559f, -0.2150435121f), new Float3(-0.3784019401f, 0.2199816631f, -0.1044989934f), new Float3(-0.05635805671f, 0.1485737441f, 0.4210102279f), new Float3(0.3251428613f, 0.09666046873f, -0.2957006485f), new Float3(-0.4190995804f, 0.1406751354f, -0.08405978803f), new Float3(-0.3253150961f, -0.3080335042f, -0.04225456877f), new Float3(0.2857945863f, -0.05796152095f, 0.3427271751f), new Float3(-0.2733604046f, 0.1973770973f, -0.2980207554f), new Float3(0.219003657f, 0.2410037886f, -0.3105713639f), new Float3(0.3182767252f, -0.271342949f, 0.1660509868f), new Float3(-0.03222023115f, -0.3331161506f, -0.300824678f), new Float3(-0.3087780231f, 0.1992794134f, -0.2596995338f), new Float3(-0.06487611647f, -0.4311322747f, 0.1114273361f), new Float3(0.3921171432f, -0.06294284106f, -0.2116183942f), new Float3(-0.1606404506f, -0.358928121f, -0.2187812825f), new Float3(-0.03767771199f, -0.2290351443f, 0.3855169162f), new Float3(0.1394866832f, -0.3602213994f, 0.2308332918f), new Float3(-0.4345093872f, 0.005751117145f, 0.1169124335f), new Float3(-0.1044637494f, 0.4168128432f, -0.1336202785f), new Float3(0.2658727501f, 0.2551943237f, 0.2582393035f), new Float3(0.2051461999f, 0.1975390727f, 0.3484154868f), new Float3(-0.266085566f, 0.23483312f, 0.2766800993f), new Float3(0.07849405464f, -0.3300346342f, -0.2956616708f), new Float3(-0.2160686338f, 0.05376451292f, -0.3910546287f), new Float3(-0.185779186f, 0.2148499206f, 0.3490352499f), new Float3(0.02492421743f, -0.3229954284f, -0.3123343347f), new Float3(-0.120167831f, 0.4017266681f, 0.1633259825f), new Float3(-0.02160084693f, -0.06885389554f, 0.4441762538f), new Float3(0.2597670064f, 0.3096300784f, 0.1978643903f), new Float3(-0.1611553854f, -0.09823036005f, 0.4085091653f), new Float3(-0.3278896792f, 0.1461670309f, 0.2713366126f), new Float3(0.2822734956f, 0.03754421121f, -0.3484423997f), new Float3(0.03169341113f, 0.347405252f, -0.2842624114f), new Float3(0.2202613604f, -0.3460788041f, -0.1849713341f), new Float3(0.2933396046f, 0.3031973659f, 0.1565989581f), new Float3(-0.3194922995f, 0.2453752201f, -0.200538455f), new Float3(-0.3441586045f, -0.1698856132f, -0.2349334659f), new Float3(0.2703645948f, -0.3574277231f, 0.04060059933f), new Float3(0.2298568861f, 0.3744156221f, 0.0973588921f), new Float3(0.09326603877f, -0.3170108894f, 0.3054595587f), new Float3(-0.1116165319f, -0.2985018719f, 0.3177080142f), new Float3(0.2172907365f, -0.3460005203f, -0.1885958001f), new Float3(0.1991339479f, 0.3820341668f, -0.1299829458f), new Float3(-0.0541918155f, -0.2103145071f, 0.39412061f), new Float3(0.08871336998f, 0.2012117383f, 0.3926114802f), new Float3(0.2787673278f, 0.3505404674f, 0.04370535101f), new Float3(-0.322166438f, 0.3067213525f, 0.06804996813f), new Float3(-0.4277366384f, 0.132066775f, 0.04582286686f), new Float3(0.240131882f, -0.1612516055f, 0.344723946f), new Float3(0.1448607981f, -0.2387819045f, 0.3528435224f), new Float3(-0.3837065682f, -0.2206398454f, 0.08116235683f), new Float3(-0.4382627882f, -0.09082753406f, -0.04664855374f), new Float3(-0.37728353f, 0.05445141085f, 0.2391488697f), new Float3(0.1259579313f, 0.348394558f, 0.2554522098f), new Float3(-0.1406285511f, -0.270877371f, -0.3306796947f), new Float3(-0.1580694418f, 0.4162931958f, -0.06491553533f), new Float3(0.2477612106f, -0.2927867412f, -0.2353514536f), new Float3(0.2916132853f, 0.3312535401f, 0.08793624968f), new Float3(0.07365265219f, -0.1666159848f, 0.411478311f), new Float3(-0.26126526f, -0.2422237692f, 0.2748965434f), new Float3(-0.3721862032f, 0.252790166f, 0.008634938242f), new Float3(-0.3691191571f, -0.255281188f, 0.03290232422f), new Float3(0.2278441737f, -0.3358364886f, 0.1944244981f), new Float3(0.363398169f, -0.2310190248f, 0.1306597909f), new Float3(-0.304231482f, -0.2698452035f, 0.1926830856f), new Float3(-0.3199312232f, 0.316332536f, -0.008816977938f), new Float3(0.2874852279f, 0.1642275508f, -0.304764754f), new Float3(-0.1451096801f, 0.3277541114f, -0.2720669462f), new Float3(0.3220090754f, 0.0511344108f, 0.3101538769f), new Float3(-0.1247400865f, -0.04333605335f, -0.4301882115f), new Float3(-0.2829555867f, -0.3056190617f, -0.1703910946f), new Float3(0.1069384374f, 0.3491024667f, -0.2630430352f), new Float3(-0.1420661144f, -0.3055376754f, -0.2982682484f), new Float3(-0.250548338f, 0.3156466809f, -0.2002316239f), new Float3(0.3265787872f, 0.1871229129f, 0.2466400438f), new Float3(0.07646097258f, -0.3026690852f, 0.324106687f), new Float3(0.3451771584f, 0.2757120714f, -0.0856480183f), new Float3(0.298137964f, 0.2852657134f, 0.179547284f), new Float3(0.2812250376f, 0.3466716415f, 0.05684409612f), new Float3(0.4390345476f, -0.09790429955f, -0.01278335452f), new Float3(0.2148373234f, 0.1850172527f, 0.3494474791f), new Float3(0.2595421179f, -0.07946825393f, 0.3589187731f), new Float3(0.3182823114f, -0.307355516f, -0.08203022006f), new Float3(-0.4089859285f, -0.04647718411f, 0.1818526372f), new Float3(-0.2826749061f, 0.07417482322f, 0.3421885344f), new Float3(0.3483864637f, 0.225442246f, -0.1740766085f), new Float3(-0.3226415069f, -0.1420585388f, -0.2796816575f), new Float3(0.4330734858f, -0.118868561f, -0.02859407492f), new Float3(-0.08717822568f, -0.3909896417f, -0.2050050172f), new Float3(-0.2149678299f, 0.3939973956f, -0.03247898316f), new Float3(-0.2687330705f, 0.322686276f, -0.1617284888f), new Float3(0.2105665099f, -0.1961317136f, -0.3459683451f), new Float3(0.4361845915f, -0.1105517485f, 0.004616608544f), new Float3(0.05333333359f, -0.313639498f, -0.3182543336f), new Float3(-0.05986216652f, 0.1361029153f, -0.4247264031f), new Float3(0.3664988455f, 0.2550543014f, -0.05590974511f), new Float3(-0.2341015558f, -0.182405731f, 0.3382670703f), new Float3(-0.04730947785f, -0.4222150243f, -0.1483114513f), new Float3(-0.2391566239f, -0.2577696514f, -0.2808182972f), new Float3(-0.1242081035f, 0.4256953395f, -0.07652336246f), new Float3(0.2614832715f, -0.3650179274f, 0.02980623099f), new Float3(-0.2728794681f, -0.3499628774f, 0.07458404908f), new Float3(0.007892900508f, -0.1672771315f, 0.4176793787f), new Float3(-0.01730330376f, 0.2978486637f, -0.3368779738f), new Float3(0.2054835762f, -0.3252600376f, -0.2334146693f), new Float3(-0.3231994983f, 0.1564282844f, -0.2712420987f), new Float3(-0.2669545963f, 0.2599343665f, -0.2523278991f), new Float3(-0.05554372779f, 0.3170813944f, -0.3144428146f), new Float3(-0.2083935713f, -0.310922837f, -0.2497981362f), new Float3(0.06989323478f, -0.3156141536f, 0.3130537363f), new Float3(0.3847566193f, -0.1605309138f, -0.1693876312f), new Float3(-0.3026215288f, -0.3001537679f, -0.1443188342f), new Float3(0.3450735512f, 0.08611519592f, 0.2756962409f), new Float3(0.1814473292f, -0.2788782453f, -0.3029914042f), new Float3(-0.03855010448f, 0.09795110726f, 0.4375151083f), new Float3(0.3533670318f, 0.2665752752f, 0.08105160988f), new Float3(-0.007945601311f, 0.140359426f, -0.4274764309f), new Float3(0.4063099273f, -0.1491768253f, -0.1231199324f), new Float3(-0.2016773589f, 0.008816271194f, -0.4021797064f), new Float3(-0.07527055435f, -0.425643481f, -0.1251477955f), + }; + + private static int FastFloor(float f) { + return (f >= 0 ? (int) f : (int) f - 1); + } + + private static int FastRound(float f) { + return (f >= 0) ? (int) (f + (float) 0.5) : (int) (f - (float) 0.5); + } + + private static float Lerp(float a, float b, float t) { + return a + t * (b - a); + } + + private static float InterpHermiteFunc(float t) { + return t * t * (3 - 2 * t); + } + + private static float InterpQuinticFunc(float t) { + return t * t * t * (t * (t * 6 - 15) + 10); + } + + private static float CubicLerp(float a, float b, float c, float d, float t) { + float p = (d - c) - (a - b); + return t * t * t * p + t * t * ((a - b) - p) + t * (c - a) + b; + } + + private void CalculateFractalBounding() { + float amp = m_gain; + float ampFractal = 1; + for (int i = 1; i < m_octaves; i++) { + ampFractal += amp; + amp *= m_gain; + } + m_fractalBounding = 1 / ampFractal; + } + + // Hashing + private final static int X_PRIME = 1619; + private final static int Y_PRIME = 31337; + private final static int Z_PRIME = 6971; + private final static int W_PRIME = 1013; + + private static int Hash2D(int seed, int x, int y) { + int hash = seed; + hash ^= X_PRIME * x; + hash ^= Y_PRIME * y; + + hash = hash * hash * hash * 60493; + hash = (hash >> 13) ^ hash; + + return hash; + } + + private static int Hash3D(int seed, int x, int y, int z) { + int hash = seed; + hash ^= X_PRIME * x; + hash ^= Y_PRIME * y; + hash ^= Z_PRIME * z; + + hash = hash * hash * hash * 60493; + hash = (hash >> 13) ^ hash; + + return hash; + } + + public static int Hash4D(int seed, int x, int y, int z, int w) { + int hash = seed; + hash ^= X_PRIME * x; + hash ^= Y_PRIME * y; + hash ^= Z_PRIME * z; + hash ^= W_PRIME * w; + + hash = hash * hash * hash * 60493; + hash = (hash >> 13) ^ hash; + + return hash; + } + + private static float ValCoord2D(int seed, int x, int y) { + int n = seed; + n ^= X_PRIME * x; + n ^= Y_PRIME * y; + + return (n * n * n * 60493) / (float) 2147483648.0; + } + + private static float ValCoord3D(int seed, int x, int y, int z) { + int n = seed; + n ^= X_PRIME * x; + n ^= Y_PRIME * y; + n ^= Z_PRIME * z; + + return (n * n * n * 60493) / (float) 2147483648.0; + } + + private static float ValCoord4D(int seed, int x, int y, int z, int w) { + int n = seed; + n ^= X_PRIME * x; + n ^= Y_PRIME * y; + n ^= Z_PRIME * z; + n ^= W_PRIME * w; + + return (n * n * n * 60493) / (float) 2147483648.0; + } + + private static float GradCoord2D(int seed, int x, int y, float xd, float yd) { + int hash = seed; + hash ^= X_PRIME * x; + hash ^= Y_PRIME * y; + + hash = hash * hash * hash * 60493; + hash = (hash >> 13) ^ hash; + + Float2 g = GRAD_2D[hash & 7]; + + return xd * g.x + yd * g.y; + } + + private static float GradCoord3D(int seed, int x, int y, int z, float xd, float yd, float zd) { + int hash = seed; + hash ^= X_PRIME * x; + hash ^= Y_PRIME * y; + hash ^= Z_PRIME * z; + + hash = hash * hash * hash * 60493; + hash = (hash >> 13) ^ hash; + + Float3 g = GRAD_3D[hash & 15]; + + return xd * g.x + yd * g.y + zd * g.z; + } + + private static float GradCoord4D(int seed, int x, int y, int z, int w, float xd, float yd, float zd, float wd) { + int hash = seed; + hash ^= X_PRIME * x; + hash ^= Y_PRIME * y; + hash ^= Z_PRIME * z; + hash ^= W_PRIME * w; + + hash = hash * hash * hash * 60493; + hash = (hash >> 13) ^ hash; + + hash &= 31; + float a = yd, b = zd, c = wd; // X,Y,Z + switch (hash >> 3) { // OR, DEPENDING ON HIGH ORDER 2 BITS: + case 1: + a = wd; + b = xd; + c = yd; + break; // W,X,Y + case 2: + a = zd; + b = wd; + c = xd; + break; // Z,W,X + case 3: + a = yd; + b = zd; + c = wd; + break; // Y,Z,W + } + return ((hash & 4) == 0 ? -a : a) + ((hash & 2) == 0 ? -b : b) + ((hash & 1) == 0 ? -c : c); + } + + public float GetNoise(float x, float y, float z) { + x *= m_frequency; + y *= m_frequency; + z *= m_frequency; + + switch (m_noiseType) { + case Value: + return SingleValue(m_seed, x, y, z); + case ValueFractal: + switch (m_fractalType) { + case FBM: + return SingleValueFractalFBM(x, y, z); + case Billow: + return SingleValueFractalBillow(x, y, z); + case RigidMulti: + return SingleValueFractalRigidMulti(x, y, z); + default: + return 0; + } + case Perlin: + return SinglePerlin(m_seed, x, y, z); + case PerlinFractal: + switch (m_fractalType) { + case FBM: + return SinglePerlinFractalFBM(x, y, z); + case Billow: + return SinglePerlinFractalBillow(x, y, z); + case RigidMulti: + return SinglePerlinFractalRigidMulti(x, y, z); + default: + return 0; + } + case Simplex: + return SingleSimplex(m_seed, x, y, z); + case SimplexFractal: + switch (m_fractalType) { + case FBM: + return SingleSimplexFractalFBM(x, y, z); + case Billow: + return SingleSimplexFractalBillow(x, y, z); + case RigidMulti: + return SingleSimplexFractalRigidMulti(x, y, z); + default: + return 0; + } + case Cellular: + switch (m_cellularReturnType) { + case CellValue: + case NoiseLookup: + case Distance: + return SingleCellular(x, y, z); + default: + return SingleCellular2Edge(x, y, z); + } + case WhiteNoise: + return GetWhiteNoise(x, y, z); + case Cubic: + return SingleCubic(m_seed, x, y, z); + case CubicFractal: + switch (m_fractalType) { + case FBM: + return SingleCubicFractalFBM(x, y, z); + case Billow: + return SingleCubicFractalBillow(x, y, z); + case RigidMulti: + return SingleCubicFractalRigidMulti(x, y, z); + default: + return 0; + } + default: + return 0; + } + } + + public float GetNoise(float x, float y) { + x *= m_frequency; + y *= m_frequency; + + switch (m_noiseType) { + case Value: + return SingleValue(m_seed, x, y); + case ValueFractal: + switch (m_fractalType) { + case FBM: + return SingleValueFractalFBM(x, y); + case Billow: + return SingleValueFractalBillow(x, y); + case RigidMulti: + return SingleValueFractalRigidMulti(x, y); + default: + return 0; + } + case Perlin: + return SinglePerlin(m_seed, x, y); + case PerlinFractal: + switch (m_fractalType) { + case FBM: + return SinglePerlinFractalFBM(x, y); + case Billow: + return SinglePerlinFractalBillow(x, y); + case RigidMulti: + return SinglePerlinFractalRigidMulti(x, y); + default: + return 0; + } + case Simplex: + return SingleSimplex(m_seed, x, y); + case SimplexFractal: + switch (m_fractalType) { + case FBM: + return SingleSimplexFractalFBM(x, y); + case Billow: + return SingleSimplexFractalBillow(x, y); + case RigidMulti: + return SingleSimplexFractalRigidMulti(x, y); + default: + return 0; + } + case Cellular: + switch (m_cellularReturnType) { + case CellValue: + case NoiseLookup: + case Distance: + return SingleCellular(x, y); + default: + return SingleCellular2Edge(x, y); + } + case WhiteNoise: + return GetWhiteNoise(x, y); + case Cubic: + return SingleCubic(m_seed, x, y); + case CubicFractal: + switch (m_fractalType) { + case FBM: + return SingleCubicFractalFBM(x, y); + case Billow: + return SingleCubicFractalBillow(x, y); + case RigidMulti: + return SingleCubicFractalRigidMulti(x, y); + default: + return 0; + } + default: + return 0; + } + } + + // White Noise + + private int FloatCast2Int(float f) { + int i = Float.floatToRawIntBits(f); + + return i ^ (i >> 16); + } + + public float GetWhiteNoise(float x, float y, float z, float w) { + int xi = FloatCast2Int(x); + int yi = FloatCast2Int(y); + int zi = FloatCast2Int(z); + int wi = FloatCast2Int(w); + + return ValCoord4D(m_seed, xi, yi, zi, wi); + } + + public float GetWhiteNoise(double x, double y, double z) { + int xi = FloatCast2Int((float) x); + int yi = FloatCast2Int((float) y); + int zi = FloatCast2Int((float) z); + + return ValCoord3D(m_seed, xi, yi, zi); + } + + public float GetWhiteNoise(double x, double y) { + int xi = FloatCast2Int((float) x); + int yi = FloatCast2Int((float) y); + + return ValCoord2D(m_seed, xi, yi); + } + + public float GetWhiteNoiseInt(int x, int y, int z, int w) { + return ValCoord4D(m_seed, x, y, z, w); + } + + public float GetWhiteNoiseInt(int x, int y, int z) { + return ValCoord3D(m_seed, x, y, z); + } + + public float GetWhiteNoiseInt(int x, int y) { + return ValCoord2D(m_seed, x, y); + } + + // Value Noise + public float GetValueFractal(float x, float y, float z) { + x *= m_frequency; + y *= m_frequency; + z *= m_frequency; + + switch (m_fractalType) { + case FBM: + return SingleValueFractalFBM(x, y, z); + case Billow: + return SingleValueFractalBillow(x, y, z); + case RigidMulti: + return SingleValueFractalRigidMulti(x, y, z); + default: + return 0; + } + } + + private float SingleValueFractalFBM(float x, float y, float z) { + int seed = m_seed; + float sum = SingleValue(seed, x, y, z); + float amp = 1; + + for (int i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum += SingleValue(++seed, x, y, z) * amp; + } + + return sum * m_fractalBounding; + } + + private float SingleValueFractalBillow(float x, float y, float z) { + int seed = m_seed; + float sum = Math.abs(SingleValue(seed, x, y, z)) * 2 - 1; + float amp = 1; + + for (int i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum += (Math.abs(SingleValue(++seed, x, y, z)) * 2 - 1) * amp; + } + + return sum * m_fractalBounding; + } + + private float SingleValueFractalRigidMulti(float x, float y, float z) { + int seed = m_seed; + float sum = 1 - Math.abs(SingleValue(seed, x, y, z)); + float amp = 1; + + for (int i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum -= (1 - Math.abs(SingleValue(++seed, x, y, z))) * amp; + } + + return sum; + } + + public float GetValue(float x, float y, float z) { + return SingleValue(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); + } + + private float SingleValue(int seed, float x, float y, float z) { + int x0 = FastFloor(x); + int y0 = FastFloor(y); + int z0 = FastFloor(z); + int x1 = x0 + 1; + int y1 = y0 + 1; + int z1 = z0 + 1; + + float xs, ys, zs; + switch (m_interp) { + default: + case Linear: + xs = x - x0; + ys = y - y0; + zs = z - z0; + break; + case Hermite: + xs = InterpHermiteFunc(x - x0); + ys = InterpHermiteFunc(y - y0); + zs = InterpHermiteFunc(z - z0); + break; + case Quintic: + xs = InterpQuinticFunc(x - x0); + ys = InterpQuinticFunc(y - y0); + zs = InterpQuinticFunc(z - z0); + break; + } + + float xf00 = Lerp(ValCoord3D(seed, x0, y0, z0), ValCoord3D(seed, x1, y0, z0), xs); + float xf10 = Lerp(ValCoord3D(seed, x0, y1, z0), ValCoord3D(seed, x1, y1, z0), xs); + float xf01 = Lerp(ValCoord3D(seed, x0, y0, z1), ValCoord3D(seed, x1, y0, z1), xs); + float xf11 = Lerp(ValCoord3D(seed, x0, y1, z1), ValCoord3D(seed, x1, y1, z1), xs); + + float yf0 = Lerp(xf00, xf10, ys); + float yf1 = Lerp(xf01, xf11, ys); + + return Lerp(yf0, yf1, zs); + } + + public float GetValueFractal(float x, float y) { + x *= m_frequency; + y *= m_frequency; + + switch (m_fractalType) { + case FBM: + return SingleValueFractalFBM(x, y); + case Billow: + return SingleValueFractalBillow(x, y); + case RigidMulti: + return SingleValueFractalRigidMulti(x, y); + default: + return 0; + } + } + + private float SingleValueFractalFBM(float x, float y) { + int seed = m_seed; + float sum = SingleValue(seed, x, y); + float amp = 1; + + for (int i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + + amp *= m_gain; + sum += SingleValue(++seed, x, y) * amp; + } + + return sum * m_fractalBounding; + } + + private float SingleValueFractalBillow(float x, float y) { + int seed = m_seed; + float sum = Math.abs(SingleValue(seed, x, y)) * 2 - 1; + float amp = 1; + + for (int i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + amp *= m_gain; + sum += (Math.abs(SingleValue(++seed, x, y)) * 2 - 1) * amp; + } + + return sum * m_fractalBounding; + } + + private float SingleValueFractalRigidMulti(float x, float y) { + int seed = m_seed; + float sum = 1 - Math.abs(SingleValue(seed, x, y)); + float amp = 1; + + for (int i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + + amp *= m_gain; + sum -= (1 - Math.abs(SingleValue(++seed, x, y))) * amp; + } + + return sum; + } + + public float GetValue(float x, float y) { + return SingleValue(m_seed, x * m_frequency, y * m_frequency); + } + + private float SingleValue(int seed, float x, float y) { + int x0 = FastFloor(x); + int y0 = FastFloor(y); + int x1 = x0 + 1; + int y1 = y0 + 1; + + float xs, ys; + switch (m_interp) { + default: + case Linear: + xs = x - x0; + ys = y - y0; + break; + case Hermite: + xs = InterpHermiteFunc(x - x0); + ys = InterpHermiteFunc(y - y0); + break; + case Quintic: + xs = InterpQuinticFunc(x - x0); + ys = InterpQuinticFunc(y - y0); + break; + } + + float xf0 = Lerp(ValCoord2D(seed, x0, y0), ValCoord2D(seed, x1, y0), xs); + float xf1 = Lerp(ValCoord2D(seed, x0, y1), ValCoord2D(seed, x1, y1), xs); + + return Lerp(xf0, xf1, ys); + } + + // Gradient Noise + public float GetPerlinFractal(float x, float y, float z) { + x *= m_frequency; + y *= m_frequency; + z *= m_frequency; + + switch (m_fractalType) { + case FBM: + return SinglePerlinFractalFBM(x, y, z); + case Billow: + return SinglePerlinFractalBillow(x, y, z); + case RigidMulti: + return SinglePerlinFractalRigidMulti(x, y, z); + default: + return 0; + } + } + + private float SinglePerlinFractalFBM(float x, float y, float z) { + int seed = m_seed; + float sum = SinglePerlin(seed, x, y, z); + float amp = 1; + + for (int i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum += SinglePerlin(++seed, x, y, z) * amp; + } + + return sum * m_fractalBounding; + } + + private float SinglePerlinFractalBillow(float x, float y, float z) { + int seed = m_seed; + float sum = Math.abs(SinglePerlin(seed, x, y, z)) * 2 - 1; + float amp = 1; + + for (int i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum += (Math.abs(SinglePerlin(++seed, x, y, z)) * 2 - 1) * amp; + } + + return sum * m_fractalBounding; + } + + private float SinglePerlinFractalRigidMulti(float x, float y, float z) { + int seed = m_seed; + float sum = 1 - Math.abs(SinglePerlin(seed, x, y, z)); + float amp = 1; + + for (int i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum -= (1 - Math.abs(SinglePerlin(++seed, x, y, z))) * amp; + } + + return sum; + } + + public float GetPerlin(float x, float y, float z) { + return SinglePerlin(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); + } + + private float SinglePerlin(int seed, float x, float y, float z) { + int x0 = FastFloor(x); + int y0 = FastFloor(y); + int z0 = FastFloor(z); + int x1 = x0 + 1; + int y1 = y0 + 1; + int z1 = z0 + 1; + + float xs, ys, zs; + switch (m_interp) { + default: + case Linear: + xs = x - x0; + ys = y - y0; + zs = z - z0; + break; + case Hermite: + xs = InterpHermiteFunc(x - x0); + ys = InterpHermiteFunc(y - y0); + zs = InterpHermiteFunc(z - z0); + break; + case Quintic: + xs = InterpQuinticFunc(x - x0); + ys = InterpQuinticFunc(y - y0); + zs = InterpQuinticFunc(z - z0); + break; + } + + float xd0 = x - x0; + float yd0 = y - y0; + float zd0 = z - z0; + float xd1 = xd0 - 1; + float yd1 = yd0 - 1; + float zd1 = zd0 - 1; + + float xf00 = Lerp(GradCoord3D(seed, x0, y0, z0, xd0, yd0, zd0), GradCoord3D(seed, x1, y0, z0, xd1, yd0, zd0), xs); + float xf10 = Lerp(GradCoord3D(seed, x0, y1, z0, xd0, yd1, zd0), GradCoord3D(seed, x1, y1, z0, xd1, yd1, zd0), xs); + float xf01 = Lerp(GradCoord3D(seed, x0, y0, z1, xd0, yd0, zd1), GradCoord3D(seed, x1, y0, z1, xd1, yd0, zd1), xs); + float xf11 = Lerp(GradCoord3D(seed, x0, y1, z1, xd0, yd1, zd1), GradCoord3D(seed, x1, y1, z1, xd1, yd1, zd1), xs); + + float yf0 = Lerp(xf00, xf10, ys); + float yf1 = Lerp(xf01, xf11, ys); + + return Lerp(yf0, yf1, zs); + } + + public float GetPerlinFractal(float x, float y) { + x *= m_frequency; + y *= m_frequency; + + switch (m_fractalType) { + case FBM: + return SinglePerlinFractalFBM(x, y); + case Billow: + return SinglePerlinFractalBillow(x, y); + case RigidMulti: + return SinglePerlinFractalRigidMulti(x, y); + default: + return 0; + } + } + + private float SinglePerlinFractalFBM(float x, float y) { + int seed = m_seed; + float sum = SinglePerlin(seed, x, y); + float amp = 1; + + for (int i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + + amp *= m_gain; + sum += SinglePerlin(++seed, x, y) * amp; + } + + return sum * m_fractalBounding; + } + + private float SinglePerlinFractalBillow(float x, float y) { + int seed = m_seed; + float sum = Math.abs(SinglePerlin(seed, x, y)) * 2 - 1; + float amp = 1; + + for (int i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + + amp *= m_gain; + sum += (Math.abs(SinglePerlin(++seed, x, y)) * 2 - 1) * amp; + } + + return sum * m_fractalBounding; + } + + private float SinglePerlinFractalRigidMulti(float x, float y) { + int seed = m_seed; + float sum = 1 - Math.abs(SinglePerlin(seed, x, y)); + float amp = 1; + + for (int i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + + amp *= m_gain; + sum -= (1 - Math.abs(SinglePerlin(++seed, x, y))) * amp; + } + + return sum; + } + + public float GetPerlin(float x, float y) { + return SinglePerlin(m_seed, x * m_frequency, y * m_frequency); + } + + private float SinglePerlin(int seed, float x, float y) { + int x0 = FastFloor(x); + int y0 = FastFloor(y); + int x1 = x0 + 1; + int y1 = y0 + 1; + + float xs, ys; + switch (m_interp) { + default: + case Linear: + xs = x - x0; + ys = y - y0; + break; + case Hermite: + xs = InterpHermiteFunc(x - x0); + ys = InterpHermiteFunc(y - y0); + break; + case Quintic: + xs = InterpQuinticFunc(x - x0); + ys = InterpQuinticFunc(y - y0); + break; + } + + float xd0 = x - x0; + float yd0 = y - y0; + float xd1 = xd0 - 1; + float yd1 = yd0 - 1; + + float xf0 = Lerp(GradCoord2D(seed, x0, y0, xd0, yd0), GradCoord2D(seed, x1, y0, xd1, yd0), xs); + float xf1 = Lerp(GradCoord2D(seed, x0, y1, xd0, yd1), GradCoord2D(seed, x1, y1, xd1, yd1), xs); + + return Lerp(xf0, xf1, ys); + } + + // Simplex Noise + public float GetSimplexFractal(float x, float y, float z) { + x *= m_frequency; + y *= m_frequency; + z *= m_frequency; + + switch (m_fractalType) { + case FBM: + return SingleSimplexFractalFBM(x, y, z); + case Billow: + return SingleSimplexFractalBillow(x, y, z); + case RigidMulti: + return SingleSimplexFractalRigidMulti(x, y, z); + default: + return 0; + } + } + + private float SingleSimplexFractalFBM(float x, float y, float z) { + int seed = m_seed; + float sum = SingleSimplex(seed, x, y, z); + float amp = 1; + + for (int i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum += SingleSimplex(++seed, x, y, z) * amp; + } + + return sum * m_fractalBounding; + } + + private float SingleSimplexFractalBillow(float x, float y, float z) { + int seed = m_seed; + float sum = Math.abs(SingleSimplex(seed, x, y, z)) * 2 - 1; + float amp = 1; + + for (int i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum += (Math.abs(SingleSimplex(++seed, x, y, z)) * 2 - 1) * amp; + } + + return sum * m_fractalBounding; + } + + private float SingleSimplexFractalRigidMulti(float x, float y, float z) { + int seed = m_seed; + float sum = 1 - Math.abs(SingleSimplex(seed, x, y, z)); + float amp = 1; + + for (int i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum -= (1 - Math.abs(SingleSimplex(++seed, x, y, z))) * amp; + } + + return sum; + } + + public float GetSimplex(float x, float y, float z) { + return SingleSimplex(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); + } + + private final static float F3 = (float) (1.0 / 3.0); + private final static float G3 = (float) (1.0 / 6.0); + private final static float G33 = G3 * 3 - 1; + + private float SingleSimplex(int seed, float x, float y, float z) { + float t = (x + y + z) * F3; + int i = FastFloor(x + t); + int j = FastFloor(y + t); + int k = FastFloor(z + t); + + t = (i + j + k) * G3; + float x0 = x - (i - t); + float y0 = y - (j - t); + float z0 = z - (k - t); + + int i1, j1, k1; + int i2, j2, k2; + + if (x0 >= y0) { + if (y0 >= z0) { + i1 = 1; + j1 = 0; + k1 = 0; + i2 = 1; + j2 = 1; + k2 = 0; + } else if (x0 >= z0) { + i1 = 1; + j1 = 0; + k1 = 0; + i2 = 1; + j2 = 0; + k2 = 1; + } else // x0 < z0 + { + i1 = 0; + j1 = 0; + k1 = 1; + i2 = 1; + j2 = 0; + k2 = 1; + } + } else // x0 < y0 + { + if (y0 < z0) { + i1 = 0; + j1 = 0; + k1 = 1; + i2 = 0; + j2 = 1; + k2 = 1; + } else if (x0 < z0) { + i1 = 0; + j1 = 1; + k1 = 0; + i2 = 0; + j2 = 1; + k2 = 1; + } else // x0 >= z0 + { + i1 = 0; + j1 = 1; + k1 = 0; + i2 = 1; + j2 = 1; + k2 = 0; + } + } + + float x1 = x0 - i1 + G3; + float y1 = y0 - j1 + G3; + float z1 = z0 - k1 + G3; + float x2 = x0 - i2 + F3; + float y2 = y0 - j2 + F3; + float z2 = z0 - k2 + F3; + float x3 = x0 + G33; + float y3 = y0 + G33; + float z3 = z0 + G33; + + float n0, n1, n2, n3; + + t = (float) 0.6 - x0 * x0 - y0 * y0 - z0 * z0; + if (t < 0) + n0 = 0; + else { + t *= t; + n0 = t * t * GradCoord3D(seed, i, j, k, x0, y0, z0); + } + + t = (float) 0.6 - x1 * x1 - y1 * y1 - z1 * z1; + if (t < 0) + n1 = 0; + else { + t *= t; + n1 = t * t * GradCoord3D(seed, i + i1, j + j1, k + k1, x1, y1, z1); + } + + t = (float) 0.6 - x2 * x2 - y2 * y2 - z2 * z2; + if (t < 0) + n2 = 0; + else { + t *= t; + n2 = t * t * GradCoord3D(seed, i + i2, j + j2, k + k2, x2, y2, z2); + } + + t = (float) 0.6 - x3 * x3 - y3 * y3 - z3 * z3; + if (t < 0) + n3 = 0; + else { + t *= t; + n3 = t * t * GradCoord3D(seed, i + 1, j + 1, k + 1, x3, y3, z3); + } + + return 32 * (n0 + n1 + n2 + n3); + } + + public float GetSimplexFractal(float x, float y) { + x *= m_frequency; + y *= m_frequency; + + switch (m_fractalType) { + case FBM: + return SingleSimplexFractalFBM(x, y); + case Billow: + return SingleSimplexFractalBillow(x, y); + case RigidMulti: + return SingleSimplexFractalRigidMulti(x, y); + default: + return 0; + } + } + + private float SingleSimplexFractalFBM(float x, float y) { + int seed = m_seed; + float sum = SingleSimplex(seed, x, y); + float amp = 1; + + for (int i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + + amp *= m_gain; + sum += SingleSimplex(++seed, x, y) * amp; + } + + return sum * m_fractalBounding; + } + + private float SingleSimplexFractalBillow(float x, float y) { + int seed = m_seed; + float sum = Math.abs(SingleSimplex(seed, x, y)) * 2 - 1; + float amp = 1; + + for (int i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + + amp *= m_gain; + sum += (Math.abs(SingleSimplex(++seed, x, y)) * 2 - 1) * amp; + } + + return sum * m_fractalBounding; + } + + private float SingleSimplexFractalRigidMulti(float x, float y) { + int seed = m_seed; + float sum = 1 - Math.abs(SingleSimplex(seed, x, y)); + float amp = 1; + + for (int i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + + amp *= m_gain; + sum -= (1 - Math.abs(SingleSimplex(++seed, x, y))) * amp; + } + + return sum; + } + + public float GetSimplex(float x, float y) { + return SingleSimplex(m_seed, x * m_frequency, y * m_frequency); + } + + // private final static float F2 = (float) (1.0 / 2.0); + // private final static float G2 = (float) (1.0 / 4.0); + + private final static float SQRT3 = (float) 1.7320508075688772935274463415059; + private final static float F2 = 0.5f * (SQRT3 - 1.0f); + private final static float G2 = (3.0f - SQRT3) / 6.0f; + + private float SingleSimplex(int seed, float x, float y) { + float t = (x + y) * F2; + int i = FastFloor(x + t); + int j = FastFloor(y + t); + + t = (i + j) * G2; + float X0 = i - t; + float Y0 = j - t; + + float x0 = x - X0; + float y0 = y - Y0; + + int i1, j1; + if (x0 > y0) { + i1 = 1; + j1 = 0; + } else { + i1 = 0; + j1 = 1; + } + + float x1 = x0 - i1 + G2; + float y1 = y0 - j1 + G2; + float x2 = x0 - 1 + 2 * G2; + float y2 = y0 - 1 + 2 * G2; + + float n0, n1, n2; + + t = (float) 0.5 - x0 * x0 - y0 * y0; + if (t < 0) + n0 = 0; + else { + t *= t; + n0 = t * t * GradCoord2D(seed, i, j, x0, y0); + } + + t = (float) 0.5 - x1 * x1 - y1 * y1; + if (t < 0) + n1 = 0; + else { + t *= t; + n1 = t * t * GradCoord2D(seed, i + i1, j + j1, x1, y1); + } + + t = (float) 0.5 - x2 * x2 - y2 * y2; + if (t < 0) + n2 = 0; + else { + t *= t; + n2 = t * t * GradCoord2D(seed, i + 1, j + 1, x2, y2); + } + + return 50 * (n0 + n1 + n2); + } + + public float GetSimplex(float x, float y, float z, float w) { + return SingleSimplex(m_seed, x * m_frequency, y * m_frequency, z * m_frequency, w * m_frequency); + } + + private static final byte[] SIMPLEX_4D = {0, 1, 2, 3, 0, 1, 3, 2, 0, 0, 0, 0, 0, 2, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 0, 2, 1, 3, 0, 0, 0, 0, 0, 3, 1, 2, 0, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 3, 0, 0, 0, 0, 1, 3, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 0, 1, 2, 3, 1, 0, 1, 0, 2, 3, 1, 0, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 1, 0, 0, 0, 0, 2, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 1, 2, 3, 0, 2, 1, 0, 0, 0, 0, 3, 1, 2, 0, 2, 1, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 1, 0, 2, 0, 0, 0, 0, 3, 2, 0, 1, 3, 2, 1, 0 + }; + + private final static float F4 = (float) ((2.23606797 - 1.0) / 4.0); + private final static float G4 = (float) ((5.0 - 2.23606797) / 20.0); + + private float SingleSimplex(int seed, float x, float y, float z, float w) { + float n0, n1, n2, n3, n4; + float t = (x + y + z + w) * F4; + int i = FastFloor(x + t); + int j = FastFloor(y + t); + int k = FastFloor(z + t); + int l = FastFloor(w + t); + t = (i + j + k + l) * G4; + float X0 = i - t; + float Y0 = j - t; + float Z0 = k - t; + float W0 = l - t; + float x0 = x - X0; + float y0 = y - Y0; + float z0 = z - Z0; + float w0 = w - W0; + + int c = (x0 > y0) ? 32 : 0; + c += (x0 > z0) ? 16 : 0; + c += (y0 > z0) ? 8 : 0; + c += (x0 > w0) ? 4 : 0; + c += (y0 > w0) ? 2 : 0; + c += (z0 > w0) ? 1 : 0; + c <<= 2; + + int i1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; + int i2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; + int i3 = SIMPLEX_4D[c++] >= 1 ? 1 : 0; + int j1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; + int j2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; + int j3 = SIMPLEX_4D[c++] >= 1 ? 1 : 0; + int k1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; + int k2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; + int k3 = SIMPLEX_4D[c++] >= 1 ? 1 : 0; + int l1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; + int l2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; + int l3 = SIMPLEX_4D[c] >= 1 ? 1 : 0; + + float x1 = x0 - i1 + G4; + float y1 = y0 - j1 + G4; + float z1 = z0 - k1 + G4; + float w1 = w0 - l1 + G4; + float x2 = x0 - i2 + 2 * G4; + float y2 = y0 - j2 + 2 * G4; + float z2 = z0 - k2 + 2 * G4; + float w2 = w0 - l2 + 2 * G4; + float x3 = x0 - i3 + 3 * G4; + float y3 = y0 - j3 + 3 * G4; + float z3 = z0 - k3 + 3 * G4; + float w3 = w0 - l3 + 3 * G4; + float x4 = x0 - 1 + 4 * G4; + float y4 = y0 - 1 + 4 * G4; + float z4 = z0 - 1 + 4 * G4; + float w4 = w0 - 1 + 4 * G4; + + t = (float) 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0; + if (t < 0) + n0 = 0; + else { + t *= t; + n0 = t * t * GradCoord4D(seed, i, j, k, l, x0, y0, z0, w0); + } + t = (float) 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1; + if (t < 0) + n1 = 0; + else { + t *= t; + n1 = t * t * GradCoord4D(seed, i + i1, j + j1, k + k1, l + l1, x1, y1, z1, w1); + } + t = (float) 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2; + if (t < 0) + n2 = 0; + else { + t *= t; + n2 = t * t * GradCoord4D(seed, i + i2, j + j2, k + k2, l + l2, x2, y2, z2, w2); + } + t = (float) 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3; + if (t < 0) + n3 = 0; + else { + t *= t; + n3 = t * t * GradCoord4D(seed, i + i3, j + j3, k + k3, l + l3, x3, y3, z3, w3); + } + t = (float) 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4; + if (t < 0) + n4 = 0; + else { + t *= t; + n4 = t * t * GradCoord4D(seed, i + 1, j + 1, k + 1, l + 1, x4, y4, z4, w4); + } + + return 27 * (n0 + n1 + n2 + n3 + n4); + } + + // Cubic Noise + public float GetCubicFractal(float x, float y, float z) { + x *= m_frequency; + y *= m_frequency; + z *= m_frequency; + + switch (m_fractalType) { + case FBM: + return SingleCubicFractalFBM(x, y, z); + case Billow: + return SingleCubicFractalBillow(x, y, z); + case RigidMulti: + return SingleCubicFractalRigidMulti(x, y, z); + default: + return 0; + } + } + + private float SingleCubicFractalFBM(float x, float y, float z) { + int seed = m_seed; + float sum = SingleCubic(seed, x, y, z); + float amp = 1; + int i = 0; + + while (++i < m_octaves) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum += SingleCubic(++seed, x, y, z) * amp; + } + + return sum * m_fractalBounding; + } + + private float SingleCubicFractalBillow(float x, float y, float z) { + int seed = m_seed; + float sum = Math.abs(SingleCubic(seed, x, y, z)) * 2 - 1; + float amp = 1; + int i = 0; + + while (++i < m_octaves) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum += (Math.abs(SingleCubic(++seed, x, y, z)) * 2 - 1) * amp; + } + + return sum * m_fractalBounding; + } + + private float SingleCubicFractalRigidMulti(float x, float y, float z) { + int seed = m_seed; + float sum = 1 - Math.abs(SingleCubic(seed, x, y, z)); + float amp = 1; + int i = 0; + + while (++i < m_octaves) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum -= (1 - Math.abs(SingleCubic(++seed, x, y, z))) * amp; + } + + return sum; + } + + public float GetCubic(float x, float y, float z) { + return SingleCubic(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); + } + + private final static float CUBIC_3D_BOUNDING = 1 / (float) (1.5 * 1.5 * 1.5); + + private float SingleCubic(int seed, float x, float y, float z) { + int x1 = FastFloor(x); + int y1 = FastFloor(y); + int z1 = FastFloor(z); + + int x0 = x1 - 1; + int y0 = y1 - 1; + int z0 = z1 - 1; + int x2 = x1 + 1; + int y2 = y1 + 1; + int z2 = z1 + 1; + int x3 = x1 + 2; + int y3 = y1 + 2; + int z3 = z1 + 2; + + float xs = x - (float) x1; + float ys = y - (float) y1; + float zs = z - (float) z1; + + return CubicLerp(CubicLerp(CubicLerp(ValCoord3D(seed, x0, y0, z0), ValCoord3D(seed, x1, y0, z0), ValCoord3D(seed, x2, y0, z0), ValCoord3D(seed, x3, y0, z0), xs), CubicLerp(ValCoord3D(seed, x0, y1, z0), ValCoord3D(seed, x1, y1, z0), ValCoord3D(seed, x2, y1, z0), ValCoord3D(seed, x3, y1, z0), xs), CubicLerp(ValCoord3D(seed, x0, y2, z0), ValCoord3D(seed, x1, y2, z0), ValCoord3D(seed, x2, y2, z0), ValCoord3D(seed, x3, y2, z0), xs), CubicLerp(ValCoord3D(seed, x0, y3, z0), ValCoord3D(seed, x1, y3, z0), ValCoord3D(seed, x2, y3, z0), ValCoord3D(seed, x3, y3, z0), xs), ys), CubicLerp(CubicLerp(ValCoord3D(seed, x0, y0, z1), ValCoord3D(seed, x1, y0, z1), ValCoord3D(seed, x2, y0, z1), ValCoord3D(seed, x3, y0, z1), xs), CubicLerp(ValCoord3D(seed, x0, y1, z1), ValCoord3D(seed, x1, y1, z1), ValCoord3D(seed, x2, y1, z1), ValCoord3D(seed, x3, y1, z1), xs), CubicLerp(ValCoord3D(seed, x0, y2, z1), ValCoord3D(seed, x1, y2, z1), ValCoord3D(seed, x2, y2, z1), ValCoord3D(seed, x3, y2, z1), xs), CubicLerp(ValCoord3D(seed, x0, y3, z1), ValCoord3D(seed, x1, y3, z1), ValCoord3D(seed, x2, y3, z1), ValCoord3D(seed, x3, y3, z1), xs), ys), CubicLerp(CubicLerp(ValCoord3D(seed, x0, y0, z2), ValCoord3D(seed, x1, y0, z2), ValCoord3D(seed, x2, y0, z2), ValCoord3D(seed, x3, y0, z2), xs), CubicLerp(ValCoord3D(seed, x0, y1, z2), ValCoord3D(seed, x1, y1, z2), ValCoord3D(seed, x2, y1, z2), ValCoord3D(seed, x3, y1, z2), xs), CubicLerp(ValCoord3D(seed, x0, y2, z2), ValCoord3D(seed, x1, y2, z2), ValCoord3D(seed, x2, y2, z2), ValCoord3D(seed, x3, y2, z2), xs), CubicLerp(ValCoord3D(seed, x0, y3, z2), ValCoord3D(seed, x1, y3, z2), ValCoord3D(seed, x2, y3, z2), ValCoord3D(seed, x3, y3, z2), xs), ys), CubicLerp(CubicLerp(ValCoord3D(seed, x0, y0, z3), ValCoord3D(seed, x1, y0, z3), ValCoord3D(seed, x2, y0, z3), ValCoord3D(seed, x3, y0, z3), xs), CubicLerp(ValCoord3D(seed, x0, y1, z3), ValCoord3D(seed, x1, y1, z3), ValCoord3D(seed, x2, y1, z3), ValCoord3D(seed, x3, y1, z3), xs), CubicLerp(ValCoord3D(seed, x0, y2, z3), ValCoord3D(seed, x1, y2, z3), ValCoord3D(seed, x2, y2, z3), ValCoord3D(seed, x3, y2, z3), xs), CubicLerp(ValCoord3D(seed, x0, y3, z3), ValCoord3D(seed, x1, y3, z3), ValCoord3D(seed, x2, y3, z3), ValCoord3D(seed, x3, y3, z3), xs), ys), zs) * CUBIC_3D_BOUNDING; + } + + public float GetCubicFractal(float x, float y) { + x *= m_frequency; + y *= m_frequency; + + switch (m_fractalType) { + case FBM: + return SingleCubicFractalFBM(x, y); + case Billow: + return SingleCubicFractalBillow(x, y); + case RigidMulti: + return SingleCubicFractalRigidMulti(x, y); + default: + return 0; + } + } + + private float SingleCubicFractalFBM(float x, float y) { + int seed = m_seed; + float sum = SingleCubic(seed, x, y); + float amp = 1; + int i = 0; + + while (++i < m_octaves) { + x *= m_lacunarity; + y *= m_lacunarity; + + amp *= m_gain; + sum += SingleCubic(++seed, x, y) * amp; + } + + return sum * m_fractalBounding; + } + + private float SingleCubicFractalBillow(float x, float y) { + int seed = m_seed; + float sum = Math.abs(SingleCubic(seed, x, y)) * 2 - 1; + float amp = 1; + int i = 0; + + while (++i < m_octaves) { + x *= m_lacunarity; + y *= m_lacunarity; + + amp *= m_gain; + sum += (Math.abs(SingleCubic(++seed, x, y)) * 2 - 1) * amp; + } + + return sum * m_fractalBounding; + } + + private float SingleCubicFractalRigidMulti(float x, float y) { + int seed = m_seed; + float sum = 1 - Math.abs(SingleCubic(seed, x, y)); + float amp = 1; + int i = 0; + + while (++i < m_octaves) { + x *= m_lacunarity; + y *= m_lacunarity; + + amp *= m_gain; + sum -= (1 - Math.abs(SingleCubic(++seed, x, y))) * amp; + } + + return sum; + } + + public float GetCubic(float x, float y) { + x *= m_frequency; + y *= m_frequency; + + return SingleCubic(0, x, y); + } + + private final static float CUBIC_2D_BOUNDING = 1 / (float) (1.5 * 1.5); + + private float SingleCubic(int seed, float x, float y) { + int x1 = FastFloor(x); + int y1 = FastFloor(y); + + int x0 = x1 - 1; + int y0 = y1 - 1; + int x2 = x1 + 1; + int y2 = y1 + 1; + int x3 = x1 + 2; + int y3 = y1 + 2; + + float xs = x - (float) x1; + float ys = y - (float) y1; + + return CubicLerp(CubicLerp(ValCoord2D(seed, x0, y0), ValCoord2D(seed, x1, y0), ValCoord2D(seed, x2, y0), ValCoord2D(seed, x3, y0), xs), CubicLerp(ValCoord2D(seed, x0, y1), ValCoord2D(seed, x1, y1), ValCoord2D(seed, x2, y1), ValCoord2D(seed, x3, y1), xs), CubicLerp(ValCoord2D(seed, x0, y2), ValCoord2D(seed, x1, y2), ValCoord2D(seed, x2, y2), ValCoord2D(seed, x3, y2), xs), CubicLerp(ValCoord2D(seed, x0, y3), ValCoord2D(seed, x1, y3), ValCoord2D(seed, x2, y3), ValCoord2D(seed, x3, y3), xs), ys) * CUBIC_2D_BOUNDING; + } + + // Cellular Noise + public float GetCellular(float x, float y, float z) { + x *= m_frequency; + y *= m_frequency; + z *= m_frequency; + + switch (m_cellularReturnType) { + case CellValue: + case NoiseLookup: + case Distance: + return SingleCellular(x, y, z); + default: + return SingleCellular2Edge(x, y, z); + } + } + + private float SingleCellular(float x, float y, float z) { + int xr = FastRound(x); + int yr = FastRound(y); + int zr = FastRound(z); + + float distance = 999999; + int xc = 0, yc = 0, zc = 0; + + switch (m_cellularDistanceFunction) { + case Euclidean: + for (int xi = xr - 1; xi <= xr + 1; xi++) { + for (int yi = yr - 1; yi <= yr + 1; yi++) { + for (int zi = zr - 1; zi <= zr + 1; zi++) { + Float3 vec = CELL_3D[Hash3D(m_seed, xi, yi, zi) & 255]; + + float vecX = xi - x + vec.x; + float vecY = yi - y + vec.y; + float vecZ = zi - z + vec.z; + + float newDistance = vecX * vecX + vecY * vecY + vecZ * vecZ; + + if (newDistance < distance) { + distance = newDistance; + xc = xi; + yc = yi; + zc = zi; + } + } + } + } + break; + case Manhattan: + for (int xi = xr - 1; xi <= xr + 1; xi++) { + for (int yi = yr - 1; yi <= yr + 1; yi++) { + for (int zi = zr - 1; zi <= zr + 1; zi++) { + Float3 vec = CELL_3D[Hash3D(m_seed, xi, yi, zi) & 255]; + + float vecX = xi - x + vec.x; + float vecY = yi - y + vec.y; + float vecZ = zi - z + vec.z; + + float newDistance = Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ); + + if (newDistance < distance) { + distance = newDistance; + xc = xi; + yc = yi; + zc = zi; + } + } + } + } + break; + case Natural: + for (int xi = xr - 1; xi <= xr + 1; xi++) { + for (int yi = yr - 1; yi <= yr + 1; yi++) { + for (int zi = zr - 1; zi <= zr + 1; zi++) { + Float3 vec = CELL_3D[Hash3D(m_seed, xi, yi, zi) & 255]; + + float vecX = xi - x + vec.x; + float vecY = yi - y + vec.y; + float vecZ = zi - z + vec.z; + + float newDistance = (Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ)) + (vecX * vecX + vecY * vecY + vecZ * vecZ); + + if (newDistance < distance) { + distance = newDistance; + xc = xi; + yc = yi; + zc = zi; + } + } + } + } + break; + } + + switch (m_cellularReturnType) { + case CellValue: + return ValCoord3D(0, xc, yc, zc); + + case NoiseLookup: + Float3 vec = CELL_3D[Hash3D(m_seed, xc, yc, zc) & 255]; + return m_cellularNoiseLookup.GetNoise(xc + vec.x, yc + vec.y, zc + vec.z); + + case Distance: + return distance - 1; + default: + return 0; + } + } + + private float SingleCellular2Edge(float x, float y, float z) { + int xr = FastRound(x); + int yr = FastRound(y); + int zr = FastRound(z); + + float distance = 999999; + float distance2 = 999999; + + switch (m_cellularDistanceFunction) { + case Euclidean: + for (int xi = xr - 1; xi <= xr + 1; xi++) { + for (int yi = yr - 1; yi <= yr + 1; yi++) { + for (int zi = zr - 1; zi <= zr + 1; zi++) { + Float3 vec = CELL_3D[Hash3D(m_seed, xi, yi, zi) & 255]; + + float vecX = xi - x + vec.x; + float vecY = yi - y + vec.y; + float vecZ = zi - z + vec.z; + + float newDistance = vecX * vecX + vecY * vecY + vecZ * vecZ; + + distance2 = Math.max(Math.min(distance2, newDistance), distance); + distance = Math.min(distance, newDistance); + } + } + } + break; + case Manhattan: + for (int xi = xr - 1; xi <= xr + 1; xi++) { + for (int yi = yr - 1; yi <= yr + 1; yi++) { + for (int zi = zr - 1; zi <= zr + 1; zi++) { + Float3 vec = CELL_3D[Hash3D(m_seed, xi, yi, zi) & 255]; + + float vecX = xi - x + vec.x; + float vecY = yi - y + vec.y; + float vecZ = zi - z + vec.z; + + float newDistance = Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ); + + distance2 = Math.max(Math.min(distance2, newDistance), distance); + distance = Math.min(distance, newDistance); + } + } + } + break; + case Natural: + for (int xi = xr - 1; xi <= xr + 1; xi++) { + for (int yi = yr - 1; yi <= yr + 1; yi++) { + for (int zi = zr - 1; zi <= zr + 1; zi++) { + Float3 vec = CELL_3D[Hash3D(m_seed, xi, yi, zi) & 255]; + + float vecX = xi - x + vec.x; + float vecY = yi - y + vec.y; + float vecZ = zi - z + vec.z; + + float newDistance = (Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ)) + (vecX * vecX + vecY * vecY + vecZ * vecZ); + + distance2 = Math.max(Math.min(distance2, newDistance), distance); + distance = Math.min(distance, newDistance); + } + } + } + break; + default: + break; + } + + switch (m_cellularReturnType) { + case Distance2: + return distance2 - 1; + case Distance2Add: + return distance2 + distance - 1; + case Distance2Sub: + return distance2 - distance - 1; + case Distance2Mul: + return distance2 * distance - 1; + case Distance2Div: + return distance / distance2 - 1; + default: + return 0; + } + } + + public float GetCellular(float x, float y) { + x *= m_frequency; + y *= m_frequency; + + switch (m_cellularReturnType) { + case CellValue: + case NoiseLookup: + case Distance: + return SingleCellular(x, y); + default: + return SingleCellular2Edge(x, y); + } + } + + private float SingleCellular(float x, float y) { + int xr = FastRound(x); + int yr = FastRound(y); + + float distance = 999999; + int xc = 0, yc = 0; + + switch (m_cellularDistanceFunction) { + default: + case Euclidean: + for (int xi = xr - 1; xi <= xr + 1; xi++) { + for (int yi = yr - 1; yi <= yr + 1; yi++) { + Float2 vec = CELL_2D[Hash2D(m_seed, xi, yi) & 255]; + + float vecX = xi - x + vec.x; + float vecY = yi - y + vec.y; + + float newDistance = vecX * vecX + vecY * vecY; + + if (newDistance < distance) { + distance = newDistance; + xc = xi; + yc = yi; + } + } + } + break; + case Manhattan: + for (int xi = xr - 1; xi <= xr + 1; xi++) { + for (int yi = yr - 1; yi <= yr + 1; yi++) { + Float2 vec = CELL_2D[Hash2D(m_seed, xi, yi) & 255]; + + float vecX = xi - x + vec.x; + float vecY = yi - y + vec.y; + + float newDistance = (Math.abs(vecX) + Math.abs(vecY)); + + if (newDistance < distance) { + distance = newDistance; + xc = xi; + yc = yi; + } + } + } + break; + case Natural: + for (int xi = xr - 1; xi <= xr + 1; xi++) { + for (int yi = yr - 1; yi <= yr + 1; yi++) { + Float2 vec = CELL_2D[Hash2D(m_seed, xi, yi) & 255]; + + float vecX = xi - x + vec.x; + float vecY = yi - y + vec.y; + + float newDistance = (Math.abs(vecX) + Math.abs(vecY)) + (vecX * vecX + vecY * vecY); + + if (newDistance < distance) { + distance = newDistance; + xc = xi; + yc = yi; + } + } + } + break; + } + + switch (m_cellularReturnType) { + case CellValue: + return ValCoord2D(0, xc, yc); + + case NoiseLookup: + Float2 vec = CELL_2D[Hash2D(m_seed, xc, yc) & 255]; + return m_cellularNoiseLookup.GetNoise(xc + vec.x, yc + vec.y); + + case Distance: + return distance - 1; + default: + return 0; + } + } + + private float SingleCellular2Edge(float x, float y) { + int xr = FastRound(x); + int yr = FastRound(y); + + float distance = 999999; + float distance2 = 999999; + + switch (m_cellularDistanceFunction) { + default: + case Euclidean: + for (int xi = xr - 1; xi <= xr + 1; xi++) { + for (int yi = yr - 1; yi <= yr + 1; yi++) { + Float2 vec = CELL_2D[Hash2D(m_seed, xi, yi) & 255]; + + float vecX = xi - x + vec.x; + float vecY = yi - y + vec.y; + + float newDistance = vecX * vecX + vecY * vecY; + + distance2 = Math.max(Math.min(distance2, newDistance), distance); + distance = Math.min(distance, newDistance); + } + } + break; + case Manhattan: + for (int xi = xr - 1; xi <= xr + 1; xi++) { + for (int yi = yr - 1; yi <= yr + 1; yi++) { + Float2 vec = CELL_2D[Hash2D(m_seed, xi, yi) & 255]; + + float vecX = xi - x + vec.x; + float vecY = yi - y + vec.y; + + float newDistance = Math.abs(vecX) + Math.abs(vecY); + + distance2 = Math.max(Math.min(distance2, newDistance), distance); + distance = Math.min(distance, newDistance); + } + } + break; + case Natural: + for (int xi = xr - 1; xi <= xr + 1; xi++) { + for (int yi = yr - 1; yi <= yr + 1; yi++) { + Float2 vec = CELL_2D[Hash2D(m_seed, xi, yi) & 255]; + + float vecX = xi - x + vec.x; + float vecY = yi - y + vec.y; + + float newDistance = (Math.abs(vecX) + Math.abs(vecY)) + (vecX * vecX + vecY * vecY); + + distance2 = Math.max(Math.min(distance2, newDistance), distance); + distance = Math.min(distance, newDistance); + } + } + break; + } + + switch (m_cellularReturnType) { + case Distance2: + return distance2 - 1; + case Distance2Add: + return distance2 + distance - 1; + case Distance2Sub: + return distance2 - distance - 1; + case Distance2Mul: + return distance2 * distance - 1; + case Distance2Div: + return distance / distance2 - 1; + default: + return 0; + } + } + + public void GradientPerturb(Vector3f v3) { + SingleGradientPerturb(m_seed, m_gradientPerturbAmp, m_frequency, v3); + } + + public void GradientPerturbFractal(Vector3f v3) { + int seed = m_seed; + float amp = m_gradientPerturbAmp * m_fractalBounding; + float freq = m_frequency; + + SingleGradientPerturb(seed, amp, m_frequency, v3); + + for (int i = 1; i < m_octaves; i++) { + freq *= m_lacunarity; + amp *= m_gain; + SingleGradientPerturb(++seed, amp, freq, v3); + } + } + + private void SingleGradientPerturb(int seed, float perturbAmp, float frequency, Vector3f v3) { + float xf = v3.x * frequency; + float yf = v3.y * frequency; + float zf = v3.z * frequency; + + int x0 = FastFloor(xf); + int y0 = FastFloor(yf); + int z0 = FastFloor(zf); + int x1 = x0 + 1; + int y1 = y0 + 1; + int z1 = z0 + 1; + + float xs, ys, zs; + switch (m_interp) { + default: + case Linear: + xs = xf - x0; + ys = yf - y0; + zs = zf - z0; + break; + case Hermite: + xs = InterpHermiteFunc(xf - x0); + ys = InterpHermiteFunc(yf - y0); + zs = InterpHermiteFunc(zf - z0); + break; + case Quintic: + xs = InterpQuinticFunc(xf - x0); + ys = InterpQuinticFunc(yf - y0); + zs = InterpQuinticFunc(zf - z0); + break; + } + + Float3 vec0 = CELL_3D[Hash3D(seed, x0, y0, z0) & 255]; + Float3 vec1 = CELL_3D[Hash3D(seed, x1, y0, z0) & 255]; + + float lx0x = Lerp(vec0.x, vec1.x, xs); + float ly0x = Lerp(vec0.y, vec1.y, xs); + float lz0x = Lerp(vec0.z, vec1.z, xs); + + vec0 = CELL_3D[Hash3D(seed, x0, y1, z0) & 255]; + vec1 = CELL_3D[Hash3D(seed, x1, y1, z0) & 255]; + + float lx1x = Lerp(vec0.x, vec1.x, xs); + float ly1x = Lerp(vec0.y, vec1.y, xs); + float lz1x = Lerp(vec0.z, vec1.z, xs); + + float lx0y = Lerp(lx0x, lx1x, ys); + float ly0y = Lerp(ly0x, ly1x, ys); + float lz0y = Lerp(lz0x, lz1x, ys); + + vec0 = CELL_3D[Hash3D(seed, x0, y0, z1) & 255]; + vec1 = CELL_3D[Hash3D(seed, x1, y0, z1) & 255]; + + lx0x = Lerp(vec0.x, vec1.x, xs); + ly0x = Lerp(vec0.y, vec1.y, xs); + lz0x = Lerp(vec0.z, vec1.z, xs); + + vec0 = CELL_3D[Hash3D(seed, x0, y1, z1) & 255]; + vec1 = CELL_3D[Hash3D(seed, x1, y1, z1) & 255]; + + lx1x = Lerp(vec0.x, vec1.x, xs); + ly1x = Lerp(vec0.y, vec1.y, xs); + lz1x = Lerp(vec0.z, vec1.z, xs); + + v3.x += Lerp(lx0y, Lerp(lx0x, lx1x, ys), zs) * perturbAmp; + v3.y += Lerp(ly0y, Lerp(ly0x, ly1x, ys), zs) * perturbAmp; + v3.z += Lerp(lz0y, Lerp(lz0x, lz1x, ys), zs) * perturbAmp; + } + + public void GradientPerturb(Vector2f v2) { + SingleGradientPerturb(m_seed, m_gradientPerturbAmp, m_frequency, v2); + } + + public void GradientPerturbFractal(Vector2f v2) { + int seed = m_seed; + float amp = m_gradientPerturbAmp * m_fractalBounding; + float freq = m_frequency; + + SingleGradientPerturb(seed, amp, m_frequency, v2); + + for (int i = 1; i < m_octaves; i++) { + freq *= m_lacunarity; + amp *= m_gain; + SingleGradientPerturb(++seed, amp, freq, v2); + } + } + + private void SingleGradientPerturb(int seed, float perturbAmp, float frequency, Vector2f v2) { + float xf = v2.x * frequency; + float yf = v2.y * frequency; + + int x0 = FastFloor(xf); + int y0 = FastFloor(yf); + int x1 = x0 + 1; + int y1 = y0 + 1; + + float xs, ys; + switch (m_interp) { + default: + case Linear: + xs = xf - x0; + ys = yf - y0; + break; + case Hermite: + xs = InterpHermiteFunc(xf - x0); + ys = InterpHermiteFunc(yf - y0); + break; + case Quintic: + xs = InterpQuinticFunc(xf - x0); + ys = InterpQuinticFunc(yf - y0); + break; + } + + Float2 vec0 = CELL_2D[Hash2D(seed, x0, y0) & 255]; + Float2 vec1 = CELL_2D[Hash2D(seed, x1, y0) & 255]; + + float lx0x = Lerp(vec0.x, vec1.x, xs); + float ly0x = Lerp(vec0.y, vec1.y, xs); + + vec0 = CELL_2D[Hash2D(seed, x0, y1) & 255]; + vec1 = CELL_2D[Hash2D(seed, x1, y1) & 255]; + + float lx1x = Lerp(vec0.x, vec1.x, xs); + float ly1x = Lerp(vec0.y, vec1.y, xs); + + v2.x += Lerp(lx0x, lx1x, ys) * perturbAmp; + v2.y += Lerp(ly0x, ly1x, ys) * perturbAmp; + } } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/generator/noise/FastNoiseDouble.java b/src/main/java/com/volmit/iris/generator/noise/FastNoiseDouble.java index d1f8bcc29..8ec4ab5d6 100644 --- a/src/main/java/com/volmit/iris/generator/noise/FastNoiseDouble.java +++ b/src/main/java/com/volmit/iris/generator/noise/FastNoiseDouble.java @@ -30,2333 +30,2096 @@ package com.volmit.iris.generator.noise; import com.volmit.iris.util.Vector2f; import com.volmit.iris.util.Vector3f; -public class FastNoiseDouble -{ - public enum NoiseType - { - Value, - ValueFractal, - Perlin, - PerlinFractal, - Simplex, - SimplexFractal, - Cellular, - WhiteNoise, - Cubic, - CubicFractal - } - - public enum Longerp - { - Linear, - Hermite, - Qulongic - } - - public enum FractalType - { - FBM, - Billow, - RigidMulti - } - - public enum CellularDistanceFunction - { - Euclidean, - Manhattan, - Natural - } - - public enum CellularReturnType - { - CellValue, - NoiseLookup, - Distance, - Distance2, - Distance2Add, - Distance2Sub, - Distance2Mul, - Distance2Div - } - - private long m_seed = 1337; - private double m_frequency = (double) 0.01; - public Longerp m_longerp = Longerp.Linear; - private NoiseType m_noiseType = NoiseType.Simplex; - - private long m_octaves = 3; - private double m_lacunarity = (double) 2.0; - private double m_gain = (double) 0.5; - private FractalType m_fractalType = FractalType.FBM; - - private double m_fractalBounding; - - private CellularDistanceFunction m_cellularDistanceFunction = CellularDistanceFunction.Euclidean; - private CellularReturnType m_cellularReturnType = CellularReturnType.CellValue; - private FastNoiseDouble m_cellularNoiseLookup = null; - - private double m_gradientPerturbAmp = (double) (1.0 / 0.45); - - public FastNoiseDouble() - { - this(1337); - } - - public FastNoiseDouble(long seed) - { - m_seed = seed; - calculateFractalBounding(); - } - - // Returns a 0 double/double - public static double getDecimalType() - { - return 0; - } - - // Returns the seed used by this object - public long getSeed() - { - return m_seed; - } - - // Sets seed used for all noise types - // Default: 1337 - public void setSeed(long seed) - { - m_seed = seed; - } - - // Sets frequency for all noise types - // Default: 0.01 - public void setFrequency(double frequency) - { - m_frequency = frequency; - } - - // Changes the longerpolation method used to smooth between noise values - // Possible longerpolation methods (lowest to highest quality) : - // - Linear - // - Hermite - // - Qulongic - // Used in Value, Gradient Noise and Position Perturbing - // Default: Qulongic - public void setLongerp(Longerp longerp) - { - m_longerp = longerp; - } - - // Sets noise return type of GetNoise(...) - // Default: Simplex - public void setNoiseType(NoiseType noiseType) - { - m_noiseType = noiseType; - } - - // Sets octave count for all fractal noise types - // Default: 3 - public void setFractalOctaves(long octaves) - { - m_octaves = octaves; - calculateFractalBounding(); - } - - // Sets octave lacunarity for all fractal noise types - // Default: 2.0 - public void setFractalLacunarity(double lacunarity) - { - m_lacunarity = lacunarity; - } - - // Sets octave gain for all fractal noise types - // Default: 0.5 - public void setFractalGain(double gain) - { - m_gain = gain; - calculateFractalBounding(); - } - - // Sets method for combining octaves in all fractal noise types - // Default: FBM - public void setFractalType(FractalType fractalType) - { - m_fractalType = fractalType; - } - - // Sets return type from cellular noise calculations - // Note: NoiseLookup requires another FastNoise object be set with - // SetCellularNoiseLookup() to function - // Default: CellValue - public void setCellularDistanceFunction(CellularDistanceFunction cellularDistanceFunction) - { - m_cellularDistanceFunction = cellularDistanceFunction; - } - - // Sets distance function used in cellular noise calculations - // Default: Euclidean - public void setCellularReturnType(CellularReturnType cellularReturnType) - { - m_cellularReturnType = cellularReturnType; - } - - // Noise used to calculate a cell value if cellular return type is NoiseLookup - // The lookup value is acquired through GetNoise() so ensure you SetNoiseType() - // on the noise lookup, value, gradient or simplex is recommended - public void setCellularNoiseLookup(FastNoiseDouble noise) - { - m_cellularNoiseLookup = noise; - } - - // Sets the maximum perturb distance from original location when using - // GradientPerturb{Fractal}(...) - // Default: 1.0 - public void setGradientPerturbAmp(double gradientPerturbAmp) - { - m_gradientPerturbAmp = gradientPerturbAmp / (double) 0.45; - } - - private static class Double2 - { - public final double x, y; - - public Double2(double x, double y) - { - this.x = x; - this.y = y; - } - } - - private static class Double3 - { - public final double x, y, z; - - public Double3(double x, double y, double z) - { - this.x = x; - this.y = y; - this.z = z; - } - } - - private static final Double2[] GRAD_2D = {new Double2(-1, -1), new Double2(1, -1), new Double2(-1, 1), new Double2(1, 1), new Double2(0, -1), new Double2(-1, 0), new Double2(0, 1), new Double2(1, 0), - }; - - private static final Double3[] GRAD_3D = {new Double3(1, 1, 0), new Double3(-1, 1, 0), new Double3(1, -1, 0), new Double3(-1, -1, 0), new Double3(1, 0, 1), new Double3(-1, 0, 1), new Double3(1, 0, -1), new Double3(-1, 0, -1), new Double3(0, 1, 1), new Double3(0, -1, 1), new Double3(0, 1, -1), new Double3(0, -1, -1), new Double3(1, 1, 0), new Double3(0, -1, 1), new Double3(-1, 1, 0), new Double3(0, -1, -1), - }; - - private static final Double2[] CELL_2D = {new Double2(-0.4313539279f, 0.1281943404f), new Double2(-0.1733316799f, 0.415278375f), new Double2(-0.2821957395f, -0.3505218461f), new Double2(-0.2806473808f, 0.3517627718f), new Double2(0.3125508975f, -0.3237467165f), new Double2(0.3383018443f, -0.2967353402f), new Double2(-0.4393982022f, -0.09710417025f), new Double2(-0.4460443703f, -0.05953502905f), new Double2(-0.302223039f, 0.3334085102f), new Double2(-0.212681052f, -0.3965687458f), new Double2(-0.2991156529f, 0.3361990872f), new Double2(0.2293323691f, 0.3871778202f), new Double2(0.4475439151f, -0.04695150755f), new Double2(0.1777518f, 0.41340573f), new Double2(0.1688522499f, -0.4171197882f), new Double2(-0.0976597166f, 0.4392750616f), new Double2(0.08450188373f, 0.4419948321f), new Double2(-0.4098760448f, -0.1857461384f), new Double2(0.3476585782f, -0.2857157906f), new Double2(-0.3350670039f, -0.30038326f), new Double2(0.2298190031f, -0.3868891648f), new Double2(-0.01069924099f, 0.449872789f), new Double2(-0.4460141246f, -0.05976119672f), new Double2(0.3650293864f, 0.2631606867f), new Double2(-0.349479423f, 0.2834856838f), new Double2(-0.4122720642f, 0.1803655873f), new Double2(-0.267327811f, 0.3619887311f), new Double2(0.322124041f, -0.3142230135f), new Double2(0.2880445931f, -0.3457315612f), new Double2(0.3892170926f, -0.2258540565f), new Double2(0.4492085018f, -0.02667811596f), new Double2(-0.4497724772f, 0.01430799601f), new Double2(0.1278175387f, -0.4314657307f), new Double2(-0.03572100503f, 0.4485799926f), new Double2(-0.4297407068f, -0.1335025276f), new Double2(-0.3217817723f, 0.3145735065f), new Double2(-0.3057158873f, 0.3302087162f), new Double2(-0.414503978f, 0.1751754899f), new Double2(-0.3738139881f, 0.2505256519f), new Double2(0.2236891408f, -0.3904653228f), new Double2(0.002967775577f, -0.4499902136f), new Double2(0.1747128327f, -0.4146991995f), new Double2(-0.4423772489f, -0.08247647938f), new Double2(-0.2763960987f, -0.355112935f), new Double2(-0.4019385906f, -0.2023496216f), new Double2(0.3871414161f, -0.2293938184f), new Double2(-0.430008727f, 0.1326367019f), new Double2(-0.03037574274f, -0.4489736231f), new Double2(-0.3486181573f, 0.2845441624f), new Double2(0.04553517144f, -0.4476902368f), new Double2(-0.0375802926f, 0.4484280562f), new Double2(0.3266408905f, 0.3095250049f), new Double2(0.06540017593f, -0.4452222108f), new Double2(0.03409025829f, 0.448706869f), new Double2(-0.4449193635f, 0.06742966669f), new Double2(-0.4255936157f, -0.1461850686f), new Double2(0.449917292f, 0.008627302568f), new Double2(0.05242606404f, 0.4469356864f), new Double2(-0.4495305179f, -0.02055026661f), new Double2(-0.1204775703f, 0.4335725488f), new Double2(-0.341986385f, -0.2924813028f), new Double2(0.3865320182f, 0.2304191809f), new Double2(0.04506097811f, -0.447738214f), new Double2(-0.06283465979f, 0.4455915232f), new Double2(0.3932600341f, -0.2187385324f), new Double2(0.4472261803f, -0.04988730975f), new Double2(0.3753571011f, -0.2482076684f), new Double2(-0.273662295f, 0.357223947f), new Double2(0.1700461538f, 0.4166344988f), new Double2(0.4102692229f, 0.1848760794f), new Double2(0.323227187f, -0.3130881435f), new Double2(-0.2882310238f, -0.3455761521f), new Double2(0.2050972664f, 0.4005435199f), new Double2(0.4414085979f, -0.08751256895f), new Double2(-0.1684700334f, 0.4172743077f), new Double2(-0.003978032396f, 0.4499824166f), new Double2(-0.2055133639f, 0.4003301853f), new Double2(-0.006095674897f, -0.4499587123f), new Double2(-0.1196228124f, -0.4338091548f), new Double2(0.3901528491f, -0.2242337048f), new Double2(0.01723531752f, 0.4496698165f), new Double2(-0.3015070339f, 0.3340561458f), new Double2(-0.01514262423f, -0.4497451511f), new Double2(-0.4142574071f, -0.1757577897f), new Double2(-0.1916377265f, -0.4071547394f), new Double2(0.3749248747f, 0.2488600778f), new Double2(-0.2237774255f, 0.3904147331f), new Double2(-0.4166343106f, -0.1700466149f), new Double2(0.3619171625f, 0.267424695f), new Double2(0.1891126846f, -0.4083336779f), new Double2(-0.3127425077f, 0.323561623f), new Double2(-0.3281807787f, 0.307891826f), new Double2(-0.2294806661f, 0.3870899429f), new Double2(-0.3445266136f, 0.2894847362f), new Double2(-0.4167095422f, -0.1698621719f), new Double2(-0.257890321f, -0.3687717212f), new Double2(-0.3612037825f, 0.2683874578f), new Double2(0.2267996491f, 0.3886668486f), new Double2(0.207157062f, 0.3994821043f), new Double2(0.08355176718f, -0.4421754202f), new Double2(-0.4312233307f, 0.1286329626f), new Double2(0.3257055497f, 0.3105090899f), new Double2(0.177701095f, -0.4134275279f), new Double2(-0.445182522f, 0.06566979625f), new Double2(0.3955143435f, 0.2146355146f), new Double2(-0.4264613988f, 0.1436338239f), new Double2(-0.3793799665f, -0.2420141339f), new Double2(0.04617599081f, -0.4476245948f), new Double2(-0.371405428f, -0.2540826796f), new Double2(0.2563570295f, -0.3698392535f), new Double2(0.03476646309f, 0.4486549822f), new Double2(-0.3065454405f, 0.3294387544f), new Double2(-0.2256979823f, 0.3893076172f), new Double2(0.4116448463f, -0.1817925206f), new Double2(-0.2907745828f, -0.3434387019f), new Double2(0.2842278468f, -0.348876097f), new Double2(0.3114589359f, -0.3247973695f), new Double2(0.4464155859f, -0.0566844308f), new Double2(-0.3037334033f, -0.3320331606f), new Double2(0.4079607166f, 0.1899159123f), new Double2(-0.3486948919f, -0.2844501228f), new Double2(0.3264821436f, 0.3096924441f), new Double2(0.3211142406f, 0.3152548881f), new Double2(0.01183382662f, 0.4498443737f), new Double2(0.4333844092f, 0.1211526057f), new Double2(0.3118668416f, 0.324405723f), new Double2(-0.272753471f, 0.3579183483f), new Double2(-0.422228622f, -0.1556373694f), new Double2(-0.1009700099f, -0.4385260051f), new Double2(-0.2741171231f, -0.3568750521f), new Double2(-0.1465125133f, 0.4254810025f), new Double2(0.2302279044f, -0.3866459777f), new Double2(-0.3699435608f, 0.2562064828f), new Double2(0.105700352f, -0.4374099171f), new Double2(-0.2646713633f, 0.3639355292f), new Double2(0.3521828122f, 0.2801200935f), new Double2(-0.1864187807f, -0.4095705534f), new Double2(0.1994492955f, -0.4033856449f), new Double2(0.3937065066f, 0.2179339044f), new Double2(-0.3226158377f, 0.3137180602f), new Double2(0.3796235338f, 0.2416318948f), new Double2(0.1482921929f, 0.4248640083f), new Double2(-0.407400394f, 0.1911149365f), new Double2(0.4212853031f, 0.1581729856f), new Double2(-0.2621297173f, 0.3657704353f), new Double2(-0.2536986953f, -0.3716678248f), new Double2(-0.2100236383f, 0.3979825013f), new Double2(0.3624152444f, 0.2667493029f), new Double2(-0.3645038479f, -0.2638881295f), new Double2(0.2318486784f, 0.3856762766f), new Double2(-0.3260457004f, 0.3101519002f), new Double2(-0.2130045332f, -0.3963950918f), new Double2(0.3814998766f, -0.2386584257f), new Double2(-0.342977305f, 0.2913186713f), new Double2(-0.4355865605f, 0.1129794154f), new Double2(-0.2104679605f, 0.3977477059f), new Double2(0.3348364681f, -0.3006402163f), new Double2(0.3430468811f, 0.2912367377f), new Double2(-0.2291836801f, -0.3872658529f), new Double2(0.2547707298f, -0.3709337882f), new Double2(0.4236174945f, -0.151816397f), new Double2(-0.15387742f, 0.4228731957f), new Double2(-0.4407449312f, 0.09079595574f), new Double2(-0.06805276192f, -0.444824484f), new Double2(0.4453517192f, -0.06451237284f), new Double2(0.2562464609f, -0.3699158705f), new Double2(0.3278198355f, -0.3082761026f), new Double2(-0.4122774207f, -0.1803533432f), new Double2(0.3354090914f, -0.3000012356f), new Double2(0.446632869f, -0.05494615882f), new Double2(-0.1608953296f, 0.4202531296f), new Double2(-0.09463954939f, 0.4399356268f), new Double2(-0.02637688324f, -0.4492262904f), new Double2(0.447102804f, -0.05098119915f), new Double2(-0.4365670908f, 0.1091291678f), new Double2(-0.3959858651f, 0.2137643437f), new Double2(-0.4240048207f, -0.1507312575f), new Double2(-0.3882794568f, 0.2274622243f), new Double2(-0.4283652566f, -0.1378521198f), new Double2(0.3303888091f, 0.305521251f), new Double2(0.3321434919f, -0.3036127481f), new Double2(-0.413021046f, -0.1786438231f), new Double2(0.08403060337f, -0.4420846725f), new Double2(-0.3822882919f, 0.2373934748f), new Double2(-0.3712395594f, -0.2543249683f), new Double2(0.4472363971f, -0.04979563372f), new Double2(-0.4466591209f, 0.05473234629f), new Double2(0.0486272539f, -0.4473649407f), new Double2(-0.4203101295f, -0.1607463688f), new Double2(0.2205360833f, 0.39225481f), new Double2(-0.3624900666f, 0.2666476169f), new Double2(-0.4036086833f, -0.1989975647f), new Double2(0.2152727807f, 0.3951678503f), new Double2(-0.4359392962f, -0.1116106179f), new Double2(0.4178354266f, 0.1670735057f), new Double2(0.2007630161f, 0.4027334247f), new Double2(-0.07278067175f, -0.4440754146f), new Double2(0.3644748615f, -0.2639281632f), new Double2(-0.4317451775f, 0.126870413f), new Double2(-0.297436456f, 0.3376855855f), new Double2(-0.2998672222f, 0.3355289094f), new Double2(-0.2673674124f, 0.3619594822f), new Double2(0.2808423357f, 0.3516071423f), new Double2(0.3498946567f, 0.2829730186f), new Double2(-0.2229685561f, 0.390877248f), new Double2(0.3305823267f, 0.3053118493f), new Double2(-0.2436681211f, -0.3783197679f), new Double2(-0.03402776529f, 0.4487116125f), new Double2(-0.319358823f, 0.3170330301f), new Double2(0.4454633477f, -0.06373700535f), new Double2(0.4483504221f, 0.03849544189f), new Double2(-0.4427358436f, -0.08052932871f), new Double2(0.05452298565f, 0.4466847255f), new Double2(-0.2812560807f, 0.3512762688f), new Double2(0.1266696921f, 0.4318041097f), new Double2(-0.3735981243f, 0.2508474468f), new Double2(0.2959708351f, -0.3389708908f), new Double2(-0.3714377181f, 0.254035473f), new Double2(-0.404467102f, -0.1972469604f), new Double2(0.1636165687f, -0.419201167f), new Double2(0.3289185495f, -0.3071035458f), new Double2(-0.2494824991f, -0.3745109914f), new Double2(0.03283133272f, 0.4488007393f), new Double2(-0.166306057f, -0.4181414777f), new Double2(-0.106833179f, 0.4371346153f), new Double2(0.06440260376f, -0.4453676062f), new Double2(-0.4483230967f, 0.03881238203f), new Double2(-0.421377757f, -0.1579265206f), new Double2(0.05097920662f, -0.4471030312f), new Double2(0.2050584153f, -0.4005634111f), new Double2(0.4178098529f, -0.167137449f), new Double2(-0.3565189504f, -0.2745801121f), new Double2(0.4478398129f, 0.04403977727f), new Double2(-0.3399999602f, -0.2947881053f), new Double2(0.3767121994f, 0.2461461331f), new Double2(-0.3138934434f, 0.3224451987f), new Double2(-0.1462001792f, -0.4255884251f), new Double2(0.3970290489f, -0.2118205239f), new Double2(0.4459149305f, -0.06049689889f), new Double2(-0.4104889426f, -0.1843877112f), new Double2(0.1475103971f, -0.4251360756f), new Double2(0.09258030352f, 0.4403735771f), new Double2(-0.1589664637f, -0.4209865359f), new Double2(0.2482445008f, 0.3753327428f), new Double2(0.4383624232f, -0.1016778537f), new Double2(0.06242802956f, 0.4456486745f), new Double2(0.2846591015f, -0.3485243118f), new Double2(-0.344202744f, -0.2898697484f), new Double2(0.1198188883f, -0.4337550392f), new Double2(-0.243590703f, 0.3783696201f), new Double2(0.2958191174f, -0.3391033025f), new Double2(-0.1164007991f, 0.4346847754f), new Double2(0.1274037151f, -0.4315881062f), new Double2(0.368047306f, 0.2589231171f), new Double2(0.2451436949f, 0.3773652989f), new Double2(-0.4314509715f, 0.12786735f), - }; - - private static final Double3[] CELL_3D = {new Double3(0.1453787434f, -0.4149781685f, -0.0956981749f), new Double3(-0.01242829687f, -0.1457918398f, -0.4255470325f), new Double3(0.2877979582f, -0.02606483451f, -0.3449535616f), new Double3(-0.07732986802f, 0.2377094325f, 0.3741848704f), new Double3(0.1107205875f, -0.3552302079f, -0.2530858567f), new Double3(0.2755209141f, 0.2640521179f, -0.238463215f), new Double3(0.294168941f, 0.1526064594f, 0.3044271714f), new Double3(0.4000921098f, -0.2034056362f, 0.03244149937f), new Double3(-0.1697304074f, 0.3970864695f, -0.1265461359f), new Double3(-0.1483224484f, -0.3859694688f, 0.1775613147f), new Double3(0.2623596946f, -0.2354852944f, 0.2796677792f), new Double3(-0.2709003183f, 0.3505271138f, -0.07901746678f), new Double3(-0.03516550699f, 0.3885234328f, 0.2243054374f), new Double3(-0.1267712655f, 0.1920044036f, 0.3867342179f), new Double3(0.02952021915f, 0.4409685861f, 0.08470692262f), new Double3(-0.2806854217f, -0.266996757f, 0.2289725438f), new Double3(-0.171159547f, 0.2141185563f, 0.3568720405f), new Double3(0.2113227183f, 0.3902405947f, -0.07453178509f), new Double3(-0.1024352839f, 0.2128044156f, -0.3830421561f), new Double3(-0.3304249877f, -0.1566986703f, 0.2622305365f), new Double3(0.2091111325f, 0.3133278055f, -0.2461670583f), new Double3(0.344678154f, -0.1944240454f, -0.2142341261f), new Double3(0.1984478035f, -0.3214342325f, -0.2445373252f), new Double3(-0.2929008603f, 0.2262915116f, 0.2559320961f), new Double3(-0.1617332831f, 0.006314769776f, -0.4198838754f), new Double3(-0.3582060271f, -0.148303178f, -0.2284613961f), new Double3(-0.1852067326f, -0.3454119342f, -0.2211087107f), new Double3(0.3046301062f, 0.1026310383f, 0.314908508f), new Double3(-0.03816768434f, -0.2551766358f, -0.3686842991f), new Double3(-0.4084952196f, 0.1805950793f, 0.05492788837f), new Double3(-0.02687443361f, -0.2749741471f, 0.3551999201f), new Double3(-0.03801098351f, 0.3277859044f, 0.3059600725f), new Double3(0.2371120802f, 0.2900386767f, -0.2493099024f), new Double3(0.4447660503f, 0.03946930643f, 0.05590469027f), new Double3(0.01985147278f, -0.01503183293f, -0.4493105419f), new Double3(0.4274339143f, 0.03345994256f, -0.1366772882f), new Double3(-0.2072988631f, 0.2871414597f, -0.2776273824f), new Double3(-0.3791240978f, 0.1281177671f, 0.2057929936f), new Double3(-0.2098721267f, -0.1007087278f, -0.3851122467f), new Double3(0.01582798878f, 0.4263894424f, 0.1429738373f), new Double3(-0.1888129464f, -0.3160996813f, -0.2587096108f), new Double3(0.1612988974f, -0.1974805082f, -0.3707885038f), new Double3(-0.08974491322f, 0.229148752f, -0.3767448739f), new Double3(0.07041229526f, 0.4150230285f, -0.1590534329f), new Double3(-0.1082925611f, -0.1586061639f, 0.4069604477f), new Double3(0.2474100658f, -0.3309414609f, 0.1782302128f), new Double3(-0.1068836661f, -0.2701644537f, -0.3436379634f), new Double3(0.2396452163f, 0.06803600538f, -0.3747549496f), new Double3(-0.3063886072f, 0.2597428179f, 0.2028785103f), new Double3(0.1593342891f, -0.3114350249f, -0.2830561951f), new Double3(0.2709690528f, 0.1412648683f, -0.3303331794f), new Double3(-0.1519780427f, 0.3623355133f, 0.2193527988f), new Double3(0.1699773681f, 0.3456012883f, 0.2327390037f), new Double3(-0.1986155616f, 0.3836276443f, -0.1260225743f), new Double3(-0.1887482106f, -0.2050154888f, -0.353330953f), new Double3(0.2659103394f, 0.3015631259f, -0.2021172246f), new Double3(-0.08838976154f, -0.4288819642f, -0.1036702021f), new Double3(-0.04201869311f, 0.3099592485f, 0.3235115047f), new Double3(-0.3230334656f, 0.201549922f, -0.2398478873f), new Double3(0.2612720941f, 0.2759854499f, -0.2409749453f), new Double3(0.385713046f, 0.2193460345f, 0.07491837764f), new Double3(0.07654967953f, 0.3721732183f, 0.241095919f), new Double3(0.4317038818f, -0.02577753072f, 0.1243675091f), new Double3(-0.2890436293f, -0.3418179959f, -0.04598084447f), new Double3(-0.2201947582f, 0.383023377f, -0.08548310451f), new Double3(0.4161322773f, -0.1669634289f, -0.03817251927f), new Double3(0.2204718095f, 0.02654238946f, -0.391391981f), new Double3(-0.1040307469f, 0.3890079625f, -0.2008741118f), new Double3(-0.1432122615f, 0.371614387f, -0.2095065525f), new Double3(0.3978380468f, -0.06206669342f, 0.2009293758f), new Double3(-0.2599274663f, 0.2616724959f, -0.2578084893f), new Double3(0.4032618332f, -0.1124593585f, 0.1650235939f), new Double3(-0.08953470255f, -0.3048244735f, 0.3186935478f), new Double3(0.118937202f, -0.2875221847f, 0.325092195f), new Double3(0.02167047076f, -0.03284630549f, -0.4482761547f), new Double3(-0.3411343612f, 0.2500031105f, 0.1537068389f), new Double3(0.3162964612f, 0.3082064153f, -0.08640228117f), new Double3(0.2355138889f, -0.3439334267f, -0.1695376245f), new Double3(-0.02874541518f, -0.3955933019f, 0.2125550295f), new Double3(-0.2461455173f, 0.02020282325f, -0.3761704803f), new Double3(0.04208029445f, -0.4470439576f, 0.02968078139f), new Double3(0.2727458746f, 0.2288471896f, -0.2752065618f), new Double3(-0.1347522818f, -0.02720848277f, -0.4284874806f), new Double3(0.3829624424f, 0.1231931484f, -0.2016512234f), new Double3(-0.3547613644f, 0.1271702173f, 0.2459107769f), new Double3(0.2305790207f, 0.3063895591f, 0.2354968222f), new Double3(-0.08323845599f, -0.1922245118f, 0.3982726409f), new Double3(0.2993663085f, -0.2619918095f, -0.2103333191f), new Double3(-0.2154865723f, 0.2706747713f, 0.287751117f), new Double3(0.01683355354f, -0.2680655787f, -0.3610505186f), new Double3(0.05240429123f, 0.4335128183f, -0.1087217856f), new Double3(0.00940104872f, -0.4472890582f, 0.04841609928f), new Double3(0.3465688735f, 0.01141914583f, -0.2868093776f), new Double3(-0.3706867948f, -0.2551104378f, 0.003156692623f), new Double3(0.2741169781f, 0.2139972417f, -0.2855959784f), new Double3(0.06413433865f, 0.1708718512f, 0.4113266307f), new Double3(-0.388187972f, -0.03973280434f, -0.2241236325f), new Double3(0.06419469312f, -0.2803682491f, 0.3460819069f), new Double3(-0.1986120739f, -0.3391173584f, 0.2192091725f), new Double3(-0.203203009f, -0.3871641506f, 0.1063600375f), new Double3(-0.1389736354f, -0.2775901578f, -0.3257760473f), new Double3(-0.06555641638f, 0.342253257f, -0.2847192729f), new Double3(-0.2529246486f, -0.2904227915f, 0.2327739768f), new Double3(0.1444476522f, 0.1069184044f, 0.4125570634f), new Double3(-0.3643780054f, -0.2447099973f, -0.09922543227f), new Double3(0.4286142488f, -0.1358496089f, -0.01829506817f), new Double3(0.165872923f, -0.3136808464f, -0.2767498872f), new Double3(0.2219610524f, -0.3658139958f, 0.1393320198f), new Double3(0.04322940318f, -0.3832730794f, 0.2318037215f), new Double3(-0.08481269795f, -0.4404869674f, -0.03574965489f), new Double3(0.1822082075f, -0.3953259299f, 0.1140946023f), new Double3(-0.3269323334f, 0.3036542563f, 0.05838957105f), new Double3(-0.4080485344f, 0.04227858267f, -0.184956522f), new Double3(0.2676025294f, -0.01299671652f, 0.36155217f), new Double3(0.3024892441f, -0.1009990293f, -0.3174892964f), new Double3(0.1448494052f, 0.425921681f, -0.0104580805f), new Double3(0.4198402157f, 0.08062320474f, 0.1404780841f), new Double3(-0.3008872161f, -0.333040905f, -0.03241355801f), new Double3(0.3639310428f, -0.1291284382f, -0.2310412139f), new Double3(0.3295806598f, 0.0184175994f, -0.3058388149f), new Double3(0.2776259487f, -0.2974929052f, -0.1921504723f), new Double3(0.4149000507f, -0.144793182f, -0.09691688386f), new Double3(0.145016715f, -0.0398992945f, 0.4241205002f), new Double3(0.09299023471f, -0.299732164f, -0.3225111565f), new Double3(0.1028907093f, -0.361266869f, 0.247789732f), new Double3(0.2683057049f, -0.07076041213f, -0.3542668666f), new Double3(-0.4227307273f, -0.07933161816f, -0.1323073187f), new Double3(-0.1781224702f, 0.1806857196f, -0.3716517945f), new Double3(0.4390788626f, -0.02841848598f, -0.09435116353f), new Double3(0.2972583585f, 0.2382799621f, -0.2394997452f), new Double3(-0.1707002821f, 0.2215845691f, 0.3525077196f), new Double3(0.3806686614f, 0.1471852559f, -0.1895464869f), new Double3(-0.1751445661f, -0.274887877f, 0.3102596268f), new Double3(-0.2227237566f, -0.2316778837f, 0.3149912482f), new Double3(0.1369633021f, 0.1341343041f, -0.4071228836f), new Double3(-0.3529503428f, -0.2472893463f, -0.129514612f), new Double3(-0.2590744185f, -0.2985577559f, -0.2150435121f), new Double3(-0.3784019401f, 0.2199816631f, -0.1044989934f), new Double3(-0.05635805671f, 0.1485737441f, 0.4210102279f), new Double3(0.3251428613f, 0.09666046873f, -0.2957006485f), new Double3(-0.4190995804f, 0.1406751354f, -0.08405978803f), new Double3(-0.3253150961f, -0.3080335042f, -0.04225456877f), new Double3(0.2857945863f, -0.05796152095f, 0.3427271751f), new Double3(-0.2733604046f, 0.1973770973f, -0.2980207554f), new Double3(0.219003657f, 0.2410037886f, -0.3105713639f), new Double3(0.3182767252f, -0.271342949f, 0.1660509868f), new Double3(-0.03222023115f, -0.3331161506f, -0.300824678f), new Double3(-0.3087780231f, 0.1992794134f, -0.2596995338f), new Double3(-0.06487611647f, -0.4311322747f, 0.1114273361f), new Double3(0.3921171432f, -0.06294284106f, -0.2116183942f), new Double3(-0.1606404506f, -0.358928121f, -0.2187812825f), new Double3(-0.03767771199f, -0.2290351443f, 0.3855169162f), new Double3(0.1394866832f, -0.3602213994f, 0.2308332918f), new Double3(-0.4345093872f, 0.005751117145f, 0.1169124335f), new Double3(-0.1044637494f, 0.4168128432f, -0.1336202785f), new Double3(0.2658727501f, 0.2551943237f, 0.2582393035f), new Double3(0.2051461999f, 0.1975390727f, 0.3484154868f), new Double3(-0.266085566f, 0.23483312f, 0.2766800993f), new Double3(0.07849405464f, -0.3300346342f, -0.2956616708f), new Double3(-0.2160686338f, 0.05376451292f, -0.3910546287f), new Double3(-0.185779186f, 0.2148499206f, 0.3490352499f), new Double3(0.02492421743f, -0.3229954284f, -0.3123343347f), new Double3(-0.120167831f, 0.4017266681f, 0.1633259825f), new Double3(-0.02160084693f, -0.06885389554f, 0.4441762538f), new Double3(0.2597670064f, 0.3096300784f, 0.1978643903f), new Double3(-0.1611553854f, -0.09823036005f, 0.4085091653f), new Double3(-0.3278896792f, 0.1461670309f, 0.2713366126f), new Double3(0.2822734956f, 0.03754421121f, -0.3484423997f), new Double3(0.03169341113f, 0.347405252f, -0.2842624114f), new Double3(0.2202613604f, -0.3460788041f, -0.1849713341f), new Double3(0.2933396046f, 0.3031973659f, 0.1565989581f), new Double3(-0.3194922995f, 0.2453752201f, -0.200538455f), new Double3(-0.3441586045f, -0.1698856132f, -0.2349334659f), new Double3(0.2703645948f, -0.3574277231f, 0.04060059933f), new Double3(0.2298568861f, 0.3744156221f, 0.0973588921f), new Double3(0.09326603877f, -0.3170108894f, 0.3054595587f), new Double3(-0.1116165319f, -0.2985018719f, 0.3177080142f), new Double3(0.2172907365f, -0.3460005203f, -0.1885958001f), new Double3(0.1991339479f, 0.3820341668f, -0.1299829458f), new Double3(-0.0541918155f, -0.2103145071f, 0.39412061f), new Double3(0.08871336998f, 0.2012117383f, 0.3926114802f), new Double3(0.2787673278f, 0.3505404674f, 0.04370535101f), new Double3(-0.322166438f, 0.3067213525f, 0.06804996813f), new Double3(-0.4277366384f, 0.132066775f, 0.04582286686f), new Double3(0.240131882f, -0.1612516055f, 0.344723946f), new Double3(0.1448607981f, -0.2387819045f, 0.3528435224f), new Double3(-0.3837065682f, -0.2206398454f, 0.08116235683f), new Double3(-0.4382627882f, -0.09082753406f, -0.04664855374f), new Double3(-0.37728353f, 0.05445141085f, 0.2391488697f), new Double3(0.1259579313f, 0.348394558f, 0.2554522098f), new Double3(-0.1406285511f, -0.270877371f, -0.3306796947f), new Double3(-0.1580694418f, 0.4162931958f, -0.06491553533f), new Double3(0.2477612106f, -0.2927867412f, -0.2353514536f), new Double3(0.2916132853f, 0.3312535401f, 0.08793624968f), new Double3(0.07365265219f, -0.1666159848f, 0.411478311f), new Double3(-0.26126526f, -0.2422237692f, 0.2748965434f), new Double3(-0.3721862032f, 0.252790166f, 0.008634938242f), new Double3(-0.3691191571f, -0.255281188f, 0.03290232422f), new Double3(0.2278441737f, -0.3358364886f, 0.1944244981f), new Double3(0.363398169f, -0.2310190248f, 0.1306597909f), new Double3(-0.304231482f, -0.2698452035f, 0.1926830856f), new Double3(-0.3199312232f, 0.316332536f, -0.008816977938f), new Double3(0.2874852279f, 0.1642275508f, -0.304764754f), new Double3(-0.1451096801f, 0.3277541114f, -0.2720669462f), new Double3(0.3220090754f, 0.0511344108f, 0.3101538769f), new Double3(-0.1247400865f, -0.04333605335f, -0.4301882115f), new Double3(-0.2829555867f, -0.3056190617f, -0.1703910946f), new Double3(0.1069384374f, 0.3491024667f, -0.2630430352f), new Double3(-0.1420661144f, -0.3055376754f, -0.2982682484f), new Double3(-0.250548338f, 0.3156466809f, -0.2002316239f), new Double3(0.3265787872f, 0.1871229129f, 0.2466400438f), new Double3(0.07646097258f, -0.3026690852f, 0.324106687f), new Double3(0.3451771584f, 0.2757120714f, -0.0856480183f), new Double3(0.298137964f, 0.2852657134f, 0.179547284f), new Double3(0.2812250376f, 0.3466716415f, 0.05684409612f), new Double3(0.4390345476f, -0.09790429955f, -0.01278335452f), new Double3(0.2148373234f, 0.1850172527f, 0.3494474791f), new Double3(0.2595421179f, -0.07946825393f, 0.3589187731f), new Double3(0.3182823114f, -0.307355516f, -0.08203022006f), new Double3(-0.4089859285f, -0.04647718411f, 0.1818526372f), new Double3(-0.2826749061f, 0.07417482322f, 0.3421885344f), new Double3(0.3483864637f, 0.225442246f, -0.1740766085f), new Double3(-0.3226415069f, -0.1420585388f, -0.2796816575f), new Double3(0.4330734858f, -0.118868561f, -0.02859407492f), new Double3(-0.08717822568f, -0.3909896417f, -0.2050050172f), new Double3(-0.2149678299f, 0.3939973956f, -0.03247898316f), new Double3(-0.2687330705f, 0.322686276f, -0.1617284888f), new Double3(0.2105665099f, -0.1961317136f, -0.3459683451f), new Double3(0.4361845915f, -0.1105517485f, 0.004616608544f), new Double3(0.05333333359f, -0.313639498f, -0.3182543336f), new Double3(-0.05986216652f, 0.1361029153f, -0.4247264031f), new Double3(0.3664988455f, 0.2550543014f, -0.05590974511f), new Double3(-0.2341015558f, -0.182405731f, 0.3382670703f), new Double3(-0.04730947785f, -0.4222150243f, -0.1483114513f), new Double3(-0.2391566239f, -0.2577696514f, -0.2808182972f), new Double3(-0.1242081035f, 0.4256953395f, -0.07652336246f), new Double3(0.2614832715f, -0.3650179274f, 0.02980623099f), new Double3(-0.2728794681f, -0.3499628774f, 0.07458404908f), new Double3(0.007892900508f, -0.1672771315f, 0.4176793787f), new Double3(-0.01730330376f, 0.2978486637f, -0.3368779738f), new Double3(0.2054835762f, -0.3252600376f, -0.2334146693f), new Double3(-0.3231994983f, 0.1564282844f, -0.2712420987f), new Double3(-0.2669545963f, 0.2599343665f, -0.2523278991f), new Double3(-0.05554372779f, 0.3170813944f, -0.3144428146f), new Double3(-0.2083935713f, -0.310922837f, -0.2497981362f), new Double3(0.06989323478f, -0.3156141536f, 0.3130537363f), new Double3(0.3847566193f, -0.1605309138f, -0.1693876312f), new Double3(-0.3026215288f, -0.3001537679f, -0.1443188342f), new Double3(0.3450735512f, 0.08611519592f, 0.2756962409f), new Double3(0.1814473292f, -0.2788782453f, -0.3029914042f), new Double3(-0.03855010448f, 0.09795110726f, 0.4375151083f), new Double3(0.3533670318f, 0.2665752752f, 0.08105160988f), new Double3(-0.007945601311f, 0.140359426f, -0.4274764309f), new Double3(0.4063099273f, -0.1491768253f, -0.1231199324f), new Double3(-0.2016773589f, 0.008816271194f, -0.4021797064f), new Double3(-0.07527055435f, -0.425643481f, -0.1251477955f), - }; - - private static long fastFloor(double f) - { - return (f >= 0 ? (long) f : (long) f - 1); - } - - private static long fastRound(double f) - { - return (f >= 0) ? (long) (f + (double) 0.5) : (long) (f - (double) 0.5); - } - - private static double lerp(double a, double b, double t) - { - return a + t * (b - a); - } - - private static double longerpHermiteFunc(double t) - { - return t * t * (3 - 2 * t); - } - - private static double longerpQulongicFunc(double t) - { - return t * t * t * (t * (t * 6 - 15) + 10); - } - - private static double cubicLerp(double a, double b, double c, double d, double t) - { - double p = (d - c) - (a - b); - return t * t * t * p + t * t * ((a - b) - p) + t * (c - a) + b; - } - - private void calculateFractalBounding() - { - double amp = m_gain; - double ampFractal = 1; - for(long i = 1; i < m_octaves; i++) - { - ampFractal += amp; - amp *= m_gain; - } - m_fractalBounding = 1 / ampFractal; - } - - // Hashing - private final static long X_PRIME = 1619; - private final static long Y_PRIME = 31337; - private final static long Z_PRIME = 6971; - private final static long W_PRIME = 1013; - - private static long hash2D(long seed, long x, long y) - { - long hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - return hash; - } - - private static long hash3D(long seed, long x, long y, long z) - { - long hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - hash ^= Z_PRIME * z; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - return hash; - } - - public static long hash4D(long seed, long x, long y, long z, long w) - { - long hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - hash ^= Z_PRIME * z; - hash ^= W_PRIME * w; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - return hash; - } - - private static double valCoord2D(long seed, long x, long y) - { - long n = seed; - n ^= X_PRIME * x; - n ^= Y_PRIME * y; - - return ((n * n * n * 60493L) / (double) Long.MAX_VALUE); - } - - private static double valCoord3D(long seed, long x, long y, long z) - { - long n = seed; - n ^= X_PRIME * x; - n ^= Y_PRIME * y; - n ^= Z_PRIME * z; - - return ((n * n * n * 60493L) / (double) Long.MAX_VALUE); - } - - private static double valCoord4D(long seed, long x, long y, long z, long w) - { - long n = seed; - n ^= X_PRIME * x; - n ^= Y_PRIME * y; - n ^= Z_PRIME * z; - n ^= W_PRIME * w; - - return ((n * n * n * 60493L) / (double) Long.MAX_VALUE); - } - - private static double GradCoord2D(long seed, long x, long y, double xd, double yd) - { - long hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - Double2 g = GRAD_2D[(int) hash & 7]; - - return xd * g.x + yd * g.y; - } - - private static double GradCoord3D(long seed, long x, long y, long z, double xd, double yd, double zd) - { - long hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - hash ^= Z_PRIME * z; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - Double3 g = GRAD_3D[(int) (hash & 15)]; - - return xd * g.x + yd * g.y + zd * g.z; - } - - private static double GradCoord4D(long seed, long x, long y, long z, long w, double xd, double yd, double zd, double wd) - { - long hash = seed; - hash ^= X_PRIME * x; - hash ^= Y_PRIME * y; - hash ^= Z_PRIME * z; - hash ^= W_PRIME * w; - - hash = hash * hash * hash * 60493; - hash = (hash >> 13) ^ hash; - - hash &= 31; - double a = yd, b = zd, c = wd; // X,Y,Z - switch((int) hash >> 3) - { // OR, DEPENDING ON HIGH ORDER 2 BITS: - case 1: - a = wd; - b = xd; - c = yd; - break; // W,X,Y - case 2: - a = zd; - b = wd; - c = xd; - break; // Z,W,X - case 3: - a = yd; - b = zd; - c = wd; - break; // Y,Z,W - } - return ((hash & 4) == 0 ? -a : a) + ((hash & 2) == 0 ? -b : b) + ((hash & 1) == 0 ? -c : c); - } - - public double GetNoise(double x, double y, double z) - { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - switch(m_noiseType) - { - case Value: - return SingleValue(m_seed, x, y, z); - case ValueFractal: - switch(m_fractalType) - { - case FBM: - return SingleValueFractalFBM(x, y, z); - case Billow: - return SingleValueFractalBillow(x, y, z); - case RigidMulti: - return SingleValueFractalRigidMulti(x, y, z); - default: - return 0; - } - case Perlin: - return SinglePerlin(m_seed, x, y, z); - case PerlinFractal: - switch(m_fractalType) - { - case FBM: - return SinglePerlinFractalFBM(x, y, z); - case Billow: - return SinglePerlinFractalBillow(x, y, z); - case RigidMulti: - return SinglePerlinFractalRigidMulti(x, y, z); - default: - return 0; - } - case Simplex: - return SingleSimplex(m_seed, x, y, z); - case SimplexFractal: - switch(m_fractalType) - { - case FBM: - return SingleSimplexFractalFBM(x, y, z); - case Billow: - return SingleSimplexFractalBillow(x, y, z); - case RigidMulti: - return SingleSimplexFractalRigidMulti(x, y, z); - default: - return 0; - } - case Cellular: - switch(m_cellularReturnType) - { - case CellValue: - case NoiseLookup: - case Distance: - return SingleCellular(x, y, z); - default: - return SingleCellular2Edge(x, y, z); - } - case WhiteNoise: - return GetWhiteNoise(x, y, z); - case Cubic: - return SingleCubic(m_seed, x, y, z); - case CubicFractal: - switch(m_fractalType) - { - case FBM: - return SingleCubicFractalFBM(x, y, z); - case Billow: - return SingleCubicFractalBillow(x, y, z); - case RigidMulti: - return SingleCubicFractalRigidMulti(x, y, z); - default: - return 0; - } - default: - return 0; - } - } - - public double GetNoise(double x, double y) - { - x *= m_frequency; - y *= m_frequency; - - switch(m_noiseType) - { - case Value: - return SingleValue(m_seed, x, y); - case ValueFractal: - switch(m_fractalType) - { - case FBM: - return SingleValueFractalFBM(x, y); - case Billow: - return SingleValueFractalBillow(x, y); - case RigidMulti: - return SingleValueFractalRigidMulti(x, y); - default: - return 0; - } - case Perlin: - return SinglePerlin(m_seed, x, y); - case PerlinFractal: - switch(m_fractalType) - { - case FBM: - return SinglePerlinFractalFBM(x, y); - case Billow: - return SinglePerlinFractalBillow(x, y); - case RigidMulti: - return SinglePerlinFractalRigidMulti(x, y); - default: - return 0; - } - case Simplex: - return SingleSimplex(m_seed, x, y); - case SimplexFractal: - switch(m_fractalType) - { - case FBM: - return SingleSimplexFractalFBM(x, y); - case Billow: - return SingleSimplexFractalBillow(x, y); - case RigidMulti: - return SingleSimplexFractalRigidMulti(x, y); - default: - return 0; - } - case Cellular: - switch(m_cellularReturnType) - { - case CellValue: - case NoiseLookup: - case Distance: - return SingleCellular(x, y); - default: - return SingleCellular2Edge(x, y); - } - case WhiteNoise: - return GetWhiteNoise(x, y); - case Cubic: - return SingleCubic(m_seed, x, y); - case CubicFractal: - switch(m_fractalType) - { - case FBM: - return SingleCubicFractalFBM(x, y); - case Billow: - return SingleCubicFractalBillow(x, y); - case RigidMulti: - return SingleCubicFractalRigidMulti(x, y); - default: - return 0; - } - default: - return 0; - } - } - - // White Noise - - private long DoubleCast2Long(double f) - { - long i = Double.doubleToRawLongBits(f); - - return i ^ (i >> 16); - } - - public double GetWhiteNoise(double x, double y, double z, double w) - { - long xi = DoubleCast2Long(x); - long yi = DoubleCast2Long(y); - long zi = DoubleCast2Long(z); - long wi = DoubleCast2Long(w); - - return valCoord4D(m_seed, xi, yi, zi, wi); - } - - public double GetWhiteNoise(double x, double y, double z) - { - long xi = DoubleCast2Long(x); - long yi = DoubleCast2Long(y); - long zi = DoubleCast2Long(z); - - return valCoord3D(m_seed, xi, yi, zi); - } - - public double GetWhiteNoise(double x, double y) - { - long xi = DoubleCast2Long(x); - long yi = DoubleCast2Long(y); - - return valCoord2D(m_seed, xi, yi); - } - - public double GetWhiteNoiseLong(long x, long y, long z, long w) - { - return valCoord4D(m_seed, x, y, z, w); - } - - public double GetWhiteNoiseLong(long x, long y, long z) - { - return valCoord3D(m_seed, x, y, z); - } - - public double GetWhiteNoiseLong(long x, long y) - { - return valCoord2D(m_seed, x, y); - } - - // Value Noise - public double GetValueFractal(double x, double y, double z) - { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - switch(m_fractalType) - { - case FBM: - return SingleValueFractalFBM(x, y, z); - case Billow: - return SingleValueFractalBillow(x, y, z); - case RigidMulti: - return SingleValueFractalRigidMulti(x, y, z); - default: - return 0; - } - } - - private double SingleValueFractalFBM(double x, double y, double z) - { - long seed = m_seed; - double sum = SingleValue(seed, x, y, z); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += SingleValue(++seed, x, y, z) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleValueFractalBillow(double x, double y, double z) - { - long seed = m_seed; - double sum = Math.abs(SingleValue(seed, x, y, z)) * 2 - 1; - double amp = 1; - - for(long i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SingleValue(++seed, x, y, z)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleValueFractalRigidMulti(double x, double y, double z) - { - long seed = m_seed; - double sum = 1 - Math.abs(SingleValue(seed, x, y, z)); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleValue(++seed, x, y, z))) * amp; - } - - return sum; - } - - public double GetValue(double x, double y, double z) - { - return SingleValue(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); - } - - private double SingleValue(long seed, double x, double y, double z) - { - long x0 = fastFloor(x); - long y0 = fastFloor(y); - long z0 = fastFloor(z); - long x1 = x0 + 1; - long y1 = y0 + 1; - long z1 = z0 + 1; - - double xs, ys, zs; - switch(m_longerp) - { - default: - case Linear: - xs = x - x0; - ys = y - y0; - zs = z - z0; - break; - case Hermite: - xs = longerpHermiteFunc(x - x0); - ys = longerpHermiteFunc(y - y0); - zs = longerpHermiteFunc(z - z0); - break; - case Qulongic: - xs = longerpQulongicFunc(x - x0); - ys = longerpQulongicFunc(y - y0); - zs = longerpQulongicFunc(z - z0); - break; - } - - double xf00 = lerp(valCoord3D(seed, x0, y0, z0), valCoord3D(seed, x1, y0, z0), xs); - double xf10 = lerp(valCoord3D(seed, x0, y1, z0), valCoord3D(seed, x1, y1, z0), xs); - double xf01 = lerp(valCoord3D(seed, x0, y0, z1), valCoord3D(seed, x1, y0, z1), xs); - double xf11 = lerp(valCoord3D(seed, x0, y1, z1), valCoord3D(seed, x1, y1, z1), xs); - - double yf0 = lerp(xf00, xf10, ys); - double yf1 = lerp(xf01, xf11, ys); - - return lerp(yf0, yf1, zs); - } - - public double GetValueFractal(double x, double y) - { - x *= m_frequency; - y *= m_frequency; - - switch(m_fractalType) - { - case FBM: - return SingleValueFractalFBM(x, y); - case Billow: - return SingleValueFractalBillow(x, y); - case RigidMulti: - return SingleValueFractalRigidMulti(x, y); - default: - return 0; - } - } - - private double SingleValueFractalFBM(double x, double y) - { - long seed = m_seed; - double sum = SingleValue(seed, x, y); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += SingleValue(++seed, x, y) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleValueFractalBillow(double x, double y) - { - long seed = m_seed; - double sum = Math.abs(SingleValue(seed, x, y)) * 2 - 1; - double amp = 1; - - for(long i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - amp *= m_gain; - sum += (Math.abs(SingleValue(++seed, x, y)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleValueFractalRigidMulti(double x, double y) - { - long seed = m_seed; - double sum = 1 - Math.abs(SingleValue(seed, x, y)); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleValue(++seed, x, y))) * amp; - } - - return sum; - } - - public double GetValue(double x, double y) - { - return SingleValue(m_seed, x * m_frequency, y * m_frequency); - } - - private double SingleValue(long seed, double x, double y) - { - long x0 = fastFloor(x); - long y0 = fastFloor(y); - long x1 = x0 + 1; - long y1 = y0 + 1; - - double xs, ys; - switch(m_longerp) - { - default: - case Linear: - xs = x - x0; - ys = y - y0; - break; - case Hermite: - xs = longerpHermiteFunc(x - x0); - ys = longerpHermiteFunc(y - y0); - break; - case Qulongic: - xs = longerpQulongicFunc(x - x0); - ys = longerpQulongicFunc(y - y0); - break; - } - - double xf0 = lerp(valCoord2D(seed, x0, y0), valCoord2D(seed, x1, y0), xs); - double xf1 = lerp(valCoord2D(seed, x0, y1), valCoord2D(seed, x1, y1), xs); - - return lerp(xf0, xf1, ys); - } - - // Gradient Noise - public double GetPerlinFractal(double x, double y, double z) - { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - switch(m_fractalType) - { - case FBM: - return SinglePerlinFractalFBM(x, y, z); - case Billow: - return SinglePerlinFractalBillow(x, y, z); - case RigidMulti: - return SinglePerlinFractalRigidMulti(x, y, z); - default: - return 0; - } - } - - private double SinglePerlinFractalFBM(double x, double y, double z) - { - long seed = m_seed; - double sum = SinglePerlin(seed, x, y, z); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += SinglePerlin(++seed, x, y, z) * amp; - } - - return sum * m_fractalBounding; - } - - private double SinglePerlinFractalBillow(double x, double y, double z) - { - long seed = m_seed; - double sum = Math.abs(SinglePerlin(seed, x, y, z)) * 2 - 1; - double amp = 1; - - for(long i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SinglePerlin(++seed, x, y, z)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private double SinglePerlinFractalRigidMulti(double x, double y, double z) - { - long seed = m_seed; - double sum = 1 - Math.abs(SinglePerlin(seed, x, y, z)); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SinglePerlin(++seed, x, y, z))) * amp; - } - - return sum; - } - - public double GetPerlin(double x, double y, double z) - { - return SinglePerlin(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); - } - - private double SinglePerlin(long seed, double x, double y, double z) - { - long x0 = fastFloor(x); - long y0 = fastFloor(y); - long z0 = fastFloor(z); - long x1 = x0 + 1; - long y1 = y0 + 1; - long z1 = z0 + 1; - - double xs, ys, zs; - switch(m_longerp) - { - default: - case Linear: - xs = x - x0; - ys = y - y0; - zs = z - z0; - break; - case Hermite: - xs = longerpHermiteFunc(x - x0); - ys = longerpHermiteFunc(y - y0); - zs = longerpHermiteFunc(z - z0); - break; - case Qulongic: - xs = longerpQulongicFunc(x - x0); - ys = longerpQulongicFunc(y - y0); - zs = longerpQulongicFunc(z - z0); - break; - } - - double xd0 = x - x0; - double yd0 = y - y0; - double zd0 = z - z0; - double xd1 = xd0 - 1; - double yd1 = yd0 - 1; - double zd1 = zd0 - 1; - - double xf00 = lerp(GradCoord3D(seed, x0, y0, z0, xd0, yd0, zd0), GradCoord3D(seed, x1, y0, z0, xd1, yd0, zd0), xs); - double xf10 = lerp(GradCoord3D(seed, x0, y1, z0, xd0, yd1, zd0), GradCoord3D(seed, x1, y1, z0, xd1, yd1, zd0), xs); - double xf01 = lerp(GradCoord3D(seed, x0, y0, z1, xd0, yd0, zd1), GradCoord3D(seed, x1, y0, z1, xd1, yd0, zd1), xs); - double xf11 = lerp(GradCoord3D(seed, x0, y1, z1, xd0, yd1, zd1), GradCoord3D(seed, x1, y1, z1, xd1, yd1, zd1), xs); - - double yf0 = lerp(xf00, xf10, ys); - double yf1 = lerp(xf01, xf11, ys); - - return lerp(yf0, yf1, zs); - } - - public double GetPerlinFractal(double x, double y) - { - x *= m_frequency; - y *= m_frequency; - - switch(m_fractalType) - { - case FBM: - return SinglePerlinFractalFBM(x, y); - case Billow: - return SinglePerlinFractalBillow(x, y); - case RigidMulti: - return SinglePerlinFractalRigidMulti(x, y); - default: - return 0; - } - } - - private double SinglePerlinFractalFBM(double x, double y) - { - long seed = m_seed; - double sum = SinglePerlin(seed, x, y); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += SinglePerlin(++seed, x, y) * amp; - } - - return sum * m_fractalBounding; - } - - private double SinglePerlinFractalBillow(double x, double y) - { - long seed = m_seed; - double sum = Math.abs(SinglePerlin(seed, x, y)) * 2 - 1; - double amp = 1; - - for(long i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SinglePerlin(++seed, x, y)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private double SinglePerlinFractalRigidMulti(double x, double y) - { - long seed = m_seed; - double sum = 1 - Math.abs(SinglePerlin(seed, x, y)); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SinglePerlin(++seed, x, y))) * amp; - } - - return sum; - } - - public double GetPerlin(double x, double y) - { - return SinglePerlin(m_seed, x * m_frequency, y * m_frequency); - } - - private double SinglePerlin(long seed, double x, double y) - { - long x0 = fastFloor(x); - long y0 = fastFloor(y); - long x1 = x0 + 1; - long y1 = y0 + 1; - - double xs = 0, ys = 0; - switch (m_longerp) { - case Linear -> { - xs = x - x0; - ys = y - y0; - } - case Hermite -> { - xs = longerpHermiteFunc(x - x0); - ys = longerpHermiteFunc(y - y0); - } - case Qulongic -> { - xs = longerpQulongicFunc(x - x0); - ys = longerpQulongicFunc(y - y0); - } - } - - double xd0 = x - x0; - double yd0 = y - y0; - double xd1 = xd0 - 1; - double yd1 = yd0 - 1; - - double xf0 = lerp(GradCoord2D(seed, x0, y0, xd0, yd0), GradCoord2D(seed, x1, y0, xd1, yd0), xs); - double xf1 = lerp(GradCoord2D(seed, x0, y1, xd0, yd1), GradCoord2D(seed, x1, y1, xd1, yd1), xs); - - return lerp(xf0, xf1, ys); - } - - // Simplex Noise - public double GetSimplexFractal(double x, double y, double z) - { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - switch(m_fractalType) - { - case FBM: - return SingleSimplexFractalFBM(x, y, z); - case Billow: - return SingleSimplexFractalBillow(x, y, z); - case RigidMulti: - return SingleSimplexFractalRigidMulti(x, y, z); - default: - return 0; - } - } - - private double SingleSimplexFractalFBM(double x, double y, double z) - { - long seed = m_seed; - double sum = SingleSimplex(seed, x, y, z); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += SingleSimplex(++seed, x, y, z) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleSimplexFractalBillow(double x, double y, double z) - { - long seed = m_seed; - double sum = Math.abs(SingleSimplex(seed, x, y, z)) * 2 - 1; - double amp = 1; - - for(long i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SingleSimplex(++seed, x, y, z)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleSimplexFractalRigidMulti(double x, double y, double z) - { - long seed = m_seed; - double sum = 1 - Math.abs(SingleSimplex(seed, x, y, z)); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleSimplex(++seed, x, y, z))) * amp; - } - - return sum; - } - - public double GetSimplex(double x, double y, double z) - { - return SingleSimplex(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); - } - - private final static double F3 = (double) (1.0 / 3.0); - private final static double G3 = (double) (1.0 / 6.0); - private final static double G33 = G3 * 3 - 1; - - private double SingleSimplex(long seed, double x, double y, double z) - { - double t = (x + y + z) * F3; - long i = fastFloor(x + t); - long j = fastFloor(y + t); - long k = fastFloor(z + t); - - t = (i + j + k) * G3; - double x0 = x - (i - t); - double y0 = y - (j - t); - double z0 = z - (k - t); - - long i1, j1, k1; - long i2, j2, k2; - - if(x0 >= y0) - { - if(y0 >= z0) - { - i1 = 1; - j1 = 0; - k1 = 0; - i2 = 1; - j2 = 1; - k2 = 0; - } - else if(x0 >= z0) - { - i1 = 1; - j1 = 0; - k1 = 0; - i2 = 1; - j2 = 0; - k2 = 1; - } - else // x0 < z0 - { - i1 = 0; - j1 = 0; - k1 = 1; - i2 = 1; - j2 = 0; - k2 = 1; - } - } - else // x0 < y0 - { - if(y0 < z0) - { - i1 = 0; - j1 = 0; - k1 = 1; - i2 = 0; - j2 = 1; - k2 = 1; - } - else if(x0 < z0) - { - i1 = 0; - j1 = 1; - k1 = 0; - i2 = 0; - j2 = 1; - k2 = 1; - } - else // x0 >= z0 - { - i1 = 0; - j1 = 1; - k1 = 0; - i2 = 1; - j2 = 1; - k2 = 0; - } - } - - double x1 = x0 - i1 + G3; - double y1 = y0 - j1 + G3; - double z1 = z0 - k1 + G3; - double x2 = x0 - i2 + F3; - double y2 = y0 - j2 + F3; - double z2 = z0 - k2 + F3; - double x3 = x0 + G33; - double y3 = y0 + G33; - double z3 = z0 + G33; - - double n0, n1, n2, n3; - - t = (double) 0.6 - x0 * x0 - y0 * y0 - z0 * z0; - if(t < 0) - n0 = 0; - else - { - t *= t; - n0 = t * t * GradCoord3D(seed, i, j, k, x0, y0, z0); - } - - t = (double) 0.6 - x1 * x1 - y1 * y1 - z1 * z1; - if(t < 0) - n1 = 0; - else - { - t *= t; - n1 = t * t * GradCoord3D(seed, i + i1, j + j1, k + k1, x1, y1, z1); - } - - t = (double) 0.6 - x2 * x2 - y2 * y2 - z2 * z2; - if(t < 0) - n2 = 0; - else - { - t *= t; - n2 = t * t * GradCoord3D(seed, i + i2, j + j2, k + k2, x2, y2, z2); - } - - t = (double) 0.6 - x3 * x3 - y3 * y3 - z3 * z3; - if(t < 0) - n3 = 0; - else - { - t *= t; - n3 = t * t * GradCoord3D(seed, i + 1, j + 1, k + 1, x3, y3, z3); - } - - return 32 * (n0 + n1 + n2 + n3); - } - - public double GetSimplexFractal(double x, double y) - { - x *= m_frequency; - y *= m_frequency; - - switch(m_fractalType) - { - case FBM: - return SingleSimplexFractalFBM(x, y); - case Billow: - return SingleSimplexFractalBillow(x, y); - case RigidMulti: - return SingleSimplexFractalRigidMulti(x, y); - default: - return 0; - } - } - - private double SingleSimplexFractalFBM(double x, double y) - { - long seed = m_seed; - double sum = SingleSimplex(seed, x, y); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += SingleSimplex(++seed, x, y) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleSimplexFractalBillow(double x, double y) - { - long seed = m_seed; - double sum = Math.abs(SingleSimplex(seed, x, y)) * 2 - 1; - double amp = 1; - - for(long i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SingleSimplex(++seed, x, y)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleSimplexFractalRigidMulti(double x, double y) - { - long seed = m_seed; - double sum = 1 - Math.abs(SingleSimplex(seed, x, y)); - double amp = 1; - - for(long i = 1; i < m_octaves; i++) - { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleSimplex(++seed, x, y))) * amp; - } - - return sum; - } - - public double GetSimplex(double x, double y) - { - return SingleSimplex(m_seed, x * m_frequency, y * m_frequency); - } - - private final static double F2 = (double) (1.0 / 2.0); - private final static double G2 = (double) (1.0 / 4.0); - - private double SingleSimplex(long seed, double x, double y) - { - double t = (x + y) * F2; - long i = fastFloor(x + t); - long j = fastFloor(y + t); - - t = (i + j) * G2; - double X0 = i - t; - double Y0 = j - t; - - double x0 = x - X0; - double y0 = y - Y0; - - long i1, j1; - if(x0 > y0) - { - i1 = 1; - j1 = 0; - } - else - { - i1 = 0; - j1 = 1; - } - - double x1 = x0 - i1 + G2; - double y1 = y0 - j1 + G2; - double x2 = x0 - 1 + F2; - double y2 = y0 - 1 + F2; - - double n0, n1, n2; - - t = (double) 0.5 - x0 * x0 - y0 * y0; - if(t < 0) - n0 = 0; - else - { - t *= t; - n0 = t * t * GradCoord2D(seed, i, j, x0, y0); - } - - t = (double) 0.5 - x1 * x1 - y1 * y1; - if(t < 0) - n1 = 0; - else - { - t *= t; - n1 = t * t * GradCoord2D(seed, i + i1, j + j1, x1, y1); - } - - t = (double) 0.5 - x2 * x2 - y2 * y2; - if(t < 0) - n2 = 0; - else - { - t *= t; - n2 = t * t * GradCoord2D(seed, i + 1, j + 1, x2, y2); - } - - return 50 * (n0 + n1 + n2); - } - - public double GetSimplex(double x, double y, double z, double w) - { - return SingleSimplex(m_seed, x * m_frequency, y * m_frequency, z * m_frequency, w * m_frequency); - } - - private static final byte[] SIMPLEX_4D = {0, 1, 2, 3, 0, 1, 3, 2, 0, 0, 0, 0, 0, 2, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 0, 2, 1, 3, 0, 0, 0, 0, 0, 3, 1, 2, 0, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 3, 0, 0, 0, 0, 1, 3, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 0, 1, 2, 3, 1, 0, 1, 0, 2, 3, 1, 0, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 1, 0, 0, 0, 0, 2, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 1, 2, 3, 0, 2, 1, 0, 0, 0, 0, 3, 1, 2, 0, 2, 1, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 1, 0, 2, 0, 0, 0, 0, 3, 2, 0, 1, 3, 2, 1, 0 - }; - - private final static double F4 = (double) ((2.23606797 - 1.0) / 4.0); - private final static double G4 = (double) ((5.0 - 2.23606797) / 20.0); - - private double SingleSimplex(long seed, double x, double y, double z, double w) - { - double n0, n1, n2, n3, n4; - double t = (x + y + z + w) * F4; - long i = fastFloor(x + t); - long j = fastFloor(y + t); - long k = fastFloor(z + t); - long l = fastFloor(w + t); - t = (i + j + k + l) * G4; - double X0 = i - t; - double Y0 = j - t; - double Z0 = k - t; - double W0 = l - t; - double x0 = x - X0; - double y0 = y - Y0; - double z0 = z - Z0; - double w0 = w - W0; - - int c = (x0 > y0) ? 32 : 0; - c += (x0 > z0) ? 16 : 0; - c += (y0 > z0) ? 8 : 0; - c += (x0 > w0) ? 4 : 0; - c += (y0 > w0) ? 2 : 0; - c += (z0 > w0) ? 1 : 0; - c <<= 2; - - long i1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; - long i2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; - long i3 = SIMPLEX_4D[c++] >= 1 ? 1 : 0; - long j1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; - long j2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; - long j3 = SIMPLEX_4D[c++] >= 1 ? 1 : 0; - long k1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; - long k2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; - long k3 = SIMPLEX_4D[c++] >= 1 ? 1 : 0; - long l1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; - long l2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; - long l3 = SIMPLEX_4D[c] >= 1 ? 1 : 0; - - double x1 = x0 - i1 + G4; - double y1 = y0 - j1 + G4; - double z1 = z0 - k1 + G4; - double w1 = w0 - l1 + G4; - double x2 = x0 - i2 + 2 * G4; - double y2 = y0 - j2 + 2 * G4; - double z2 = z0 - k2 + 2 * G4; - double w2 = w0 - l2 + 2 * G4; - double x3 = x0 - i3 + 3 * G4; - double y3 = y0 - j3 + 3 * G4; - double z3 = z0 - k3 + 3 * G4; - double w3 = w0 - l3 + 3 * G4; - double x4 = x0 - 1 + 4 * G4; - double y4 = y0 - 1 + 4 * G4; - double z4 = z0 - 1 + 4 * G4; - double w4 = w0 - 1 + 4 * G4; - - t = (double) 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0; - if(t < 0) - n0 = 0; - else - { - t *= t; - n0 = t * t * GradCoord4D(seed, i, j, k, l, x0, y0, z0, w0); - } - t = (double) 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1; - if(t < 0) - n1 = 0; - else - { - t *= t; - n1 = t * t * GradCoord4D(seed, i + i1, j + j1, k + k1, l + l1, x1, y1, z1, w1); - } - t = (double) 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2; - if(t < 0) - n2 = 0; - else - { - t *= t; - n2 = t * t * GradCoord4D(seed, i + i2, j + j2, k + k2, l + l2, x2, y2, z2, w2); - } - t = (double) 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3; - if(t < 0) - n3 = 0; - else - { - t *= t; - n3 = t * t * GradCoord4D(seed, i + i3, j + j3, k + k3, l + l3, x3, y3, z3, w3); - } - t = (double) 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4; - if(t < 0) - n4 = 0; - else - { - t *= t; - n4 = t * t * GradCoord4D(seed, i + 1, j + 1, k + 1, l + 1, x4, y4, z4, w4); - } - - return 27 * (n0 + n1 + n2 + n3 + n4); - } - - // Cubic Noise - public double GetCubicFractal(double x, double y, double z) - { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - switch(m_fractalType) - { - case FBM: - return SingleCubicFractalFBM(x, y, z); - case Billow: - return SingleCubicFractalBillow(x, y, z); - case RigidMulti: - return SingleCubicFractalRigidMulti(x, y, z); - default: - return 0; - } - } - - private double SingleCubicFractalFBM(double x, double y, double z) - { - long seed = m_seed; - double sum = SingleCubic(seed, x, y, z); - double amp = 1; - long i = 0; - - while(++i < m_octaves) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += SingleCubic(++seed, x, y, z) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleCubicFractalBillow(double x, double y, double z) - { - long seed = m_seed; - double sum = Math.abs(SingleCubic(seed, x, y, z)) * 2 - 1; - double amp = 1; - long i = 0; - - while(++i < m_octaves) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SingleCubic(++seed, x, y, z)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleCubicFractalRigidMulti(double x, double y, double z) - { - long seed = m_seed; - double sum = 1 - Math.abs(SingleCubic(seed, x, y, z)); - double amp = 1; - long i = 0; - - while(++i < m_octaves) - { - x *= m_lacunarity; - y *= m_lacunarity; - z *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleCubic(++seed, x, y, z))) * amp; - } - - return sum; - } - - public double GetCubic(double x, double y, double z) - { - return SingleCubic(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); - } - - private final static double CUBIC_3D_BOUNDING = 1 / (double) (1.5 * 1.5 * 1.5); - - private double SingleCubic(long seed, double x, double y, double z) - { - long x1 = fastFloor(x); - long y1 = fastFloor(y); - long z1 = fastFloor(z); - - long x0 = x1 - 1; - long y0 = y1 - 1; - long z0 = z1 - 1; - long x2 = x1 + 1; - long y2 = y1 + 1; - long z2 = z1 + 1; - long x3 = x1 + 2; - long y3 = y1 + 2; - long z3 = z1 + 2; - - double xs = x - (double) x1; - double ys = y - (double) y1; - double zs = z - (double) z1; - - return cubicLerp(cubicLerp(cubicLerp(valCoord3D(seed, x0, y0, z0), valCoord3D(seed, x1, y0, z0), valCoord3D(seed, x2, y0, z0), valCoord3D(seed, x3, y0, z0), xs), cubicLerp(valCoord3D(seed, x0, y1, z0), valCoord3D(seed, x1, y1, z0), valCoord3D(seed, x2, y1, z0), valCoord3D(seed, x3, y1, z0), xs), cubicLerp(valCoord3D(seed, x0, y2, z0), valCoord3D(seed, x1, y2, z0), valCoord3D(seed, x2, y2, z0), valCoord3D(seed, x3, y2, z0), xs), cubicLerp(valCoord3D(seed, x0, y3, z0), valCoord3D(seed, x1, y3, z0), valCoord3D(seed, x2, y3, z0), valCoord3D(seed, x3, y3, z0), xs), ys), cubicLerp(cubicLerp(valCoord3D(seed, x0, y0, z1), valCoord3D(seed, x1, y0, z1), valCoord3D(seed, x2, y0, z1), valCoord3D(seed, x3, y0, z1), xs), cubicLerp(valCoord3D(seed, x0, y1, z1), valCoord3D(seed, x1, y1, z1), valCoord3D(seed, x2, y1, z1), valCoord3D(seed, x3, y1, z1), xs), cubicLerp(valCoord3D(seed, x0, y2, z1), valCoord3D(seed, x1, y2, z1), valCoord3D(seed, x2, y2, z1), valCoord3D(seed, x3, y2, z1), xs), cubicLerp(valCoord3D(seed, x0, y3, z1), valCoord3D(seed, x1, y3, z1), valCoord3D(seed, x2, y3, z1), valCoord3D(seed, x3, y3, z1), xs), ys), cubicLerp(cubicLerp(valCoord3D(seed, x0, y0, z2), valCoord3D(seed, x1, y0, z2), valCoord3D(seed, x2, y0, z2), valCoord3D(seed, x3, y0, z2), xs), cubicLerp(valCoord3D(seed, x0, y1, z2), valCoord3D(seed, x1, y1, z2), valCoord3D(seed, x2, y1, z2), valCoord3D(seed, x3, y1, z2), xs), cubicLerp(valCoord3D(seed, x0, y2, z2), valCoord3D(seed, x1, y2, z2), valCoord3D(seed, x2, y2, z2), valCoord3D(seed, x3, y2, z2), xs), cubicLerp(valCoord3D(seed, x0, y3, z2), valCoord3D(seed, x1, y3, z2), valCoord3D(seed, x2, y3, z2), valCoord3D(seed, x3, y3, z2), xs), ys), cubicLerp(cubicLerp(valCoord3D(seed, x0, y0, z3), valCoord3D(seed, x1, y0, z3), valCoord3D(seed, x2, y0, z3), valCoord3D(seed, x3, y0, z3), xs), cubicLerp(valCoord3D(seed, x0, y1, z3), valCoord3D(seed, x1, y1, z3), valCoord3D(seed, x2, y1, z3), valCoord3D(seed, x3, y1, z3), xs), cubicLerp(valCoord3D(seed, x0, y2, z3), valCoord3D(seed, x1, y2, z3), valCoord3D(seed, x2, y2, z3), valCoord3D(seed, x3, y2, z3), xs), cubicLerp(valCoord3D(seed, x0, y3, z3), valCoord3D(seed, x1, y3, z3), valCoord3D(seed, x2, y3, z3), valCoord3D(seed, x3, y3, z3), xs), ys), zs) * CUBIC_3D_BOUNDING; - } - - public double GetCubicFractal(double x, double y) - { - x *= m_frequency; - y *= m_frequency; - - switch(m_fractalType) - { - case FBM: - return SingleCubicFractalFBM(x, y); - case Billow: - return SingleCubicFractalBillow(x, y); - case RigidMulti: - return SingleCubicFractalRigidMulti(x, y); - default: - return 0; - } - } - - private double SingleCubicFractalFBM(double x, double y) - { - long seed = m_seed; - double sum = SingleCubic(seed, x, y); - double amp = 1; - long i = 0; - - while(++i < m_octaves) - { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += SingleCubic(++seed, x, y) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleCubicFractalBillow(double x, double y) - { - long seed = m_seed; - double sum = Math.abs(SingleCubic(seed, x, y)) * 2 - 1; - double amp = 1; - long i = 0; - - while(++i < m_octaves) - { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum += (Math.abs(SingleCubic(++seed, x, y)) * 2 - 1) * amp; - } - - return sum * m_fractalBounding; - } - - private double SingleCubicFractalRigidMulti(double x, double y) - { - long seed = m_seed; - double sum = 1 - Math.abs(SingleCubic(seed, x, y)); - double amp = 1; - long i = 0; - - while(++i < m_octaves) - { - x *= m_lacunarity; - y *= m_lacunarity; - - amp *= m_gain; - sum -= (1 - Math.abs(SingleCubic(++seed, x, y))) * amp; - } - - return sum; - } - - public double GetCubic(double x, double y) - { - x *= m_frequency; - y *= m_frequency; - - return SingleCubic(0, x, y); - } - - private final static double CUBIC_2D_BOUNDING = 1 / (double) (1.5 * 1.5); - - private double SingleCubic(long seed, double x, double y) - { - long x1 = fastFloor(x); - long y1 = fastFloor(y); - - long x0 = x1 - 1; - long y0 = y1 - 1; - long x2 = x1 + 1; - long y2 = y1 + 1; - long x3 = x1 + 2; - long y3 = y1 + 2; - - double xs = x - (double) x1; - double ys = y - (double) y1; - - return cubicLerp(cubicLerp(valCoord2D(seed, x0, y0), valCoord2D(seed, x1, y0), valCoord2D(seed, x2, y0), valCoord2D(seed, x3, y0), xs), cubicLerp(valCoord2D(seed, x0, y1), valCoord2D(seed, x1, y1), valCoord2D(seed, x2, y1), valCoord2D(seed, x3, y1), xs), cubicLerp(valCoord2D(seed, x0, y2), valCoord2D(seed, x1, y2), valCoord2D(seed, x2, y2), valCoord2D(seed, x3, y2), xs), cubicLerp(valCoord2D(seed, x0, y3), valCoord2D(seed, x1, y3), valCoord2D(seed, x2, y3), valCoord2D(seed, x3, y3), xs), ys) * CUBIC_2D_BOUNDING; - } - - // Cellular Noise - public double GetCellular(double x, double y, double z) - { - x *= m_frequency; - y *= m_frequency; - z *= m_frequency; - - switch(m_cellularReturnType) - { - case CellValue: - case NoiseLookup: - case Distance: - return SingleCellular(x, y, z); - default: - return SingleCellular2Edge(x, y, z); - } - } - - private double SingleCellular(double x, double y, double z) - { - long xr = fastRound(x); - long yr = fastRound(y); - long zr = fastRound(z); - - double distance = 999999; - long xc = 0, yc = 0, zc = 0; - - switch(m_cellularDistanceFunction) - { - case Euclidean: - for(long xi = xr - 1; xi <= xr + 1; xi++) - { - for(long yi = yr - 1; yi <= yr + 1; yi++) - { - for(long zi = zr - 1; zi <= zr + 1; zi++) - { - Double3 vec = CELL_3D[(int) hash3D(m_seed, xi, yi, zi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - double vecZ = zi - z + vec.z; - - double newDistance = vecX * vecX + vecY * vecY + vecZ * vecZ; - - if(newDistance < distance) - { - distance = newDistance; - xc = xi; - yc = yi; - zc = zi; - } - } - } - } - break; - case Manhattan: - for(long xi = xr - 1; xi <= xr + 1; xi++) - { - for(long yi = yr - 1; yi <= yr + 1; yi++) - { - for(long zi = zr - 1; zi <= zr + 1; zi++) - { - Double3 vec = CELL_3D[(int) hash3D(m_seed, xi, yi, zi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - double vecZ = zi - z + vec.z; - - double newDistance = Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ); - - if(newDistance < distance) - { - distance = newDistance; - xc = xi; - yc = yi; - zc = zi; - } - } - } - } - break; - case Natural: - for(long xi = xr - 1; xi <= xr + 1; xi++) - { - for(long yi = yr - 1; yi <= yr + 1; yi++) - { - for(long zi = zr - 1; zi <= zr + 1; zi++) - { - Double3 vec = CELL_3D[(int) hash3D(m_seed, xi, yi, zi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - double vecZ = zi - z + vec.z; - - double newDistance = (Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ)) + (vecX * vecX + vecY * vecY + vecZ * vecZ); - - if(newDistance < distance) - { - distance = newDistance; - xc = xi; - yc = yi; - zc = zi; - } - } - } - } - break; - } - - switch(m_cellularReturnType) - { - case CellValue: - return valCoord3D(0, xc, yc, zc); - - case NoiseLookup: - Double3 vec = CELL_3D[(int) hash3D(m_seed, xc, yc, zc) & 255]; - return m_cellularNoiseLookup.GetNoise(xc + vec.x, yc + vec.y, zc + vec.z); - - case Distance: - return distance - 1; - default: - return 0; - } - } - - private double SingleCellular2Edge(double x, double y, double z) - { - long xr = fastRound(x); - long yr = fastRound(y); - long zr = fastRound(z); - - double distance = 999999; - double distance2 = 999999; - - switch(m_cellularDistanceFunction) - { - case Euclidean: - for(long xi = xr - 1; xi <= xr + 1; xi++) - { - for(long yi = yr - 1; yi <= yr + 1; yi++) - { - for(long zi = zr - 1; zi <= zr + 1; zi++) - { - Double3 vec = CELL_3D[(int) hash3D(m_seed, xi, yi, zi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - double vecZ = zi - z + vec.z; - - double newDistance = vecX * vecX + vecY * vecY + vecZ * vecZ; - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - } - break; - case Manhattan: - for(long xi = xr - 1; xi <= xr + 1; xi++) - { - for(long yi = yr - 1; yi <= yr + 1; yi++) - { - for(long zi = zr - 1; zi <= zr + 1; zi++) - { - Double3 vec = CELL_3D[(int) hash3D(m_seed, xi, yi, zi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - double vecZ = zi - z + vec.z; - - double newDistance = Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ); - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - } - break; - case Natural: - for(long xi = xr - 1; xi <= xr + 1; xi++) - { - for(long yi = yr - 1; yi <= yr + 1; yi++) - { - for(long zi = zr - 1; zi <= zr + 1; zi++) - { - Double3 vec = CELL_3D[(int) hash3D(m_seed, xi, yi, zi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - double vecZ = zi - z + vec.z; - - double newDistance = (Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ)) + (vecX * vecX + vecY * vecY + vecZ * vecZ); - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - } - break; - default: - break; - } - - switch(m_cellularReturnType) - { - case Distance2: - return distance2 - 1; - case Distance2Add: - return distance2 + distance - 1; - case Distance2Sub: - return distance2 - distance - 1; - case Distance2Mul: - return distance2 * distance - 1; - case Distance2Div: - return distance / distance2 - 1; - default: - return 0; - } - } - - public double GetCellular(double x, double y) - { - x *= m_frequency; - y *= m_frequency; - - switch(m_cellularReturnType) - { - case CellValue: - case NoiseLookup: - case Distance: - return SingleCellular(x, y); - default: - return SingleCellular2Edge(x, y); - } - } - - private double SingleCellular(double x, double y) - { - long xr = fastRound(x); - long yr = fastRound(y); - - double distance = 999999; - long xc = 0, yc = 0; - - switch(m_cellularDistanceFunction) - { - default: - case Euclidean: - for(long xi = xr - 1; xi <= xr + 1; xi++) - { - for(long yi = yr - 1; yi <= yr + 1; yi++) - { - Double2 vec = CELL_2D[(int) hash2D(m_seed, xi, yi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - - double newDistance = vecX * vecX + vecY * vecY; - - if(newDistance < distance) - { - distance = newDistance; - xc = xi; - yc = yi; - } - } - } - break; - case Manhattan: - for(long xi = xr - 1; xi <= xr + 1; xi++) - { - for(long yi = yr - 1; yi <= yr + 1; yi++) - { - Double2 vec = CELL_2D[(int) hash2D(m_seed, xi, yi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - - double newDistance = (Math.abs(vecX) + Math.abs(vecY)); - - if(newDistance < distance) - { - distance = newDistance; - xc = xi; - yc = yi; - } - } - } - break; - case Natural: - for(long xi = xr - 1; xi <= xr + 1; xi++) - { - for(long yi = yr - 1; yi <= yr + 1; yi++) - { - Double2 vec = CELL_2D[(int) hash2D(m_seed, xi, yi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - - double newDistance = (Math.abs(vecX) + Math.abs(vecY)) + (vecX * vecX + vecY * vecY); - - if(newDistance < distance) - { - distance = newDistance; - xc = xi; - yc = yi; - } - } - } - break; - } - - switch(m_cellularReturnType) - { - case CellValue: - return valCoord2D(0, xc, yc); - - case NoiseLookup: - Double2 vec = CELL_2D[(int) hash2D(m_seed, xc, yc) & 255]; - return m_cellularNoiseLookup.GetNoise(xc + vec.x, yc + vec.y); - - case Distance: - return distance - 1; - default: - return 0; - } - } - - private double SingleCellular2Edge(double x, double y) - { - long xr = fastRound(x); - long yr = fastRound(y); - - double distance = 999999; - double distance2 = 999999; - - switch(m_cellularDistanceFunction) - { - default: - case Euclidean: - for(long xi = xr - 1; xi <= xr + 1; xi++) - { - for(long yi = yr - 1; yi <= yr + 1; yi++) - { - Double2 vec = CELL_2D[(int) hash2D(m_seed, xi, yi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - - double newDistance = vecX * vecX + vecY * vecY; - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - break; - case Manhattan: - for(long xi = xr - 1; xi <= xr + 1; xi++) - { - for(long yi = yr - 1; yi <= yr + 1; yi++) - { - Double2 vec = CELL_2D[(int) hash2D(m_seed, xi, yi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - - double newDistance = Math.abs(vecX) + Math.abs(vecY); - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - break; - case Natural: - for(long xi = xr - 1; xi <= xr + 1; xi++) - { - for(long yi = yr - 1; yi <= yr + 1; yi++) - { - Double2 vec = CELL_2D[(int) hash2D(m_seed, xi, yi) & 255]; - - double vecX = xi - x + vec.x; - double vecY = yi - y + vec.y; - - double newDistance = (Math.abs(vecX) + Math.abs(vecY)) + (vecX * vecX + vecY * vecY); - - distance2 = Math.max(Math.min(distance2, newDistance), distance); - distance = Math.min(distance, newDistance); - } - } - break; - } - - switch(m_cellularReturnType) - { - case Distance2: - return distance2 - 1; - case Distance2Add: - return distance2 + distance - 1; - case Distance2Sub: - return distance2 - distance - 1; - case Distance2Mul: - return distance2 * distance - 1; - case Distance2Div: - return distance / distance2 - 1; - default: - return 0; - } - } - - public void GradientPerturb(Vector3f v3) - { - SingleGradientPerturb(m_seed, m_gradientPerturbAmp, m_frequency, v3); - } - - public void GradientPerturbFractal(Vector3f v3) - { - long seed = m_seed; - double amp = m_gradientPerturbAmp * m_fractalBounding; - double freq = m_frequency; - - SingleGradientPerturb(seed, amp, m_frequency, v3); - - for(long i = 1; i < m_octaves; i++) - { - freq *= m_lacunarity; - amp *= m_gain; - SingleGradientPerturb(++seed, amp, freq, v3); - } - } - - private void SingleGradientPerturb(long seed, double perturbAmp, double frequency, Vector3f v3) - { - double xf = v3.x * frequency; - double yf = v3.y * frequency; - double zf = v3.z * frequency; - - long x0 = fastFloor(xf); - long y0 = fastFloor(yf); - long z0 = fastFloor(zf); - long x1 = x0 + 1; - long y1 = y0 + 1; - long z1 = z0 + 1; - - double xs, ys, zs; - switch(m_longerp) - { - default: - case Linear: - xs = xf - x0; - ys = yf - y0; - zs = zf - z0; - break; - case Hermite: - xs = longerpHermiteFunc(xf - x0); - ys = longerpHermiteFunc(yf - y0); - zs = longerpHermiteFunc(zf - z0); - break; - case Qulongic: - xs = longerpQulongicFunc(xf - x0); - ys = longerpQulongicFunc(yf - y0); - zs = longerpQulongicFunc(zf - z0); - break; - } - - Double3 vec0 = CELL_3D[(int) hash3D(seed, x0, y0, z0) & 255]; - Double3 vec1 = CELL_3D[(int) hash3D(seed, x1, y0, z0) & 255]; - - double lx0x = lerp(vec0.x, vec1.x, xs); - double ly0x = lerp(vec0.y, vec1.y, xs); - double lz0x = lerp(vec0.z, vec1.z, xs); - - vec0 = CELL_3D[(int) hash3D(seed, x0, y1, z0) & 255]; - vec1 = CELL_3D[(int) hash3D(seed, x1, y1, z0) & 255]; - - double lx1x = lerp(vec0.x, vec1.x, xs); - double ly1x = lerp(vec0.y, vec1.y, xs); - double lz1x = lerp(vec0.z, vec1.z, xs); - - double lx0y = lerp(lx0x, lx1x, ys); - double ly0y = lerp(ly0x, ly1x, ys); - double lz0y = lerp(lz0x, lz1x, ys); - - vec0 = CELL_3D[(int) hash3D(seed, x0, y0, z1) & 255]; - vec1 = CELL_3D[(int) hash3D(seed, x1, y0, z1) & 255]; - - lx0x = lerp(vec0.x, vec1.x, xs); - ly0x = lerp(vec0.y, vec1.y, xs); - lz0x = lerp(vec0.z, vec1.z, xs); - - vec0 = CELL_3D[(int) hash3D(seed, x0, y1, z1) & 255]; - vec1 = CELL_3D[(int) hash3D(seed, x1, y1, z1) & 255]; - - lx1x = lerp(vec0.x, vec1.x, xs); - ly1x = lerp(vec0.y, vec1.y, xs); - lz1x = lerp(vec0.z, vec1.z, xs); - - v3.x += lerp(lx0y, lerp(lx0x, lx1x, ys), zs) * perturbAmp; - v3.y += lerp(ly0y, lerp(ly0x, ly1x, ys), zs) * perturbAmp; - v3.z += lerp(lz0y, lerp(lz0x, lz1x, ys), zs) * perturbAmp; - } - - public void GradientPerturb(Vector2f v2) - { - SingleGradientPerturb(m_seed, m_gradientPerturbAmp, m_frequency, v2); - } - - public void GradientPerturbFractal(Vector2f v2) - { - long seed = m_seed; - double amp = m_gradientPerturbAmp * m_fractalBounding; - double freq = m_frequency; - - SingleGradientPerturb(seed, amp, m_frequency, v2); - - for(long i = 1; i < m_octaves; i++) - { - freq *= m_lacunarity; - amp *= m_gain; - SingleGradientPerturb(++seed, amp, freq, v2); - } - } - - private void SingleGradientPerturb(long seed, double perturbAmp, double frequency, Vector2f v2) - { - double xf = v2.x * frequency; - double yf = v2.y * frequency; - - long x0 = fastFloor(xf); - long y0 = fastFloor(yf); - long x1 = x0 + 1; - long y1 = y0 + 1; - - double xs, ys; - switch(m_longerp) - { - default: - case Linear: - xs = xf - x0; - ys = yf - y0; - break; - case Hermite: - xs = longerpHermiteFunc(xf - x0); - ys = longerpHermiteFunc(yf - y0); - break; - case Qulongic: - xs = longerpQulongicFunc(xf - x0); - ys = longerpQulongicFunc(yf - y0); - break; - } - - Double2 vec0 = CELL_2D[(int) hash2D(seed, x0, y0) & 255]; - Double2 vec1 = CELL_2D[(int) hash2D(seed, x1, y0) & 255]; - - double lx0x = lerp(vec0.x, vec1.x, xs); - double ly0x = lerp(vec0.y, vec1.y, xs); - - vec0 = CELL_2D[(int) hash2D(seed, x0, y1) & 255]; - vec1 = CELL_2D[(int) hash2D(seed, x1, y1) & 255]; - - double lx1x = lerp(vec0.x, vec1.x, xs); - double ly1x = lerp(vec0.y, vec1.y, xs); - - v2.x += lerp(lx0x, lx1x, ys) * perturbAmp; - v2.y += lerp(ly0x, ly1x, ys) * perturbAmp; - } +public class FastNoiseDouble { + public enum NoiseType { + Value, + ValueFractal, + Perlin, + PerlinFractal, + Simplex, + SimplexFractal, + Cellular, + WhiteNoise, + Cubic, + CubicFractal + } + + public enum Longerp { + Linear, + Hermite, + Qulongic + } + + public enum FractalType { + FBM, + Billow, + RigidMulti + } + + public enum CellularDistanceFunction { + Euclidean, + Manhattan, + Natural + } + + public enum CellularReturnType { + CellValue, + NoiseLookup, + Distance, + Distance2, + Distance2Add, + Distance2Sub, + Distance2Mul, + Distance2Div + } + + private long m_seed = 1337; + private double m_frequency = 0.01; + public Longerp m_longerp = Longerp.Linear; + private NoiseType m_noiseType = NoiseType.Simplex; + + private long m_octaves = 3; + private double m_lacunarity = 2.0; + private double m_gain = 0.5; + private FractalType m_fractalType = FractalType.FBM; + + private double m_fractalBounding; + + private CellularDistanceFunction m_cellularDistanceFunction = CellularDistanceFunction.Euclidean; + private CellularReturnType m_cellularReturnType = CellularReturnType.CellValue; + private FastNoiseDouble m_cellularNoiseLookup = null; + + private double m_gradientPerturbAmp = 1.0 / 0.45; + + public FastNoiseDouble() { + this(1337); + } + + public FastNoiseDouble(long seed) { + m_seed = seed; + calculateFractalBounding(); + } + + // Returns a 0 double/double + public static double getDecimalType() { + return 0; + } + + // Returns the seed used by this object + public long getSeed() { + return m_seed; + } + + // Sets seed used for all noise types + // Default: 1337 + public void setSeed(long seed) { + m_seed = seed; + } + + // Sets frequency for all noise types + // Default: 0.01 + public void setFrequency(double frequency) { + m_frequency = frequency; + } + + // Changes the longerpolation method used to smooth between noise values + // Possible longerpolation methods (lowest to highest quality) : + // - Linear + // - Hermite + // - Qulongic + // Used in Value, Gradient Noise and Position Perturbing + // Default: Qulongic + public void setLongerp(Longerp longerp) { + m_longerp = longerp; + } + + // Sets noise return type of GetNoise(...) + // Default: Simplex + public void setNoiseType(NoiseType noiseType) { + m_noiseType = noiseType; + } + + // Sets octave count for all fractal noise types + // Default: 3 + public void setFractalOctaves(long octaves) { + m_octaves = octaves; + calculateFractalBounding(); + } + + // Sets octave lacunarity for all fractal noise types + // Default: 2.0 + public void setFractalLacunarity(double lacunarity) { + m_lacunarity = lacunarity; + } + + // Sets octave gain for all fractal noise types + // Default: 0.5 + public void setFractalGain(double gain) { + m_gain = gain; + calculateFractalBounding(); + } + + // Sets method for combining octaves in all fractal noise types + // Default: FBM + public void setFractalType(FractalType fractalType) { + m_fractalType = fractalType; + } + + // Sets return type from cellular noise calculations + // Note: NoiseLookup requires another FastNoise object be set with + // SetCellularNoiseLookup() to function + // Default: CellValue + public void setCellularDistanceFunction(CellularDistanceFunction cellularDistanceFunction) { + m_cellularDistanceFunction = cellularDistanceFunction; + } + + // Sets distance function used in cellular noise calculations + // Default: Euclidean + public void setCellularReturnType(CellularReturnType cellularReturnType) { + m_cellularReturnType = cellularReturnType; + } + + // Noise used to calculate a cell value if cellular return type is NoiseLookup + // The lookup value is acquired through GetNoise() so ensure you SetNoiseType() + // on the noise lookup, value, gradient or simplex is recommended + public void setCellularNoiseLookup(FastNoiseDouble noise) { + m_cellularNoiseLookup = noise; + } + + // Sets the maximum perturb distance from original location when using + // GradientPerturb{Fractal}(...) + // Default: 1.0 + public void setGradientPerturbAmp(double gradientPerturbAmp) { + m_gradientPerturbAmp = gradientPerturbAmp / 0.45; + } + + private static class Double2 { + public final double x, y; + + public Double2(double x, double y) { + this.x = x; + this.y = y; + } + } + + private static class Double3 { + public final double x, y, z; + + public Double3(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } + } + + private static final Double2[] GRAD_2D = {new Double2(-1, -1), new Double2(1, -1), new Double2(-1, 1), new Double2(1, 1), new Double2(0, -1), new Double2(-1, 0), new Double2(0, 1), new Double2(1, 0), + }; + + private static final Double3[] GRAD_3D = {new Double3(1, 1, 0), new Double3(-1, 1, 0), new Double3(1, -1, 0), new Double3(-1, -1, 0), new Double3(1, 0, 1), new Double3(-1, 0, 1), new Double3(1, 0, -1), new Double3(-1, 0, -1), new Double3(0, 1, 1), new Double3(0, -1, 1), new Double3(0, 1, -1), new Double3(0, -1, -1), new Double3(1, 1, 0), new Double3(0, -1, 1), new Double3(-1, 1, 0), new Double3(0, -1, -1), + }; + + private static final Double2[] CELL_2D = {new Double2(-0.4313539279f, 0.1281943404f), new Double2(-0.1733316799f, 0.415278375f), new Double2(-0.2821957395f, -0.3505218461f), new Double2(-0.2806473808f, 0.3517627718f), new Double2(0.3125508975f, -0.3237467165f), new Double2(0.3383018443f, -0.2967353402f), new Double2(-0.4393982022f, -0.09710417025f), new Double2(-0.4460443703f, -0.05953502905f), new Double2(-0.302223039f, 0.3334085102f), new Double2(-0.212681052f, -0.3965687458f), new Double2(-0.2991156529f, 0.3361990872f), new Double2(0.2293323691f, 0.3871778202f), new Double2(0.4475439151f, -0.04695150755f), new Double2(0.1777518f, 0.41340573f), new Double2(0.1688522499f, -0.4171197882f), new Double2(-0.0976597166f, 0.4392750616f), new Double2(0.08450188373f, 0.4419948321f), new Double2(-0.4098760448f, -0.1857461384f), new Double2(0.3476585782f, -0.2857157906f), new Double2(-0.3350670039f, -0.30038326f), new Double2(0.2298190031f, -0.3868891648f), new Double2(-0.01069924099f, 0.449872789f), new Double2(-0.4460141246f, -0.05976119672f), new Double2(0.3650293864f, 0.2631606867f), new Double2(-0.349479423f, 0.2834856838f), new Double2(-0.4122720642f, 0.1803655873f), new Double2(-0.267327811f, 0.3619887311f), new Double2(0.322124041f, -0.3142230135f), new Double2(0.2880445931f, -0.3457315612f), new Double2(0.3892170926f, -0.2258540565f), new Double2(0.4492085018f, -0.02667811596f), new Double2(-0.4497724772f, 0.01430799601f), new Double2(0.1278175387f, -0.4314657307f), new Double2(-0.03572100503f, 0.4485799926f), new Double2(-0.4297407068f, -0.1335025276f), new Double2(-0.3217817723f, 0.3145735065f), new Double2(-0.3057158873f, 0.3302087162f), new Double2(-0.414503978f, 0.1751754899f), new Double2(-0.3738139881f, 0.2505256519f), new Double2(0.2236891408f, -0.3904653228f), new Double2(0.002967775577f, -0.4499902136f), new Double2(0.1747128327f, -0.4146991995f), new Double2(-0.4423772489f, -0.08247647938f), new Double2(-0.2763960987f, -0.355112935f), new Double2(-0.4019385906f, -0.2023496216f), new Double2(0.3871414161f, -0.2293938184f), new Double2(-0.430008727f, 0.1326367019f), new Double2(-0.03037574274f, -0.4489736231f), new Double2(-0.3486181573f, 0.2845441624f), new Double2(0.04553517144f, -0.4476902368f), new Double2(-0.0375802926f, 0.4484280562f), new Double2(0.3266408905f, 0.3095250049f), new Double2(0.06540017593f, -0.4452222108f), new Double2(0.03409025829f, 0.448706869f), new Double2(-0.4449193635f, 0.06742966669f), new Double2(-0.4255936157f, -0.1461850686f), new Double2(0.449917292f, 0.008627302568f), new Double2(0.05242606404f, 0.4469356864f), new Double2(-0.4495305179f, -0.02055026661f), new Double2(-0.1204775703f, 0.4335725488f), new Double2(-0.341986385f, -0.2924813028f), new Double2(0.3865320182f, 0.2304191809f), new Double2(0.04506097811f, -0.447738214f), new Double2(-0.06283465979f, 0.4455915232f), new Double2(0.3932600341f, -0.2187385324f), new Double2(0.4472261803f, -0.04988730975f), new Double2(0.3753571011f, -0.2482076684f), new Double2(-0.273662295f, 0.357223947f), new Double2(0.1700461538f, 0.4166344988f), new Double2(0.4102692229f, 0.1848760794f), new Double2(0.323227187f, -0.3130881435f), new Double2(-0.2882310238f, -0.3455761521f), new Double2(0.2050972664f, 0.4005435199f), new Double2(0.4414085979f, -0.08751256895f), new Double2(-0.1684700334f, 0.4172743077f), new Double2(-0.003978032396f, 0.4499824166f), new Double2(-0.2055133639f, 0.4003301853f), new Double2(-0.006095674897f, -0.4499587123f), new Double2(-0.1196228124f, -0.4338091548f), new Double2(0.3901528491f, -0.2242337048f), new Double2(0.01723531752f, 0.4496698165f), new Double2(-0.3015070339f, 0.3340561458f), new Double2(-0.01514262423f, -0.4497451511f), new Double2(-0.4142574071f, -0.1757577897f), new Double2(-0.1916377265f, -0.4071547394f), new Double2(0.3749248747f, 0.2488600778f), new Double2(-0.2237774255f, 0.3904147331f), new Double2(-0.4166343106f, -0.1700466149f), new Double2(0.3619171625f, 0.267424695f), new Double2(0.1891126846f, -0.4083336779f), new Double2(-0.3127425077f, 0.323561623f), new Double2(-0.3281807787f, 0.307891826f), new Double2(-0.2294806661f, 0.3870899429f), new Double2(-0.3445266136f, 0.2894847362f), new Double2(-0.4167095422f, -0.1698621719f), new Double2(-0.257890321f, -0.3687717212f), new Double2(-0.3612037825f, 0.2683874578f), new Double2(0.2267996491f, 0.3886668486f), new Double2(0.207157062f, 0.3994821043f), new Double2(0.08355176718f, -0.4421754202f), new Double2(-0.4312233307f, 0.1286329626f), new Double2(0.3257055497f, 0.3105090899f), new Double2(0.177701095f, -0.4134275279f), new Double2(-0.445182522f, 0.06566979625f), new Double2(0.3955143435f, 0.2146355146f), new Double2(-0.4264613988f, 0.1436338239f), new Double2(-0.3793799665f, -0.2420141339f), new Double2(0.04617599081f, -0.4476245948f), new Double2(-0.371405428f, -0.2540826796f), new Double2(0.2563570295f, -0.3698392535f), new Double2(0.03476646309f, 0.4486549822f), new Double2(-0.3065454405f, 0.3294387544f), new Double2(-0.2256979823f, 0.3893076172f), new Double2(0.4116448463f, -0.1817925206f), new Double2(-0.2907745828f, -0.3434387019f), new Double2(0.2842278468f, -0.348876097f), new Double2(0.3114589359f, -0.3247973695f), new Double2(0.4464155859f, -0.0566844308f), new Double2(-0.3037334033f, -0.3320331606f), new Double2(0.4079607166f, 0.1899159123f), new Double2(-0.3486948919f, -0.2844501228f), new Double2(0.3264821436f, 0.3096924441f), new Double2(0.3211142406f, 0.3152548881f), new Double2(0.01183382662f, 0.4498443737f), new Double2(0.4333844092f, 0.1211526057f), new Double2(0.3118668416f, 0.324405723f), new Double2(-0.272753471f, 0.3579183483f), new Double2(-0.422228622f, -0.1556373694f), new Double2(-0.1009700099f, -0.4385260051f), new Double2(-0.2741171231f, -0.3568750521f), new Double2(-0.1465125133f, 0.4254810025f), new Double2(0.2302279044f, -0.3866459777f), new Double2(-0.3699435608f, 0.2562064828f), new Double2(0.105700352f, -0.4374099171f), new Double2(-0.2646713633f, 0.3639355292f), new Double2(0.3521828122f, 0.2801200935f), new Double2(-0.1864187807f, -0.4095705534f), new Double2(0.1994492955f, -0.4033856449f), new Double2(0.3937065066f, 0.2179339044f), new Double2(-0.3226158377f, 0.3137180602f), new Double2(0.3796235338f, 0.2416318948f), new Double2(0.1482921929f, 0.4248640083f), new Double2(-0.407400394f, 0.1911149365f), new Double2(0.4212853031f, 0.1581729856f), new Double2(-0.2621297173f, 0.3657704353f), new Double2(-0.2536986953f, -0.3716678248f), new Double2(-0.2100236383f, 0.3979825013f), new Double2(0.3624152444f, 0.2667493029f), new Double2(-0.3645038479f, -0.2638881295f), new Double2(0.2318486784f, 0.3856762766f), new Double2(-0.3260457004f, 0.3101519002f), new Double2(-0.2130045332f, -0.3963950918f), new Double2(0.3814998766f, -0.2386584257f), new Double2(-0.342977305f, 0.2913186713f), new Double2(-0.4355865605f, 0.1129794154f), new Double2(-0.2104679605f, 0.3977477059f), new Double2(0.3348364681f, -0.3006402163f), new Double2(0.3430468811f, 0.2912367377f), new Double2(-0.2291836801f, -0.3872658529f), new Double2(0.2547707298f, -0.3709337882f), new Double2(0.4236174945f, -0.151816397f), new Double2(-0.15387742f, 0.4228731957f), new Double2(-0.4407449312f, 0.09079595574f), new Double2(-0.06805276192f, -0.444824484f), new Double2(0.4453517192f, -0.06451237284f), new Double2(0.2562464609f, -0.3699158705f), new Double2(0.3278198355f, -0.3082761026f), new Double2(-0.4122774207f, -0.1803533432f), new Double2(0.3354090914f, -0.3000012356f), new Double2(0.446632869f, -0.05494615882f), new Double2(-0.1608953296f, 0.4202531296f), new Double2(-0.09463954939f, 0.4399356268f), new Double2(-0.02637688324f, -0.4492262904f), new Double2(0.447102804f, -0.05098119915f), new Double2(-0.4365670908f, 0.1091291678f), new Double2(-0.3959858651f, 0.2137643437f), new Double2(-0.4240048207f, -0.1507312575f), new Double2(-0.3882794568f, 0.2274622243f), new Double2(-0.4283652566f, -0.1378521198f), new Double2(0.3303888091f, 0.305521251f), new Double2(0.3321434919f, -0.3036127481f), new Double2(-0.413021046f, -0.1786438231f), new Double2(0.08403060337f, -0.4420846725f), new Double2(-0.3822882919f, 0.2373934748f), new Double2(-0.3712395594f, -0.2543249683f), new Double2(0.4472363971f, -0.04979563372f), new Double2(-0.4466591209f, 0.05473234629f), new Double2(0.0486272539f, -0.4473649407f), new Double2(-0.4203101295f, -0.1607463688f), new Double2(0.2205360833f, 0.39225481f), new Double2(-0.3624900666f, 0.2666476169f), new Double2(-0.4036086833f, -0.1989975647f), new Double2(0.2152727807f, 0.3951678503f), new Double2(-0.4359392962f, -0.1116106179f), new Double2(0.4178354266f, 0.1670735057f), new Double2(0.2007630161f, 0.4027334247f), new Double2(-0.07278067175f, -0.4440754146f), new Double2(0.3644748615f, -0.2639281632f), new Double2(-0.4317451775f, 0.126870413f), new Double2(-0.297436456f, 0.3376855855f), new Double2(-0.2998672222f, 0.3355289094f), new Double2(-0.2673674124f, 0.3619594822f), new Double2(0.2808423357f, 0.3516071423f), new Double2(0.3498946567f, 0.2829730186f), new Double2(-0.2229685561f, 0.390877248f), new Double2(0.3305823267f, 0.3053118493f), new Double2(-0.2436681211f, -0.3783197679f), new Double2(-0.03402776529f, 0.4487116125f), new Double2(-0.319358823f, 0.3170330301f), new Double2(0.4454633477f, -0.06373700535f), new Double2(0.4483504221f, 0.03849544189f), new Double2(-0.4427358436f, -0.08052932871f), new Double2(0.05452298565f, 0.4466847255f), new Double2(-0.2812560807f, 0.3512762688f), new Double2(0.1266696921f, 0.4318041097f), new Double2(-0.3735981243f, 0.2508474468f), new Double2(0.2959708351f, -0.3389708908f), new Double2(-0.3714377181f, 0.254035473f), new Double2(-0.404467102f, -0.1972469604f), new Double2(0.1636165687f, -0.419201167f), new Double2(0.3289185495f, -0.3071035458f), new Double2(-0.2494824991f, -0.3745109914f), new Double2(0.03283133272f, 0.4488007393f), new Double2(-0.166306057f, -0.4181414777f), new Double2(-0.106833179f, 0.4371346153f), new Double2(0.06440260376f, -0.4453676062f), new Double2(-0.4483230967f, 0.03881238203f), new Double2(-0.421377757f, -0.1579265206f), new Double2(0.05097920662f, -0.4471030312f), new Double2(0.2050584153f, -0.4005634111f), new Double2(0.4178098529f, -0.167137449f), new Double2(-0.3565189504f, -0.2745801121f), new Double2(0.4478398129f, 0.04403977727f), new Double2(-0.3399999602f, -0.2947881053f), new Double2(0.3767121994f, 0.2461461331f), new Double2(-0.3138934434f, 0.3224451987f), new Double2(-0.1462001792f, -0.4255884251f), new Double2(0.3970290489f, -0.2118205239f), new Double2(0.4459149305f, -0.06049689889f), new Double2(-0.4104889426f, -0.1843877112f), new Double2(0.1475103971f, -0.4251360756f), new Double2(0.09258030352f, 0.4403735771f), new Double2(-0.1589664637f, -0.4209865359f), new Double2(0.2482445008f, 0.3753327428f), new Double2(0.4383624232f, -0.1016778537f), new Double2(0.06242802956f, 0.4456486745f), new Double2(0.2846591015f, -0.3485243118f), new Double2(-0.344202744f, -0.2898697484f), new Double2(0.1198188883f, -0.4337550392f), new Double2(-0.243590703f, 0.3783696201f), new Double2(0.2958191174f, -0.3391033025f), new Double2(-0.1164007991f, 0.4346847754f), new Double2(0.1274037151f, -0.4315881062f), new Double2(0.368047306f, 0.2589231171f), new Double2(0.2451436949f, 0.3773652989f), new Double2(-0.4314509715f, 0.12786735f), + }; + + private static final Double3[] CELL_3D = {new Double3(0.1453787434f, -0.4149781685f, -0.0956981749f), new Double3(-0.01242829687f, -0.1457918398f, -0.4255470325f), new Double3(0.2877979582f, -0.02606483451f, -0.3449535616f), new Double3(-0.07732986802f, 0.2377094325f, 0.3741848704f), new Double3(0.1107205875f, -0.3552302079f, -0.2530858567f), new Double3(0.2755209141f, 0.2640521179f, -0.238463215f), new Double3(0.294168941f, 0.1526064594f, 0.3044271714f), new Double3(0.4000921098f, -0.2034056362f, 0.03244149937f), new Double3(-0.1697304074f, 0.3970864695f, -0.1265461359f), new Double3(-0.1483224484f, -0.3859694688f, 0.1775613147f), new Double3(0.2623596946f, -0.2354852944f, 0.2796677792f), new Double3(-0.2709003183f, 0.3505271138f, -0.07901746678f), new Double3(-0.03516550699f, 0.3885234328f, 0.2243054374f), new Double3(-0.1267712655f, 0.1920044036f, 0.3867342179f), new Double3(0.02952021915f, 0.4409685861f, 0.08470692262f), new Double3(-0.2806854217f, -0.266996757f, 0.2289725438f), new Double3(-0.171159547f, 0.2141185563f, 0.3568720405f), new Double3(0.2113227183f, 0.3902405947f, -0.07453178509f), new Double3(-0.1024352839f, 0.2128044156f, -0.3830421561f), new Double3(-0.3304249877f, -0.1566986703f, 0.2622305365f), new Double3(0.2091111325f, 0.3133278055f, -0.2461670583f), new Double3(0.344678154f, -0.1944240454f, -0.2142341261f), new Double3(0.1984478035f, -0.3214342325f, -0.2445373252f), new Double3(-0.2929008603f, 0.2262915116f, 0.2559320961f), new Double3(-0.1617332831f, 0.006314769776f, -0.4198838754f), new Double3(-0.3582060271f, -0.148303178f, -0.2284613961f), new Double3(-0.1852067326f, -0.3454119342f, -0.2211087107f), new Double3(0.3046301062f, 0.1026310383f, 0.314908508f), new Double3(-0.03816768434f, -0.2551766358f, -0.3686842991f), new Double3(-0.4084952196f, 0.1805950793f, 0.05492788837f), new Double3(-0.02687443361f, -0.2749741471f, 0.3551999201f), new Double3(-0.03801098351f, 0.3277859044f, 0.3059600725f), new Double3(0.2371120802f, 0.2900386767f, -0.2493099024f), new Double3(0.4447660503f, 0.03946930643f, 0.05590469027f), new Double3(0.01985147278f, -0.01503183293f, -0.4493105419f), new Double3(0.4274339143f, 0.03345994256f, -0.1366772882f), new Double3(-0.2072988631f, 0.2871414597f, -0.2776273824f), new Double3(-0.3791240978f, 0.1281177671f, 0.2057929936f), new Double3(-0.2098721267f, -0.1007087278f, -0.3851122467f), new Double3(0.01582798878f, 0.4263894424f, 0.1429738373f), new Double3(-0.1888129464f, -0.3160996813f, -0.2587096108f), new Double3(0.1612988974f, -0.1974805082f, -0.3707885038f), new Double3(-0.08974491322f, 0.229148752f, -0.3767448739f), new Double3(0.07041229526f, 0.4150230285f, -0.1590534329f), new Double3(-0.1082925611f, -0.1586061639f, 0.4069604477f), new Double3(0.2474100658f, -0.3309414609f, 0.1782302128f), new Double3(-0.1068836661f, -0.2701644537f, -0.3436379634f), new Double3(0.2396452163f, 0.06803600538f, -0.3747549496f), new Double3(-0.3063886072f, 0.2597428179f, 0.2028785103f), new Double3(0.1593342891f, -0.3114350249f, -0.2830561951f), new Double3(0.2709690528f, 0.1412648683f, -0.3303331794f), new Double3(-0.1519780427f, 0.3623355133f, 0.2193527988f), new Double3(0.1699773681f, 0.3456012883f, 0.2327390037f), new Double3(-0.1986155616f, 0.3836276443f, -0.1260225743f), new Double3(-0.1887482106f, -0.2050154888f, -0.353330953f), new Double3(0.2659103394f, 0.3015631259f, -0.2021172246f), new Double3(-0.08838976154f, -0.4288819642f, -0.1036702021f), new Double3(-0.04201869311f, 0.3099592485f, 0.3235115047f), new Double3(-0.3230334656f, 0.201549922f, -0.2398478873f), new Double3(0.2612720941f, 0.2759854499f, -0.2409749453f), new Double3(0.385713046f, 0.2193460345f, 0.07491837764f), new Double3(0.07654967953f, 0.3721732183f, 0.241095919f), new Double3(0.4317038818f, -0.02577753072f, 0.1243675091f), new Double3(-0.2890436293f, -0.3418179959f, -0.04598084447f), new Double3(-0.2201947582f, 0.383023377f, -0.08548310451f), new Double3(0.4161322773f, -0.1669634289f, -0.03817251927f), new Double3(0.2204718095f, 0.02654238946f, -0.391391981f), new Double3(-0.1040307469f, 0.3890079625f, -0.2008741118f), new Double3(-0.1432122615f, 0.371614387f, -0.2095065525f), new Double3(0.3978380468f, -0.06206669342f, 0.2009293758f), new Double3(-0.2599274663f, 0.2616724959f, -0.2578084893f), new Double3(0.4032618332f, -0.1124593585f, 0.1650235939f), new Double3(-0.08953470255f, -0.3048244735f, 0.3186935478f), new Double3(0.118937202f, -0.2875221847f, 0.325092195f), new Double3(0.02167047076f, -0.03284630549f, -0.4482761547f), new Double3(-0.3411343612f, 0.2500031105f, 0.1537068389f), new Double3(0.3162964612f, 0.3082064153f, -0.08640228117f), new Double3(0.2355138889f, -0.3439334267f, -0.1695376245f), new Double3(-0.02874541518f, -0.3955933019f, 0.2125550295f), new Double3(-0.2461455173f, 0.02020282325f, -0.3761704803f), new Double3(0.04208029445f, -0.4470439576f, 0.02968078139f), new Double3(0.2727458746f, 0.2288471896f, -0.2752065618f), new Double3(-0.1347522818f, -0.02720848277f, -0.4284874806f), new Double3(0.3829624424f, 0.1231931484f, -0.2016512234f), new Double3(-0.3547613644f, 0.1271702173f, 0.2459107769f), new Double3(0.2305790207f, 0.3063895591f, 0.2354968222f), new Double3(-0.08323845599f, -0.1922245118f, 0.3982726409f), new Double3(0.2993663085f, -0.2619918095f, -0.2103333191f), new Double3(-0.2154865723f, 0.2706747713f, 0.287751117f), new Double3(0.01683355354f, -0.2680655787f, -0.3610505186f), new Double3(0.05240429123f, 0.4335128183f, -0.1087217856f), new Double3(0.00940104872f, -0.4472890582f, 0.04841609928f), new Double3(0.3465688735f, 0.01141914583f, -0.2868093776f), new Double3(-0.3706867948f, -0.2551104378f, 0.003156692623f), new Double3(0.2741169781f, 0.2139972417f, -0.2855959784f), new Double3(0.06413433865f, 0.1708718512f, 0.4113266307f), new Double3(-0.388187972f, -0.03973280434f, -0.2241236325f), new Double3(0.06419469312f, -0.2803682491f, 0.3460819069f), new Double3(-0.1986120739f, -0.3391173584f, 0.2192091725f), new Double3(-0.203203009f, -0.3871641506f, 0.1063600375f), new Double3(-0.1389736354f, -0.2775901578f, -0.3257760473f), new Double3(-0.06555641638f, 0.342253257f, -0.2847192729f), new Double3(-0.2529246486f, -0.2904227915f, 0.2327739768f), new Double3(0.1444476522f, 0.1069184044f, 0.4125570634f), new Double3(-0.3643780054f, -0.2447099973f, -0.09922543227f), new Double3(0.4286142488f, -0.1358496089f, -0.01829506817f), new Double3(0.165872923f, -0.3136808464f, -0.2767498872f), new Double3(0.2219610524f, -0.3658139958f, 0.1393320198f), new Double3(0.04322940318f, -0.3832730794f, 0.2318037215f), new Double3(-0.08481269795f, -0.4404869674f, -0.03574965489f), new Double3(0.1822082075f, -0.3953259299f, 0.1140946023f), new Double3(-0.3269323334f, 0.3036542563f, 0.05838957105f), new Double3(-0.4080485344f, 0.04227858267f, -0.184956522f), new Double3(0.2676025294f, -0.01299671652f, 0.36155217f), new Double3(0.3024892441f, -0.1009990293f, -0.3174892964f), new Double3(0.1448494052f, 0.425921681f, -0.0104580805f), new Double3(0.4198402157f, 0.08062320474f, 0.1404780841f), new Double3(-0.3008872161f, -0.333040905f, -0.03241355801f), new Double3(0.3639310428f, -0.1291284382f, -0.2310412139f), new Double3(0.3295806598f, 0.0184175994f, -0.3058388149f), new Double3(0.2776259487f, -0.2974929052f, -0.1921504723f), new Double3(0.4149000507f, -0.144793182f, -0.09691688386f), new Double3(0.145016715f, -0.0398992945f, 0.4241205002f), new Double3(0.09299023471f, -0.299732164f, -0.3225111565f), new Double3(0.1028907093f, -0.361266869f, 0.247789732f), new Double3(0.2683057049f, -0.07076041213f, -0.3542668666f), new Double3(-0.4227307273f, -0.07933161816f, -0.1323073187f), new Double3(-0.1781224702f, 0.1806857196f, -0.3716517945f), new Double3(0.4390788626f, -0.02841848598f, -0.09435116353f), new Double3(0.2972583585f, 0.2382799621f, -0.2394997452f), new Double3(-0.1707002821f, 0.2215845691f, 0.3525077196f), new Double3(0.3806686614f, 0.1471852559f, -0.1895464869f), new Double3(-0.1751445661f, -0.274887877f, 0.3102596268f), new Double3(-0.2227237566f, -0.2316778837f, 0.3149912482f), new Double3(0.1369633021f, 0.1341343041f, -0.4071228836f), new Double3(-0.3529503428f, -0.2472893463f, -0.129514612f), new Double3(-0.2590744185f, -0.2985577559f, -0.2150435121f), new Double3(-0.3784019401f, 0.2199816631f, -0.1044989934f), new Double3(-0.05635805671f, 0.1485737441f, 0.4210102279f), new Double3(0.3251428613f, 0.09666046873f, -0.2957006485f), new Double3(-0.4190995804f, 0.1406751354f, -0.08405978803f), new Double3(-0.3253150961f, -0.3080335042f, -0.04225456877f), new Double3(0.2857945863f, -0.05796152095f, 0.3427271751f), new Double3(-0.2733604046f, 0.1973770973f, -0.2980207554f), new Double3(0.219003657f, 0.2410037886f, -0.3105713639f), new Double3(0.3182767252f, -0.271342949f, 0.1660509868f), new Double3(-0.03222023115f, -0.3331161506f, -0.300824678f), new Double3(-0.3087780231f, 0.1992794134f, -0.2596995338f), new Double3(-0.06487611647f, -0.4311322747f, 0.1114273361f), new Double3(0.3921171432f, -0.06294284106f, -0.2116183942f), new Double3(-0.1606404506f, -0.358928121f, -0.2187812825f), new Double3(-0.03767771199f, -0.2290351443f, 0.3855169162f), new Double3(0.1394866832f, -0.3602213994f, 0.2308332918f), new Double3(-0.4345093872f, 0.005751117145f, 0.1169124335f), new Double3(-0.1044637494f, 0.4168128432f, -0.1336202785f), new Double3(0.2658727501f, 0.2551943237f, 0.2582393035f), new Double3(0.2051461999f, 0.1975390727f, 0.3484154868f), new Double3(-0.266085566f, 0.23483312f, 0.2766800993f), new Double3(0.07849405464f, -0.3300346342f, -0.2956616708f), new Double3(-0.2160686338f, 0.05376451292f, -0.3910546287f), new Double3(-0.185779186f, 0.2148499206f, 0.3490352499f), new Double3(0.02492421743f, -0.3229954284f, -0.3123343347f), new Double3(-0.120167831f, 0.4017266681f, 0.1633259825f), new Double3(-0.02160084693f, -0.06885389554f, 0.4441762538f), new Double3(0.2597670064f, 0.3096300784f, 0.1978643903f), new Double3(-0.1611553854f, -0.09823036005f, 0.4085091653f), new Double3(-0.3278896792f, 0.1461670309f, 0.2713366126f), new Double3(0.2822734956f, 0.03754421121f, -0.3484423997f), new Double3(0.03169341113f, 0.347405252f, -0.2842624114f), new Double3(0.2202613604f, -0.3460788041f, -0.1849713341f), new Double3(0.2933396046f, 0.3031973659f, 0.1565989581f), new Double3(-0.3194922995f, 0.2453752201f, -0.200538455f), new Double3(-0.3441586045f, -0.1698856132f, -0.2349334659f), new Double3(0.2703645948f, -0.3574277231f, 0.04060059933f), new Double3(0.2298568861f, 0.3744156221f, 0.0973588921f), new Double3(0.09326603877f, -0.3170108894f, 0.3054595587f), new Double3(-0.1116165319f, -0.2985018719f, 0.3177080142f), new Double3(0.2172907365f, -0.3460005203f, -0.1885958001f), new Double3(0.1991339479f, 0.3820341668f, -0.1299829458f), new Double3(-0.0541918155f, -0.2103145071f, 0.39412061f), new Double3(0.08871336998f, 0.2012117383f, 0.3926114802f), new Double3(0.2787673278f, 0.3505404674f, 0.04370535101f), new Double3(-0.322166438f, 0.3067213525f, 0.06804996813f), new Double3(-0.4277366384f, 0.132066775f, 0.04582286686f), new Double3(0.240131882f, -0.1612516055f, 0.344723946f), new Double3(0.1448607981f, -0.2387819045f, 0.3528435224f), new Double3(-0.3837065682f, -0.2206398454f, 0.08116235683f), new Double3(-0.4382627882f, -0.09082753406f, -0.04664855374f), new Double3(-0.37728353f, 0.05445141085f, 0.2391488697f), new Double3(0.1259579313f, 0.348394558f, 0.2554522098f), new Double3(-0.1406285511f, -0.270877371f, -0.3306796947f), new Double3(-0.1580694418f, 0.4162931958f, -0.06491553533f), new Double3(0.2477612106f, -0.2927867412f, -0.2353514536f), new Double3(0.2916132853f, 0.3312535401f, 0.08793624968f), new Double3(0.07365265219f, -0.1666159848f, 0.411478311f), new Double3(-0.26126526f, -0.2422237692f, 0.2748965434f), new Double3(-0.3721862032f, 0.252790166f, 0.008634938242f), new Double3(-0.3691191571f, -0.255281188f, 0.03290232422f), new Double3(0.2278441737f, -0.3358364886f, 0.1944244981f), new Double3(0.363398169f, -0.2310190248f, 0.1306597909f), new Double3(-0.304231482f, -0.2698452035f, 0.1926830856f), new Double3(-0.3199312232f, 0.316332536f, -0.008816977938f), new Double3(0.2874852279f, 0.1642275508f, -0.304764754f), new Double3(-0.1451096801f, 0.3277541114f, -0.2720669462f), new Double3(0.3220090754f, 0.0511344108f, 0.3101538769f), new Double3(-0.1247400865f, -0.04333605335f, -0.4301882115f), new Double3(-0.2829555867f, -0.3056190617f, -0.1703910946f), new Double3(0.1069384374f, 0.3491024667f, -0.2630430352f), new Double3(-0.1420661144f, -0.3055376754f, -0.2982682484f), new Double3(-0.250548338f, 0.3156466809f, -0.2002316239f), new Double3(0.3265787872f, 0.1871229129f, 0.2466400438f), new Double3(0.07646097258f, -0.3026690852f, 0.324106687f), new Double3(0.3451771584f, 0.2757120714f, -0.0856480183f), new Double3(0.298137964f, 0.2852657134f, 0.179547284f), new Double3(0.2812250376f, 0.3466716415f, 0.05684409612f), new Double3(0.4390345476f, -0.09790429955f, -0.01278335452f), new Double3(0.2148373234f, 0.1850172527f, 0.3494474791f), new Double3(0.2595421179f, -0.07946825393f, 0.3589187731f), new Double3(0.3182823114f, -0.307355516f, -0.08203022006f), new Double3(-0.4089859285f, -0.04647718411f, 0.1818526372f), new Double3(-0.2826749061f, 0.07417482322f, 0.3421885344f), new Double3(0.3483864637f, 0.225442246f, -0.1740766085f), new Double3(-0.3226415069f, -0.1420585388f, -0.2796816575f), new Double3(0.4330734858f, -0.118868561f, -0.02859407492f), new Double3(-0.08717822568f, -0.3909896417f, -0.2050050172f), new Double3(-0.2149678299f, 0.3939973956f, -0.03247898316f), new Double3(-0.2687330705f, 0.322686276f, -0.1617284888f), new Double3(0.2105665099f, -0.1961317136f, -0.3459683451f), new Double3(0.4361845915f, -0.1105517485f, 0.004616608544f), new Double3(0.05333333359f, -0.313639498f, -0.3182543336f), new Double3(-0.05986216652f, 0.1361029153f, -0.4247264031f), new Double3(0.3664988455f, 0.2550543014f, -0.05590974511f), new Double3(-0.2341015558f, -0.182405731f, 0.3382670703f), new Double3(-0.04730947785f, -0.4222150243f, -0.1483114513f), new Double3(-0.2391566239f, -0.2577696514f, -0.2808182972f), new Double3(-0.1242081035f, 0.4256953395f, -0.07652336246f), new Double3(0.2614832715f, -0.3650179274f, 0.02980623099f), new Double3(-0.2728794681f, -0.3499628774f, 0.07458404908f), new Double3(0.007892900508f, -0.1672771315f, 0.4176793787f), new Double3(-0.01730330376f, 0.2978486637f, -0.3368779738f), new Double3(0.2054835762f, -0.3252600376f, -0.2334146693f), new Double3(-0.3231994983f, 0.1564282844f, -0.2712420987f), new Double3(-0.2669545963f, 0.2599343665f, -0.2523278991f), new Double3(-0.05554372779f, 0.3170813944f, -0.3144428146f), new Double3(-0.2083935713f, -0.310922837f, -0.2497981362f), new Double3(0.06989323478f, -0.3156141536f, 0.3130537363f), new Double3(0.3847566193f, -0.1605309138f, -0.1693876312f), new Double3(-0.3026215288f, -0.3001537679f, -0.1443188342f), new Double3(0.3450735512f, 0.08611519592f, 0.2756962409f), new Double3(0.1814473292f, -0.2788782453f, -0.3029914042f), new Double3(-0.03855010448f, 0.09795110726f, 0.4375151083f), new Double3(0.3533670318f, 0.2665752752f, 0.08105160988f), new Double3(-0.007945601311f, 0.140359426f, -0.4274764309f), new Double3(0.4063099273f, -0.1491768253f, -0.1231199324f), new Double3(-0.2016773589f, 0.008816271194f, -0.4021797064f), new Double3(-0.07527055435f, -0.425643481f, -0.1251477955f), + }; + + private static long fastFloor(double f) { + return (f >= 0 ? (long) f : (long) f - 1); + } + + private static long fastRound(double f) { + return (f >= 0) ? (long) (f + 0.5) : (long) (f - 0.5); + } + + private static double lerp(double a, double b, double t) { + return a + t * (b - a); + } + + private static double longerpHermiteFunc(double t) { + return t * t * (3 - 2 * t); + } + + private static double longerpQulongicFunc(double t) { + return t * t * t * (t * (t * 6 - 15) + 10); + } + + private static double cubicLerp(double a, double b, double c, double d, double t) { + double p = (d - c) - (a - b); + return t * t * t * p + t * t * ((a - b) - p) + t * (c - a) + b; + } + + private void calculateFractalBounding() { + double amp = m_gain; + double ampFractal = 1; + for (long i = 1; i < m_octaves; i++) { + ampFractal += amp; + amp *= m_gain; + } + m_fractalBounding = 1 / ampFractal; + } + + // Hashing + private final static long X_PRIME = 1619; + private final static long Y_PRIME = 31337; + private final static long Z_PRIME = 6971; + private final static long W_PRIME = 1013; + + private static long hash2D(long seed, long x, long y) { + long hash = seed; + hash ^= X_PRIME * x; + hash ^= Y_PRIME * y; + + hash = hash * hash * hash * 60493; + hash = (hash >> 13) ^ hash; + + return hash; + } + + private static long hash3D(long seed, long x, long y, long z) { + long hash = seed; + hash ^= X_PRIME * x; + hash ^= Y_PRIME * y; + hash ^= Z_PRIME * z; + + hash = hash * hash * hash * 60493; + hash = (hash >> 13) ^ hash; + + return hash; + } + + public static long hash4D(long seed, long x, long y, long z, long w) { + long hash = seed; + hash ^= X_PRIME * x; + hash ^= Y_PRIME * y; + hash ^= Z_PRIME * z; + hash ^= W_PRIME * w; + + hash = hash * hash * hash * 60493; + hash = (hash >> 13) ^ hash; + + return hash; + } + + private static double valCoord2D(long seed, long x, long y) { + long n = seed; + n ^= X_PRIME * x; + n ^= Y_PRIME * y; + + return ((n * n * n * 60493L) / (double) Long.MAX_VALUE); + } + + private static double valCoord3D(long seed, long x, long y, long z) { + long n = seed; + n ^= X_PRIME * x; + n ^= Y_PRIME * y; + n ^= Z_PRIME * z; + + return ((n * n * n * 60493L) / (double) Long.MAX_VALUE); + } + + private static double valCoord4D(long seed, long x, long y, long z, long w) { + long n = seed; + n ^= X_PRIME * x; + n ^= Y_PRIME * y; + n ^= Z_PRIME * z; + n ^= W_PRIME * w; + + return ((n * n * n * 60493L) / (double) Long.MAX_VALUE); + } + + private static double GradCoord2D(long seed, long x, long y, double xd, double yd) { + long hash = seed; + hash ^= X_PRIME * x; + hash ^= Y_PRIME * y; + + hash = hash * hash * hash * 60493; + hash = (hash >> 13) ^ hash; + + Double2 g = GRAD_2D[(int) hash & 7]; + + return xd * g.x + yd * g.y; + } + + private static double GradCoord3D(long seed, long x, long y, long z, double xd, double yd, double zd) { + long hash = seed; + hash ^= X_PRIME * x; + hash ^= Y_PRIME * y; + hash ^= Z_PRIME * z; + + hash = hash * hash * hash * 60493; + hash = (hash >> 13) ^ hash; + + Double3 g = GRAD_3D[(int) (hash & 15)]; + + return xd * g.x + yd * g.y + zd * g.z; + } + + private static double GradCoord4D(long seed, long x, long y, long z, long w, double xd, double yd, double zd, double wd) { + long hash = seed; + hash ^= X_PRIME * x; + hash ^= Y_PRIME * y; + hash ^= Z_PRIME * z; + hash ^= W_PRIME * w; + + hash = hash * hash * hash * 60493; + hash = (hash >> 13) ^ hash; + + hash &= 31; + double a = yd, b = zd, c = wd; // X,Y,Z + switch ((int) hash >> 3) { // OR, DEPENDING ON HIGH ORDER 2 BITS: + case 1: + a = wd; + b = xd; + c = yd; + break; // W,X,Y + case 2: + a = zd; + b = wd; + c = xd; + break; // Z,W,X + case 3: + a = yd; + b = zd; + c = wd; + break; // Y,Z,W + } + return ((hash & 4) == 0 ? -a : a) + ((hash & 2) == 0 ? -b : b) + ((hash & 1) == 0 ? -c : c); + } + + public double GetNoise(double x, double y, double z) { + x *= m_frequency; + y *= m_frequency; + z *= m_frequency; + + switch (m_noiseType) { + case Value: + return SingleValue(m_seed, x, y, z); + case ValueFractal: + switch (m_fractalType) { + case FBM: + return SingleValueFractalFBM(x, y, z); + case Billow: + return SingleValueFractalBillow(x, y, z); + case RigidMulti: + return SingleValueFractalRigidMulti(x, y, z); + default: + return 0; + } + case Perlin: + return SinglePerlin(m_seed, x, y, z); + case PerlinFractal: + switch (m_fractalType) { + case FBM: + return SinglePerlinFractalFBM(x, y, z); + case Billow: + return SinglePerlinFractalBillow(x, y, z); + case RigidMulti: + return SinglePerlinFractalRigidMulti(x, y, z); + default: + return 0; + } + case Simplex: + return SingleSimplex(m_seed, x, y, z); + case SimplexFractal: + switch (m_fractalType) { + case FBM: + return SingleSimplexFractalFBM(x, y, z); + case Billow: + return SingleSimplexFractalBillow(x, y, z); + case RigidMulti: + return SingleSimplexFractalRigidMulti(x, y, z); + default: + return 0; + } + case Cellular: + switch (m_cellularReturnType) { + case CellValue: + case NoiseLookup: + case Distance: + return SingleCellular(x, y, z); + default: + return SingleCellular2Edge(x, y, z); + } + case WhiteNoise: + return GetWhiteNoise(x, y, z); + case Cubic: + return SingleCubic(m_seed, x, y, z); + case CubicFractal: + switch (m_fractalType) { + case FBM: + return SingleCubicFractalFBM(x, y, z); + case Billow: + return SingleCubicFractalBillow(x, y, z); + case RigidMulti: + return SingleCubicFractalRigidMulti(x, y, z); + default: + return 0; + } + default: + return 0; + } + } + + public double GetNoise(double x, double y) { + x *= m_frequency; + y *= m_frequency; + + switch (m_noiseType) { + case Value: + return SingleValue(m_seed, x, y); + case ValueFractal: + switch (m_fractalType) { + case FBM: + return SingleValueFractalFBM(x, y); + case Billow: + return SingleValueFractalBillow(x, y); + case RigidMulti: + return SingleValueFractalRigidMulti(x, y); + default: + return 0; + } + case Perlin: + return SinglePerlin(m_seed, x, y); + case PerlinFractal: + switch (m_fractalType) { + case FBM: + return SinglePerlinFractalFBM(x, y); + case Billow: + return SinglePerlinFractalBillow(x, y); + case RigidMulti: + return SinglePerlinFractalRigidMulti(x, y); + default: + return 0; + } + case Simplex: + return SingleSimplex(m_seed, x, y); + case SimplexFractal: + switch (m_fractalType) { + case FBM: + return SingleSimplexFractalFBM(x, y); + case Billow: + return SingleSimplexFractalBillow(x, y); + case RigidMulti: + return SingleSimplexFractalRigidMulti(x, y); + default: + return 0; + } + case Cellular: + switch (m_cellularReturnType) { + case CellValue: + case NoiseLookup: + case Distance: + return SingleCellular(x, y); + default: + return SingleCellular2Edge(x, y); + } + case WhiteNoise: + return GetWhiteNoise(x, y); + case Cubic: + return SingleCubic(m_seed, x, y); + case CubicFractal: + switch (m_fractalType) { + case FBM: + return SingleCubicFractalFBM(x, y); + case Billow: + return SingleCubicFractalBillow(x, y); + case RigidMulti: + return SingleCubicFractalRigidMulti(x, y); + default: + return 0; + } + default: + return 0; + } + } + + // White Noise + + private long DoubleCast2Long(double f) { + long i = Double.doubleToRawLongBits(f); + + return i ^ (i >> 16); + } + + public double GetWhiteNoise(double x, double y, double z, double w) { + long xi = DoubleCast2Long(x); + long yi = DoubleCast2Long(y); + long zi = DoubleCast2Long(z); + long wi = DoubleCast2Long(w); + + return valCoord4D(m_seed, xi, yi, zi, wi); + } + + public double GetWhiteNoise(double x, double y, double z) { + long xi = DoubleCast2Long(x); + long yi = DoubleCast2Long(y); + long zi = DoubleCast2Long(z); + + return valCoord3D(m_seed, xi, yi, zi); + } + + public double GetWhiteNoise(double x, double y) { + long xi = DoubleCast2Long(x); + long yi = DoubleCast2Long(y); + + return valCoord2D(m_seed, xi, yi); + } + + public double GetWhiteNoiseLong(long x, long y, long z, long w) { + return valCoord4D(m_seed, x, y, z, w); + } + + public double GetWhiteNoiseLong(long x, long y, long z) { + return valCoord3D(m_seed, x, y, z); + } + + public double GetWhiteNoiseLong(long x, long y) { + return valCoord2D(m_seed, x, y); + } + + // Value Noise + public double GetValueFractal(double x, double y, double z) { + x *= m_frequency; + y *= m_frequency; + z *= m_frequency; + + switch (m_fractalType) { + case FBM: + return SingleValueFractalFBM(x, y, z); + case Billow: + return SingleValueFractalBillow(x, y, z); + case RigidMulti: + return SingleValueFractalRigidMulti(x, y, z); + default: + return 0; + } + } + + private double SingleValueFractalFBM(double x, double y, double z) { + long seed = m_seed; + double sum = SingleValue(seed, x, y, z); + double amp = 1; + + for (long i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum += SingleValue(++seed, x, y, z) * amp; + } + + return sum * m_fractalBounding; + } + + private double SingleValueFractalBillow(double x, double y, double z) { + long seed = m_seed; + double sum = Math.abs(SingleValue(seed, x, y, z)) * 2 - 1; + double amp = 1; + + for (long i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum += (Math.abs(SingleValue(++seed, x, y, z)) * 2 - 1) * amp; + } + + return sum * m_fractalBounding; + } + + private double SingleValueFractalRigidMulti(double x, double y, double z) { + long seed = m_seed; + double sum = 1 - Math.abs(SingleValue(seed, x, y, z)); + double amp = 1; + + for (long i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum -= (1 - Math.abs(SingleValue(++seed, x, y, z))) * amp; + } + + return sum; + } + + public double GetValue(double x, double y, double z) { + return SingleValue(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); + } + + private double SingleValue(long seed, double x, double y, double z) { + long x0 = fastFloor(x); + long y0 = fastFloor(y); + long z0 = fastFloor(z); + long x1 = x0 + 1; + long y1 = y0 + 1; + long z1 = z0 + 1; + + double xs, ys, zs; + switch (m_longerp) { + default: + case Linear: + xs = x - x0; + ys = y - y0; + zs = z - z0; + break; + case Hermite: + xs = longerpHermiteFunc(x - x0); + ys = longerpHermiteFunc(y - y0); + zs = longerpHermiteFunc(z - z0); + break; + case Qulongic: + xs = longerpQulongicFunc(x - x0); + ys = longerpQulongicFunc(y - y0); + zs = longerpQulongicFunc(z - z0); + break; + } + + double xf00 = lerp(valCoord3D(seed, x0, y0, z0), valCoord3D(seed, x1, y0, z0), xs); + double xf10 = lerp(valCoord3D(seed, x0, y1, z0), valCoord3D(seed, x1, y1, z0), xs); + double xf01 = lerp(valCoord3D(seed, x0, y0, z1), valCoord3D(seed, x1, y0, z1), xs); + double xf11 = lerp(valCoord3D(seed, x0, y1, z1), valCoord3D(seed, x1, y1, z1), xs); + + double yf0 = lerp(xf00, xf10, ys); + double yf1 = lerp(xf01, xf11, ys); + + return lerp(yf0, yf1, zs); + } + + public double GetValueFractal(double x, double y) { + x *= m_frequency; + y *= m_frequency; + + switch (m_fractalType) { + case FBM: + return SingleValueFractalFBM(x, y); + case Billow: + return SingleValueFractalBillow(x, y); + case RigidMulti: + return SingleValueFractalRigidMulti(x, y); + default: + return 0; + } + } + + private double SingleValueFractalFBM(double x, double y) { + long seed = m_seed; + double sum = SingleValue(seed, x, y); + double amp = 1; + + for (long i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + + amp *= m_gain; + sum += SingleValue(++seed, x, y) * amp; + } + + return sum * m_fractalBounding; + } + + private double SingleValueFractalBillow(double x, double y) { + long seed = m_seed; + double sum = Math.abs(SingleValue(seed, x, y)) * 2 - 1; + double amp = 1; + + for (long i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + amp *= m_gain; + sum += (Math.abs(SingleValue(++seed, x, y)) * 2 - 1) * amp; + } + + return sum * m_fractalBounding; + } + + private double SingleValueFractalRigidMulti(double x, double y) { + long seed = m_seed; + double sum = 1 - Math.abs(SingleValue(seed, x, y)); + double amp = 1; + + for (long i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + + amp *= m_gain; + sum -= (1 - Math.abs(SingleValue(++seed, x, y))) * amp; + } + + return sum; + } + + public double GetValue(double x, double y) { + return SingleValue(m_seed, x * m_frequency, y * m_frequency); + } + + private double SingleValue(long seed, double x, double y) { + long x0 = fastFloor(x); + long y0 = fastFloor(y); + long x1 = x0 + 1; + long y1 = y0 + 1; + + double xs, ys; + switch (m_longerp) { + default: + case Linear: + xs = x - x0; + ys = y - y0; + break; + case Hermite: + xs = longerpHermiteFunc(x - x0); + ys = longerpHermiteFunc(y - y0); + break; + case Qulongic: + xs = longerpQulongicFunc(x - x0); + ys = longerpQulongicFunc(y - y0); + break; + } + + double xf0 = lerp(valCoord2D(seed, x0, y0), valCoord2D(seed, x1, y0), xs); + double xf1 = lerp(valCoord2D(seed, x0, y1), valCoord2D(seed, x1, y1), xs); + + return lerp(xf0, xf1, ys); + } + + // Gradient Noise + public double GetPerlinFractal(double x, double y, double z) { + x *= m_frequency; + y *= m_frequency; + z *= m_frequency; + + switch (m_fractalType) { + case FBM: + return SinglePerlinFractalFBM(x, y, z); + case Billow: + return SinglePerlinFractalBillow(x, y, z); + case RigidMulti: + return SinglePerlinFractalRigidMulti(x, y, z); + default: + return 0; + } + } + + private double SinglePerlinFractalFBM(double x, double y, double z) { + long seed = m_seed; + double sum = SinglePerlin(seed, x, y, z); + double amp = 1; + + for (long i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum += SinglePerlin(++seed, x, y, z) * amp; + } + + return sum * m_fractalBounding; + } + + private double SinglePerlinFractalBillow(double x, double y, double z) { + long seed = m_seed; + double sum = Math.abs(SinglePerlin(seed, x, y, z)) * 2 - 1; + double amp = 1; + + for (long i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum += (Math.abs(SinglePerlin(++seed, x, y, z)) * 2 - 1) * amp; + } + + return sum * m_fractalBounding; + } + + private double SinglePerlinFractalRigidMulti(double x, double y, double z) { + long seed = m_seed; + double sum = 1 - Math.abs(SinglePerlin(seed, x, y, z)); + double amp = 1; + + for (long i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum -= (1 - Math.abs(SinglePerlin(++seed, x, y, z))) * amp; + } + + return sum; + } + + public double GetPerlin(double x, double y, double z) { + return SinglePerlin(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); + } + + private double SinglePerlin(long seed, double x, double y, double z) { + long x0 = fastFloor(x); + long y0 = fastFloor(y); + long z0 = fastFloor(z); + long x1 = x0 + 1; + long y1 = y0 + 1; + long z1 = z0 + 1; + + double xs, ys, zs; + switch (m_longerp) { + default: + case Linear: + xs = x - x0; + ys = y - y0; + zs = z - z0; + break; + case Hermite: + xs = longerpHermiteFunc(x - x0); + ys = longerpHermiteFunc(y - y0); + zs = longerpHermiteFunc(z - z0); + break; + case Qulongic: + xs = longerpQulongicFunc(x - x0); + ys = longerpQulongicFunc(y - y0); + zs = longerpQulongicFunc(z - z0); + break; + } + + double xd0 = x - x0; + double yd0 = y - y0; + double zd0 = z - z0; + double xd1 = xd0 - 1; + double yd1 = yd0 - 1; + double zd1 = zd0 - 1; + + double xf00 = lerp(GradCoord3D(seed, x0, y0, z0, xd0, yd0, zd0), GradCoord3D(seed, x1, y0, z0, xd1, yd0, zd0), xs); + double xf10 = lerp(GradCoord3D(seed, x0, y1, z0, xd0, yd1, zd0), GradCoord3D(seed, x1, y1, z0, xd1, yd1, zd0), xs); + double xf01 = lerp(GradCoord3D(seed, x0, y0, z1, xd0, yd0, zd1), GradCoord3D(seed, x1, y0, z1, xd1, yd0, zd1), xs); + double xf11 = lerp(GradCoord3D(seed, x0, y1, z1, xd0, yd1, zd1), GradCoord3D(seed, x1, y1, z1, xd1, yd1, zd1), xs); + + double yf0 = lerp(xf00, xf10, ys); + double yf1 = lerp(xf01, xf11, ys); + + return lerp(yf0, yf1, zs); + } + + public double GetPerlinFractal(double x, double y) { + x *= m_frequency; + y *= m_frequency; + + switch (m_fractalType) { + case FBM: + return SinglePerlinFractalFBM(x, y); + case Billow: + return SinglePerlinFractalBillow(x, y); + case RigidMulti: + return SinglePerlinFractalRigidMulti(x, y); + default: + return 0; + } + } + + private double SinglePerlinFractalFBM(double x, double y) { + long seed = m_seed; + double sum = SinglePerlin(seed, x, y); + double amp = 1; + + for (long i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + + amp *= m_gain; + sum += SinglePerlin(++seed, x, y) * amp; + } + + return sum * m_fractalBounding; + } + + private double SinglePerlinFractalBillow(double x, double y) { + long seed = m_seed; + double sum = Math.abs(SinglePerlin(seed, x, y)) * 2 - 1; + double amp = 1; + + for (long i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + + amp *= m_gain; + sum += (Math.abs(SinglePerlin(++seed, x, y)) * 2 - 1) * amp; + } + + return sum * m_fractalBounding; + } + + private double SinglePerlinFractalRigidMulti(double x, double y) { + long seed = m_seed; + double sum = 1 - Math.abs(SinglePerlin(seed, x, y)); + double amp = 1; + + for (long i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + + amp *= m_gain; + sum -= (1 - Math.abs(SinglePerlin(++seed, x, y))) * amp; + } + + return sum; + } + + public double GetPerlin(double x, double y) { + return SinglePerlin(m_seed, x * m_frequency, y * m_frequency); + } + + private double SinglePerlin(long seed, double x, double y) { + long x0 = fastFloor(x); + long y0 = fastFloor(y); + long x1 = x0 + 1; + long y1 = y0 + 1; + + double xs = 0, ys = 0; + switch (m_longerp) { + case Linear -> { + xs = x - x0; + ys = y - y0; + } + case Hermite -> { + xs = longerpHermiteFunc(x - x0); + ys = longerpHermiteFunc(y - y0); + } + case Qulongic -> { + xs = longerpQulongicFunc(x - x0); + ys = longerpQulongicFunc(y - y0); + } + } + + double xd0 = x - x0; + double yd0 = y - y0; + double xd1 = xd0 - 1; + double yd1 = yd0 - 1; + + double xf0 = lerp(GradCoord2D(seed, x0, y0, xd0, yd0), GradCoord2D(seed, x1, y0, xd1, yd0), xs); + double xf1 = lerp(GradCoord2D(seed, x0, y1, xd0, yd1), GradCoord2D(seed, x1, y1, xd1, yd1), xs); + + return lerp(xf0, xf1, ys); + } + + // Simplex Noise + public double GetSimplexFractal(double x, double y, double z) { + x *= m_frequency; + y *= m_frequency; + z *= m_frequency; + + switch (m_fractalType) { + case FBM: + return SingleSimplexFractalFBM(x, y, z); + case Billow: + return SingleSimplexFractalBillow(x, y, z); + case RigidMulti: + return SingleSimplexFractalRigidMulti(x, y, z); + default: + return 0; + } + } + + private double SingleSimplexFractalFBM(double x, double y, double z) { + long seed = m_seed; + double sum = SingleSimplex(seed, x, y, z); + double amp = 1; + + for (long i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum += SingleSimplex(++seed, x, y, z) * amp; + } + + return sum * m_fractalBounding; + } + + private double SingleSimplexFractalBillow(double x, double y, double z) { + long seed = m_seed; + double sum = Math.abs(SingleSimplex(seed, x, y, z)) * 2 - 1; + double amp = 1; + + for (long i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum += (Math.abs(SingleSimplex(++seed, x, y, z)) * 2 - 1) * amp; + } + + return sum * m_fractalBounding; + } + + private double SingleSimplexFractalRigidMulti(double x, double y, double z) { + long seed = m_seed; + double sum = 1 - Math.abs(SingleSimplex(seed, x, y, z)); + double amp = 1; + + for (long i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum -= (1 - Math.abs(SingleSimplex(++seed, x, y, z))) * amp; + } + + return sum; + } + + public double GetSimplex(double x, double y, double z) { + return SingleSimplex(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); + } + + private final static double F3 = 1.0 / 3.0; + private final static double G3 = 1.0 / 6.0; + private final static double G33 = G3 * 3 - 1; + + private double SingleSimplex(long seed, double x, double y, double z) { + double t = (x + y + z) * F3; + long i = fastFloor(x + t); + long j = fastFloor(y + t); + long k = fastFloor(z + t); + + t = (i + j + k) * G3; + double x0 = x - (i - t); + double y0 = y - (j - t); + double z0 = z - (k - t); + + long i1, j1, k1; + long i2, j2, k2; + + if (x0 >= y0) { + if (y0 >= z0) { + i1 = 1; + j1 = 0; + k1 = 0; + i2 = 1; + j2 = 1; + k2 = 0; + } else if (x0 >= z0) { + i1 = 1; + j1 = 0; + k1 = 0; + i2 = 1; + j2 = 0; + k2 = 1; + } else // x0 < z0 + { + i1 = 0; + j1 = 0; + k1 = 1; + i2 = 1; + j2 = 0; + k2 = 1; + } + } else // x0 < y0 + { + if (y0 < z0) { + i1 = 0; + j1 = 0; + k1 = 1; + i2 = 0; + j2 = 1; + k2 = 1; + } else if (x0 < z0) { + i1 = 0; + j1 = 1; + k1 = 0; + i2 = 0; + j2 = 1; + k2 = 1; + } else // x0 >= z0 + { + i1 = 0; + j1 = 1; + k1 = 0; + i2 = 1; + j2 = 1; + k2 = 0; + } + } + + double x1 = x0 - i1 + G3; + double y1 = y0 - j1 + G3; + double z1 = z0 - k1 + G3; + double x2 = x0 - i2 + F3; + double y2 = y0 - j2 + F3; + double z2 = z0 - k2 + F3; + double x3 = x0 + G33; + double y3 = y0 + G33; + double z3 = z0 + G33; + + double n0, n1, n2, n3; + + t = 0.6 - x0 * x0 - y0 * y0 - z0 * z0; + if (t < 0) + n0 = 0; + else { + t *= t; + n0 = t * t * GradCoord3D(seed, i, j, k, x0, y0, z0); + } + + t = 0.6 - x1 * x1 - y1 * y1 - z1 * z1; + if (t < 0) + n1 = 0; + else { + t *= t; + n1 = t * t * GradCoord3D(seed, i + i1, j + j1, k + k1, x1, y1, z1); + } + + t = 0.6 - x2 * x2 - y2 * y2 - z2 * z2; + if (t < 0) + n2 = 0; + else { + t *= t; + n2 = t * t * GradCoord3D(seed, i + i2, j + j2, k + k2, x2, y2, z2); + } + + t = 0.6 - x3 * x3 - y3 * y3 - z3 * z3; + if (t < 0) + n3 = 0; + else { + t *= t; + n3 = t * t * GradCoord3D(seed, i + 1, j + 1, k + 1, x3, y3, z3); + } + + return 32 * (n0 + n1 + n2 + n3); + } + + public double GetSimplexFractal(double x, double y) { + x *= m_frequency; + y *= m_frequency; + + switch (m_fractalType) { + case FBM: + return SingleSimplexFractalFBM(x, y); + case Billow: + return SingleSimplexFractalBillow(x, y); + case RigidMulti: + return SingleSimplexFractalRigidMulti(x, y); + default: + return 0; + } + } + + private double SingleSimplexFractalFBM(double x, double y) { + long seed = m_seed; + double sum = SingleSimplex(seed, x, y); + double amp = 1; + + for (long i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + + amp *= m_gain; + sum += SingleSimplex(++seed, x, y) * amp; + } + + return sum * m_fractalBounding; + } + + private double SingleSimplexFractalBillow(double x, double y) { + long seed = m_seed; + double sum = Math.abs(SingleSimplex(seed, x, y)) * 2 - 1; + double amp = 1; + + for (long i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + + amp *= m_gain; + sum += (Math.abs(SingleSimplex(++seed, x, y)) * 2 - 1) * amp; + } + + return sum * m_fractalBounding; + } + + private double SingleSimplexFractalRigidMulti(double x, double y) { + long seed = m_seed; + double sum = 1 - Math.abs(SingleSimplex(seed, x, y)); + double amp = 1; + + for (long i = 1; i < m_octaves; i++) { + x *= m_lacunarity; + y *= m_lacunarity; + + amp *= m_gain; + sum -= (1 - Math.abs(SingleSimplex(++seed, x, y))) * amp; + } + + return sum; + } + + public double GetSimplex(double x, double y) { + return SingleSimplex(m_seed, x * m_frequency, y * m_frequency); + } + + private final static double F2 = 1.0 / 2.0; + private final static double G2 = 1.0 / 4.0; + + private double SingleSimplex(long seed, double x, double y) { + double t = (x + y) * F2; + long i = fastFloor(x + t); + long j = fastFloor(y + t); + + t = (i + j) * G2; + double X0 = i - t; + double Y0 = j - t; + + double x0 = x - X0; + double y0 = y - Y0; + + long i1, j1; + if (x0 > y0) { + i1 = 1; + j1 = 0; + } else { + i1 = 0; + j1 = 1; + } + + double x1 = x0 - i1 + G2; + double y1 = y0 - j1 + G2; + double x2 = x0 - 1 + F2; + double y2 = y0 - 1 + F2; + + double n0, n1, n2; + + t = 0.5 - x0 * x0 - y0 * y0; + if (t < 0) + n0 = 0; + else { + t *= t; + n0 = t * t * GradCoord2D(seed, i, j, x0, y0); + } + + t = 0.5 - x1 * x1 - y1 * y1; + if (t < 0) + n1 = 0; + else { + t *= t; + n1 = t * t * GradCoord2D(seed, i + i1, j + j1, x1, y1); + } + + t = 0.5 - x2 * x2 - y2 * y2; + if (t < 0) + n2 = 0; + else { + t *= t; + n2 = t * t * GradCoord2D(seed, i + 1, j + 1, x2, y2); + } + + return 50 * (n0 + n1 + n2); + } + + public double GetSimplex(double x, double y, double z, double w) { + return SingleSimplex(m_seed, x * m_frequency, y * m_frequency, z * m_frequency, w * m_frequency); + } + + private static final byte[] SIMPLEX_4D = {0, 1, 2, 3, 0, 1, 3, 2, 0, 0, 0, 0, 0, 2, 3, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 3, 0, 0, 2, 1, 3, 0, 0, 0, 0, 0, 3, 1, 2, 0, 3, 2, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 2, 0, 3, 0, 0, 0, 0, 1, 3, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 0, 1, 2, 3, 1, 0, 1, 0, 2, 3, 1, 0, 3, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 3, 1, 0, 0, 0, 0, 2, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 1, 2, 3, 0, 2, 1, 0, 0, 0, 0, 3, 1, 2, 0, 2, 1, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 1, 0, 2, 0, 0, 0, 0, 3, 2, 0, 1, 3, 2, 1, 0 + }; + + private final static double F4 = (2.23606797 - 1.0) / 4.0; + private final static double G4 = (5.0 - 2.23606797) / 20.0; + + private double SingleSimplex(long seed, double x, double y, double z, double w) { + double n0, n1, n2, n3, n4; + double t = (x + y + z + w) * F4; + long i = fastFloor(x + t); + long j = fastFloor(y + t); + long k = fastFloor(z + t); + long l = fastFloor(w + t); + t = (i + j + k + l) * G4; + double X0 = i - t; + double Y0 = j - t; + double Z0 = k - t; + double W0 = l - t; + double x0 = x - X0; + double y0 = y - Y0; + double z0 = z - Z0; + double w0 = w - W0; + + int c = (x0 > y0) ? 32 : 0; + c += (x0 > z0) ? 16 : 0; + c += (y0 > z0) ? 8 : 0; + c += (x0 > w0) ? 4 : 0; + c += (y0 > w0) ? 2 : 0; + c += (z0 > w0) ? 1 : 0; + c <<= 2; + + long i1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; + long i2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; + long i3 = SIMPLEX_4D[c++] >= 1 ? 1 : 0; + long j1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; + long j2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; + long j3 = SIMPLEX_4D[c++] >= 1 ? 1 : 0; + long k1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; + long k2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; + long k3 = SIMPLEX_4D[c++] >= 1 ? 1 : 0; + long l1 = SIMPLEX_4D[c] >= 3 ? 1 : 0; + long l2 = SIMPLEX_4D[c] >= 2 ? 1 : 0; + long l3 = SIMPLEX_4D[c] >= 1 ? 1 : 0; + + double x1 = x0 - i1 + G4; + double y1 = y0 - j1 + G4; + double z1 = z0 - k1 + G4; + double w1 = w0 - l1 + G4; + double x2 = x0 - i2 + 2 * G4; + double y2 = y0 - j2 + 2 * G4; + double z2 = z0 - k2 + 2 * G4; + double w2 = w0 - l2 + 2 * G4; + double x3 = x0 - i3 + 3 * G4; + double y3 = y0 - j3 + 3 * G4; + double z3 = z0 - k3 + 3 * G4; + double w3 = w0 - l3 + 3 * G4; + double x4 = x0 - 1 + 4 * G4; + double y4 = y0 - 1 + 4 * G4; + double z4 = z0 - 1 + 4 * G4; + double w4 = w0 - 1 + 4 * G4; + + t = 0.6 - x0 * x0 - y0 * y0 - z0 * z0 - w0 * w0; + if (t < 0) + n0 = 0; + else { + t *= t; + n0 = t * t * GradCoord4D(seed, i, j, k, l, x0, y0, z0, w0); + } + t = 0.6 - x1 * x1 - y1 * y1 - z1 * z1 - w1 * w1; + if (t < 0) + n1 = 0; + else { + t *= t; + n1 = t * t * GradCoord4D(seed, i + i1, j + j1, k + k1, l + l1, x1, y1, z1, w1); + } + t = 0.6 - x2 * x2 - y2 * y2 - z2 * z2 - w2 * w2; + if (t < 0) + n2 = 0; + else { + t *= t; + n2 = t * t * GradCoord4D(seed, i + i2, j + j2, k + k2, l + l2, x2, y2, z2, w2); + } + t = 0.6 - x3 * x3 - y3 * y3 - z3 * z3 - w3 * w3; + if (t < 0) + n3 = 0; + else { + t *= t; + n3 = t * t * GradCoord4D(seed, i + i3, j + j3, k + k3, l + l3, x3, y3, z3, w3); + } + t = 0.6 - x4 * x4 - y4 * y4 - z4 * z4 - w4 * w4; + if (t < 0) + n4 = 0; + else { + t *= t; + n4 = t * t * GradCoord4D(seed, i + 1, j + 1, k + 1, l + 1, x4, y4, z4, w4); + } + + return 27 * (n0 + n1 + n2 + n3 + n4); + } + + // Cubic Noise + public double GetCubicFractal(double x, double y, double z) { + x *= m_frequency; + y *= m_frequency; + z *= m_frequency; + + switch (m_fractalType) { + case FBM: + return SingleCubicFractalFBM(x, y, z); + case Billow: + return SingleCubicFractalBillow(x, y, z); + case RigidMulti: + return SingleCubicFractalRigidMulti(x, y, z); + default: + return 0; + } + } + + private double SingleCubicFractalFBM(double x, double y, double z) { + long seed = m_seed; + double sum = SingleCubic(seed, x, y, z); + double amp = 1; + long i = 0; + + while (++i < m_octaves) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum += SingleCubic(++seed, x, y, z) * amp; + } + + return sum * m_fractalBounding; + } + + private double SingleCubicFractalBillow(double x, double y, double z) { + long seed = m_seed; + double sum = Math.abs(SingleCubic(seed, x, y, z)) * 2 - 1; + double amp = 1; + long i = 0; + + while (++i < m_octaves) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum += (Math.abs(SingleCubic(++seed, x, y, z)) * 2 - 1) * amp; + } + + return sum * m_fractalBounding; + } + + private double SingleCubicFractalRigidMulti(double x, double y, double z) { + long seed = m_seed; + double sum = 1 - Math.abs(SingleCubic(seed, x, y, z)); + double amp = 1; + long i = 0; + + while (++i < m_octaves) { + x *= m_lacunarity; + y *= m_lacunarity; + z *= m_lacunarity; + + amp *= m_gain; + sum -= (1 - Math.abs(SingleCubic(++seed, x, y, z))) * amp; + } + + return sum; + } + + public double GetCubic(double x, double y, double z) { + return SingleCubic(m_seed, x * m_frequency, y * m_frequency, z * m_frequency); + } + + private final static double CUBIC_3D_BOUNDING = 1 / (1.5 * 1.5 * 1.5); + + private double SingleCubic(long seed, double x, double y, double z) { + long x1 = fastFloor(x); + long y1 = fastFloor(y); + long z1 = fastFloor(z); + + long x0 = x1 - 1; + long y0 = y1 - 1; + long z0 = z1 - 1; + long x2 = x1 + 1; + long y2 = y1 + 1; + long z2 = z1 + 1; + long x3 = x1 + 2; + long y3 = y1 + 2; + long z3 = z1 + 2; + + double xs = x - (double) x1; + double ys = y - (double) y1; + double zs = z - (double) z1; + + return cubicLerp(cubicLerp(cubicLerp(valCoord3D(seed, x0, y0, z0), valCoord3D(seed, x1, y0, z0), valCoord3D(seed, x2, y0, z0), valCoord3D(seed, x3, y0, z0), xs), cubicLerp(valCoord3D(seed, x0, y1, z0), valCoord3D(seed, x1, y1, z0), valCoord3D(seed, x2, y1, z0), valCoord3D(seed, x3, y1, z0), xs), cubicLerp(valCoord3D(seed, x0, y2, z0), valCoord3D(seed, x1, y2, z0), valCoord3D(seed, x2, y2, z0), valCoord3D(seed, x3, y2, z0), xs), cubicLerp(valCoord3D(seed, x0, y3, z0), valCoord3D(seed, x1, y3, z0), valCoord3D(seed, x2, y3, z0), valCoord3D(seed, x3, y3, z0), xs), ys), cubicLerp(cubicLerp(valCoord3D(seed, x0, y0, z1), valCoord3D(seed, x1, y0, z1), valCoord3D(seed, x2, y0, z1), valCoord3D(seed, x3, y0, z1), xs), cubicLerp(valCoord3D(seed, x0, y1, z1), valCoord3D(seed, x1, y1, z1), valCoord3D(seed, x2, y1, z1), valCoord3D(seed, x3, y1, z1), xs), cubicLerp(valCoord3D(seed, x0, y2, z1), valCoord3D(seed, x1, y2, z1), valCoord3D(seed, x2, y2, z1), valCoord3D(seed, x3, y2, z1), xs), cubicLerp(valCoord3D(seed, x0, y3, z1), valCoord3D(seed, x1, y3, z1), valCoord3D(seed, x2, y3, z1), valCoord3D(seed, x3, y3, z1), xs), ys), cubicLerp(cubicLerp(valCoord3D(seed, x0, y0, z2), valCoord3D(seed, x1, y0, z2), valCoord3D(seed, x2, y0, z2), valCoord3D(seed, x3, y0, z2), xs), cubicLerp(valCoord3D(seed, x0, y1, z2), valCoord3D(seed, x1, y1, z2), valCoord3D(seed, x2, y1, z2), valCoord3D(seed, x3, y1, z2), xs), cubicLerp(valCoord3D(seed, x0, y2, z2), valCoord3D(seed, x1, y2, z2), valCoord3D(seed, x2, y2, z2), valCoord3D(seed, x3, y2, z2), xs), cubicLerp(valCoord3D(seed, x0, y3, z2), valCoord3D(seed, x1, y3, z2), valCoord3D(seed, x2, y3, z2), valCoord3D(seed, x3, y3, z2), xs), ys), cubicLerp(cubicLerp(valCoord3D(seed, x0, y0, z3), valCoord3D(seed, x1, y0, z3), valCoord3D(seed, x2, y0, z3), valCoord3D(seed, x3, y0, z3), xs), cubicLerp(valCoord3D(seed, x0, y1, z3), valCoord3D(seed, x1, y1, z3), valCoord3D(seed, x2, y1, z3), valCoord3D(seed, x3, y1, z3), xs), cubicLerp(valCoord3D(seed, x0, y2, z3), valCoord3D(seed, x1, y2, z3), valCoord3D(seed, x2, y2, z3), valCoord3D(seed, x3, y2, z3), xs), cubicLerp(valCoord3D(seed, x0, y3, z3), valCoord3D(seed, x1, y3, z3), valCoord3D(seed, x2, y3, z3), valCoord3D(seed, x3, y3, z3), xs), ys), zs) * CUBIC_3D_BOUNDING; + } + + public double GetCubicFractal(double x, double y) { + x *= m_frequency; + y *= m_frequency; + + switch (m_fractalType) { + case FBM: + return SingleCubicFractalFBM(x, y); + case Billow: + return SingleCubicFractalBillow(x, y); + case RigidMulti: + return SingleCubicFractalRigidMulti(x, y); + default: + return 0; + } + } + + private double SingleCubicFractalFBM(double x, double y) { + long seed = m_seed; + double sum = SingleCubic(seed, x, y); + double amp = 1; + long i = 0; + + while (++i < m_octaves) { + x *= m_lacunarity; + y *= m_lacunarity; + + amp *= m_gain; + sum += SingleCubic(++seed, x, y) * amp; + } + + return sum * m_fractalBounding; + } + + private double SingleCubicFractalBillow(double x, double y) { + long seed = m_seed; + double sum = Math.abs(SingleCubic(seed, x, y)) * 2 - 1; + double amp = 1; + long i = 0; + + while (++i < m_octaves) { + x *= m_lacunarity; + y *= m_lacunarity; + + amp *= m_gain; + sum += (Math.abs(SingleCubic(++seed, x, y)) * 2 - 1) * amp; + } + + return sum * m_fractalBounding; + } + + private double SingleCubicFractalRigidMulti(double x, double y) { + long seed = m_seed; + double sum = 1 - Math.abs(SingleCubic(seed, x, y)); + double amp = 1; + long i = 0; + + while (++i < m_octaves) { + x *= m_lacunarity; + y *= m_lacunarity; + + amp *= m_gain; + sum -= (1 - Math.abs(SingleCubic(++seed, x, y))) * amp; + } + + return sum; + } + + public double GetCubic(double x, double y) { + x *= m_frequency; + y *= m_frequency; + + return SingleCubic(0, x, y); + } + + private final static double CUBIC_2D_BOUNDING = 1 / (1.5 * 1.5); + + private double SingleCubic(long seed, double x, double y) { + long x1 = fastFloor(x); + long y1 = fastFloor(y); + + long x0 = x1 - 1; + long y0 = y1 - 1; + long x2 = x1 + 1; + long y2 = y1 + 1; + long x3 = x1 + 2; + long y3 = y1 + 2; + + double xs = x - (double) x1; + double ys = y - (double) y1; + + return cubicLerp(cubicLerp(valCoord2D(seed, x0, y0), valCoord2D(seed, x1, y0), valCoord2D(seed, x2, y0), valCoord2D(seed, x3, y0), xs), cubicLerp(valCoord2D(seed, x0, y1), valCoord2D(seed, x1, y1), valCoord2D(seed, x2, y1), valCoord2D(seed, x3, y1), xs), cubicLerp(valCoord2D(seed, x0, y2), valCoord2D(seed, x1, y2), valCoord2D(seed, x2, y2), valCoord2D(seed, x3, y2), xs), cubicLerp(valCoord2D(seed, x0, y3), valCoord2D(seed, x1, y3), valCoord2D(seed, x2, y3), valCoord2D(seed, x3, y3), xs), ys) * CUBIC_2D_BOUNDING; + } + + // Cellular Noise + public double GetCellular(double x, double y, double z) { + x *= m_frequency; + y *= m_frequency; + z *= m_frequency; + + switch (m_cellularReturnType) { + case CellValue: + case NoiseLookup: + case Distance: + return SingleCellular(x, y, z); + default: + return SingleCellular2Edge(x, y, z); + } + } + + private double SingleCellular(double x, double y, double z) { + long xr = fastRound(x); + long yr = fastRound(y); + long zr = fastRound(z); + + double distance = 999999; + long xc = 0, yc = 0, zc = 0; + + switch (m_cellularDistanceFunction) { + case Euclidean: + for (long xi = xr - 1; xi <= xr + 1; xi++) { + for (long yi = yr - 1; yi <= yr + 1; yi++) { + for (long zi = zr - 1; zi <= zr + 1; zi++) { + Double3 vec = CELL_3D[(int) hash3D(m_seed, xi, yi, zi) & 255]; + + double vecX = xi - x + vec.x; + double vecY = yi - y + vec.y; + double vecZ = zi - z + vec.z; + + double newDistance = vecX * vecX + vecY * vecY + vecZ * vecZ; + + if (newDistance < distance) { + distance = newDistance; + xc = xi; + yc = yi; + zc = zi; + } + } + } + } + break; + case Manhattan: + for (long xi = xr - 1; xi <= xr + 1; xi++) { + for (long yi = yr - 1; yi <= yr + 1; yi++) { + for (long zi = zr - 1; zi <= zr + 1; zi++) { + Double3 vec = CELL_3D[(int) hash3D(m_seed, xi, yi, zi) & 255]; + + double vecX = xi - x + vec.x; + double vecY = yi - y + vec.y; + double vecZ = zi - z + vec.z; + + double newDistance = Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ); + + if (newDistance < distance) { + distance = newDistance; + xc = xi; + yc = yi; + zc = zi; + } + } + } + } + break; + case Natural: + for (long xi = xr - 1; xi <= xr + 1; xi++) { + for (long yi = yr - 1; yi <= yr + 1; yi++) { + for (long zi = zr - 1; zi <= zr + 1; zi++) { + Double3 vec = CELL_3D[(int) hash3D(m_seed, xi, yi, zi) & 255]; + + double vecX = xi - x + vec.x; + double vecY = yi - y + vec.y; + double vecZ = zi - z + vec.z; + + double newDistance = (Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ)) + (vecX * vecX + vecY * vecY + vecZ * vecZ); + + if (newDistance < distance) { + distance = newDistance; + xc = xi; + yc = yi; + zc = zi; + } + } + } + } + break; + } + + switch (m_cellularReturnType) { + case CellValue: + return valCoord3D(0, xc, yc, zc); + + case NoiseLookup: + Double3 vec = CELL_3D[(int) hash3D(m_seed, xc, yc, zc) & 255]; + return m_cellularNoiseLookup.GetNoise(xc + vec.x, yc + vec.y, zc + vec.z); + + case Distance: + return distance - 1; + default: + return 0; + } + } + + private double SingleCellular2Edge(double x, double y, double z) { + long xr = fastRound(x); + long yr = fastRound(y); + long zr = fastRound(z); + + double distance = 999999; + double distance2 = 999999; + + switch (m_cellularDistanceFunction) { + case Euclidean: + for (long xi = xr - 1; xi <= xr + 1; xi++) { + for (long yi = yr - 1; yi <= yr + 1; yi++) { + for (long zi = zr - 1; zi <= zr + 1; zi++) { + Double3 vec = CELL_3D[(int) hash3D(m_seed, xi, yi, zi) & 255]; + + double vecX = xi - x + vec.x; + double vecY = yi - y + vec.y; + double vecZ = zi - z + vec.z; + + double newDistance = vecX * vecX + vecY * vecY + vecZ * vecZ; + + distance2 = Math.max(Math.min(distance2, newDistance), distance); + distance = Math.min(distance, newDistance); + } + } + } + break; + case Manhattan: + for (long xi = xr - 1; xi <= xr + 1; xi++) { + for (long yi = yr - 1; yi <= yr + 1; yi++) { + for (long zi = zr - 1; zi <= zr + 1; zi++) { + Double3 vec = CELL_3D[(int) hash3D(m_seed, xi, yi, zi) & 255]; + + double vecX = xi - x + vec.x; + double vecY = yi - y + vec.y; + double vecZ = zi - z + vec.z; + + double newDistance = Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ); + + distance2 = Math.max(Math.min(distance2, newDistance), distance); + distance = Math.min(distance, newDistance); + } + } + } + break; + case Natural: + for (long xi = xr - 1; xi <= xr + 1; xi++) { + for (long yi = yr - 1; yi <= yr + 1; yi++) { + for (long zi = zr - 1; zi <= zr + 1; zi++) { + Double3 vec = CELL_3D[(int) hash3D(m_seed, xi, yi, zi) & 255]; + + double vecX = xi - x + vec.x; + double vecY = yi - y + vec.y; + double vecZ = zi - z + vec.z; + + double newDistance = (Math.abs(vecX) + Math.abs(vecY) + Math.abs(vecZ)) + (vecX * vecX + vecY * vecY + vecZ * vecZ); + + distance2 = Math.max(Math.min(distance2, newDistance), distance); + distance = Math.min(distance, newDistance); + } + } + } + break; + default: + break; + } + + switch (m_cellularReturnType) { + case Distance2: + return distance2 - 1; + case Distance2Add: + return distance2 + distance - 1; + case Distance2Sub: + return distance2 - distance - 1; + case Distance2Mul: + return distance2 * distance - 1; + case Distance2Div: + return distance / distance2 - 1; + default: + return 0; + } + } + + public double GetCellular(double x, double y) { + x *= m_frequency; + y *= m_frequency; + + switch (m_cellularReturnType) { + case CellValue: + case NoiseLookup: + case Distance: + return SingleCellular(x, y); + default: + return SingleCellular2Edge(x, y); + } + } + + private double SingleCellular(double x, double y) { + long xr = fastRound(x); + long yr = fastRound(y); + + double distance = 999999; + long xc = 0, yc = 0; + + switch (m_cellularDistanceFunction) { + default: + case Euclidean: + for (long xi = xr - 1; xi <= xr + 1; xi++) { + for (long yi = yr - 1; yi <= yr + 1; yi++) { + Double2 vec = CELL_2D[(int) hash2D(m_seed, xi, yi) & 255]; + + double vecX = xi - x + vec.x; + double vecY = yi - y + vec.y; + + double newDistance = vecX * vecX + vecY * vecY; + + if (newDistance < distance) { + distance = newDistance; + xc = xi; + yc = yi; + } + } + } + break; + case Manhattan: + for (long xi = xr - 1; xi <= xr + 1; xi++) { + for (long yi = yr - 1; yi <= yr + 1; yi++) { + Double2 vec = CELL_2D[(int) hash2D(m_seed, xi, yi) & 255]; + + double vecX = xi - x + vec.x; + double vecY = yi - y + vec.y; + + double newDistance = (Math.abs(vecX) + Math.abs(vecY)); + + if (newDistance < distance) { + distance = newDistance; + xc = xi; + yc = yi; + } + } + } + break; + case Natural: + for (long xi = xr - 1; xi <= xr + 1; xi++) { + for (long yi = yr - 1; yi <= yr + 1; yi++) { + Double2 vec = CELL_2D[(int) hash2D(m_seed, xi, yi) & 255]; + + double vecX = xi - x + vec.x; + double vecY = yi - y + vec.y; + + double newDistance = (Math.abs(vecX) + Math.abs(vecY)) + (vecX * vecX + vecY * vecY); + + if (newDistance < distance) { + distance = newDistance; + xc = xi; + yc = yi; + } + } + } + break; + } + + switch (m_cellularReturnType) { + case CellValue: + return valCoord2D(0, xc, yc); + + case NoiseLookup: + Double2 vec = CELL_2D[(int) hash2D(m_seed, xc, yc) & 255]; + return m_cellularNoiseLookup.GetNoise(xc + vec.x, yc + vec.y); + + case Distance: + return distance - 1; + default: + return 0; + } + } + + private double SingleCellular2Edge(double x, double y) { + long xr = fastRound(x); + long yr = fastRound(y); + + double distance = 999999; + double distance2 = 999999; + + switch (m_cellularDistanceFunction) { + default: + case Euclidean: + for (long xi = xr - 1; xi <= xr + 1; xi++) { + for (long yi = yr - 1; yi <= yr + 1; yi++) { + Double2 vec = CELL_2D[(int) hash2D(m_seed, xi, yi) & 255]; + + double vecX = xi - x + vec.x; + double vecY = yi - y + vec.y; + + double newDistance = vecX * vecX + vecY * vecY; + + distance2 = Math.max(Math.min(distance2, newDistance), distance); + distance = Math.min(distance, newDistance); + } + } + break; + case Manhattan: + for (long xi = xr - 1; xi <= xr + 1; xi++) { + for (long yi = yr - 1; yi <= yr + 1; yi++) { + Double2 vec = CELL_2D[(int) hash2D(m_seed, xi, yi) & 255]; + + double vecX = xi - x + vec.x; + double vecY = yi - y + vec.y; + + double newDistance = Math.abs(vecX) + Math.abs(vecY); + + distance2 = Math.max(Math.min(distance2, newDistance), distance); + distance = Math.min(distance, newDistance); + } + } + break; + case Natural: + for (long xi = xr - 1; xi <= xr + 1; xi++) { + for (long yi = yr - 1; yi <= yr + 1; yi++) { + Double2 vec = CELL_2D[(int) hash2D(m_seed, xi, yi) & 255]; + + double vecX = xi - x + vec.x; + double vecY = yi - y + vec.y; + + double newDistance = (Math.abs(vecX) + Math.abs(vecY)) + (vecX * vecX + vecY * vecY); + + distance2 = Math.max(Math.min(distance2, newDistance), distance); + distance = Math.min(distance, newDistance); + } + } + break; + } + + switch (m_cellularReturnType) { + case Distance2: + return distance2 - 1; + case Distance2Add: + return distance2 + distance - 1; + case Distance2Sub: + return distance2 - distance - 1; + case Distance2Mul: + return distance2 * distance - 1; + case Distance2Div: + return distance / distance2 - 1; + default: + return 0; + } + } + + public void GradientPerturb(Vector3f v3) { + SingleGradientPerturb(m_seed, m_gradientPerturbAmp, m_frequency, v3); + } + + public void GradientPerturbFractal(Vector3f v3) { + long seed = m_seed; + double amp = m_gradientPerturbAmp * m_fractalBounding; + double freq = m_frequency; + + SingleGradientPerturb(seed, amp, m_frequency, v3); + + for (long i = 1; i < m_octaves; i++) { + freq *= m_lacunarity; + amp *= m_gain; + SingleGradientPerturb(++seed, amp, freq, v3); + } + } + + private void SingleGradientPerturb(long seed, double perturbAmp, double frequency, Vector3f v3) { + double xf = v3.x * frequency; + double yf = v3.y * frequency; + double zf = v3.z * frequency; + + long x0 = fastFloor(xf); + long y0 = fastFloor(yf); + long z0 = fastFloor(zf); + long x1 = x0 + 1; + long y1 = y0 + 1; + long z1 = z0 + 1; + + double xs, ys, zs; + switch (m_longerp) { + default: + case Linear: + xs = xf - x0; + ys = yf - y0; + zs = zf - z0; + break; + case Hermite: + xs = longerpHermiteFunc(xf - x0); + ys = longerpHermiteFunc(yf - y0); + zs = longerpHermiteFunc(zf - z0); + break; + case Qulongic: + xs = longerpQulongicFunc(xf - x0); + ys = longerpQulongicFunc(yf - y0); + zs = longerpQulongicFunc(zf - z0); + break; + } + + Double3 vec0 = CELL_3D[(int) hash3D(seed, x0, y0, z0) & 255]; + Double3 vec1 = CELL_3D[(int) hash3D(seed, x1, y0, z0) & 255]; + + double lx0x = lerp(vec0.x, vec1.x, xs); + double ly0x = lerp(vec0.y, vec1.y, xs); + double lz0x = lerp(vec0.z, vec1.z, xs); + + vec0 = CELL_3D[(int) hash3D(seed, x0, y1, z0) & 255]; + vec1 = CELL_3D[(int) hash3D(seed, x1, y1, z0) & 255]; + + double lx1x = lerp(vec0.x, vec1.x, xs); + double ly1x = lerp(vec0.y, vec1.y, xs); + double lz1x = lerp(vec0.z, vec1.z, xs); + + double lx0y = lerp(lx0x, lx1x, ys); + double ly0y = lerp(ly0x, ly1x, ys); + double lz0y = lerp(lz0x, lz1x, ys); + + vec0 = CELL_3D[(int) hash3D(seed, x0, y0, z1) & 255]; + vec1 = CELL_3D[(int) hash3D(seed, x1, y0, z1) & 255]; + + lx0x = lerp(vec0.x, vec1.x, xs); + ly0x = lerp(vec0.y, vec1.y, xs); + lz0x = lerp(vec0.z, vec1.z, xs); + + vec0 = CELL_3D[(int) hash3D(seed, x0, y1, z1) & 255]; + vec1 = CELL_3D[(int) hash3D(seed, x1, y1, z1) & 255]; + + lx1x = lerp(vec0.x, vec1.x, xs); + ly1x = lerp(vec0.y, vec1.y, xs); + lz1x = lerp(vec0.z, vec1.z, xs); + + v3.x += lerp(lx0y, lerp(lx0x, lx1x, ys), zs) * perturbAmp; + v3.y += lerp(ly0y, lerp(ly0x, ly1x, ys), zs) * perturbAmp; + v3.z += lerp(lz0y, lerp(lz0x, lz1x, ys), zs) * perturbAmp; + } + + public void GradientPerturb(Vector2f v2) { + SingleGradientPerturb(m_seed, m_gradientPerturbAmp, m_frequency, v2); + } + + public void GradientPerturbFractal(Vector2f v2) { + long seed = m_seed; + double amp = m_gradientPerturbAmp * m_fractalBounding; + double freq = m_frequency; + + SingleGradientPerturb(seed, amp, m_frequency, v2); + + for (long i = 1; i < m_octaves; i++) { + freq *= m_lacunarity; + amp *= m_gain; + SingleGradientPerturb(++seed, amp, freq, v2); + } + } + + private void SingleGradientPerturb(long seed, double perturbAmp, double frequency, Vector2f v2) { + double xf = v2.x * frequency; + double yf = v2.y * frequency; + + long x0 = fastFloor(xf); + long y0 = fastFloor(yf); + long x1 = x0 + 1; + long y1 = y0 + 1; + + double xs, ys; + switch (m_longerp) { + default: + case Linear: + xs = xf - x0; + ys = yf - y0; + break; + case Hermite: + xs = longerpHermiteFunc(xf - x0); + ys = longerpHermiteFunc(yf - y0); + break; + case Qulongic: + xs = longerpQulongicFunc(xf - x0); + ys = longerpQulongicFunc(yf - y0); + break; + } + + Double2 vec0 = CELL_2D[(int) hash2D(seed, x0, y0) & 255]; + Double2 vec1 = CELL_2D[(int) hash2D(seed, x1, y0) & 255]; + + double lx0x = lerp(vec0.x, vec1.x, xs); + double ly0x = lerp(vec0.y, vec1.y, xs); + + vec0 = CELL_2D[(int) hash2D(seed, x0, y1) & 255]; + vec1 = CELL_2D[(int) hash2D(seed, x1, y1) & 255]; + + double lx1x = lerp(vec0.x, vec1.x, xs); + double ly1x = lerp(vec0.y, vec1.y, xs); + + v2.x += lerp(lx0x, lx1x, ys) * perturbAmp; + v2.y += lerp(ly0x, ly1x, ys) * perturbAmp; + } } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/generator/noise/FlatNoise.java b/src/main/java/com/volmit/iris/generator/noise/FlatNoise.java index baa7030e9..897dfd34d 100644 --- a/src/main/java/com/volmit/iris/generator/noise/FlatNoise.java +++ b/src/main/java/com/volmit/iris/generator/noise/FlatNoise.java @@ -1,27 +1,22 @@ package com.volmit.iris.generator.noise; -public class FlatNoise implements NoiseGenerator -{ - public FlatNoise(long seed) - { +public class FlatNoise implements NoiseGenerator { + public FlatNoise(long seed) { - } + } - @Override - public double noise(double x) - { - return 1D; - } + @Override + public double noise(double x) { + return 1D; + } - @Override - public double noise(double x, double z) - { - return 1D; - } + @Override + public double noise(double x, double z) { + return 1D; + } - @Override - public double noise(double x, double y, double z) - { - return 1D; - } + @Override + public double noise(double x, double y, double z) { + return 1D; + } } diff --git a/src/main/java/com/volmit/iris/generator/noise/FractalBillowPerlinNoise.java b/src/main/java/com/volmit/iris/generator/noise/FractalBillowPerlinNoise.java index 90b638398..f1a19f539 100644 --- a/src/main/java/com/volmit/iris/generator/noise/FractalBillowPerlinNoise.java +++ b/src/main/java/com/volmit/iris/generator/noise/FractalBillowPerlinNoise.java @@ -3,43 +3,36 @@ package com.volmit.iris.generator.noise; import com.volmit.iris.generator.noise.FastNoiseDouble.FractalType; import com.volmit.iris.util.RNG; -public class FractalBillowPerlinNoise implements NoiseGenerator, OctaveNoise -{ - private final FastNoiseDouble n; +public class FractalBillowPerlinNoise implements NoiseGenerator, OctaveNoise { + private final FastNoiseDouble n; - public FractalBillowPerlinNoise(long seed) - { - this.n = new FastNoiseDouble(new RNG(seed).lmax()); - n.setFractalOctaves(1); - n.setFractalType(FractalType.Billow); - } + public FractalBillowPerlinNoise(long seed) { + this.n = new FastNoiseDouble(new RNG(seed).lmax()); + n.setFractalOctaves(1); + n.setFractalType(FractalType.Billow); + } - public double f(double v) - { - return (v / 2D) + 0.5D; - } + public double f(double v) { + return (v / 2D) + 0.5D; + } - @Override - public double noise(double x) - { - return f(n.GetPerlinFractal(x, 0f)); - } + @Override + public double noise(double x) { + return f(n.GetPerlinFractal(x, 0f)); + } - @Override - public double noise(double x, double z) - { - return f(n.GetPerlinFractal(x, z)); - } + @Override + public double noise(double x, double z) { + return f(n.GetPerlinFractal(x, z)); + } - @Override - public double noise(double x, double y, double z) - { - return f(n.GetPerlinFractal(x, y, z)); - } + @Override + public double noise(double x, double y, double z) { + return f(n.GetPerlinFractal(x, y, z)); + } - @Override - public void setOctaves(int o) - { - n.setFractalOctaves(o); - } + @Override + public void setOctaves(int o) { + n.setFractalOctaves(o); + } } diff --git a/src/main/java/com/volmit/iris/generator/noise/FractalBillowSimplexNoise.java b/src/main/java/com/volmit/iris/generator/noise/FractalBillowSimplexNoise.java index 1be8dbc53..03207afd5 100644 --- a/src/main/java/com/volmit/iris/generator/noise/FractalBillowSimplexNoise.java +++ b/src/main/java/com/volmit/iris/generator/noise/FractalBillowSimplexNoise.java @@ -3,43 +3,36 @@ package com.volmit.iris.generator.noise; import com.volmit.iris.generator.noise.FastNoiseDouble.FractalType; import com.volmit.iris.util.RNG; -public class FractalBillowSimplexNoise implements NoiseGenerator, OctaveNoise -{ - private final FastNoiseDouble n; +public class FractalBillowSimplexNoise implements NoiseGenerator, OctaveNoise { + private final FastNoiseDouble n; - public FractalBillowSimplexNoise(long seed) - { - this.n = new FastNoiseDouble(new RNG(seed).lmax()); - n.setFractalOctaves(1); - n.setFractalType(FractalType.Billow); - } + public FractalBillowSimplexNoise(long seed) { + this.n = new FastNoiseDouble(new RNG(seed).lmax()); + n.setFractalOctaves(1); + n.setFractalType(FractalType.Billow); + } - public double f(double v) - { - return (v / 2D) + 0.5D; - } + public double f(double v) { + return (v / 2D) + 0.5D; + } - @Override - public double noise(double x) - { - return f(n.GetSimplexFractal(x, 0d)); - } + @Override + public double noise(double x) { + return f(n.GetSimplexFractal(x, 0d)); + } - @Override - public double noise(double x, double z) - { - return f(n.GetSimplexFractal(x, z)); - } + @Override + public double noise(double x, double z) { + return f(n.GetSimplexFractal(x, z)); + } - @Override - public double noise(double x, double y, double z) - { - return f(n.GetSimplexFractal(x, y, z)); - } + @Override + public double noise(double x, double y, double z) { + return f(n.GetSimplexFractal(x, y, z)); + } - @Override - public void setOctaves(int o) - { - n.setFractalOctaves(o); - } + @Override + public void setOctaves(int o) { + n.setFractalOctaves(o); + } } diff --git a/src/main/java/com/volmit/iris/generator/noise/FractalCubicNoise.java b/src/main/java/com/volmit/iris/generator/noise/FractalCubicNoise.java index 750d98b02..c87be8070 100644 --- a/src/main/java/com/volmit/iris/generator/noise/FractalCubicNoise.java +++ b/src/main/java/com/volmit/iris/generator/noise/FractalCubicNoise.java @@ -3,36 +3,30 @@ package com.volmit.iris.generator.noise; import com.volmit.iris.generator.noise.FastNoiseDouble.FractalType; import com.volmit.iris.util.RNG; -public class FractalCubicNoise implements NoiseGenerator -{ - private final FastNoiseDouble n; +public class FractalCubicNoise implements NoiseGenerator { + private final FastNoiseDouble n; - public FractalCubicNoise(long seed) - { - this.n = new FastNoiseDouble(new RNG(seed).lmax()); - n.setFractalType(FractalType.Billow); - } + public FractalCubicNoise(long seed) { + this.n = new FastNoiseDouble(new RNG(seed).lmax()); + n.setFractalType(FractalType.Billow); + } - private double f(double n) - { - return (n / 2D) + 0.5D; - } + private double f(double n) { + return (n / 2D) + 0.5D; + } - @Override - public double noise(double x) - { - return f(n.GetCubicFractal(x, 0)); - } + @Override + public double noise(double x) { + return f(n.GetCubicFractal(x, 0)); + } - @Override - public double noise(double x, double z) - { - return f(n.GetCubicFractal(x, z)); - } + @Override + public double noise(double x, double z) { + return f(n.GetCubicFractal(x, z)); + } - @Override - public double noise(double x, double y, double z) - { - return f(n.GetCubicFractal(x, y, z)); - } + @Override + public double noise(double x, double y, double z) { + return f(n.GetCubicFractal(x, y, z)); + } } diff --git a/src/main/java/com/volmit/iris/generator/noise/FractalFBMSimplexNoise.java b/src/main/java/com/volmit/iris/generator/noise/FractalFBMSimplexNoise.java index 9f1b0a2a9..4789e4f8c 100644 --- a/src/main/java/com/volmit/iris/generator/noise/FractalFBMSimplexNoise.java +++ b/src/main/java/com/volmit/iris/generator/noise/FractalFBMSimplexNoise.java @@ -3,43 +3,36 @@ package com.volmit.iris.generator.noise; import com.volmit.iris.generator.noise.FastNoiseDouble.FractalType; import com.volmit.iris.util.RNG; -public class FractalFBMSimplexNoise implements NoiseGenerator, OctaveNoise -{ - private final FastNoiseDouble n; +public class FractalFBMSimplexNoise implements NoiseGenerator, OctaveNoise { + private final FastNoiseDouble n; - public FractalFBMSimplexNoise(long seed) - { - this.n = new FastNoiseDouble(new RNG(seed).lmax()); - n.setFractalOctaves(1); - n.setFractalType(FractalType.FBM); - } + public FractalFBMSimplexNoise(long seed) { + this.n = new FastNoiseDouble(new RNG(seed).lmax()); + n.setFractalOctaves(1); + n.setFractalType(FractalType.FBM); + } - public double f(double v) - { - return (v / 2D) + 0.5D; - } + public double f(double v) { + return (v / 2D) + 0.5D; + } - @Override - public double noise(double x) - { - return f(n.GetSimplexFractal(x, 0d)); - } + @Override + public double noise(double x) { + return f(n.GetSimplexFractal(x, 0d)); + } - @Override - public double noise(double x, double z) - { - return f(n.GetSimplexFractal(x, z)); - } + @Override + public double noise(double x, double z) { + return f(n.GetSimplexFractal(x, z)); + } - @Override - public double noise(double x, double y, double z) - { - return f(n.GetSimplexFractal(x, y, z)); - } + @Override + public double noise(double x, double y, double z) { + return f(n.GetSimplexFractal(x, y, z)); + } - @Override - public void setOctaves(int o) - { - n.setFractalOctaves(o); - } + @Override + public void setOctaves(int o) { + n.setFractalOctaves(o); + } } diff --git a/src/main/java/com/volmit/iris/generator/noise/FractalRigidMultiSimplexNoise.java b/src/main/java/com/volmit/iris/generator/noise/FractalRigidMultiSimplexNoise.java index d2c197ac1..40ec8d270 100644 --- a/src/main/java/com/volmit/iris/generator/noise/FractalRigidMultiSimplexNoise.java +++ b/src/main/java/com/volmit/iris/generator/noise/FractalRigidMultiSimplexNoise.java @@ -3,43 +3,36 @@ package com.volmit.iris.generator.noise; import com.volmit.iris.generator.noise.FastNoiseDouble.FractalType; import com.volmit.iris.util.RNG; -public class FractalRigidMultiSimplexNoise implements NoiseGenerator, OctaveNoise -{ - private final FastNoiseDouble n; +public class FractalRigidMultiSimplexNoise implements NoiseGenerator, OctaveNoise { + private final FastNoiseDouble n; - public FractalRigidMultiSimplexNoise(long seed) - { - this.n = new FastNoiseDouble(new RNG(seed).lmax()); - n.setFractalOctaves(1); - n.setFractalType(FractalType.RigidMulti); - } + public FractalRigidMultiSimplexNoise(long seed) { + this.n = new FastNoiseDouble(new RNG(seed).lmax()); + n.setFractalOctaves(1); + n.setFractalType(FractalType.RigidMulti); + } - public double f(double v) - { - return (v / 2D) + 0.5D; - } + public double f(double v) { + return (v / 2D) + 0.5D; + } - @Override - public double noise(double x) - { - return f(n.GetSimplexFractal(x, 0d)); - } + @Override + public double noise(double x) { + return f(n.GetSimplexFractal(x, 0d)); + } - @Override - public double noise(double x, double z) - { - return f(n.GetSimplexFractal(x, z)); - } + @Override + public double noise(double x, double z) { + return f(n.GetSimplexFractal(x, z)); + } - @Override - public double noise(double x, double y, double z) - { - return f(n.GetSimplexFractal(x, y, z)); - } + @Override + public double noise(double x, double y, double z) { + return f(n.GetSimplexFractal(x, y, z)); + } - @Override - public void setOctaves(int o) - { - n.setFractalOctaves(o); - } + @Override + public void setOctaves(int o) { + n.setFractalOctaves(o); + } } diff --git a/src/main/java/com/volmit/iris/generator/noise/GlobNoise.java b/src/main/java/com/volmit/iris/generator/noise/GlobNoise.java index c339db713..938c352a8 100644 --- a/src/main/java/com/volmit/iris/generator/noise/GlobNoise.java +++ b/src/main/java/com/volmit/iris/generator/noise/GlobNoise.java @@ -2,38 +2,32 @@ package com.volmit.iris.generator.noise; import com.volmit.iris.util.RNG; -public class GlobNoise implements NoiseGenerator -{ - private final FastNoiseDouble n; +public class GlobNoise implements NoiseGenerator { + private final FastNoiseDouble n; - public GlobNoise(long seed) - { - this.n = new FastNoiseDouble(new RNG(seed).lmax()); - n.setNoiseType(FastNoiseDouble.NoiseType.Cellular); - n.setCellularReturnType(FastNoiseDouble.CellularReturnType.Distance2Div); - n.setCellularDistanceFunction(FastNoiseDouble.CellularDistanceFunction.Natural); - } + public GlobNoise(long seed) { + this.n = new FastNoiseDouble(new RNG(seed).lmax()); + n.setNoiseType(FastNoiseDouble.NoiseType.Cellular); + n.setCellularReturnType(FastNoiseDouble.CellularReturnType.Distance2Div); + n.setCellularDistanceFunction(FastNoiseDouble.CellularDistanceFunction.Natural); + } - private double f(double n) - { - return n + 1D; - } + private double f(double n) { + return n + 1D; + } - @Override - public double noise(double x) - { - return f(n.GetCellular(x, 0)); - } + @Override + public double noise(double x) { + return f(n.GetCellular(x, 0)); + } - @Override - public double noise(double x, double z) - { - return f(n.GetCellular(x, z)); - } + @Override + public double noise(double x, double z) { + return f(n.GetCellular(x, z)); + } - @Override - public double noise(double x, double y, double z) - { - return f(n.GetCellular(x, y, z)); - } + @Override + public double noise(double x, double y, double z) { + return f(n.GetCellular(x, y, z)); + } } diff --git a/src/main/java/com/volmit/iris/generator/noise/NoiseFactory.java b/src/main/java/com/volmit/iris/generator/noise/NoiseFactory.java index 7fbf98eeb..bbe56e338 100644 --- a/src/main/java/com/volmit/iris/generator/noise/NoiseFactory.java +++ b/src/main/java/com/volmit/iris/generator/noise/NoiseFactory.java @@ -1,7 +1,6 @@ package com.volmit.iris.generator.noise; @FunctionalInterface -public interface NoiseFactory -{ - NoiseGenerator create(long seed); +public interface NoiseFactory { + NoiseGenerator create(long seed); } diff --git a/src/main/java/com/volmit/iris/generator/noise/NoiseGenerator.java b/src/main/java/com/volmit/iris/generator/noise/NoiseGenerator.java index 7ae3d1336..9a88c4ac0 100644 --- a/src/main/java/com/volmit/iris/generator/noise/NoiseGenerator.java +++ b/src/main/java/com/volmit/iris/generator/noise/NoiseGenerator.java @@ -1,15 +1,13 @@ package com.volmit.iris.generator.noise; -public interface NoiseGenerator -{ - public double noise(double x); - - public double noise(double x, double z); - - public double noise(double x, double y, double z); +public interface NoiseGenerator { + double noise(double x); - public default boolean isStatic() - { - return false; - } + double noise(double x, double z); + + double noise(double x, double y, double z); + + default boolean isStatic() { + return false; + } } diff --git a/src/main/java/com/volmit/iris/generator/noise/NoiseType.java b/src/main/java/com/volmit/iris/generator/noise/NoiseType.java index 554f5eca4..a986c1b3e 100644 --- a/src/main/java/com/volmit/iris/generator/noise/NoiseType.java +++ b/src/main/java/com/volmit/iris/generator/noise/NoiseType.java @@ -1,28 +1,28 @@ package com.volmit.iris.generator.noise; public enum NoiseType { - WHITE(WhiteNoise::new), - SIMPLEX(SimplexNoise::new), - PERLIN(seed -> new PerlinNoise(seed).hermite()), - FRACTAL_BILLOW_SIMPLEX(FractalBillowSimplexNoise::new), - FRACTAL_BILLOW_PERLIN(FractalBillowPerlinNoise::new), - FRACTAL_FBM_SIMPLEX(FractalFBMSimplexNoise::new), - FRACTAL_RIGID_MULTI_SIMPLEX(FractalRigidMultiSimplexNoise::new), - FLAT(FlatNoise::new), - CELLULAR(CellularNoise::new), - GLOB(GlobNoise::new), - CUBIC(CubicNoise::new), - FRACTAL_CUBIC(FractalCubicNoise::new), - CELLULAR_HEIGHT(CellHeightNoise::new), - VASCULAR(VascularNoise::new); + WHITE(WhiteNoise::new), + SIMPLEX(SimplexNoise::new), + PERLIN(seed -> new PerlinNoise(seed).hermite()), + FRACTAL_BILLOW_SIMPLEX(FractalBillowSimplexNoise::new), + FRACTAL_BILLOW_PERLIN(FractalBillowPerlinNoise::new), + FRACTAL_FBM_SIMPLEX(FractalFBMSimplexNoise::new), + FRACTAL_RIGID_MULTI_SIMPLEX(FractalRigidMultiSimplexNoise::new), + FLAT(FlatNoise::new), + CELLULAR(CellularNoise::new), + GLOB(GlobNoise::new), + CUBIC(CubicNoise::new), + FRACTAL_CUBIC(FractalCubicNoise::new), + CELLULAR_HEIGHT(CellHeightNoise::new), + VASCULAR(VascularNoise::new); - private final NoiseFactory f; + private final NoiseFactory f; - private NoiseType(NoiseFactory f) { - this.f = f; - } + NoiseType(NoiseFactory f) { + this.f = f; + } - public NoiseGenerator create(long seed) { - return f.create(seed); - } + public NoiseGenerator create(long seed) { + return f.create(seed); + } } diff --git a/src/main/java/com/volmit/iris/generator/noise/OctaveNoise.java b/src/main/java/com/volmit/iris/generator/noise/OctaveNoise.java index 5d213c91a..aa77f8db4 100644 --- a/src/main/java/com/volmit/iris/generator/noise/OctaveNoise.java +++ b/src/main/java/com/volmit/iris/generator/noise/OctaveNoise.java @@ -1,6 +1,5 @@ package com.volmit.iris.generator.noise; -public interface OctaveNoise -{ - public void setOctaves(int o); +public interface OctaveNoise { + void setOctaves(int o); } diff --git a/src/main/java/com/volmit/iris/generator/noise/PerlinNoise.java b/src/main/java/com/volmit/iris/generator/noise/PerlinNoise.java index 4532bcd3d..a26baefb7 100644 --- a/src/main/java/com/volmit/iris/generator/noise/PerlinNoise.java +++ b/src/main/java/com/volmit/iris/generator/noise/PerlinNoise.java @@ -2,97 +2,85 @@ package com.volmit.iris.generator.noise; import com.volmit.iris.util.RNG; -public class PerlinNoise implements NoiseGenerator, OctaveNoise -{ - private final FastNoiseDouble n; - private int octaves; +public class PerlinNoise implements NoiseGenerator, OctaveNoise { + private final FastNoiseDouble n; + private int octaves; - public PerlinNoise(long seed) - { - this.n = new FastNoiseDouble(new RNG(seed).lmax()); - octaves = 1; - } + public PerlinNoise(long seed) { + this.n = new FastNoiseDouble(new RNG(seed).lmax()); + octaves = 1; + } - public double f(double v) - { - return (v / 2D) + 0.5D; - } + public double f(double v) { + return (v / 2D) + 0.5D; + } - @Override - public double noise(double x) - { - if(octaves <= 1) - { - return f(n.GetPerlin(x, 0)); - } + @Override + public double noise(double x) { + if (octaves <= 1) { + return f(n.GetPerlin(x, 0)); + } - double f = 1; - double m = 0; - double v = 0; + double f = 1; + double m = 0; + double v = 0; - for(int i = 0; i < octaves; i++) - { - v += n.GetPerlin((x * (f == 1 ? f++ : (f *= 2))), 0) * f; - m += f; - } + for (int i = 0; i < octaves; i++) { + v += n.GetPerlin((x * (f == 1 ? f++ : (f *= 2))), 0) * f; + m += f; + } - return f(v / m); - } + return f(v / m); + } - @Override - public double noise(double x, double z) - { - if(octaves <= 1) - { - return f(n.GetPerlin(x, z)); - } - double f = 1; - double m = 0; - double v = 0; + @Override + public double noise(double x, double z) { + if (octaves <= 1) { + return f(n.GetPerlin(x, z)); + } + double f = 1; + double m = 0; + double v = 0; - for(int i = 0; i < octaves; i++) - { - f = f == 1 ? f + 1 : f * 2; - v += n.GetPerlin((x * f), (z * f)) * f; - m += f; - } + for (int i = 0; i < octaves; i++) { + f = f == 1 ? f + 1 : f * 2; + v += n.GetPerlin((x * f), (z * f)) * f; + m += f; + } - return f(v / m); - } + return f(v / m); + } - @Override - public double noise(double x, double y, double z) - { - if(octaves <= 1) - { - return f(n.GetPerlin(x, y, z)); - } - double f = 1; - double m = 0; - double v = 0; + @Override + public double noise(double x, double y, double z) { + if (octaves <= 1) { + return f(n.GetPerlin(x, y, z)); + } + double f = 1; + double m = 0; + double v = 0; - for(int i = 0; i < octaves; i++) - { - f = f == 1 ? f + 1 : f * 2; - v += n.GetPerlin((x * f), (y * f), (z * f)) * f; - m += f; - } + for (int i = 0; i < octaves; i++) { + f = f == 1 ? f + 1 : f * 2; + v += n.GetPerlin((x * f), (y * f), (z * f)) * f; + m += f; + } - return f(v / m); - } + return f(v / m); + } - @Override - public void setOctaves(int o) - { - octaves = o; - } + @Override + public void setOctaves(int o) { + octaves = o; + } - public NoiseGenerator hermite() { - n.m_longerp = FastNoiseDouble.Longerp.Hermite; - return this; - } - public NoiseGenerator quad() { - n.m_longerp = FastNoiseDouble.Longerp.Qulongic; - return this; - } + public NoiseGenerator hermite() { + n.m_longerp = FastNoiseDouble.Longerp.Hermite; + return this; + } + + public NoiseGenerator quad() { + n.m_longerp = FastNoiseDouble.Longerp.Qulongic; + return this; + } } diff --git a/src/main/java/com/volmit/iris/generator/noise/RarityCellGenerator.java b/src/main/java/com/volmit/iris/generator/noise/RarityCellGenerator.java index 8afa6458e..32f2f1e35 100644 --- a/src/main/java/com/volmit/iris/generator/noise/RarityCellGenerator.java +++ b/src/main/java/com/volmit/iris/generator/noise/RarityCellGenerator.java @@ -4,64 +4,49 @@ import com.volmit.iris.util.IRare; import com.volmit.iris.util.KList; import com.volmit.iris.util.RNG; -public class RarityCellGenerator extends CellGenerator -{ - public RarityCellGenerator(RNG rng) - { - super(rng); - } +public class RarityCellGenerator extends CellGenerator { + public RarityCellGenerator(RNG rng) { + super(rng); + } - public T get(double x, double z, KList b) - { - if(b.size() == 0) - { - return null; - } + public T get(double x, double z, KList b) { + if (b.size() == 0) { + return null; + } - if(b.size() == 1) - { - return b.get(0); - } + if (b.size() == 1) { + return b.get(0); + } - KList rarityMapped = new KList<>(); - boolean o = false; - int max = 1; - for(T i : b) - { - if(i.getRarity() > max) - { - max = i.getRarity(); - } - } + KList rarityMapped = new KList<>(); + boolean o = false; + int max = 1; + for (T i : b) { + if (i.getRarity() > max) { + max = i.getRarity(); + } + } - max++; + max++; - for(T i : b) - { - for(int j = 0; j < max - i.getRarity(); j++) - { - if(o = !o) - { - rarityMapped.add(i); - } + for (T i : b) { + for (int j = 0; j < max - i.getRarity(); j++) { + if (o = !o) { + rarityMapped.add(i); + } else { + rarityMapped.add(0, i); + } + } + } - else - { - rarityMapped.add(0, i); - } - } - } + if (rarityMapped.size() == 1) { + return rarityMapped.get(0); + } - if(rarityMapped.size() == 1) - { - return rarityMapped.get(0); - } + if (rarityMapped.isEmpty()) { + throw new RuntimeException("BAD RARITY MAP! RELATED TO: " + b.toString(", or possibly ")); + } - if(rarityMapped.isEmpty()) - { - throw new RuntimeException("BAD RARITY MAP! RELATED TO: " + b.toString(", or possibly ")); - } - - return rarityMapped.get(getIndex(x, z, rarityMapped.size())); - } + return rarityMapped.get(getIndex(x, z, rarityMapped.size())); + } } diff --git a/src/main/java/com/volmit/iris/generator/noise/SimplexNoise.java b/src/main/java/com/volmit/iris/generator/noise/SimplexNoise.java index bbff624da..8ee42e2be 100644 --- a/src/main/java/com/volmit/iris/generator/noise/SimplexNoise.java +++ b/src/main/java/com/volmit/iris/generator/noise/SimplexNoise.java @@ -2,88 +2,75 @@ package com.volmit.iris.generator.noise; import com.volmit.iris.util.RNG; -public class SimplexNoise implements NoiseGenerator, OctaveNoise -{ - private final FastNoiseDouble n; - private int octaves; +public class SimplexNoise implements NoiseGenerator, OctaveNoise { + private final FastNoiseDouble n; + private int octaves; - public SimplexNoise(long seed) - { - this.n = new FastNoiseDouble(new RNG(seed).lmax()); - octaves = 1; - } + public SimplexNoise(long seed) { + this.n = new FastNoiseDouble(new RNG(seed).lmax()); + octaves = 1; + } - public double f(double v) - { - return (v / 2D) + 0.5D; - } + public double f(double v) { + return (v / 2D) + 0.5D; + } - @Override - public double noise(double x) - { - if(octaves <= 1) - { - return f(n.GetSimplex(x, 0d)); - } + @Override + public double noise(double x) { + if (octaves <= 1) { + return f(n.GetSimplex(x, 0d)); + } - double f = 1; - double m = 0; - double v = 0; + double f = 1; + double m = 0; + double v = 0; - for(int i = 0; i < octaves; i++) - { - v += n.GetSimplex((x * (f == 1 ? f++ : (f *= 2))), 0d) * f; - m += f; - } + for (int i = 0; i < octaves; i++) { + v += n.GetSimplex((x * (f == 1 ? f++ : (f *= 2))), 0d) * f; + m += f; + } - return f(v / m); - } + return f(v / m); + } - @Override - public double noise(double x, double z) - { - if(octaves <= 1) - { - return f(n.GetSimplex(x, z)); - } - double f = 1; - double m = 0; - double v = 0; + @Override + public double noise(double x, double z) { + if (octaves <= 1) { + return f(n.GetSimplex(x, z)); + } + double f = 1; + double m = 0; + double v = 0; - for(int i = 0; i < octaves; i++) - { - f = f == 1 ? f + 1 : f * 2; - v += n.GetSimplex((x * f), (z * f)) * f; - m += f; - } + for (int i = 0; i < octaves; i++) { + f = f == 1 ? f + 1 : f * 2; + v += n.GetSimplex((x * f), (z * f)) * f; + m += f; + } - return f(v / m); - } + return f(v / m); + } - @Override - public double noise(double x, double y, double z) - { - if(octaves <= 1) - { - return f(n.GetSimplex(x, y, z)); - } - double f = 1; - double m = 0; - double v = 0; + @Override + public double noise(double x, double y, double z) { + if (octaves <= 1) { + return f(n.GetSimplex(x, y, z)); + } + double f = 1; + double m = 0; + double v = 0; - for(int i = 0; i < octaves; i++) - { - f = f == 1 ? f + 1 : f * 2; - v += n.GetSimplex((x * f), (y * f), (z * f)) * f; - m += f; - } + for (int i = 0; i < octaves; i++) { + f = f == 1 ? f + 1 : f * 2; + v += n.GetSimplex((x * f), (y * f), (z * f)) * f; + m += f; + } - return f(v / m); - } + return f(v / m); + } - @Override - public void setOctaves(int o) - { - octaves = o; - } + @Override + public void setOctaves(int o) { + octaves = o; + } } diff --git a/src/main/java/com/volmit/iris/generator/noise/VascularNoise.java b/src/main/java/com/volmit/iris/generator/noise/VascularNoise.java index 8bff7cd79..a78188baa 100644 --- a/src/main/java/com/volmit/iris/generator/noise/VascularNoise.java +++ b/src/main/java/com/volmit/iris/generator/noise/VascularNoise.java @@ -3,38 +3,32 @@ package com.volmit.iris.generator.noise; import com.volmit.iris.util.M; import com.volmit.iris.util.RNG; -public class VascularNoise implements NoiseGenerator -{ - private final FastNoiseDouble n; +public class VascularNoise implements NoiseGenerator { + private final FastNoiseDouble n; - public VascularNoise(long seed) - { - this.n = new FastNoiseDouble(new RNG(seed).lmax()); - n.setNoiseType(FastNoiseDouble.NoiseType.Cellular); - n.setCellularReturnType(FastNoiseDouble.CellularReturnType.Distance2Sub); - n.setCellularDistanceFunction(FastNoiseDouble.CellularDistanceFunction.Natural); - } + public VascularNoise(long seed) { + this.n = new FastNoiseDouble(new RNG(seed).lmax()); + n.setNoiseType(FastNoiseDouble.NoiseType.Cellular); + n.setCellularReturnType(FastNoiseDouble.CellularReturnType.Distance2Sub); + n.setCellularDistanceFunction(FastNoiseDouble.CellularDistanceFunction.Natural); + } - private double filter(double noise) - { - return M.clip((noise / 2D) + 0.5D, 0D, 1D); - } + private double filter(double noise) { + return M.clip((noise / 2D) + 0.5D, 0D, 1D); + } - @Override - public double noise(double x) - { - return filter(n.GetCellular(x, 0)); - } + @Override + public double noise(double x) { + return filter(n.GetCellular(x, 0)); + } - @Override - public double noise(double x, double z) - { - return filter(n.GetCellular(x, z)); - } + @Override + public double noise(double x, double z) { + return filter(n.GetCellular(x, z)); + } - @Override - public double noise(double x, double y, double z) - { - return filter(n.GetCellular(x, y, z)); - } + @Override + public double noise(double x, double y, double z) { + return filter(n.GetCellular(x, y, z)); + } } diff --git a/src/main/java/com/volmit/iris/generator/noise/WhiteNoise.java b/src/main/java/com/volmit/iris/generator/noise/WhiteNoise.java index 2842d38bf..8081501a7 100644 --- a/src/main/java/com/volmit/iris/generator/noise/WhiteNoise.java +++ b/src/main/java/com/volmit/iris/generator/noise/WhiteNoise.java @@ -2,40 +2,33 @@ package com.volmit.iris.generator.noise; import com.volmit.iris.util.RNG; -public class WhiteNoise implements NoiseGenerator -{ - private final FastNoise n; +public class WhiteNoise implements NoiseGenerator { + private final FastNoise n; - public WhiteNoise(long seed) - { - n = new FastNoise(new RNG(seed).imax()); - } + public WhiteNoise(long seed) { + n = new FastNoise(new RNG(seed).imax()); + } - public boolean isStatic() - { - return true; - } + public boolean isStatic() { + return true; + } - private double f(double m) - { - return (m % 8192) * 1024; - } + private double f(double m) { + return (m % 8192) * 1024; + } - @Override - public double noise(double x) - { - return (n.GetWhiteNoise(f(x), 0d) / 2D) + 0.5D; - } + @Override + public double noise(double x) { + return (n.GetWhiteNoise(f(x), 0d) / 2D) + 0.5D; + } - @Override - public double noise(double x, double z) - { - return (n.GetWhiteNoise(f(x), f(z)) / 2D) + 0.5D; - } + @Override + public double noise(double x, double z) { + return (n.GetWhiteNoise(f(x), f(z)) / 2D) + 0.5D; + } - @Override - public double noise(double x, double y, double z) - { - return (n.GetWhiteNoise(f(x), f(y), f(z)) / 2D) + 0.5D; - } + @Override + public double noise(double x, double y, double z) { + return (n.GetWhiteNoise(f(x), f(y), f(z)) / 2D) + 0.5D; + } } diff --git a/src/main/java/com/volmit/iris/manager/ConversionManager.java b/src/main/java/com/volmit/iris/manager/ConversionManager.java index 3b9e73a3f..95d622e0c 100644 --- a/src/main/java/com/volmit/iris/manager/ConversionManager.java +++ b/src/main/java/com/volmit/iris/manager/ConversionManager.java @@ -4,12 +4,12 @@ import com.google.gson.Gson; import com.volmit.iris.Iris; import com.volmit.iris.object.*; import com.volmit.iris.pregen.DirectWorldWriter; -import com.volmit.iris.util.*; import com.volmit.iris.scaffold.data.nbt.io.NBTUtil; import com.volmit.iris.scaffold.data.nbt.io.NamedTag; import com.volmit.iris.scaffold.data.nbt.tag.CompoundTag; import com.volmit.iris.scaffold.data.nbt.tag.IntTag; import com.volmit.iris.scaffold.data.nbt.tag.ListTag; +import com.volmit.iris.util.*; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.data.BlockData; @@ -19,263 +19,225 @@ import java.io.File; import java.io.IOException; import java.util.concurrent.atomic.AtomicInteger; -public class ConversionManager -{ - private KList converters; - private File folder; +public class ConversionManager { + private final KList converters; + private final File folder; - public ConversionManager() - { - folder = Iris.instance.getDataFolder("convert"); - converters = new KList<>(); + public ConversionManager() { + folder = Iris.instance.getDataFolder("convert"); + converters = new KList<>(); - J.s(() -> - { - J.attemptAsync(() -> - { - if(Bukkit.getPluginManager().isPluginEnabled("WorldEdit")) - { - converters.add(new Converter() - { - @Override - public String getOutExtension() - { - return "iob"; - } + J.s(() -> + { + J.attemptAsync(() -> + { + if (Bukkit.getPluginManager().isPluginEnabled("WorldEdit")) { + converters.add(new Converter() { + @Override + public String getOutExtension() { + return "iob"; + } - @Override - public String getInExtension() - { - return "schem"; - } + @Override + public String getInExtension() { + return "schem"; + } - @Override - public void convert(File in, File out) - { - SKConversion.convertSchematic(in, out); - } - }); + @Override + public void convert(File in, File out) { + SKConversion.convertSchematic(in, out); + } + }); - converters.add(new Converter() - { - @Override - public String getOutExtension() - { - return "iob"; - } + converters.add(new Converter() { + @Override + public String getOutExtension() { + return "iob"; + } - @Override - public String getInExtension() - { - return "schematic"; - } + @Override + public String getInExtension() { + return "schematic"; + } - @Override - public void convert(File in, File out) - { - SKConversion.convertSchematic(in, out); - } - }); - } - }); - }, 5); - } + @Override + public void convert(File in, File out) { + SKConversion.convertSchematic(in, out); + } + }); + } + }); + }, 5); + } - private String toPoolName(String poolReference) - { - return poolReference.split("\\Q:\\E")[1]; - } + private String toPoolName(String poolReference) { + return poolReference.split("\\Q:\\E")[1]; + } - public void convertStructures(File in, File out, MortarSender s) - { - KMap pools = new KMap<>(); - KList roots = new KList<>(); - AtomicInteger total = new AtomicInteger(0); - AtomicInteger at = new AtomicInteger(0); - File destPools = new File(out.getAbsolutePath() + "/jigsaw-pools"); - destPools.mkdirs(); - findAllNBT(in, (folder, file) -> { - total.getAndIncrement(); - if(roots.addIfMissing(folder)) - { - String b = in.toURI().relativize(folder.toURI()).getPath(); - if(b.startsWith("/")) - { - b = b.substring(1); - } + public void convertStructures(File in, File out, MortarSender s) { + KMap pools = new KMap<>(); + KList roots = new KList<>(); + AtomicInteger total = new AtomicInteger(0); + AtomicInteger at = new AtomicInteger(0); + File destPools = new File(out.getAbsolutePath() + "/jigsaw-pools"); + destPools.mkdirs(); + findAllNBT(in, (folder, file) -> { + total.getAndIncrement(); + if (roots.addIfMissing(folder)) { + String b = in.toURI().relativize(folder.toURI()).getPath(); + if (b.startsWith("/")) { + b = b.substring(1); + } - if(b.endsWith("/")) - { - b = b.substring(0, b.length() - 1); - } + if (b.endsWith("/")) { + b = b.substring(0, b.length() - 1); + } - pools.put(b, new IrisJigsawPool()); - } - }); - findAllNBT(in, (folder, file) -> { - at.getAndIncrement(); - String b = in.toURI().relativize(folder.toURI()).getPath(); - if(b.startsWith("/")) - { - b = b.substring(1); - } + pools.put(b, new IrisJigsawPool()); + } + }); + findAllNBT(in, (folder, file) -> { + at.getAndIncrement(); + String b = in.toURI().relativize(folder.toURI()).getPath(); + if (b.startsWith("/")) { + b = b.substring(1); + } - if(b.endsWith("/")) - { - b = b.substring(0, b.length() - 1); - } - IrisJigsawPool jpool = pools.get(b); - File destObjects = new File(out.getAbsolutePath() + "/objects/" + in.toURI().relativize(folder.toURI()).getPath()); - File destPieces = new File(out.getAbsolutePath() + "/jigsaw-pieces/" + in.toURI().relativize(folder.toURI()).getPath()); - destObjects.mkdirs(); - destPieces.mkdirs(); + if (b.endsWith("/")) { + b = b.substring(0, b.length() - 1); + } + IrisJigsawPool jpool = pools.get(b); + File destObjects = new File(out.getAbsolutePath() + "/objects/" + in.toURI().relativize(folder.toURI()).getPath()); + File destPieces = new File(out.getAbsolutePath() + "/jigsaw-pieces/" + in.toURI().relativize(folder.toURI()).getPath()); + destObjects.mkdirs(); + destPieces.mkdirs(); - try { - NamedTag tag = NBTUtil.read(file); - CompoundTag compound = (CompoundTag) tag.getTag(); + try { + NamedTag tag = NBTUtil.read(file); + CompoundTag compound = (CompoundTag) tag.getTag(); - if (compound.containsKey("blocks") && compound.containsKey("palette") && compound.containsKey("size")) - { - String id = in.toURI().relativize(folder.toURI()).getPath() + file.getName().split("\\Q.\\E")[0]; - ListTag size = (ListTag) compound.getListTag("size"); - int w = size.get(0).asInt(); - int h = size.get(1).asInt(); - int d = size.get(2).asInt(); - KList palette = new KList<>(); - ListTag paletteList = (ListTag) compound.getListTag("palette"); - for(int i = 0; i < paletteList.size(); i++) - { - CompoundTag cp = paletteList.get(i); - palette.add(DirectWorldWriter.getBlockData(cp)); - } - IrisJigsawPiece piece = new IrisJigsawPiece(); - IrisObject object = new IrisObject(w,h,d); - ListTag blockList = (ListTag) compound.getListTag("blocks"); - for(int i = 0; i < blockList.size(); i++) - { - CompoundTag cp = blockList.get(i); - ListTag pos = (ListTag) cp.getListTag("pos"); - int x = pos.get(0).asInt(); - int y = pos.get(1).asInt(); - int z = pos.get(2).asInt(); - BlockData bd = palette.get(cp.getInt("state")).clone(); + if (compound.containsKey("blocks") && compound.containsKey("palette") && compound.containsKey("size")) { + String id = in.toURI().relativize(folder.toURI()).getPath() + file.getName().split("\\Q.\\E")[0]; + ListTag size = (ListTag) compound.getListTag("size"); + int w = size.get(0).asInt(); + int h = size.get(1).asInt(); + int d = size.get(2).asInt(); + KList palette = new KList<>(); + ListTag paletteList = (ListTag) compound.getListTag("palette"); + for (int i = 0; i < paletteList.size(); i++) { + CompoundTag cp = paletteList.get(i); + palette.add(DirectWorldWriter.getBlockData(cp)); + } + IrisJigsawPiece piece = new IrisJigsawPiece(); + IrisObject object = new IrisObject(w, h, d); + ListTag blockList = (ListTag) compound.getListTag("blocks"); + for (int i = 0; i < blockList.size(); i++) { + CompoundTag cp = blockList.get(i); + ListTag pos = (ListTag) cp.getListTag("pos"); + int x = pos.get(0).asInt(); + int y = pos.get(1).asInt(); + int z = pos.get(2).asInt(); + BlockData bd = palette.get(cp.getInt("state")).clone(); - if(bd.getMaterial().equals(Material.JIGSAW) && cp.containsKey("nbt")) - { - piece.setObject(in.toURI().relativize(folder.toURI()).getPath() + file.getName().split("\\Q.\\E")[0]); - IrisPosition spos = new IrisPosition(object.getSigned(x,y,z)); - CompoundTag nbt = cp.getCompoundTag("nbt"); - CompoundTag finalState = new CompoundTag(); - finalState.putString("Name", nbt.getString("final_state")); - BlockData jd = bd.clone(); - bd = DirectWorldWriter.getBlockData(finalState); - String joint = nbt.getString("joint"); - String pool = nbt.getString("pool"); - String poolId = toPoolName(pool); - String name = nbt.getString("name"); - String target = nbt.getString("target"); - pools.computeIfAbsent(poolId, (k) -> new IrisJigsawPool()); - IrisJigsawPieceConnector connector = new IrisJigsawPieceConnector(); - connector.setName(name); - connector.setTargetName(target); - connector.setRotateConnector(false); - connector.setPosition(spos); - connector.getPools().add(poolId); - connector.setDirection(IrisDirection.getDirection(((Jigsaw)jd).getOrientation())); + if (bd.getMaterial().equals(Material.JIGSAW) && cp.containsKey("nbt")) { + piece.setObject(in.toURI().relativize(folder.toURI()).getPath() + file.getName().split("\\Q.\\E")[0]); + IrisPosition spos = new IrisPosition(object.getSigned(x, y, z)); + CompoundTag nbt = cp.getCompoundTag("nbt"); + CompoundTag finalState = new CompoundTag(); + finalState.putString("Name", nbt.getString("final_state")); + BlockData jd = bd.clone(); + bd = DirectWorldWriter.getBlockData(finalState); + String joint = nbt.getString("joint"); + String pool = nbt.getString("pool"); + String poolId = toPoolName(pool); + String name = nbt.getString("name"); + String target = nbt.getString("target"); + pools.computeIfAbsent(poolId, (k) -> new IrisJigsawPool()); + IrisJigsawPieceConnector connector = new IrisJigsawPieceConnector(); + connector.setName(name); + connector.setTargetName(target); + connector.setRotateConnector(false); + connector.setPosition(spos); + connector.getPools().add(poolId); + connector.setDirection(IrisDirection.getDirection(((Jigsaw) jd).getOrientation())); - if(target.equals("minecraft:building_entrance")) - { - connector.setInnerConnector(true); - } + if (target.equals("minecraft:building_entrance")) { + connector.setInnerConnector(true); + } - piece.getConnectors().add(connector); - } + piece.getConnectors().add(connector); + } - if(!bd.getMaterial().equals(Material.STRUCTURE_VOID) && !bd.getMaterial().equals(Material.AIR)) - { - object.setUnsigned(x,y,z, bd); - } - } + if (!bd.getMaterial().equals(Material.STRUCTURE_VOID) && !bd.getMaterial().equals(Material.AIR)) { + object.setUnsigned(x, y, z, bd); + } + } - jpool.getPieces().addIfMissing(id); - object.write(new File(destObjects, file.getName().split("\\Q.\\E")[0] + ".iob")); - IO.writeAll(new File(destPieces,file.getName().split("\\Q.\\E")[0] + ".json"), new JSONObject(new Gson().toJson(piece)).toString(4)); - Iris.info("[Jigsaw]: (" + Form.pc((double)at.get() / (double)total.get(), 0) + ") Exported Piece: " + id); - } - } catch (Throwable e) { - e.printStackTrace(); - } - }); + jpool.getPieces().addIfMissing(id); + object.write(new File(destObjects, file.getName().split("\\Q.\\E")[0] + ".iob")); + IO.writeAll(new File(destPieces, file.getName().split("\\Q.\\E")[0] + ".json"), new JSONObject(new Gson().toJson(piece)).toString(4)); + Iris.info("[Jigsaw]: (" + Form.pc((double) at.get() / (double) total.get(), 0) + ") Exported Piece: " + id); + } + } catch (Throwable e) { + e.printStackTrace(); + } + }); - for(String i : pools.k()) - { - try { - IO.writeAll(new File(destPools, i + ".json"), new JSONObject(new Gson().toJson(pools.get(i))).toString(4)); - } catch (IOException e) { - e.printStackTrace(); - } - } + for (String i : pools.k()) { + try { + IO.writeAll(new File(destPools, i + ".json"), new JSONObject(new Gson().toJson(pools.get(i))).toString(4)); + } catch (IOException e) { + e.printStackTrace(); + } + } - Iris.info("Done! Exported " + Form.f((total.get() * 2) + pools.size()) + " Files!"); - } + Iris.info("Done! Exported " + Form.f((total.get() * 2) + pools.size()) + " Files!"); + } - public void findAllNBT(File path, Consumer2 inFile) - { - if(path == null) - { - return; - } + public void findAllNBT(File path, Consumer2 inFile) { + if (path == null) { + return; + } - if(path.isFile() && path.getName().endsWith(".nbt")) - { - inFile.accept(path.getParentFile(), path); - return; - } + if (path.isFile() && path.getName().endsWith(".nbt")) { + inFile.accept(path.getParentFile(), path); + return; + } - for(File i : path.listFiles()) - { - if(i.isDirectory()) - { - findAllNBT(i, inFile); - } + for (File i : path.listFiles()) { + if (i.isDirectory()) { + findAllNBT(i, inFile); + } else if (i.isFile() && i.getName().endsWith(".nbt")) { + inFile.accept(path, i); + } + } + } - else if(i.isFile() && i.getName().endsWith(".nbt")) - { - inFile.accept(path, i); - } - } - } + public void check(MortarSender s) { + int m = 0; + Iris.instance.getDataFolder("convert"); - public void check(MortarSender s) - { - int m = 0; - Iris.instance.getDataFolder("convert"); + for (File i : folder.listFiles()) { + for (Converter j : converters) { + if (i.getName().endsWith("." + j.getInExtension())) { + File out = new File(folder, i.getName().replaceAll("\\Q." + j.getInExtension() + "\\E", "." + j.getOutExtension())); + m++; + j.convert(i, out); + s.sendMessage("Converted " + i.getName() + " -> " + out.getName()); + } + } - for(File i : folder.listFiles()) - { - for(Converter j : converters) - { - if(i.getName().endsWith("." + j.getInExtension())) - { - File out = new File(folder, i.getName().replaceAll("\\Q." + j.getInExtension() + "\\E", "." + j.getOutExtension())); - m++; - j.convert(i, out); - s.sendMessage("Converted " + i.getName() + " -> " + out.getName()); - } - } + if (i.isDirectory() && i.getName().equals("structures")) { + File f = new File(folder, "jigsaw"); - if(i.isDirectory() && i.getName().equals("structures")) { - File f = new File(folder, "jigsaw"); + if (!f.exists()) { + s.sendMessage("Converting NBT Structures into Iris Jigsaw Structures..."); + f.mkdirs(); + J.a(() -> convertStructures(i, f, s)); + } + } + } - if (!f.exists()) - { - s.sendMessage("Converting NBT Structures into Iris Jigsaw Structures..."); - f.mkdirs(); - J.a(() -> convertStructures(i, f, s)); - } - } - } - - s.sendMessage("Converted " + m + " File" + (m == 1 ? "" : "s")); - } + s.sendMessage("Converted " + m + " File" + (m == 1 ? "" : "s")); + } } diff --git a/src/main/java/com/volmit/iris/manager/EditManager.java b/src/main/java/com/volmit/iris/manager/EditManager.java index 1215a4d63..460e116d0 100644 --- a/src/main/java/com/volmit/iris/manager/EditManager.java +++ b/src/main/java/com/volmit/iris/manager/EditManager.java @@ -1,13 +1,5 @@ package com.volmit.iris.manager; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.block.Biome; -import org.bukkit.block.data.BlockData; -import org.bukkit.event.EventHandler; -import org.bukkit.event.Listener; -import org.bukkit.event.world.WorldUnloadEvent; - import com.volmit.iris.Iris; import com.volmit.iris.IrisSettings; import com.volmit.iris.manager.edit.BlockEditor; @@ -15,107 +7,88 @@ import com.volmit.iris.manager.edit.BukkitBlockEditor; import com.volmit.iris.manager.edit.WEBlockEditor; import com.volmit.iris.util.KMap; import com.volmit.iris.util.M; - import io.papermc.lib.PaperLib; +import org.bukkit.Bukkit; +import org.bukkit.World; +import org.bukkit.block.Biome; +import org.bukkit.block.data.BlockData; +import org.bukkit.event.EventHandler; +import org.bukkit.event.Listener; +import org.bukkit.event.world.WorldUnloadEvent; -public class EditManager implements Listener -{ - private KMap editors; +public class EditManager implements Listener { + private final KMap editors; - public EditManager() - { - this.editors = new KMap<>(); - Iris.instance.registerListener(this); - Bukkit.getScheduler().scheduleSyncRepeatingTask(Iris.instance, this::update, 0, 0); - } + public EditManager() { + this.editors = new KMap<>(); + Iris.instance.registerListener(this); + Bukkit.getScheduler().scheduleSyncRepeatingTask(Iris.instance, this::update, 0, 0); + } - public BlockData get(World world, int x, int y, int z) - { - return open(world).get(x, y, z); - } + public BlockData get(World world, int x, int y, int z) { + return open(world).get(x, y, z); + } - public void set(World world, int x, int y, int z, BlockData d) - { - open(world).set(x, y, z, d); - } + public void set(World world, int x, int y, int z, BlockData d) { + open(world).set(x, y, z, d); + } - public void setBiome(World world, int x, int y, int z, Biome d) - { - open(world).setBiome(x, y, z, d); - } + public void setBiome(World world, int x, int y, int z, Biome d) { + open(world).setBiome(x, y, z, d); + } - public void setBiome(World world, int x, int z, Biome d) - { - open(world).setBiome(x, z, d); - } + public void setBiome(World world, int x, int z, Biome d) { + open(world).setBiome(x, z, d); + } - public Biome getBiome(World world, int x, int y, int z) - { - return open(world).getBiome(x, y, z); - } + public Biome getBiome(World world, int x, int y, int z) { + return open(world).getBiome(x, y, z); + } - public Biome getBiome(World world, int x, int z) - { - return open(world).getBiome(x, z); - } + public Biome getBiome(World world, int x, int z) { + return open(world).getBiome(x, z); + } - @EventHandler - public void on(WorldUnloadEvent e) - { - if(editors.containsKey(e.getWorld())) - { - editors.remove(e.getWorld()).close(); - } - } + @EventHandler + public void on(WorldUnloadEvent e) { + if (editors.containsKey(e.getWorld())) { + editors.remove(e.getWorld()).close(); + } + } - public void update() - { - for(World i : editors.k()) - { - if(M.ms() - editors.get(i).last() > 1000) - { - editors.remove(i).close(); - } - } - } + public void update() { + for (World i : editors.k()) { + if (M.ms() - editors.get(i).last() > 1000) { + editors.remove(i).close(); + } + } + } - public void flushNow() - { - for(World i : editors.k()) - { - editors.remove(i).close(); - } - } + public void flushNow() { + for (World i : editors.k()) { + editors.remove(i).close(); + } + } - public BlockEditor open(World world) - { - if(editors.containsKey(world)) - { - return editors.get(world); - } + public BlockEditor open(World world) { + if (editors.containsKey(world)) { + return editors.get(world); + } - BlockEditor e = null; + BlockEditor e = null; - if(Bukkit.getPluginManager().isPluginEnabled("WorldEdit") && !PaperLib.isPaper() && !IrisSettings.get().getGeneral().isIgnoreWorldEdit()) - { - try - { - e = new WEBlockEditor(world); - } + if (Bukkit.getPluginManager().isPluginEnabled("WorldEdit") && !PaperLib.isPaper() && !IrisSettings.get().getGeneral().isIgnoreWorldEdit()) { + try { + e = new WEBlockEditor(world); + } catch (Throwable ex) { + e = new BukkitBlockEditor(world); + } + } else { + e = new BukkitBlockEditor(world); + } - catch(Throwable ex) - { - e = new BukkitBlockEditor(world); - } - } + editors.put(world, e); - else - { - e = new BukkitBlockEditor(world); - } - - editors.put(world, e); - - return e; - } + return e; + } } diff --git a/src/main/java/com/volmit/iris/manager/IrisBoardManager.java b/src/main/java/com/volmit/iris/manager/IrisBoardManager.java index 4e7a6cd10..a591fd322 100644 --- a/src/main/java/com/volmit/iris/manager/IrisBoardManager.java +++ b/src/main/java/com/volmit/iris/manager/IrisBoardManager.java @@ -13,131 +13,113 @@ import org.bukkit.event.player.PlayerChangedWorldEvent; import java.util.List; -public class IrisBoardManager implements BoardProvider, Listener -{ - @DontObfuscate - private BoardManager manager; - private String mem = "..."; - public RollingSequence hits = new RollingSequence(20); - public RollingSequence tp = new RollingSequence(100); - private ChronoLatch cl = new ChronoLatch(1000); +public class IrisBoardManager implements BoardProvider, Listener { + @DontObfuscate + private final BoardManager manager; + private String mem = "..."; + public RollingSequence hits = new RollingSequence(20); + public RollingSequence tp = new RollingSequence(100); + private final ChronoLatch cl = new ChronoLatch(1000); - @DontObfuscate - public IrisBoardManager() - { - Iris.instance.registerListener(this); - //@builder - manager = new BoardManager(Iris.instance, BoardSettings.builder() - .boardProvider(this) - .scoreDirection(ScoreDirection.DOWN) - .build()); - //@done - } + @DontObfuscate + public IrisBoardManager() { + Iris.instance.registerListener(this); + //@builder + manager = new BoardManager(Iris.instance, BoardSettings.builder() + .boardProvider(this) + .scoreDirection(ScoreDirection.DOWN) + .build()); + //@done + } - @EventHandler - public void on(PlayerChangedWorldEvent e) - { - J.s(() -> updatePlayer(e.getPlayer())); - } + @EventHandler + public void on(PlayerChangedWorldEvent e) { + J.s(() -> updatePlayer(e.getPlayer())); + } - @DontObfuscate - private boolean isIrisWorld(World w) - { - return IrisWorlds.isIrisWorld(w) && IrisWorlds.access(w).isStudio(); - } + @DontObfuscate + private boolean isIrisWorld(World w) { + return IrisWorlds.isIrisWorld(w) && IrisWorlds.access(w).isStudio(); + } - public void updatePlayer(Player p) - { - if(isIrisWorld(p.getWorld())) - { - manager.remove(p); - manager.setup(p); - } + public void updatePlayer(Player p) { + if (isIrisWorld(p.getWorld())) { + manager.remove(p); + manager.setup(p); + } else { + manager.remove(p); + } + } - else - { - manager.remove(p); - } - } + @Override + public String getTitle(Player player) { + return C.GREEN + "Iris"; + } - @Override - public String getTitle(Player player) - { - return C.GREEN + "Iris"; - } + @DontObfuscate + @Override + public List getLines(Player player) { + KList v = new KList<>(); - @DontObfuscate - @Override - public List getLines(Player player) - { - KList v = new KList<>(); + if (!isIrisWorld(player.getWorld())) { + return v; + } - if(!isIrisWorld(player.getWorld())) - { - return v; - } + IrisAccess g = IrisWorlds.access(player.getWorld()); - IrisAccess g = IrisWorlds.access(player.getWorld()); + if (cl.flip()) { + // TODO MEMORY + mem = Form.memSize(0, 2); + } - if(cl.flip()) - { - // TODO MEMORY - mem = Form.memSize(0, 2); - } + int x = player.getLocation().getBlockX(); + int y = player.getLocation().getBlockY(); + int z = player.getLocation().getBlockZ(); - int x = player.getLocation().getBlockX(); - int y = player.getLocation().getBlockY(); - int z = player.getLocation().getBlockZ(); + Engine engine = g.getCompound().getEngineForHeight(y); - Engine engine = g.getCompound().getEngineForHeight(y); + int parallaxChunks = 0; + int parallaxRegions = 0; + long memoryGuess = 0; + int loadedObjects = 0; - int parallaxChunks=0; - int parallaxRegions=0; - long memoryGuess=0; - int loadedObjects=0; + for (int i = 0; i < g.getCompound().getSize(); i++) { + parallaxRegions += g.getCompound().getEngine(i).getParallax().getRegionCount(); + parallaxChunks += g.getCompound().getEngine(i).getParallax().getChunkCount(); + loadedObjects += g.getCompound().getData().getObjectLoader().getSize(); + memoryGuess += g.getCompound().getData().getObjectLoader().getTotalStorage() * 225; + memoryGuess += parallaxChunks * 3500; + memoryGuess += parallaxRegions * 1700000; + } - for(int i = 0; i < g.getCompound().getSize(); i++) - { - parallaxRegions += g.getCompound().getEngine(i).getParallax().getRegionCount(); - parallaxChunks += g.getCompound().getEngine(i).getParallax().getChunkCount(); - loadedObjects+= g.getCompound().getData().getObjectLoader().getSize(); - memoryGuess += g.getCompound().getData().getObjectLoader().getTotalStorage() * 225; - memoryGuess+= parallaxChunks * 3500; - memoryGuess += parallaxRegions * 1700000; - } - - tp.put(0); // TODO: CHUNK SPEED + tp.put(0); // TODO: CHUNK SPEED + v.add("&7&m------------------"); + v.add(C.GREEN + "Speed" + C.GRAY + ": " + Form.f(g.getGeneratedPerSecond(), 0) + "/s " + Form.duration(1000D / g.getGeneratedPerSecond(), 0)); + v.add(C.GREEN + "Memory Use" + C.GRAY + ": ~" + Form.memSize(memoryGuess, 0)); - v.add("&7&m------------------"); - v.add(C.GREEN + "Speed" + C.GRAY + ": " + Form.f(g.getGeneratedPerSecond(), 0) + "/s " + Form.duration(1000D / g.getGeneratedPerSecond(), 0)); - v.add(C.GREEN + "Memory Use" + C.GRAY + ": ~" + Form.memSize(memoryGuess, 0)); + if (engine != null) { + v.add("&7&m------------------"); + v.add(C.AQUA + "Engine" + C.GRAY + ": " + engine.getName() + " " + engine.getMinHeight() + "-" + engine.getMaxHeight()); + v.add(C.AQUA + "Region" + C.GRAY + ": " + engine.getRegion(x, z).getName()); + v.add(C.AQUA + "Biome" + C.GRAY + ": " + engine.getBiome(x, y, z).getName()); + v.add(C.AQUA + "Height" + C.GRAY + ": " + Math.round(engine.getHeight(x, z))); + v.add(C.AQUA + "Slope" + C.GRAY + ": " + Form.f(engine.getFramework().getComplex().getSlopeStream().get(x, z), 2)); + } - if(engine != null) - { - v.add("&7&m------------------"); - v.add(C.AQUA + "Engine" + C.GRAY + ": " + engine.getName() + " " + engine.getMinHeight() + "-" + engine.getMaxHeight()); - v.add(C.AQUA + "Region" + C.GRAY + ": " + engine.getRegion(x, z).getName()); - v.add(C.AQUA + "Biome" + C.GRAY + ": " + engine.getBiome(x, y, z).getName()); - v.add(C.AQUA + "Height" + C.GRAY + ": " + Math.round(engine.getHeight(x, z))); - v.add(C.AQUA + "Slope" + C.GRAY + ": " + Form.f(engine.getFramework().getComplex().getSlopeStream().get(x, z), 2)); - } + if (Iris.jobCount() > 0) { + v.add("&7&m------------------"); + v.add(C.LIGHT_PURPLE + "Tasks" + C.GRAY + ": " + Iris.jobCount()); + } - if(Iris.jobCount() > 0) - { - v.add("&7&m------------------"); - v.add(C.LIGHT_PURPLE + "Tasks" + C.GRAY + ": " + Iris.jobCount()); - } + v.add("&7&m------------------"); - v.add("&7&m------------------"); + return v; + } - return v; - } - - @DontObfuscate - public void disable() - { - manager.onDisable(); - } + @DontObfuscate + public void disable() { + manager.onDisable(); + } } diff --git a/src/main/java/com/volmit/iris/manager/IrisDataManager.java b/src/main/java/com/volmit/iris/manager/IrisDataManager.java index 0f3312b81..b90c49132 100644 --- a/src/main/java/com/volmit/iris/manager/IrisDataManager.java +++ b/src/main/java/com/volmit/iris/manager/IrisDataManager.java @@ -12,201 +12,172 @@ import java.util.Objects; import java.util.function.Function; @Data -public class IrisDataManager -{ - private ResourceLoader biomeLoader; - private ResourceLoader lootLoader; - private ResourceLoader regionLoader; - private ResourceLoader dimensionLoader; - private ResourceLoader generatorLoader; - private ResourceLoader jigsawPieceLoader; - private ResourceLoader jigsawPoolLoader; - private ResourceLoader jigsawStructureLoader; - private ResourceLoader entityLoader; - private ResourceLoader blockLoader; - private ObjectResourceLoader objectLoader; - private boolean closed; - private final File dataFolder; - private final int id; +public class IrisDataManager { + private ResourceLoader biomeLoader; + private ResourceLoader lootLoader; + private ResourceLoader regionLoader; + private ResourceLoader dimensionLoader; + private ResourceLoader generatorLoader; + private ResourceLoader jigsawPieceLoader; + private ResourceLoader jigsawPoolLoader; + private ResourceLoader jigsawStructureLoader; + private ResourceLoader entityLoader; + private ResourceLoader blockLoader; + private ObjectResourceLoader objectLoader; + private boolean closed; + private final File dataFolder; + private final int id; - public IrisDataManager(File dataFolder) - { - this(dataFolder, false); - } + public IrisDataManager(File dataFolder) { + this(dataFolder, false); + } - public IrisDataManager(File dataFolder, boolean oneshot) - { - this.dataFolder = dataFolder; - this.id = RNG.r.imax(); - closed = false; - hotloaded(); - } + public IrisDataManager(File dataFolder, boolean oneshot) { + this.dataFolder = dataFolder; + this.id = RNG.r.imax(); + closed = false; + hotloaded(); + } - public void close() - { - closed = true; - dump(); - this.lootLoader = null; - this.entityLoader = null; - this.regionLoader = null; - this.biomeLoader = null; - this.dimensionLoader = null; - this.jigsawPoolLoader = null; - this.jigsawPieceLoader = null; - this.generatorLoader = null; - this.jigsawStructureLoader = null; - this.blockLoader = null; - this.objectLoader = null; - } + public void close() { + closed = true; + dump(); + this.lootLoader = null; + this.entityLoader = null; + this.regionLoader = null; + this.biomeLoader = null; + this.dimensionLoader = null; + this.jigsawPoolLoader = null; + this.jigsawPieceLoader = null; + this.generatorLoader = null; + this.jigsawStructureLoader = null; + this.blockLoader = null; + this.objectLoader = null; + } - private static void printData(ResourceLoader rl) - { - Iris.warn(" " + rl.getResourceTypeName() + " @ /" + rl.getFolderName() + ": Cache=" + rl.getLoadCache().size() + " Folders=" + rl.getFolders().size()); - } + private static void printData(ResourceLoader rl) { + Iris.warn(" " + rl.getResourceTypeName() + " @ /" + rl.getFolderName() + ": Cache=" + rl.getLoadCache().size() + " Folders=" + rl.getFolders().size()); + } - public IrisDataManager copy() { - return new IrisDataManager(dataFolder); - } + public IrisDataManager copy() { + return new IrisDataManager(dataFolder); + } - public void hotloaded() - { - if(closed) - { - return; - } + public void hotloaded() { + if (closed) { + return; + } - File packs = dataFolder; - packs.mkdirs(); - this.lootLoader = new ResourceLoader<>(packs, this, "loot", "Loot", IrisLootTable.class); - this.entityLoader = new ResourceLoader<>(packs,this, "entities", "Entity", IrisEntity.class); - this.regionLoader = new ResourceLoader<>(packs, this, "regions", "Region", IrisRegion.class); - this.biomeLoader = new ResourceLoader<>(packs, this, "biomes", "Biome", IrisBiome.class); - this.dimensionLoader = new ResourceLoader<>(packs, this, "dimensions", "Dimension", IrisDimension.class); - this.jigsawPoolLoader = new ResourceLoader<>(packs, this, "jigsaw-pools", "Jigsaw Pool", IrisJigsawPool.class); - this.jigsawStructureLoader = new ResourceLoader<>(packs, this, "jigsaw-structures", "Jigsaw Structure", IrisJigsawStructure.class); - this.jigsawPieceLoader = new ResourceLoader<>(packs, this, "jigsaw-pieces", "Jigsaw Piece", IrisJigsawPiece.class); - this.generatorLoader = new ResourceLoader<>(packs, this, "generators", "Generator", IrisGenerator.class); - this.blockLoader = new ResourceLoader<>(packs,this, "blocks", "Block", IrisBlockData.class); - this.objectLoader = new ObjectResourceLoader(packs, this, "objects", "Object"); - } + File packs = dataFolder; + packs.mkdirs(); + this.lootLoader = new ResourceLoader<>(packs, this, "loot", "Loot", IrisLootTable.class); + this.entityLoader = new ResourceLoader<>(packs, this, "entities", "Entity", IrisEntity.class); + this.regionLoader = new ResourceLoader<>(packs, this, "regions", "Region", IrisRegion.class); + this.biomeLoader = new ResourceLoader<>(packs, this, "biomes", "Biome", IrisBiome.class); + this.dimensionLoader = new ResourceLoader<>(packs, this, "dimensions", "Dimension", IrisDimension.class); + this.jigsawPoolLoader = new ResourceLoader<>(packs, this, "jigsaw-pools", "Jigsaw Pool", IrisJigsawPool.class); + this.jigsawStructureLoader = new ResourceLoader<>(packs, this, "jigsaw-structures", "Jigsaw Structure", IrisJigsawStructure.class); + this.jigsawPieceLoader = new ResourceLoader<>(packs, this, "jigsaw-pieces", "Jigsaw Piece", IrisJigsawPiece.class); + this.generatorLoader = new ResourceLoader<>(packs, this, "generators", "Generator", IrisGenerator.class); + this.blockLoader = new ResourceLoader<>(packs, this, "blocks", "Block", IrisBlockData.class); + this.objectLoader = new ObjectResourceLoader(packs, this, "objects", "Object"); + } - public void dump() - { - if(closed) - { - return; - } - biomeLoader.clearCache(); - blockLoader.clearCache(); - lootLoader.clearCache(); - objectLoader.clearCache(); - jigsawPieceLoader.clearCache(); - jigsawPoolLoader.clearCache(); - jigsawStructureLoader.clearCache(); - regionLoader.clearCache(); - dimensionLoader.clearCache(); - entityLoader.clearCache(); - generatorLoader.clearCache(); - } + public void dump() { + if (closed) { + return; + } + biomeLoader.clearCache(); + blockLoader.clearCache(); + lootLoader.clearCache(); + objectLoader.clearCache(); + jigsawPieceLoader.clearCache(); + jigsawPoolLoader.clearCache(); + jigsawStructureLoader.clearCache(); + regionLoader.clearCache(); + dimensionLoader.clearCache(); + entityLoader.clearCache(); + generatorLoader.clearCache(); + } - public void clearLists() - { - if(closed) - { - return; - } + public void clearLists() { + if (closed) { + return; + } - lootLoader.clearList(); - blockLoader.clearList(); - entityLoader.clearList(); - biomeLoader.clearList(); - regionLoader.clearList(); - dimensionLoader.clearList(); - generatorLoader.clearList(); - jigsawStructureLoader.clearList(); - jigsawPoolLoader.clearList(); - jigsawPieceLoader.clearList(); - objectLoader.clearList(); - } + lootLoader.clearList(); + blockLoader.clearList(); + entityLoader.clearList(); + biomeLoader.clearList(); + regionLoader.clearList(); + dimensionLoader.clearList(); + generatorLoader.clearList(); + jigsawStructureLoader.clearList(); + jigsawPoolLoader.clearList(); + jigsawPieceLoader.clearList(); + objectLoader.clearList(); + } - public static IrisObject loadAnyObject(String key) - { - return loadAny(key, (dm) -> dm.getObjectLoader().load(key, false)); - } + public static IrisObject loadAnyObject(String key) { + return loadAny(key, (dm) -> dm.getObjectLoader().load(key, false)); + } - public static IrisBiome loadAnyBiome(String key) - { - return loadAny(key, (dm) -> dm.getBiomeLoader().load(key, false)); - } + public static IrisBiome loadAnyBiome(String key) { + return loadAny(key, (dm) -> dm.getBiomeLoader().load(key, false)); + } - public static IrisJigsawPiece loadAnyJigsawPiece(String key) - { - return loadAny(key, (dm) -> dm.getJigsawPieceLoader().load(key, false)); - } + public static IrisJigsawPiece loadAnyJigsawPiece(String key) { + return loadAny(key, (dm) -> dm.getJigsawPieceLoader().load(key, false)); + } - public static IrisJigsawPool loadAnyJigsawPool(String key) - { - return loadAny(key, (dm) -> dm.getJigsawPoolLoader().load(key, false)); - } + public static IrisJigsawPool loadAnyJigsawPool(String key) { + return loadAny(key, (dm) -> dm.getJigsawPoolLoader().load(key, false)); + } - public static IrisEntity loadAnyEntity(String key) - { - return loadAny(key, (dm) -> dm.getEntityLoader().load(key, false)); - } + public static IrisEntity loadAnyEntity(String key) { + return loadAny(key, (dm) -> dm.getEntityLoader().load(key, false)); + } - public static IrisLootTable loadAnyLootTable(String key) - { - return loadAny(key, (dm) -> dm.getLootLoader().load(key, false)); - } + public static IrisLootTable loadAnyLootTable(String key) { + return loadAny(key, (dm) -> dm.getLootLoader().load(key, false)); + } - public static IrisBlockData loadAnyBlock(String key) - { - return loadAny(key, (dm) -> dm.getBlockLoader().load(key, false)); - } + public static IrisBlockData loadAnyBlock(String key) { + return loadAny(key, (dm) -> dm.getBlockLoader().load(key, false)); + } - public static IrisRegion loadAnyRegion(String key) - { - return loadAny(key, (dm) -> dm.getRegionLoader().load(key, false)); - } + public static IrisRegion loadAnyRegion(String key) { + return loadAny(key, (dm) -> dm.getRegionLoader().load(key, false)); + } - public static IrisDimension loadAnyDimension(String key) - { - return loadAny(key, (dm) -> dm.getDimensionLoader().load(key, false)); - } + public static IrisDimension loadAnyDimension(String key) { + return loadAny(key, (dm) -> dm.getDimensionLoader().load(key, false)); + } - public static IrisJigsawStructure loadAnyJigsawStructure(String key) - { - return loadAny(key, (dm) -> dm.getJigsawStructureLoader().load(key, false)); - } + public static IrisJigsawStructure loadAnyJigsawStructure(String key) { + return loadAny(key, (dm) -> dm.getJigsawStructureLoader().load(key, false)); + } - public static IrisGenerator loadAnyGenerator(String key) - { - return loadAny(key, (dm) -> dm.getGeneratorLoader().load(key, false)); - } + public static IrisGenerator loadAnyGenerator(String key) { + return loadAny(key, (dm) -> dm.getGeneratorLoader().load(key, false)); + } - public static T loadAny(String key, Function v) { - try - { - for(File i : Objects.requireNonNull(Iris.instance.getDataFolder("packs").listFiles())) - { - if(i.isDirectory()) - { - IrisDataManager dm = new IrisDataManager(i, true); - T t = v.apply(dm); + public static T loadAny(String key, Function v) { + try { + for (File i : Objects.requireNonNull(Iris.instance.getDataFolder("packs").listFiles())) { + if (i.isDirectory()) { + IrisDataManager dm = new IrisDataManager(i, true); + T t = v.apply(dm); - if(t != null) - { - return t; - } - } - } - } + if (t != null) { + return t; + } + } + } + } catch (Throwable e) { + e.printStackTrace(); + } - catch(Throwable e) - { - e.printStackTrace(); - } - - return null; - } + return null; + } } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/manager/IrisProject.java b/src/main/java/com/volmit/iris/manager/IrisProject.java index 5517b910f..e6043d4ed 100644 --- a/src/main/java/com/volmit/iris/manager/IrisProject.java +++ b/src/main/java/com/volmit/iris/manager/IrisProject.java @@ -24,646 +24,560 @@ import java.util.Objects; import java.util.UUID; @Data -public class IrisProject -{ - private File path; - private String name; - private IrisAccess activeProvider; - - public IrisProject(File path) - { - this.path = path; - this.name = path.getName(); - } - - public KList scanForErrors() - { - KList reports = new KList<>(); - IrisDataManager data = new IrisDataManager(path); - - for(int i = 0; i < getActiveProvider().getCompound().getSize(); i++) - { - Engine e = getActiveProvider().getCompound().getEngine(i); - IrisDimension dim = e.getDimension(); - reports.add(scanForErrors(dim)); - } - - return reports; - } - - private KList scanForErrors(IrisDimension dim) { - KList reports = new KList<>(); - - if(dim.getFocus() != null && !dim.getFocus().isEmpty()) - { - reports.add(Report.builder() - .type(ReportType.NOTICE) - .title("Focus Mode is Enabled") - .message("Make sure to disable this before pushing") - .suggestion("Turn off focus mode") - .build()); - } - - for(IrisRegion i : dim.getAllRegions(getActiveProvider())) - { - scanForErrors(i); - } - - return reports; - } - - private KList scanForErrors(IrisRegion region) { - KList reports = new KList<>(); - - if(region.getRarity() > 60) - { - reports.add(Report.builder() - .type(ReportType.WARNING) - .title("Region " + region.getName() + " has a rarity of " + region.getRarity()) - .message("The region rarity higher than 60 can cause performance issues") - .suggestion("Scale all rarities down by 50% all at once, then repeat until all rarities are below 60") - .build()); - } - - for(IrisBiome i : region.getAllBiomes(getActiveProvider())) - { - reports.add(scanForErrors(i)); - } - - return reports; - } - - private KList scanForErrors(IrisBiome biome) { - KList reports = new KList<>(); - - for(IrisObjectPlacement i : biome.getObjects()) - { - reports.add(scanForErrors(biome, i)); - } - - for(IrisBiomePaletteLayer i : biome.getLayers()) - { - reports.add(scanForErrors(biome, i)); - } - - for(IrisBiomePaletteLayer i : biome.getSeaLayers()) - { - reports.add(scanForErrorsSeaLayers(biome, i)); - } - - return reports; - } - - private KList scanForErrors(IrisBiome biome, IrisObjectPlacement i) { - KList reports = new KList<>(); - - return reports; - } - - private KList scanForErrors(IrisBiome biome, IrisBiomePaletteLayer i) { - KList reports = new KList<>(); - - return reports; - } - - private KList scanForErrorsSeaLayers(IrisBiome biome, IrisBiomePaletteLayer i) { - KList reports = new KList<>(); - - return reports; - } - - public boolean isOpen() - { - return activeProvider != null; - } - - public KList collectFiles(File f, String json) - { - KList l = new KList<>(); - - if(f.isDirectory()) - { - for(File i : f.listFiles()) - { - l.addAll(collectFiles(i, json)); - } - } - - else if(f.getName().endsWith("."+json)) - { - l.add(f); - } - - return l; - } - - public KList collectFiles(String json) { - return collectFiles(path, json); - } - - public void open(MortarSender sender) - { - open(sender, () -> - { - }); - } - - public void open(MortarSender sender, Runnable onDone) - { - if(isOpen()) - { - close(); - } - - IrisDimension d = IrisDataManager.loadAnyDimension(getName()); - if(d == null) - { - sender.sendMessage("Can't find dimension: " + getName()); - return; - } else if(sender.isPlayer()){ - sender.player().setGameMode(GameMode.SPECTATOR); - sender.player().spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(C.BLUE + "Creating studio world. Please wait...")); - } - - J.attemptAsync(() -> - { - try - { - if (d.getLoader() == null){ - sender.sendMessage("Could not get dimension loader"); - return; - } - File f = d.getLoader().getDataFolder(); - boolean foundWork = false; - for(File i : Objects.requireNonNull(f.listFiles())) - { - if(i.getName().endsWith(".code-workspace")) - { - foundWork = true; - sender.sendMessage("Updating Workspace..."); - J.a(() -> - { - updateWorkspace(); - sender.sendMessage("Workspace Updated"); - }); - - if(IrisSettings.get().getStudio().isOpenVSCode()) - { - if (!GraphicsEnvironment.isHeadless()) { - Iris.msg("Opening VSCode. You may see the output from VSCode."); - Iris.msg("VSCode output always starts with: '(node:#####) electron'"); - Desktop.getDesktop().open(i); - } - } - - break; - } - } - - if(!foundWork) - { - File ff = new File(d.getLoader().getDataFolder(), d.getLoadKey() + ".code-workspace"); - Iris.warn("Project missing code-workspace: " + ff.getAbsolutePath() + " Re-creating code workspace."); - - try - { - IO.writeAll(ff, createCodeWorkspaceConfig()); - } - - catch(IOException e1) - { - e1.printStackTrace(); - } - sender.sendMessage("Updating Workspace..."); - updateWorkspace(); - sender.sendMessage("Workspace Updated"); - } - } - - catch(Throwable e) - { - e.printStackTrace(); - } - }); - - String wfp = "iris/" + UUID.randomUUID(); - - WorldCreator c = new IrisWorldCreator().dimension(getName()) - .seed(1337) - .name(wfp) - .studioMode() - .create(); - - IrisAccess gx = ((IrisAccess)c.generator()); - sender.sendMessage("Generating with " + Iris.getThreadCount() + " threads per chunk"); - O done = new O<>(); - done.set(false); - activeProvider = gx; - - J.a(() -> - { - double last = 0; - int req = 300; - double lpc = 0; - boolean fc; - - while(!done.get()) - { - boolean derp = false; - - assert gx != null; - double v = (double) gx.getGenerated() / (double) req; - fc = lpc != v; - lpc = v; - - if(last > v || v > 1) - { - derp = true; - v = last; - } - - else - { - last = v; - } - - if(fc) - { - sender.sendMessage(C.WHITE + "Generating " + Form.pc(v) + (derp ? (C.GRAY + " (Waiting on Server...)") : (C.GRAY + " (" + (req - gx.getGenerated()) + " Left)"))); - } - - if (sender.isPlayer()){ - sender.player().spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(C.BLUE + "Creating studio world. Please wait...")); - } - - J.sleep(1500); - - if(gx.isFailing()) - { - - sender.sendMessage("Generation Failed!"); - return; - } - } - }); - - //@builder - World world = INMS.get().createWorld(c); - if (IrisSettings.get().getStudio().isDisableTimeAndWeather()) { - world.setGameRule(GameRule.DO_WEATHER_CYCLE, false); - world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE, false); - world.setTime(6000); - } - Iris.linkMultiverseCore.removeFromConfig(world); - - done.set(true); - sender.sendMessage(C.WHITE + "Generating Complete!"); - - if(sender.isPlayer()) - { - assert world != null; - sender.player().teleport(world.getSpawnLocation()); - } - - Bukkit.getScheduler().scheduleSyncDelayedTask(Iris.instance, () -> - { - sender.sendMessage("Hotloading Active! Change any files and watch your changes appear as you load new chunks!"); - - if(sender.isPlayer()) - { - sender.player().setGameMode(GameMode.SPECTATOR); - } - - onDone.run(); - }, 0); - } - - public void close() - { - activeProvider.close(); - File folder = activeProvider.getTarget().getWorld().getWorldFolder(); - Iris.linkMultiverseCore.removeFromConfig(activeProvider.getTarget().getWorld().getName()); - Bukkit.unloadWorld(activeProvider.getTarget().getWorld().getName(), false); - J.attemptAsync(() -> IO.delete(folder)); - activeProvider = null; - } - - public File getCodeWorkspaceFile() - { - return new File(path, getName() + ".code-workspace"); - } - - public boolean updateWorkspace() - { - getPath().mkdirs(); - File ws = getCodeWorkspaceFile(); - - try - { - PrecisionStopwatch p = PrecisionStopwatch.start(); - Iris.info("Building Workspace: " + ws.getPath()); - JSONObject j = createCodeWorkspaceConfig(); - IO.writeAll(ws, j.toString(4)); - p.end(); - Iris.info("Building Workspace: " + ws.getPath() + " took " + Form.duration(p.getMilliseconds(), 2)); - return true; - } - - catch(Throwable e) - { - Iris.warn("Project invalid: " + ws.getAbsolutePath() + " Re-creating. You may loose some vs-code workspace settings! But not your actual project!"); - ws.delete(); - try - { - IO.writeAll(ws, createCodeWorkspaceConfig()); - } - - catch(IOException e1) - { - e1.printStackTrace(); - } - } - - return false; - } - - public JSONObject createCodeWorkspaceConfig() - { - JSONObject ws = new JSONObject(); - JSONArray folders = new JSONArray(); - JSONObject folder = new JSONObject(); - folder.put("path", "."); - folders.put(folder); - ws.put("folders", folders); - JSONObject settings = new JSONObject(); - settings.put("workbench.colorTheme", "Monokai"); - settings.put("workbench.preferredDarkColorTheme", "Solarized Dark"); - settings.put("workbench.tips.enabled", false); - settings.put("workbench.tree.indent", 24); - settings.put("files.autoSave", "onFocusChange"); - JSONObject jc = new JSONObject(); - jc.put("editor.autoIndent", "brackets"); - jc.put("editor.acceptSuggestionOnEnter", "smart"); - jc.put("editor.cursorSmoothCaretAnimation", true); - jc.put("editor.dragAndDrop", false); - jc.put("files.trimTrailingWhitespace", true); - jc.put("diffEditor.ignoreTrimWhitespace", true); - jc.put("files.trimFinalNewlines", true); - jc.put("editor.suggest.showKeywords", false); - jc.put("editor.suggest.showSnippets", false); - jc.put("editor.suggest.showWords", false); - JSONObject st = new JSONObject(); - st.put("strings", true); - jc.put("editor.quickSuggestions", st); - jc.put("editor.suggest.insertMode", "replace"); - settings.put("[json]", jc); - settings.put("json.maxItemsComputed", 30000); - JSONArray schemas = new JSONArray(); - IrisDataManager dm = new IrisDataManager(getPath()); - schemas.put(getSchemaEntry(IrisDimension.class, dm, "/dimensions/*.json")); - schemas.put(getSchemaEntry(IrisEntity.class, dm, "/entities/*.json")); - schemas.put(getSchemaEntry(IrisBiome.class, dm, "/biomes/*.json")); - schemas.put(getSchemaEntry(IrisRegion.class, dm, "/regions/*.json")); - schemas.put(getSchemaEntry(IrisGenerator.class,dm, "/generators/*.json")); - schemas.put(getSchemaEntry(IrisJigsawPiece.class, dm, "/jigsaw-pieces/*.json")); - schemas.put(getSchemaEntry(IrisJigsawPool.class, dm, "/jigsaw-pools/*.json")); - schemas.put(getSchemaEntry(IrisJigsawStructure.class, dm, "/jigsaw-structures/*.json")); - schemas.put(getSchemaEntry(IrisBlockData.class, dm, "/blocks/*.json")); - schemas.put(getSchemaEntry(IrisLootTable.class, dm, "/loot/*.json")); - settings.put("json.schemas", schemas); - ws.put("settings", settings); - - return ws; - } - - public JSONObject getSchemaEntry(Class i, IrisDataManager dat, String... fileMatch) - { - Iris.verbose("Processing Folder " + i.getSimpleName() + " " + fileMatch[0]); - JSONObject o = new JSONObject(); - o.put("fileMatch", new JSONArray(fileMatch)); - o.put("schema", new SchemaBuilder(i, dat).compute()); - - return o; - } - - public File compilePackage(MortarSender sender, boolean obfuscate, boolean minify) - { - String dimm = getName(); - IrisDataManager dm = new IrisDataManager(path); - IrisDimension dimension = dm.getDimensionLoader().load(dimm); - File folder = new File(Iris.instance.getDataFolder(), "exports/" + dimension.getLoadKey()); - folder.mkdirs(); - Iris.info("Packaging Dimension " + dimension.getName() + " " + (obfuscate ? "(Obfuscated)" : "")); - KSet regions = new KSet<>(); - KSet biomes = new KSet<>(); - KSet entities = new KSet<>(); - KSet generators = new KSet<>(); - KSet loot = new KSet<>(); - KSet blocks = new KSet<>(); - - for(String i : dm.getDimensionLoader().getPossibleKeys()) - { - blocks.add(dm.getBlockLoader().load(i)); - } - - //TODO: EXPORT JIGSAW PIECES FROM STRUCTURES - dimension.getRegions().forEach((i) -> regions.add(dm.getRegionLoader().load(i))); - dimension.getLoot().getTables().forEach((i) -> loot.add(dm.getLootLoader().load(i))); - regions.forEach((i) -> biomes.addAll(i.getAllBiomes(null))); - biomes.forEach((i) -> i.getGenerators().forEach((j) -> generators.add(j.getCachedGenerator(null)))); - regions.forEach((r) -> r.getLoot().getTables().forEach((i) -> loot.add(dm.getLootLoader().load(i)))); - biomes.forEach((r) -> r.getLoot().getTables().forEach((i) -> loot.add(dm.getLootLoader().load(i)))); - biomes.forEach((r) -> r.getEntitySpawnOverrides().forEach((sp) -> entities.add(dm.getEntityLoader().load(sp.getEntity())))); - regions.forEach((r) -> r.getEntitySpawnOverrides().forEach((sp) -> entities.add(dm.getEntityLoader().load(sp.getEntity())))); - dimension.getEntitySpawnOverrides().forEach((sp) -> entities.add(dm.getEntityLoader().load(sp.getEntity()))); - biomes.forEach((r) -> r.getEntityInitialSpawns().forEach((sp) -> entities.add(dm.getEntityLoader().load(sp.getEntity())))); - regions.forEach((r) -> r.getEntityInitialSpawns().forEach((sp) -> entities.add(dm.getEntityLoader().load(sp.getEntity())))); - dimension.getEntityInitialSpawns().forEach((sp) -> entities.add(dm.getEntityLoader().load(sp.getEntity()))); - KMap renameObjects = new KMap<>(); - String a; - StringBuilder b = new StringBuilder(); - StringBuilder c = new StringBuilder(); - sender.sendMessage("Serializing Objects"); - - for(IrisBiome i : biomes) - { - for(IrisObjectPlacement j : i.getObjects()) - { - b.append(j.hashCode()); - KList newNames = new KList<>(); - - for(String k : j.getPlace()) - { - if(renameObjects.containsKey(k)) - { - newNames.add(renameObjects.get(k)); - continue; - } - - String name = !obfuscate ? k : UUID.randomUUID().toString().replaceAll("-", ""); - b.append(name); - newNames.add(name); - renameObjects.put(k, name); - } - - j.setPlace(newNames); - } - } - - for(IrisBiomeMutation i : dimension.getMutations()) - { - for(IrisObjectPlacement j : i.getObjects()) - { - b.append(j.hashCode()); - KList newNames = new KList<>(); - - for(String k : j.getPlace()) - { - if(renameObjects.containsKey(k)) - { - newNames.add(renameObjects.get(k)); - continue; - } - - String name = !obfuscate ? k : UUID.randomUUID().toString().replaceAll("-", ""); - b.append(name); - newNames.add(name); - renameObjects.put(k, name); - } - - j.setPlace(newNames); - } - } - - KMap> lookupObjects = renameObjects.flip(); - StringBuilder gb = new StringBuilder(); - ChronoLatch cl = new ChronoLatch(1000); - O ggg = new O<>(); - ggg.set(0); - biomes.forEach((i) -> i.getObjects().forEach((j) -> j.getPlace().forEach((k) -> - { - try - { - File f = dm.getObjectLoader().findFile(lookupObjects.get(k).get(0)); - IO.copyFile(f, new File(folder, "objects/" + k + ".iob")); - gb.append(IO.hash(f)); - ggg.set(ggg.get() + 1); - - if(cl.flip()) - { - int g = ggg.get(); - ggg.set(0); - sender.sendMessage("Wrote another " + g + " Objects"); - } - } - - catch(Throwable ignored) - { - - } - }))); - - dimension.getMutations().forEach((i) -> i.getObjects().forEach((j) -> j.getPlace().forEach((k) -> - { - try - { - File f = dm.getObjectLoader().findFile(lookupObjects.get(k).get(0)); - IO.copyFile(f, new File(folder, "objects/" + k + ".iob")); - gb.append(IO.hash(f)); - ggg.set(ggg.get() + 1); - - if(cl.flip()) - { - int g = ggg.get(); - ggg.set(0); - sender.sendMessage("Wrote another " + g + " Objects"); - } - } - - catch(Throwable ignored) - { - - } - }))); - - b.append(IO.hash(gb.toString())); - c.append(IO.hash(b.toString())); - b = new StringBuilder(); - - Iris.info("Writing Dimensional Scaffold"); - - try - { - a = new JSONObject(new Gson().toJson(dimension)).toString(minify ? 0 : 4); - IO.writeAll(new File(folder, "dimensions/" + dimension.getLoadKey() + ".json"), a); - b.append(IO.hash(a)); - - for(IrisGenerator i : generators) - { - a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); - IO.writeAll(new File(folder, "generators/" + i.getLoadKey() + ".json"), a); - b.append(IO.hash(a)); - } - - c.append(IO.hash(b.toString())); - b = new StringBuilder(); - - for(IrisRegion i : regions) - { - a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); - IO.writeAll(new File(folder, "regions/" + i.getLoadKey() + ".json"), a); - b.append(IO.hash(a)); - } - - for(IrisBlockData i : blocks) - { - a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); - IO.writeAll(new File(folder, "blocks/" + i.getLoadKey() + ".json"), a); - b.append(IO.hash(a)); - } - - for(IrisBiome i : biomes) - { - a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); - IO.writeAll(new File(folder, "biomes/" + i.getLoadKey() + ".json"), a); - b.append(IO.hash(a)); - } - - for(IrisEntity i : entities) - { - a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); - IO.writeAll(new File(folder, "entities/" + i.getLoadKey() + ".json"), a); - b.append(IO.hash(a)); - } - - for(IrisLootTable i : loot) - { - a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); - IO.writeAll(new File(folder, "loot/" + i.getLoadKey() + ".json"), a); - b.append(IO.hash(a)); - } - - c.append(IO.hash(b.toString())); - String finalHash = IO.hash(c.toString()); - JSONObject meta = new JSONObject(); - meta.put("hash", finalHash); - meta.put("time", M.ms()); - meta.put("version", dimension.getVersion()); - IO.writeAll(new File(folder, "package.json"), meta.toString(minify ? 0 : 4)); - File p = new File(Iris.instance.getDataFolder(), "exports/" + dimension.getLoadKey() + ".iris"); - Iris.info("Compressing Package"); - ZipUtil.pack(folder, p, 9); - IO.delete(folder); - - sender.sendMessage("Package Compiled!"); - return p; - } - - catch(Throwable e) - { - e.printStackTrace(); - } - sender.sendMessage("Failed!"); - return null; - } +public class IrisProject { + private File path; + private String name; + private IrisAccess activeProvider; + + public IrisProject(File path) { + this.path = path; + this.name = path.getName(); + } + + public KList scanForErrors() { + KList reports = new KList<>(); + IrisDataManager data = new IrisDataManager(path); + + for (int i = 0; i < getActiveProvider().getCompound().getSize(); i++) { + Engine e = getActiveProvider().getCompound().getEngine(i); + IrisDimension dim = e.getDimension(); + reports.add(scanForErrors(dim)); + } + + return reports; + } + + private KList scanForErrors(IrisDimension dim) { + KList reports = new KList<>(); + + if (dim.getFocus() != null && !dim.getFocus().isEmpty()) { + reports.add(Report.builder() + .type(ReportType.NOTICE) + .title("Focus Mode is Enabled") + .message("Make sure to disable this before pushing") + .suggestion("Turn off focus mode") + .build()); + } + + for (IrisRegion i : dim.getAllRegions(getActiveProvider())) { + scanForErrors(i); + } + + return reports; + } + + private KList scanForErrors(IrisRegion region) { + KList reports = new KList<>(); + + if (region.getRarity() > 60) { + reports.add(Report.builder() + .type(ReportType.WARNING) + .title("Region " + region.getName() + " has a rarity of " + region.getRarity()) + .message("The region rarity higher than 60 can cause performance issues") + .suggestion("Scale all rarities down by 50% all at once, then repeat until all rarities are below 60") + .build()); + } + + for (IrisBiome i : region.getAllBiomes(getActiveProvider())) { + reports.add(scanForErrors(i)); + } + + return reports; + } + + private KList scanForErrors(IrisBiome biome) { + KList reports = new KList<>(); + + for (IrisObjectPlacement i : biome.getObjects()) { + reports.add(scanForErrors(biome, i)); + } + + for (IrisBiomePaletteLayer i : biome.getLayers()) { + reports.add(scanForErrors(biome, i)); + } + + for (IrisBiomePaletteLayer i : biome.getSeaLayers()) { + reports.add(scanForErrorsSeaLayers(biome, i)); + } + + return reports; + } + + private KList scanForErrors(IrisBiome biome, IrisObjectPlacement i) { + KList reports = new KList<>(); + + return reports; + } + + private KList scanForErrors(IrisBiome biome, IrisBiomePaletteLayer i) { + KList reports = new KList<>(); + + return reports; + } + + private KList scanForErrorsSeaLayers(IrisBiome biome, IrisBiomePaletteLayer i) { + KList reports = new KList<>(); + + return reports; + } + + public boolean isOpen() { + return activeProvider != null; + } + + public KList collectFiles(File f, String json) { + KList l = new KList<>(); + + if (f.isDirectory()) { + for (File i : f.listFiles()) { + l.addAll(collectFiles(i, json)); + } + } else if (f.getName().endsWith("." + json)) { + l.add(f); + } + + return l; + } + + public KList collectFiles(String json) { + return collectFiles(path, json); + } + + public void open(MortarSender sender) { + open(sender, () -> + { + }); + } + + public void open(MortarSender sender, Runnable onDone) { + if (isOpen()) { + close(); + } + + IrisDimension d = IrisDataManager.loadAnyDimension(getName()); + if (d == null) { + sender.sendMessage("Can't find dimension: " + getName()); + return; + } else if (sender.isPlayer()) { + sender.player().setGameMode(GameMode.SPECTATOR); + sender.player().spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(C.BLUE + "Creating studio world. Please wait...")); + } + + J.attemptAsync(() -> + { + try { + if (d.getLoader() == null) { + sender.sendMessage("Could not get dimension loader"); + return; + } + File f = d.getLoader().getDataFolder(); + boolean foundWork = false; + for (File i : Objects.requireNonNull(f.listFiles())) { + if (i.getName().endsWith(".code-workspace")) { + foundWork = true; + sender.sendMessage("Updating Workspace..."); + J.a(() -> + { + updateWorkspace(); + sender.sendMessage("Workspace Updated"); + }); + + if (IrisSettings.get().getStudio().isOpenVSCode()) { + if (!GraphicsEnvironment.isHeadless()) { + Iris.msg("Opening VSCode. You may see the output from VSCode."); + Iris.msg("VSCode output always starts with: '(node:#####) electron'"); + Desktop.getDesktop().open(i); + } + } + + break; + } + } + + if (!foundWork) { + File ff = new File(d.getLoader().getDataFolder(), d.getLoadKey() + ".code-workspace"); + Iris.warn("Project missing code-workspace: " + ff.getAbsolutePath() + " Re-creating code workspace."); + + try { + IO.writeAll(ff, createCodeWorkspaceConfig()); + } catch (IOException e1) { + e1.printStackTrace(); + } + sender.sendMessage("Updating Workspace..."); + updateWorkspace(); + sender.sendMessage("Workspace Updated"); + } + } catch (Throwable e) { + e.printStackTrace(); + } + }); + + String wfp = "iris/" + UUID.randomUUID(); + + WorldCreator c = new IrisWorldCreator().dimension(getName()) + .seed(1337) + .name(wfp) + .studioMode() + .create(); + + IrisAccess gx = ((IrisAccess) c.generator()); + sender.sendMessage("Generating with " + Iris.getThreadCount() + " threads per chunk"); + O done = new O<>(); + done.set(false); + activeProvider = gx; + + J.a(() -> + { + double last = 0; + int req = 300; + double lpc = 0; + boolean fc; + + while (!done.get()) { + boolean derp = false; + + assert gx != null; + double v = (double) gx.getGenerated() / (double) req; + fc = lpc != v; + lpc = v; + + if (last > v || v > 1) { + derp = true; + v = last; + } else { + last = v; + } + + if (fc) { + sender.sendMessage(C.WHITE + "Generating " + Form.pc(v) + (derp ? (C.GRAY + " (Waiting on Server...)") : (C.GRAY + " (" + (req - gx.getGenerated()) + " Left)"))); + } + + if (sender.isPlayer()) { + sender.player().spigot().sendMessage(ChatMessageType.ACTION_BAR, TextComponent.fromLegacyText(C.BLUE + "Creating studio world. Please wait...")); + } + + J.sleep(1500); + + if (gx.isFailing()) { + + sender.sendMessage("Generation Failed!"); + return; + } + } + }); + + //@builder + World world = INMS.get().createWorld(c); + if (IrisSettings.get().getStudio().isDisableTimeAndWeather()) { + world.setGameRule(GameRule.DO_WEATHER_CYCLE, false); + world.setGameRule(GameRule.DO_DAYLIGHT_CYCLE, false); + world.setTime(6000); + } + Iris.linkMultiverseCore.removeFromConfig(world); + + done.set(true); + sender.sendMessage(C.WHITE + "Generating Complete!"); + + if (sender.isPlayer()) { + assert world != null; + sender.player().teleport(world.getSpawnLocation()); + } + + Bukkit.getScheduler().scheduleSyncDelayedTask(Iris.instance, () -> + { + sender.sendMessage("Hotloading Active! Change any files and watch your changes appear as you load new chunks!"); + + if (sender.isPlayer()) { + sender.player().setGameMode(GameMode.SPECTATOR); + } + + onDone.run(); + }, 0); + } + + public void close() { + activeProvider.close(); + File folder = activeProvider.getTarget().getWorld().getWorldFolder(); + Iris.linkMultiverseCore.removeFromConfig(activeProvider.getTarget().getWorld().getName()); + Bukkit.unloadWorld(activeProvider.getTarget().getWorld().getName(), false); + J.attemptAsync(() -> IO.delete(folder)); + activeProvider = null; + } + + public File getCodeWorkspaceFile() { + return new File(path, getName() + ".code-workspace"); + } + + public boolean updateWorkspace() { + getPath().mkdirs(); + File ws = getCodeWorkspaceFile(); + + try { + PrecisionStopwatch p = PrecisionStopwatch.start(); + Iris.info("Building Workspace: " + ws.getPath()); + JSONObject j = createCodeWorkspaceConfig(); + IO.writeAll(ws, j.toString(4)); + p.end(); + Iris.info("Building Workspace: " + ws.getPath() + " took " + Form.duration(p.getMilliseconds(), 2)); + return true; + } catch (Throwable e) { + Iris.warn("Project invalid: " + ws.getAbsolutePath() + " Re-creating. You may loose some vs-code workspace settings! But not your actual project!"); + ws.delete(); + try { + IO.writeAll(ws, createCodeWorkspaceConfig()); + } catch (IOException e1) { + e1.printStackTrace(); + } + } + + return false; + } + + public JSONObject createCodeWorkspaceConfig() { + JSONObject ws = new JSONObject(); + JSONArray folders = new JSONArray(); + JSONObject folder = new JSONObject(); + folder.put("path", "."); + folders.put(folder); + ws.put("folders", folders); + JSONObject settings = new JSONObject(); + settings.put("workbench.colorTheme", "Monokai"); + settings.put("workbench.preferredDarkColorTheme", "Solarized Dark"); + settings.put("workbench.tips.enabled", false); + settings.put("workbench.tree.indent", 24); + settings.put("files.autoSave", "onFocusChange"); + JSONObject jc = new JSONObject(); + jc.put("editor.autoIndent", "brackets"); + jc.put("editor.acceptSuggestionOnEnter", "smart"); + jc.put("editor.cursorSmoothCaretAnimation", true); + jc.put("editor.dragAndDrop", false); + jc.put("files.trimTrailingWhitespace", true); + jc.put("diffEditor.ignoreTrimWhitespace", true); + jc.put("files.trimFinalNewlines", true); + jc.put("editor.suggest.showKeywords", false); + jc.put("editor.suggest.showSnippets", false); + jc.put("editor.suggest.showWords", false); + JSONObject st = new JSONObject(); + st.put("strings", true); + jc.put("editor.quickSuggestions", st); + jc.put("editor.suggest.insertMode", "replace"); + settings.put("[json]", jc); + settings.put("json.maxItemsComputed", 30000); + JSONArray schemas = new JSONArray(); + IrisDataManager dm = new IrisDataManager(getPath()); + schemas.put(getSchemaEntry(IrisDimension.class, dm, "/dimensions/*.json")); + schemas.put(getSchemaEntry(IrisEntity.class, dm, "/entities/*.json")); + schemas.put(getSchemaEntry(IrisBiome.class, dm, "/biomes/*.json")); + schemas.put(getSchemaEntry(IrisRegion.class, dm, "/regions/*.json")); + schemas.put(getSchemaEntry(IrisGenerator.class, dm, "/generators/*.json")); + schemas.put(getSchemaEntry(IrisJigsawPiece.class, dm, "/jigsaw-pieces/*.json")); + schemas.put(getSchemaEntry(IrisJigsawPool.class, dm, "/jigsaw-pools/*.json")); + schemas.put(getSchemaEntry(IrisJigsawStructure.class, dm, "/jigsaw-structures/*.json")); + schemas.put(getSchemaEntry(IrisBlockData.class, dm, "/blocks/*.json")); + schemas.put(getSchemaEntry(IrisLootTable.class, dm, "/loot/*.json")); + settings.put("json.schemas", schemas); + ws.put("settings", settings); + + return ws; + } + + public JSONObject getSchemaEntry(Class i, IrisDataManager dat, String... fileMatch) { + Iris.verbose("Processing Folder " + i.getSimpleName() + " " + fileMatch[0]); + JSONObject o = new JSONObject(); + o.put("fileMatch", new JSONArray(fileMatch)); + o.put("schema", new SchemaBuilder(i, dat).compute()); + + return o; + } + + public File compilePackage(MortarSender sender, boolean obfuscate, boolean minify) { + String dimm = getName(); + IrisDataManager dm = new IrisDataManager(path); + IrisDimension dimension = dm.getDimensionLoader().load(dimm); + File folder = new File(Iris.instance.getDataFolder(), "exports/" + dimension.getLoadKey()); + folder.mkdirs(); + Iris.info("Packaging Dimension " + dimension.getName() + " " + (obfuscate ? "(Obfuscated)" : "")); + KSet regions = new KSet<>(); + KSet biomes = new KSet<>(); + KSet entities = new KSet<>(); + KSet generators = new KSet<>(); + KSet loot = new KSet<>(); + KSet blocks = new KSet<>(); + + for (String i : dm.getDimensionLoader().getPossibleKeys()) { + blocks.add(dm.getBlockLoader().load(i)); + } + + //TODO: EXPORT JIGSAW PIECES FROM STRUCTURES + dimension.getRegions().forEach((i) -> regions.add(dm.getRegionLoader().load(i))); + dimension.getLoot().getTables().forEach((i) -> loot.add(dm.getLootLoader().load(i))); + regions.forEach((i) -> biomes.addAll(i.getAllBiomes(null))); + biomes.forEach((i) -> i.getGenerators().forEach((j) -> generators.add(j.getCachedGenerator(null)))); + regions.forEach((r) -> r.getLoot().getTables().forEach((i) -> loot.add(dm.getLootLoader().load(i)))); + biomes.forEach((r) -> r.getLoot().getTables().forEach((i) -> loot.add(dm.getLootLoader().load(i)))); + biomes.forEach((r) -> r.getEntitySpawnOverrides().forEach((sp) -> entities.add(dm.getEntityLoader().load(sp.getEntity())))); + regions.forEach((r) -> r.getEntitySpawnOverrides().forEach((sp) -> entities.add(dm.getEntityLoader().load(sp.getEntity())))); + dimension.getEntitySpawnOverrides().forEach((sp) -> entities.add(dm.getEntityLoader().load(sp.getEntity()))); + biomes.forEach((r) -> r.getEntityInitialSpawns().forEach((sp) -> entities.add(dm.getEntityLoader().load(sp.getEntity())))); + regions.forEach((r) -> r.getEntityInitialSpawns().forEach((sp) -> entities.add(dm.getEntityLoader().load(sp.getEntity())))); + dimension.getEntityInitialSpawns().forEach((sp) -> entities.add(dm.getEntityLoader().load(sp.getEntity()))); + KMap renameObjects = new KMap<>(); + String a; + StringBuilder b = new StringBuilder(); + StringBuilder c = new StringBuilder(); + sender.sendMessage("Serializing Objects"); + + for (IrisBiome i : biomes) { + for (IrisObjectPlacement j : i.getObjects()) { + b.append(j.hashCode()); + KList newNames = new KList<>(); + + for (String k : j.getPlace()) { + if (renameObjects.containsKey(k)) { + newNames.add(renameObjects.get(k)); + continue; + } + + String name = !obfuscate ? k : UUID.randomUUID().toString().replaceAll("-", ""); + b.append(name); + newNames.add(name); + renameObjects.put(k, name); + } + + j.setPlace(newNames); + } + } + + for (IrisBiomeMutation i : dimension.getMutations()) { + for (IrisObjectPlacement j : i.getObjects()) { + b.append(j.hashCode()); + KList newNames = new KList<>(); + + for (String k : j.getPlace()) { + if (renameObjects.containsKey(k)) { + newNames.add(renameObjects.get(k)); + continue; + } + + String name = !obfuscate ? k : UUID.randomUUID().toString().replaceAll("-", ""); + b.append(name); + newNames.add(name); + renameObjects.put(k, name); + } + + j.setPlace(newNames); + } + } + + KMap> lookupObjects = renameObjects.flip(); + StringBuilder gb = new StringBuilder(); + ChronoLatch cl = new ChronoLatch(1000); + O ggg = new O<>(); + ggg.set(0); + biomes.forEach((i) -> i.getObjects().forEach((j) -> j.getPlace().forEach((k) -> + { + try { + File f = dm.getObjectLoader().findFile(lookupObjects.get(k).get(0)); + IO.copyFile(f, new File(folder, "objects/" + k + ".iob")); + gb.append(IO.hash(f)); + ggg.set(ggg.get() + 1); + + if (cl.flip()) { + int g = ggg.get(); + ggg.set(0); + sender.sendMessage("Wrote another " + g + " Objects"); + } + } catch (Throwable ignored) { + + } + }))); + + dimension.getMutations().forEach((i) -> i.getObjects().forEach((j) -> j.getPlace().forEach((k) -> + { + try { + File f = dm.getObjectLoader().findFile(lookupObjects.get(k).get(0)); + IO.copyFile(f, new File(folder, "objects/" + k + ".iob")); + gb.append(IO.hash(f)); + ggg.set(ggg.get() + 1); + + if (cl.flip()) { + int g = ggg.get(); + ggg.set(0); + sender.sendMessage("Wrote another " + g + " Objects"); + } + } catch (Throwable ignored) { + + } + }))); + + b.append(IO.hash(gb.toString())); + c.append(IO.hash(b.toString())); + b = new StringBuilder(); + + Iris.info("Writing Dimensional Scaffold"); + + try { + a = new JSONObject(new Gson().toJson(dimension)).toString(minify ? 0 : 4); + IO.writeAll(new File(folder, "dimensions/" + dimension.getLoadKey() + ".json"), a); + b.append(IO.hash(a)); + + for (IrisGenerator i : generators) { + a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); + IO.writeAll(new File(folder, "generators/" + i.getLoadKey() + ".json"), a); + b.append(IO.hash(a)); + } + + c.append(IO.hash(b.toString())); + b = new StringBuilder(); + + for (IrisRegion i : regions) { + a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); + IO.writeAll(new File(folder, "regions/" + i.getLoadKey() + ".json"), a); + b.append(IO.hash(a)); + } + + for (IrisBlockData i : blocks) { + a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); + IO.writeAll(new File(folder, "blocks/" + i.getLoadKey() + ".json"), a); + b.append(IO.hash(a)); + } + + for (IrisBiome i : biomes) { + a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); + IO.writeAll(new File(folder, "biomes/" + i.getLoadKey() + ".json"), a); + b.append(IO.hash(a)); + } + + for (IrisEntity i : entities) { + a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); + IO.writeAll(new File(folder, "entities/" + i.getLoadKey() + ".json"), a); + b.append(IO.hash(a)); + } + + for (IrisLootTable i : loot) { + a = new JSONObject(new Gson().toJson(i)).toString(minify ? 0 : 4); + IO.writeAll(new File(folder, "loot/" + i.getLoadKey() + ".json"), a); + b.append(IO.hash(a)); + } + + c.append(IO.hash(b.toString())); + String finalHash = IO.hash(c.toString()); + JSONObject meta = new JSONObject(); + meta.put("hash", finalHash); + meta.put("time", M.ms()); + meta.put("version", dimension.getVersion()); + IO.writeAll(new File(folder, "package.json"), meta.toString(minify ? 0 : 4)); + File p = new File(Iris.instance.getDataFolder(), "exports/" + dimension.getLoadKey() + ".iris"); + Iris.info("Compressing Package"); + ZipUtil.pack(folder, p, 9); + IO.delete(folder); + + sender.sendMessage("Package Compiled!"); + return p; + } catch (Throwable e) { + e.printStackTrace(); + } + sender.sendMessage("Failed!"); + return null; + } } diff --git a/src/main/java/com/volmit/iris/manager/ProjectManager.java b/src/main/java/com/volmit/iris/manager/ProjectManager.java index 3c864be5c..75ba742d3 100644 --- a/src/main/java/com/volmit/iris/manager/ProjectManager.java +++ b/src/main/java/com/volmit/iris/manager/ProjectManager.java @@ -8,526 +8,413 @@ import com.volmit.iris.object.IrisDimension; import com.volmit.iris.scaffold.cache.AtomicCache; import com.volmit.iris.util.*; import lombok.Data; -import org.bukkit.potion.PotionEffectType; import org.zeroturnaround.zip.ZipUtil; import org.zeroturnaround.zip.commons.FileUtils; import java.io.File; import java.io.FileFilter; import java.io.IOException; -import java.util.Objects; import java.util.UUID; -import java.util.regex.Matcher; -import java.util.regex.Pattern; @Data -public class ProjectManager -{ - public static final String LISTING = "https://raw.githubusercontent.com/IrisDimensions/_listing/main/listing-v2.json"; - public static final String WORKSPACE_NAME = "packs"; - private KMap cacheListing = null; - private IrisProject activeProject; - private static final AtomicCache counter = new AtomicCache<>(); - - public ProjectManager() - { - if(IrisSettings.get().isStudio()) - { - J.a(() -> - { - File ignore = getWorkspaceFile(".gitignore"); - - if(!ignore.exists()) - { - File m = Iris.getCached("Pack Ignore (.gitignore)", "https://raw.githubusercontent.com/VolmitSoftware/Iris/master/packignore.ignore"); - if(m != null) - { - try - { - IO.copyFile(m, ignore); - } - - catch(IOException e) - { - - } - } - } - }); - } - } - - public static int countUniqueDimensions() { - int vv = counter.aquire(() -> { - int v = 0; - - try - { - for(File i : Iris.instance.getDataFolder(WORKSPACE_NAME).listFiles()) - { - try - { - if(i.isDirectory() && i.list().length > 0 && !Iris.proj.getListing(true).keySet().contains(i.getName())) - { - v++; - } - } - - catch(Throwable ignored) - { - - } - } - } - - catch(Throwable ignored) - { - - } - - return v; - }); - - return vv; - } - - public IrisDimension installIntoWorld(MortarSender sender, String type, File folder) - { - sender.sendMessage("Looking for Package: " + type); - File iris = new File(folder, "iris"); - File irispack = new File(folder, "iris/pack"); - IrisDimension dim = IrisDataManager.loadAnyDimension(type); - - if(dim == null) - { - for(File i : Iris.proj.getWorkspaceFolder().listFiles()) - { - if(i.isFile() && i.getName().equals(type + ".iris")) - { - sender.sendMessage("Found " + type + ".iris in " + ProjectManager.WORKSPACE_NAME + " folder"); - ZipUtil.unpack(i, irispack); - break; - } - } - } - - else - { - sender.sendMessage("Found " + type + " dimension in " + ProjectManager.WORKSPACE_NAME + " folder. Repackaging"); - File f = new IrisProject(new File(getWorkspaceFolder(), type)).getPath(); - - try - { - FileUtils.copyDirectory(f, irispack); - } - - catch(IOException e) - { - - } - } - - File dimf = new File(irispack, "dimensions/" + type + ".json"); - - if(!dimf.exists() || !dimf.isFile()) - { - Iris.proj.downloadSearch(sender, type, false); - File downloaded = Iris.proj.getWorkspaceFolder(type); - - for(File i : downloaded.listFiles()) - { - if(i.isFile()) - { - try - { - FileUtils.copyFile(i, new File(irispack, i.getName())); - } - - catch(IOException e) - { - e.printStackTrace(); - } - } - - else - { - try - { - FileUtils.copyDirectory(i, new File(irispack, i.getName())); - } - - catch(IOException e) - { - e.printStackTrace(); - } - } - } - - IO.delete(downloaded); - } - - if(!dimf.exists() || !dimf.isFile()) - { - sender.sendMessage("Can't find the " + dimf.getName() + " in the dimensions folder of this pack! Failed!"); - return null; - } - - IrisDataManager dm = new IrisDataManager(irispack); - dim = dm.getDimensionLoader().load(type); - - if(dim == null) - { - sender.sendMessage("Can't load the dimension! Failed!"); - return null; - } - - sender.sendMessage(folder.getName() + " type installed. "); - return dim; - } - - public void downloadSearch(MortarSender sender, String key, boolean trim) - { - downloadSearch(sender, key, trim, false); - } - - public void downloadSearch(MortarSender sender, String key, boolean trim, boolean forceOverwrite) - { - String url = "?"; - - try - { - url = getListing(false).get(key); - url = url == null ? key : url; - Iris.info("Assuming URL " + url); - String branch = "master"; - String[] nodes = url.split("\\Q/\\E"); - String repo = nodes[0] + "/" + nodes[1]; - branch = nodes.length > 2 ? nodes[2] : branch; - download(sender, repo, branch, trim, forceOverwrite); - } - - catch(Throwable e) - { - e.printStackTrace(); - sender.sendMessage("Failed to download '" + key + "' from " + url + "."); - } - } - - public void download(MortarSender sender, String repo, String branch, boolean trim) throws JsonSyntaxException, IOException - { - download(sender, repo, branch, trim, false); - } - - public void download(MortarSender sender, String repo, String branch, boolean trim, boolean forceOverwrite) throws JsonSyntaxException, IOException - { - String url = "https://codeload.github.com/" + repo + "/zip/refs/heads/" + branch; - sender.sendMessage("Downloading " + url); - File zip = Iris.getNonCachedFile("pack-" + trim + "-" + repo, url); - File temp = Iris.getTemp(); - File work = new File(temp, "dl-" + UUID.randomUUID()); - File packs = getWorkspaceFolder(); - sender.sendMessage("Unpacking " + repo); - try { - ZipUtil.unpack(zip, work); - } catch (Throwable e){ - e.printStackTrace(); - sender.sendMessage( - "Issue when unpacking. Please check/do the following:" + - "\n1. Do you have a functioning internet connection?" + - "\n2. Did the download corrupt?" + - "\n3. Try deleting the */plugins/iris/packs folder and re-download." + - "\n4. Download the pack from the GitHub repo: https://github.com/IrisDimensions/overworld" + - "\n5. Contact support (if all other options do not help)" - ); - } - File dir = null; - File[] zipFiles = work.listFiles(); - - if (zipFiles == null) { - sender.sendMessage("No files were extracted from the zip file."); - return; - } - - try { - dir = zipFiles.length == 1 && zipFiles[0].isDirectory() ? zipFiles[0] : null; - } catch (NullPointerException e) { - sender.sendMessage("Error when finding home directory. Are there any non-text characters in the file name?"); - return; - } - - if(dir == null) - { - sender.sendMessage("Invalid Format. Missing root folder or too many folders!"); - return; - } - - File dimensions = new File(dir, "dimensions"); - - if(!(dimensions.exists() && dimensions.isDirectory())) - { - sender.sendMessage("Invalid Format. Missing dimensions folder"); - return; - } - - if(dimensions.listFiles() == null){ - sender.sendMessage("No dimension file found in the extracted zip file."); - sender.sendMessage("Check it is there on GitHub and report this to staff!"); - } - else if (dimensions.listFiles().length != 1) - { - sender.sendMessage("Dimensions folder must have 1 file in it"); - return; - } - - File dim = dimensions.listFiles()[0]; - - if(!dim.isFile()) - { - sender.sendMessage("Invalid dimension (folder) in dimensions folder"); - return; - } - - String key = dim.getName().split("\\Q.\\E")[0]; - IrisDimension d = new Gson().fromJson(IO.readAll(dim), IrisDimension.class); - sender.sendMessage("Importing " + d.getName() + " (" + key + ")"); - File packEntry = new File(packs, key); - - if(forceOverwrite) - { - IO.delete(packEntry); - } - - if(IrisDataManager.loadAnyDimension(key) != null) - { - sender.sendMessage("Another dimension in the packs folder is already using the key " + key + " IMPORT FAILED!"); - return; - } - - if(packEntry.exists() && packEntry.listFiles().length > 0) - { - sender.sendMessage("Another pack is using the key " + key + ". IMPORT FAILED!"); - return; - } - - FileUtils.copyDirectory(dir, packEntry); - - if(trim) - { - sender.sendMessage("Trimming " + key); - File cp = compilePackage(sender, key, false, false); - IO.delete(packEntry); - packEntry.mkdirs(); - ZipUtil.unpack(cp, packEntry); - } - - sender.sendMessage("Successfully Aquired " + d.getName()); - } - - public KMap getListing(boolean cached) - { - if(cached && cacheListing != null) - { - return cacheListing; - } - - JSONObject a; - - if(cached) - { - a = new JSONObject(Iris.getCached("cachedlisting", LISTING)); - } - - else - { - a = new JSONObject(Iris.getNonCached(true + "listing", LISTING)); - } - - KMap l = new KMap<>(); - - for(String i : a.keySet()) - { - l.put(i, a.getString(i)); - } - - return l; - } - - public boolean isProjectOpen() - { - return activeProject != null && activeProject.isOpen(); - } - - public void open(MortarSender sender, String dimm) - { - try { - open(sender, dimm, () -> - { - if (sender.isPlayer()) { - } - }); - } catch (Exception e){ - sender.sendMessage("Error when creating studio world:"); - e.printStackTrace(); - } - } - - public void open(MortarSender sender, String dimm, Runnable onDone) - { - if(isProjectOpen()) - { - close(); - } - - IrisProject project = new IrisProject(new File(getWorkspaceFolder(), dimm)); - activeProject = project; - project.open(sender, onDone); - } - - public File getWorkspaceFolder(String... sub) - { - return Iris.instance.getDataFolderList(WORKSPACE_NAME, sub); - } - - public File getWorkspaceFile(String... sub) - { - return Iris.instance.getDataFileList(WORKSPACE_NAME, sub); - } - - public void close() - { - if(isProjectOpen()) - { - activeProject.close(); - activeProject = null; - } - } - - public File compilePackage(MortarSender sender, String d, boolean obfuscate, boolean minify) - { - return new IrisProject(new File(getWorkspaceFolder(), d)).compilePackage(sender, obfuscate, minify); - } - - public void createFrom(String existingPack, String newName) - { - File importPack = getWorkspaceFolder(existingPack); - File newPack = getWorkspaceFolder(newName); - - if(importPack.listFiles().length == 0) - { - Iris.warn("Couldn't find the pack to create a new dimension from."); - return; - } - - try - { - FileUtils.copyDirectory(importPack, newPack, new FileFilter() - { - @Override - public boolean accept(File pathname) - { - return !pathname.getAbsolutePath().contains(".git"); - } - }, false); - } - - catch(IOException e) - { - e.printStackTrace(); - } - - new File(importPack, existingPack + ".code-workspace").delete(); - File dimFile = new File(importPack, "dimensions/" + existingPack + ".json"); - File newDimFile = new File(newPack, "dimensions/" + newName + ".json"); - - try - { - FileUtils.copyFile(dimFile, newDimFile); - } - - catch(IOException e) - { - e.printStackTrace(); - } - - new File(newPack, "dimensions/" + existingPack + ".json").delete(); - - try - { - JSONObject json = new JSONObject(IO.readAll(newDimFile)); - - if(json.has("name")) - { - json.put("name", Form.capitalizeWords(newName.replaceAll("\\Q-\\E", " "))); - IO.writeAll(newDimFile, json.toString(4)); - } - } - - catch(JSONException | IOException e) - { - e.printStackTrace(); - } - - try - { - IrisProject p = new IrisProject(getWorkspaceFolder(newName)); - JSONObject ws = p.createCodeWorkspaceConfig(); - IO.writeAll(getWorkspaceFile(newName, newName + ".code-workspace"), ws.toString(0)); - } - - catch(JSONException | IOException e) - { - e.printStackTrace(); - } - } - - public void create(MortarSender sender, String s, String downloadable) - { - boolean shouldDelete = false; - File importPack = getWorkspaceFolder(downloadable); - - if(importPack.listFiles().length == 0) - { - downloadSearch(sender, downloadable, false); - - if(importPack.listFiles().length > 0) - { - shouldDelete = true; - } - } - - if(importPack.listFiles().length == 0) - { - sender.sendMessage("Couldn't find the pack to create a new dimension from."); - return; - } - - File importDimensionFile = new File(importPack, "dimensions/" + downloadable + ".json"); - - if(!importDimensionFile.exists()) - { - sender.sendMessage("Missing Imported Dimension File"); - return; - } - - sender.sendMessage("Importing " + downloadable + " into new Project " + s); - createFrom(downloadable, s); - if(shouldDelete) - { - importPack.delete(); - } - open(sender, s); - } - - public void create(MortarSender sender, String s) - { - create(sender, s, "example"); - } - - public void updateWorkspace() - { - if(isProjectOpen()) - { - activeProject.updateWorkspace(); - } - } +public class ProjectManager { + public static final String LISTING = "https://raw.githubusercontent.com/IrisDimensions/_listing/main/listing-v2.json"; + public static final String WORKSPACE_NAME = "packs"; + private KMap cacheListing = null; + private IrisProject activeProject; + private static final AtomicCache counter = new AtomicCache<>(); + + public ProjectManager() { + if (IrisSettings.get().isStudio()) { + J.a(() -> + { + File ignore = getWorkspaceFile(".gitignore"); + + if (!ignore.exists()) { + File m = Iris.getCached("Pack Ignore (.gitignore)", "https://raw.githubusercontent.com/VolmitSoftware/Iris/master/packignore.ignore"); + if (m != null) { + try { + IO.copyFile(m, ignore); + } catch (IOException e) { + + } + } + } + }); + } + } + + public static int countUniqueDimensions() { + int vv = counter.aquire(() -> { + int v = 0; + + try { + for (File i : Iris.instance.getDataFolder(WORKSPACE_NAME).listFiles()) { + try { + if (i.isDirectory() && i.list().length > 0 && !Iris.proj.getListing(true).containsKey(i.getName())) { + v++; + } + } catch (Throwable ignored) { + + } + } + } catch (Throwable ignored) { + + } + + return v; + }); + + return vv; + } + + public IrisDimension installIntoWorld(MortarSender sender, String type, File folder) { + sender.sendMessage("Looking for Package: " + type); + File iris = new File(folder, "iris"); + File irispack = new File(folder, "iris/pack"); + IrisDimension dim = IrisDataManager.loadAnyDimension(type); + + if (dim == null) { + for (File i : Iris.proj.getWorkspaceFolder().listFiles()) { + if (i.isFile() && i.getName().equals(type + ".iris")) { + sender.sendMessage("Found " + type + ".iris in " + ProjectManager.WORKSPACE_NAME + " folder"); + ZipUtil.unpack(i, irispack); + break; + } + } + } else { + sender.sendMessage("Found " + type + " dimension in " + ProjectManager.WORKSPACE_NAME + " folder. Repackaging"); + File f = new IrisProject(new File(getWorkspaceFolder(), type)).getPath(); + + try { + FileUtils.copyDirectory(f, irispack); + } catch (IOException e) { + + } + } + + File dimf = new File(irispack, "dimensions/" + type + ".json"); + + if (!dimf.exists() || !dimf.isFile()) { + Iris.proj.downloadSearch(sender, type, false); + File downloaded = Iris.proj.getWorkspaceFolder(type); + + for (File i : downloaded.listFiles()) { + if (i.isFile()) { + try { + FileUtils.copyFile(i, new File(irispack, i.getName())); + } catch (IOException e) { + e.printStackTrace(); + } + } else { + try { + FileUtils.copyDirectory(i, new File(irispack, i.getName())); + } catch (IOException e) { + e.printStackTrace(); + } + } + } + + IO.delete(downloaded); + } + + if (!dimf.exists() || !dimf.isFile()) { + sender.sendMessage("Can't find the " + dimf.getName() + " in the dimensions folder of this pack! Failed!"); + return null; + } + + IrisDataManager dm = new IrisDataManager(irispack); + dim = dm.getDimensionLoader().load(type); + + if (dim == null) { + sender.sendMessage("Can't load the dimension! Failed!"); + return null; + } + + sender.sendMessage(folder.getName() + " type installed. "); + return dim; + } + + public void downloadSearch(MortarSender sender, String key, boolean trim) { + downloadSearch(sender, key, trim, false); + } + + public void downloadSearch(MortarSender sender, String key, boolean trim, boolean forceOverwrite) { + String url = "?"; + + try { + url = getListing(false).get(key); + url = url == null ? key : url; + Iris.info("Assuming URL " + url); + String branch = "master"; + String[] nodes = url.split("\\Q/\\E"); + String repo = nodes[0] + "/" + nodes[1]; + branch = nodes.length > 2 ? nodes[2] : branch; + download(sender, repo, branch, trim, forceOverwrite); + } catch (Throwable e) { + e.printStackTrace(); + sender.sendMessage("Failed to download '" + key + "' from " + url + "."); + } + } + + public void download(MortarSender sender, String repo, String branch, boolean trim) throws JsonSyntaxException, IOException { + download(sender, repo, branch, trim, false); + } + + public void download(MortarSender sender, String repo, String branch, boolean trim, boolean forceOverwrite) throws JsonSyntaxException, IOException { + String url = "https://codeload.github.com/" + repo + "/zip/refs/heads/" + branch; + sender.sendMessage("Downloading " + url); + File zip = Iris.getNonCachedFile("pack-" + trim + "-" + repo, url); + File temp = Iris.getTemp(); + File work = new File(temp, "dl-" + UUID.randomUUID()); + File packs = getWorkspaceFolder(); + sender.sendMessage("Unpacking " + repo); + try { + ZipUtil.unpack(zip, work); + } catch (Throwable e) { + e.printStackTrace(); + sender.sendMessage( + "Issue when unpacking. Please check/do the following:" + + "\n1. Do you have a functioning internet connection?" + + "\n2. Did the download corrupt?" + + "\n3. Try deleting the */plugins/iris/packs folder and re-download." + + "\n4. Download the pack from the GitHub repo: https://github.com/IrisDimensions/overworld" + + "\n5. Contact support (if all other options do not help)" + ); + } + File dir = null; + File[] zipFiles = work.listFiles(); + + if (zipFiles == null) { + sender.sendMessage("No files were extracted from the zip file."); + return; + } + + try { + dir = zipFiles.length == 1 && zipFiles[0].isDirectory() ? zipFiles[0] : null; + } catch (NullPointerException e) { + sender.sendMessage("Error when finding home directory. Are there any non-text characters in the file name?"); + return; + } + + if (dir == null) { + sender.sendMessage("Invalid Format. Missing root folder or too many folders!"); + return; + } + + File dimensions = new File(dir, "dimensions"); + + if (!(dimensions.exists() && dimensions.isDirectory())) { + sender.sendMessage("Invalid Format. Missing dimensions folder"); + return; + } + + if (dimensions.listFiles() == null) { + sender.sendMessage("No dimension file found in the extracted zip file."); + sender.sendMessage("Check it is there on GitHub and report this to staff!"); + } else if (dimensions.listFiles().length != 1) { + sender.sendMessage("Dimensions folder must have 1 file in it"); + return; + } + + File dim = dimensions.listFiles()[0]; + + if (!dim.isFile()) { + sender.sendMessage("Invalid dimension (folder) in dimensions folder"); + return; + } + + String key = dim.getName().split("\\Q.\\E")[0]; + IrisDimension d = new Gson().fromJson(IO.readAll(dim), IrisDimension.class); + sender.sendMessage("Importing " + d.getName() + " (" + key + ")"); + File packEntry = new File(packs, key); + + if (forceOverwrite) { + IO.delete(packEntry); + } + + if (IrisDataManager.loadAnyDimension(key) != null) { + sender.sendMessage("Another dimension in the packs folder is already using the key " + key + " IMPORT FAILED!"); + return; + } + + if (packEntry.exists() && packEntry.listFiles().length > 0) { + sender.sendMessage("Another pack is using the key " + key + ". IMPORT FAILED!"); + return; + } + + FileUtils.copyDirectory(dir, packEntry); + + if (trim) { + sender.sendMessage("Trimming " + key); + File cp = compilePackage(sender, key, false, false); + IO.delete(packEntry); + packEntry.mkdirs(); + ZipUtil.unpack(cp, packEntry); + } + + sender.sendMessage("Successfully Aquired " + d.getName()); + } + + public KMap getListing(boolean cached) { + if (cached && cacheListing != null) { + return cacheListing; + } + + JSONObject a; + + if (cached) { + a = new JSONObject(Iris.getCached("cachedlisting", LISTING)); + } else { + a = new JSONObject(Iris.getNonCached(true + "listing", LISTING)); + } + + KMap l = new KMap<>(); + + for (String i : a.keySet()) { + l.put(i, a.getString(i)); + } + + return l; + } + + public boolean isProjectOpen() { + return activeProject != null && activeProject.isOpen(); + } + + public void open(MortarSender sender, String dimm) { + try { + open(sender, dimm, () -> + { + if (sender.isPlayer()) { + } + }); + } catch (Exception e) { + sender.sendMessage("Error when creating studio world:"); + e.printStackTrace(); + } + } + + public void open(MortarSender sender, String dimm, Runnable onDone) { + if (isProjectOpen()) { + close(); + } + + IrisProject project = new IrisProject(new File(getWorkspaceFolder(), dimm)); + activeProject = project; + project.open(sender, onDone); + } + + public File getWorkspaceFolder(String... sub) { + return Iris.instance.getDataFolderList(WORKSPACE_NAME, sub); + } + + public File getWorkspaceFile(String... sub) { + return Iris.instance.getDataFileList(WORKSPACE_NAME, sub); + } + + public void close() { + if (isProjectOpen()) { + activeProject.close(); + activeProject = null; + } + } + + public File compilePackage(MortarSender sender, String d, boolean obfuscate, boolean minify) { + return new IrisProject(new File(getWorkspaceFolder(), d)).compilePackage(sender, obfuscate, minify); + } + + public void createFrom(String existingPack, String newName) { + File importPack = getWorkspaceFolder(existingPack); + File newPack = getWorkspaceFolder(newName); + + if (importPack.listFiles().length == 0) { + Iris.warn("Couldn't find the pack to create a new dimension from."); + return; + } + + try { + FileUtils.copyDirectory(importPack, newPack, new FileFilter() { + @Override + public boolean accept(File pathname) { + return !pathname.getAbsolutePath().contains(".git"); + } + }, false); + } catch (IOException e) { + e.printStackTrace(); + } + + new File(importPack, existingPack + ".code-workspace").delete(); + File dimFile = new File(importPack, "dimensions/" + existingPack + ".json"); + File newDimFile = new File(newPack, "dimensions/" + newName + ".json"); + + try { + FileUtils.copyFile(dimFile, newDimFile); + } catch (IOException e) { + e.printStackTrace(); + } + + new File(newPack, "dimensions/" + existingPack + ".json").delete(); + + try { + JSONObject json = new JSONObject(IO.readAll(newDimFile)); + + if (json.has("name")) { + json.put("name", Form.capitalizeWords(newName.replaceAll("\\Q-\\E", " "))); + IO.writeAll(newDimFile, json.toString(4)); + } + } catch (JSONException | IOException e) { + e.printStackTrace(); + } + + try { + IrisProject p = new IrisProject(getWorkspaceFolder(newName)); + JSONObject ws = p.createCodeWorkspaceConfig(); + IO.writeAll(getWorkspaceFile(newName, newName + ".code-workspace"), ws.toString(0)); + } catch (JSONException | IOException e) { + e.printStackTrace(); + } + } + + public void create(MortarSender sender, String s, String downloadable) { + boolean shouldDelete = false; + File importPack = getWorkspaceFolder(downloadable); + + if (importPack.listFiles().length == 0) { + downloadSearch(sender, downloadable, false); + + if (importPack.listFiles().length > 0) { + shouldDelete = true; + } + } + + if (importPack.listFiles().length == 0) { + sender.sendMessage("Couldn't find the pack to create a new dimension from."); + return; + } + + File importDimensionFile = new File(importPack, "dimensions/" + downloadable + ".json"); + + if (!importDimensionFile.exists()) { + sender.sendMessage("Missing Imported Dimension File"); + return; + } + + sender.sendMessage("Importing " + downloadable + " into new Project " + s); + createFrom(downloadable, s); + if (shouldDelete) { + importPack.delete(); + } + open(sender, s); + } + + public void create(MortarSender sender, String s) { + create(sender, s, "example"); + } + + public void updateWorkspace() { + if (isProjectOpen()) { + activeProject.updateWorkspace(); + } + } } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/manager/SchemaBuilder.java b/src/main/java/com/volmit/iris/manager/SchemaBuilder.java index 44be945d8..d3b6078ce 100644 --- a/src/main/java/com/volmit/iris/manager/SchemaBuilder.java +++ b/src/main/java/com/volmit/iris/manager/SchemaBuilder.java @@ -10,1053 +10,810 @@ import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.List; -public class SchemaBuilder -{ - private static final String SYMBOL_LIMIT__N = "*"; - private static final String SYMBOL_TYPE__N = ""; - private static final JSONArray POTION_TYPES = getPotionTypes(); - private static final JSONArray ENCHANT_TYPES = getEnchantmentTypes(); - private static final JSONArray ITEM_TYPES = new JSONArray(B.getItemTypes()); - private static final JSONArray FONT_TYPES = new JSONArray(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()); - private final KMap definitions; - private final Class root; - private final KList warnings; - private final IrisDataManager data; - - public SchemaBuilder(Class root, IrisDataManager data) - { - this.data = data; - warnings = new KList<>(); - this.definitions = new KMap(); - this.root = root; - } - - public JSONObject compute() - { - JSONObject schema = new JSONObject(); - schema.put("$schema", "http://json-schema.org/draft-07/schema#"); - schema.put("$id", "http://volmit.com/iris-schema/" + root.getSimpleName().toLowerCase() + ".json"); - - JSONObject props = buildProperties(root); - - for(String i : props.keySet()) - { - if(!schema.has(i)) - { - schema.put(i, props.get(i)); - } - } - - JSONObject defs = new JSONObject(); - - for(String i : definitions.keySet()) - { - defs.put(i, definitions.get(i)); - } - - schema.put("definitions", defs); - - for(String i : warnings) - { - Iris.warn(root.getSimpleName() + ": " + i); - } - - return schema; - } - - private JSONObject buildProperties(Class c) - { - JSONObject o = new JSONObject(); - JSONObject properties = new JSONObject(); - o.put("description", getDescription(c)); - o.put("type", getType(c)); - JSONArray required = new JSONArray(); - - for(Field k : c.getDeclaredFields()) - { - k.setAccessible(true); - - if(Modifier.isStatic(k.getModifiers()) || Modifier.isFinal(k.getModifiers()) || Modifier.isTransient(k.getModifiers())) - { - continue; - } - - JSONObject property = buildProperty(k, c); - - if(property.getBoolean("!required")) - { - required.put(k.getName()); - } - - property.remove("!required"); - properties.put(k.getName(), property); - } - - if(required.length() > 0) - { - o.put("required", required); - } - - o.put("properties", properties); - - return o; - } - - private JSONObject buildProperty(Field k, Class cl) - { - JSONObject prop = new JSONObject(); - String type = getType(k.getType()); - KList description = new KList(); - prop.put("!required", k.isAnnotationPresent(Required.class)); - prop.put("type", type); - String fancyType = "Unknown Type"; - - if(type.equals("boolean")) - { - fancyType = "Boolean"; - } - - else if(type.equals("integer")) - { - fancyType = "Integer"; - if(k.isAnnotationPresent(MinNumber.class)) - { - int min = (int) k.getDeclaredAnnotation(MinNumber.class).value(); - prop.put("minimum", min); - description.add(SYMBOL_LIMIT__N + " Minimum allowed is " + min); - } - - if(k.isAnnotationPresent(MaxNumber.class)) - { - int max = (int) k.getDeclaredAnnotation(MaxNumber.class).value(); - prop.put("maximum", max); - description.add(SYMBOL_LIMIT__N + " Maximum allowed is " + max); - } - } - - else if(type.equals("number")) - { - fancyType = "Number"; - if(k.isAnnotationPresent(MinNumber.class)) - { - double min = k.getDeclaredAnnotation(MinNumber.class).value(); - prop.put("minimum", min); - description.add(SYMBOL_LIMIT__N + " Minimum allowed is " + min); - } - - if(k.isAnnotationPresent(MaxNumber.class)) - { - double max = k.getDeclaredAnnotation(MaxNumber.class).value(); - prop.put("maximum", max); - description.add(SYMBOL_LIMIT__N + " Maximum allowed is " + max); - } - } - - else if(type.equals("string")) - { - fancyType = "Text"; - if(k.isAnnotationPresent(MinNumber.class)) - { - int min = (int) k.getDeclaredAnnotation(MinNumber.class).value(); - prop.put("minLength", min); - description.add(SYMBOL_LIMIT__N + " Minimum Length allowed is " + min); - } - - if(k.isAnnotationPresent(MaxNumber.class)) - { - int max = (int) k.getDeclaredAnnotation(MaxNumber.class).value(); - prop.put("maxLength", max); - description.add(SYMBOL_LIMIT__N + " Maximum Length allowed is " + max); - } - - if(k.isAnnotationPresent(RegistryListBiome.class)) - { - String key = "enum-reg-biome"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", new JSONArray(data.getBiomeLoader().getPossibleKeys())); - definitions.put(key, j); - } - - fancyType = "Iris Biome"; - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid Biome (use ctrl+space for auto complete!)"); - - } - - else if(k.isAnnotationPresent(RegistryListMythical.class)) - { - String key = "enum-reg-mythical"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", new JSONArray(Iris.linkMythicMobs.getMythicMobTypes())); - definitions.put(key, j); - } - - fancyType = "Mythic Mob Type"; - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid Mythic Mob Type (use ctrl+space for auto complete!) Define mythic mobs with the mythic mobs plugin configuration files."); - } - - else if(k.isAnnotationPresent(RegistryListBlockType.class)) - { - String key = "enum-block-type"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - JSONArray ja = new JSONArray(); - - for(String i : data.getBlockLoader().getPossibleKeys()) - { - ja.put(i); - } - - for(String i : B.getBlockTypes()) - { - ja.put(i); - } - - j.put("enum", ja); - definitions.put(key, j); - } - - fancyType = "Block Type"; - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid Block Type (use ctrl+space for auto complete!)"); - - } - - else if(k.isAnnotationPresent(RegistryListItemType.class)) - { - String key = "enum-item-type"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", ITEM_TYPES); - definitions.put(key, j); - } - - fancyType = "Item Type"; - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid Item Type (use ctrl+space for auto complete!)"); - - } - - else if(k.isAnnotationPresent(RegistryListEntity.class)) - { - String key = "enum-reg-entity"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", new JSONArray(data.getEntityLoader().getPossibleKeys())); - definitions.put(key, j); - } - - fancyType = "Iris Entity"; - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid Iris Entity (use ctrl+space for auto complete!)"); - - } - - else if(k.isAnnotationPresent(RegistryListFont.class)) - { - String key = "enum-font"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", FONT_TYPES); - definitions.put(key, j); - } - - fancyType = "Font Family"; - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid Font Family (use ctrl+space for auto complete!)"); - - } - - else if(k.isAnnotationPresent(RegistryListLoot.class)) - { - String key = "enum-reg-loot-table"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", new JSONArray(data.getLootLoader().getPossibleKeys())); - definitions.put(key, j); - } - - fancyType = "Iris Loot Table"; - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid Loot Table (use ctrl+space for auto complete!)"); - } - - else if(k.isAnnotationPresent(RegistryListDimension.class)) - { - String key = "enum-reg-dimension"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", new JSONArray(data.getDimensionLoader().getPossibleKeys())); - definitions.put(key, j); - } - - fancyType = "Iris Dimension"; - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid Dimension (use ctrl+space for auto complete!)"); - - } - - else if(k.isAnnotationPresent(RegistryListGenerator.class)) - { - String key = "enum-reg-generator"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", new JSONArray(data.getGeneratorLoader().getPossibleKeys())); - definitions.put(key, j); - } - - fancyType = "Iris Generator"; - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid Generator (use ctrl+space for auto complete!)"); - - } - - else if(k.isAnnotationPresent(RegistryListObject.class)) - { - String key = "enum-reg-object"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", new JSONArray(data.getObjectLoader().getPossibleKeys())); - definitions.put(key, j); - } - - fancyType = "Iris Object"; - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid Object (use ctrl+space for auto complete!)"); - - } - - else if(k.isAnnotationPresent(RegistryListRegion.class)) - { - String key = "enum-reg-region"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", new JSONArray(data.getRegionLoader().getPossibleKeys())); - definitions.put(key, j); - } - - fancyType = "Iris Region"; - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid Region (use ctrl+space for auto complete!)"); - - } - - else if(k.isAnnotationPresent(RegistryListJigsawPiece.class)) - { - String key = "enum-reg-structure-piece"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", new JSONArray(data.getJigsawPieceLoader().getPossibleKeys())); - definitions.put(key, j); - } - - fancyType = "Iris Jigsaw Piece"; - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid Jigsaw Piece (use ctrl+space for auto complete!)"); - } - - else if(k.isAnnotationPresent(RegistryListJigsaw.class)) - { - String key = "enum-reg-jigsaw"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", new JSONArray(data.getJigsawStructureLoader().getPossibleKeys())); - definitions.put(key, j); - } - - fancyType = "Iris Jigsaw"; - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid Jigsaw (use ctrl+space for auto complete!)"); - } - - else if(k.isAnnotationPresent(RegistryListJigsawPool.class)) - { - String key = "enum-reg-structure-pool"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", new JSONArray(data.getJigsawPoolLoader().getPossibleKeys())); - definitions.put(key, j); - } - - fancyType = "Iris Jigsaw Pool"; - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid Jigsaw Piece (use ctrl+space for auto complete!)"); - } - - else if(k.getType().equals(Enchantment.class)) - { - String key = "enum-enchantment"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", ENCHANT_TYPES); - definitions.put(key, j); - } - - fancyType = "Enchantment Type"; - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid Enchantment Type (use ctrl+space for auto complete!)"); - } - - else if(k.getType().equals(PotionEffectType.class)) - { - String key = "enum-potion-effect-type"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", POTION_TYPES); - definitions.put(key, j); - } - - fancyType = "Potion Effect Type"; - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid Potion Effect Type (use ctrl+space for auto complete!)"); - - } - - else if(k.getType().isEnum()) - { - fancyType = k.getType().getSimpleName().replaceAll("\\QIris\\E", ""); - JSONArray a = new JSONArray(); - boolean advanced = k.getType().isAnnotationPresent(Desc.class); - for(Object gg : k.getType().getEnumConstants()) - { - if(advanced) - { - try - { - JSONObject j = new JSONObject(); - String name = ((Enum) gg).name(); - j.put("const", name); - Desc dd = k.getType().getField(name).getAnnotation(Desc.class); - j.put("description", dd == null ? ("No Description for " + name) : dd.value()); - a.put(j); - } - - catch(Throwable e) - { - e.printStackTrace(); - } - } - - else - { - a.put(((Enum) gg).name()); - } - } - - String key = (advanced ? "oneof-" : "") + "enum-" + k.getType().getCanonicalName().replaceAll("\\Q.\\E", "-").toLowerCase(); - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put(advanced ? "oneOf" : "enum", a); - definitions.put(key, j); - } - - prop.put("$ref", "#/definitions/" + key); - description.add(SYMBOL_TYPE__N + " Must be a valid " + k.getType().getSimpleName().replaceAll("\\QIris\\E", "") + " (use ctrl+space for auto complete!)"); - - } - } - - else if(type.equals("object")) - { - fancyType = k.getType().getSimpleName().replaceAll("\\QIris\\E", "") + " (Object)"; - - String key = "obj-" + k.getType().getCanonicalName().replaceAll("\\Q.\\E", "-").toLowerCase(); - - if(!definitions.containsKey(key)) - { - definitions.put(key, new JSONObject()); - definitions.put(key, buildProperties(k.getType())); - } - - prop.put("$ref", "#/definitions/" + key); - } - - else if(type.equals("array")) - { - fancyType = "List of Something...?"; - - ArrayType t = k.getDeclaredAnnotation(ArrayType.class); - - if(t != null) - { - if(t.min() > 0) - { - prop.put("minItems", t.min()); - if(t.min() == 1) - { - description.add(SYMBOL_LIMIT__N + " At least one entry must be defined, or just remove this list."); - } - - else - { - description.add(SYMBOL_LIMIT__N + " Requires at least " + t.min() + " entries."); - } - } - - String arrayType = getType(t.type()); - - if(arrayType.equals("integer")) - { - fancyType = "List of Integers"; - } - - else if(arrayType.equals("number")) - { - fancyType = "List of Numbers"; - } - - else if(arrayType.equals("object")) - { - fancyType = "List of " + t.type().getSimpleName().replaceAll("\\QIris\\E", "") + "s (Objects)"; - String key = "obj-" + t.type().getCanonicalName().replaceAll("\\Q.\\E", "-").toLowerCase(); - - if(!definitions.containsKey(key)) - { - definitions.put(key, new JSONObject()); - definitions.put(key, buildProperties(t.type())); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - } - - else if(arrayType.equals("string")) - { - fancyType = "List of Text"; - - if(k.isAnnotationPresent(RegistryListBiome.class)) - { - fancyType = "List of Iris Biomes"; - String key = "enum-reg-biome"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", new JSONArray(data.getBiomeLoader().getPossibleKeys())); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid Biome (use ctrl+space for auto complete!)"); - } - - else if(k.isAnnotationPresent(RegistryListMythical.class)) - { - fancyType = "List of Mythic Mob Types"; - String key = "enum-reg-mythical"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - JSONArray ja = new JSONArray(); - - for(String i : Iris.linkMythicMobs.getMythicMobTypes()) - { - ja.put(i); - } - - j.put("enum", ja); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid Mythic Mob Type (use ctrl+space for auto complete!) Configure mob types in the mythic mobs plugin configuration files."); - } - - else if(k.isAnnotationPresent(RegistryListBlockType.class)) - { - fancyType = "List of Block Types"; - String key = "enum-block-type"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - JSONArray ja = new JSONArray(); - - for(String i : data.getBlockLoader().getPossibleKeys()) - { - ja.put(i); - } - - for(String i : B.getBlockTypes()) - { - ja.put(i); - } - - j.put("enum", ja); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid Block Type (use ctrl+space for auto complete!)"); - } - - else if(k.isAnnotationPresent(RegistryListItemType.class)) - { - fancyType = "List of Item Types"; - String key = "enum-item-type"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", ITEM_TYPES); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid Item Type (use ctrl+space for auto complete!)"); - } - - else if(k.isAnnotationPresent(RegistryListEntity.class)) - { - fancyType = "List of Iris Entities"; - String key = "enum-reg-entity"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", new JSONArray(data.getEntityLoader().getPossibleKeys())); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid Iris Entity (use ctrl+space for auto complete!)"); - } - - else if(k.isAnnotationPresent(RegistryListFont.class)) - { - String key = "enum-font"; - fancyType = "List of Font Families"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", FONT_TYPES); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid Font Family (use ctrl+space for auto complete!)"); - } - - else if(k.isAnnotationPresent(RegistryListLoot.class)) - { - fancyType = "List of Iris Loot Tables"; - String key = "enum-reg-loot-table"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", new JSONArray(data.getLootLoader().getPossibleKeys())); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid Loot Table (use ctrl+space for auto complete!)"); - } - - else if(k.isAnnotationPresent(RegistryListDimension.class)) - { - fancyType = "List of Iris Dimensions"; - String key = "enum-reg-dimension"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", new JSONArray(data.getDimensionLoader().getPossibleKeys())); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid Dimension (use ctrl+space for auto complete!)"); - } - - else if(k.isAnnotationPresent(RegistryListGenerator.class)) - { - fancyType = "List of Iris Generators"; - String key = "enum-reg-generator"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", new JSONArray(data.getGeneratorLoader().getPossibleKeys())); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid Generator (use ctrl+space for auto complete!)"); - } - - else if(k.isAnnotationPresent(RegistryListObject.class)) - { - fancyType = "List of Iris Objects"; - String key = "enum-reg-object"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", new JSONArray(data.getObjectLoader().getPossibleKeys())); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid Object (use ctrl+space for auto complete!)"); - } - - else if(k.isAnnotationPresent(RegistryListRegion.class)) - { - fancyType = "List of Iris Regions"; - String key = "enum-reg-region"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", new JSONArray(data.getRegionLoader().getPossibleKeys())); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid Region (use ctrl+space for auto complete!)"); - } - - else if(k.isAnnotationPresent(RegistryListJigsawPiece.class)) - { - fancyType = "List of Iris Jigsaw Pieces"; - String key = "enum-reg-structure-piece"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", new JSONArray(data.getJigsawPieceLoader().getPossibleKeys())); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid Jigsaw Piece (use ctrl+space for auto complete!)"); - } - - else if(k.isAnnotationPresent(RegistryListJigsawPool.class)) - { - fancyType = "List of Iris Jigsaw Pools"; - String key = "enum-reg-structure-pool"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", new JSONArray(data.getJigsawPoolLoader().getPossibleKeys())); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid Jigsaw Pool (use ctrl+space for auto complete!)"); - } - - else if(k.isAnnotationPresent(RegistryListJigsaw.class)) - { - fancyType = "List of Iris Jigsaw Structures"; - String key = "enum-reg-jigsaw"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", new JSONArray(data.getJigsawStructureLoader().getPossibleKeys())); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid Jigsaw (use ctrl+space for auto complete!)"); - } - - else if(t.type().equals(Enchantment.class)) - { - fancyType = "List of Enchantment Types"; - String key = "enum-enchantment"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", ENCHANT_TYPES); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid Enchantment Type (use ctrl+space for auto complete!)"); - } - - else if(t.type().equals(PotionEffectType.class)) - { - fancyType = "List of Potion Effect Types"; - String key = "enum-potion-effect-type"; - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put("enum", POTION_TYPES); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid Potion Effect Type (use ctrl+space for auto complete!)"); - } - - else if(t.type().isEnum()) - { - fancyType = "List of " + t.type().getSimpleName().replaceAll("\\QIris\\E", "") + "s"; - JSONArray a = new JSONArray(); - boolean advanced = t.type().isAnnotationPresent(Desc.class); - for(Object gg : t.type().getEnumConstants()) - { - if(advanced) - { - try - { - JSONObject j = new JSONObject(); - String name = ((Enum) gg).name(); - j.put("const", name); - Desc dd = t.type().getField(name).getAnnotation(Desc.class); - j.put("description", dd == null ? ("No Description for " + name) : dd.value()); - a.put(j); - } - - catch(Throwable e) - { - e.printStackTrace(); - } - } - - else - { - a.put(((Enum) gg).name()); - } - } - - String key = (advanced ? "oneof-" : "") + "enum-" + t.type().getCanonicalName().replaceAll("\\Q.\\E", "-").toLowerCase(); - - if(!definitions.containsKey(key)) - { - JSONObject j = new JSONObject(); - j.put(advanced ? "oneOf" : "enum", a); - definitions.put(key, j); - } - - JSONObject items = new JSONObject(); - items.put("$ref", "#/definitions/" + key); - prop.put("items", items); - description.add(SYMBOL_TYPE__N + " Must be a valid " + t.type().getSimpleName().replaceAll("\\QIris\\E", "") + " (use ctrl+space for auto complete!)"); - } - } - } - - else - { - warnings.add("Undefined array type for field " + k.getName() + " (" + k.getType().getSimpleName() + ") in class " + cl.getSimpleName()); - } - } - - else - { - warnings.add("Unexpected Schema Type: " + type + " for field " + k.getName() + " (" + k.getType().getSimpleName() + ") in class " + cl.getSimpleName()); - } - - KList d = new KList<>(); - d.add(k.getName()); - d.add(getFieldDescription(k)); - d.add(" "); - d.add(fancyType); - d.add(getDescription(k.getType())); - - try - { - k.setAccessible(true); - Object value = k.get(cl.newInstance()); - - if(value != null) - { - if(value instanceof List) - { - d.add("* Default Value is an empty list"); - } - - else if(!cl.isPrimitive() && !(value instanceof Number) && !(value instanceof String) && !(cl.isEnum())) - { - d.add("* Default Value is a default object (create this object to see default properties)"); - } - - else - { - d.add("* Default Value is " + value.toString()); - } - } - } - - catch(Throwable e) - { - - } - - description.forEach((g) -> d.add(g.trim())); - prop.put("type", type); - prop.put("description", d.toString("\n")); - - return prop; - } - - private String getType(Class c) - { - if(c.equals(int.class) || c.equals(Integer.class) || c.equals(long.class)) - { - return "integer"; - } - - if(c.equals(float.class) || c.equals(double.class)) - { - return "number"; - } - - if(c.equals(boolean.class)) - { - return "boolean"; - } - - if(c.equals(String.class) || c.isEnum() || c.equals(Enchantment.class) || c.equals(PotionEffectType.class)) - { - return "string"; - } - - if(c.equals(KList.class)) - { - return "array"; - } - - if(c.equals(KMap.class)) - { - return "object"; - } - - if(!c.isAnnotationPresent(Desc.class)) - { - warnings.addIfMissing("Unsupported Type: " + c.getCanonicalName() + " Did you forget @Desc?"); - } - - return "object"; - } - - private String getFieldDescription(Field r) - { - if(r.isAnnotationPresent(Desc.class)) - { - return r.getDeclaredAnnotation(Desc.class).value(); - } - - warnings.addIfMissing("Missing @Desc on field " + r.getName() + " (" + r.getType() + ")"); - return "No Field Description"; - } - - private String getDescription(Class r) - { - if(r.isAnnotationPresent(Desc.class)) - { - return r.getDeclaredAnnotation(Desc.class).value(); - } - - if(!r.isPrimitive() && !r.equals(KList.class) && !r.equals(KMap.class) && r.getCanonicalName().startsWith("com.volmit.")) - { - warnings.addIfMissing("Missing @Desc on " + r.getSimpleName()); - } - return ""; - } - - private static JSONArray getEnchantmentTypes() - { - JSONArray a = new JSONArray(); - - for(Field gg : Enchantment.class.getDeclaredFields()) - { - a.put(gg.getName()); - } - - return a; - } - - private static JSONArray getPotionTypes() - { - JSONArray a = new JSONArray(); - - for(PotionEffectType gg : PotionEffectType.values()) - { - a.put(gg.getName().toUpperCase().replaceAll("\\Q \\E", "_")); - } - - return a; - } +public class SchemaBuilder { + private static final String SYMBOL_LIMIT__N = "*"; + private static final String SYMBOL_TYPE__N = ""; + private static final JSONArray POTION_TYPES = getPotionTypes(); + private static final JSONArray ENCHANT_TYPES = getEnchantmentTypes(); + private static final JSONArray ITEM_TYPES = new JSONArray(B.getItemTypes()); + private static final JSONArray FONT_TYPES = new JSONArray(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()); + private final KMap definitions; + private final Class root; + private final KList warnings; + private final IrisDataManager data; + + public SchemaBuilder(Class root, IrisDataManager data) { + this.data = data; + warnings = new KList<>(); + this.definitions = new KMap(); + this.root = root; + } + + public JSONObject compute() { + JSONObject schema = new JSONObject(); + schema.put("$schema", "http://json-schema.org/draft-07/schema#"); + schema.put("$id", "http://volmit.com/iris-schema/" + root.getSimpleName().toLowerCase() + ".json"); + + JSONObject props = buildProperties(root); + + for (String i : props.keySet()) { + if (!schema.has(i)) { + schema.put(i, props.get(i)); + } + } + + JSONObject defs = new JSONObject(); + + for (String i : definitions.keySet()) { + defs.put(i, definitions.get(i)); + } + + schema.put("definitions", defs); + + for (String i : warnings) { + Iris.warn(root.getSimpleName() + ": " + i); + } + + return schema; + } + + private JSONObject buildProperties(Class c) { + JSONObject o = new JSONObject(); + JSONObject properties = new JSONObject(); + o.put("description", getDescription(c)); + o.put("type", getType(c)); + JSONArray required = new JSONArray(); + + for (Field k : c.getDeclaredFields()) { + k.setAccessible(true); + + if (Modifier.isStatic(k.getModifiers()) || Modifier.isFinal(k.getModifiers()) || Modifier.isTransient(k.getModifiers())) { + continue; + } + + JSONObject property = buildProperty(k, c); + + if (property.getBoolean("!required")) { + required.put(k.getName()); + } + + property.remove("!required"); + properties.put(k.getName(), property); + } + + if (required.length() > 0) { + o.put("required", required); + } + + o.put("properties", properties); + + return o; + } + + private JSONObject buildProperty(Field k, Class cl) { + JSONObject prop = new JSONObject(); + String type = getType(k.getType()); + KList description = new KList(); + prop.put("!required", k.isAnnotationPresent(Required.class)); + prop.put("type", type); + String fancyType = "Unknown Type"; + + if (type.equals("boolean")) { + fancyType = "Boolean"; + } else if (type.equals("integer")) { + fancyType = "Integer"; + if (k.isAnnotationPresent(MinNumber.class)) { + int min = (int) k.getDeclaredAnnotation(MinNumber.class).value(); + prop.put("minimum", min); + description.add(SYMBOL_LIMIT__N + " Minimum allowed is " + min); + } + + if (k.isAnnotationPresent(MaxNumber.class)) { + int max = (int) k.getDeclaredAnnotation(MaxNumber.class).value(); + prop.put("maximum", max); + description.add(SYMBOL_LIMIT__N + " Maximum allowed is " + max); + } + } else if (type.equals("number")) { + fancyType = "Number"; + if (k.isAnnotationPresent(MinNumber.class)) { + double min = k.getDeclaredAnnotation(MinNumber.class).value(); + prop.put("minimum", min); + description.add(SYMBOL_LIMIT__N + " Minimum allowed is " + min); + } + + if (k.isAnnotationPresent(MaxNumber.class)) { + double max = k.getDeclaredAnnotation(MaxNumber.class).value(); + prop.put("maximum", max); + description.add(SYMBOL_LIMIT__N + " Maximum allowed is " + max); + } + } else if (type.equals("string")) { + fancyType = "Text"; + if (k.isAnnotationPresent(MinNumber.class)) { + int min = (int) k.getDeclaredAnnotation(MinNumber.class).value(); + prop.put("minLength", min); + description.add(SYMBOL_LIMIT__N + " Minimum Length allowed is " + min); + } + + if (k.isAnnotationPresent(MaxNumber.class)) { + int max = (int) k.getDeclaredAnnotation(MaxNumber.class).value(); + prop.put("maxLength", max); + description.add(SYMBOL_LIMIT__N + " Maximum Length allowed is " + max); + } + + if (k.isAnnotationPresent(RegistryListBiome.class)) { + String key = "enum-reg-biome"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", new JSONArray(data.getBiomeLoader().getPossibleKeys())); + definitions.put(key, j); + } + + fancyType = "Iris Biome"; + prop.put("$ref", "#/definitions/" + key); + description.add(SYMBOL_TYPE__N + " Must be a valid Biome (use ctrl+space for auto complete!)"); + + } else if (k.isAnnotationPresent(RegistryListMythical.class)) { + String key = "enum-reg-mythical"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", new JSONArray(Iris.linkMythicMobs.getMythicMobTypes())); + definitions.put(key, j); + } + + fancyType = "Mythic Mob Type"; + prop.put("$ref", "#/definitions/" + key); + description.add(SYMBOL_TYPE__N + " Must be a valid Mythic Mob Type (use ctrl+space for auto complete!) Define mythic mobs with the mythic mobs plugin configuration files."); + } else if (k.isAnnotationPresent(RegistryListBlockType.class)) { + String key = "enum-block-type"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + JSONArray ja = new JSONArray(); + + for (String i : data.getBlockLoader().getPossibleKeys()) { + ja.put(i); + } + + for (String i : B.getBlockTypes()) { + ja.put(i); + } + + j.put("enum", ja); + definitions.put(key, j); + } + + fancyType = "Block Type"; + prop.put("$ref", "#/definitions/" + key); + description.add(SYMBOL_TYPE__N + " Must be a valid Block Type (use ctrl+space for auto complete!)"); + + } else if (k.isAnnotationPresent(RegistryListItemType.class)) { + String key = "enum-item-type"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", ITEM_TYPES); + definitions.put(key, j); + } + + fancyType = "Item Type"; + prop.put("$ref", "#/definitions/" + key); + description.add(SYMBOL_TYPE__N + " Must be a valid Item Type (use ctrl+space for auto complete!)"); + + } else if (k.isAnnotationPresent(RegistryListEntity.class)) { + String key = "enum-reg-entity"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", new JSONArray(data.getEntityLoader().getPossibleKeys())); + definitions.put(key, j); + } + + fancyType = "Iris Entity"; + prop.put("$ref", "#/definitions/" + key); + description.add(SYMBOL_TYPE__N + " Must be a valid Iris Entity (use ctrl+space for auto complete!)"); + + } else if (k.isAnnotationPresent(RegistryListFont.class)) { + String key = "enum-font"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", FONT_TYPES); + definitions.put(key, j); + } + + fancyType = "Font Family"; + prop.put("$ref", "#/definitions/" + key); + description.add(SYMBOL_TYPE__N + " Must be a valid Font Family (use ctrl+space for auto complete!)"); + + } else if (k.isAnnotationPresent(RegistryListLoot.class)) { + String key = "enum-reg-loot-table"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", new JSONArray(data.getLootLoader().getPossibleKeys())); + definitions.put(key, j); + } + + fancyType = "Iris Loot Table"; + prop.put("$ref", "#/definitions/" + key); + description.add(SYMBOL_TYPE__N + " Must be a valid Loot Table (use ctrl+space for auto complete!)"); + } else if (k.isAnnotationPresent(RegistryListDimension.class)) { + String key = "enum-reg-dimension"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", new JSONArray(data.getDimensionLoader().getPossibleKeys())); + definitions.put(key, j); + } + + fancyType = "Iris Dimension"; + prop.put("$ref", "#/definitions/" + key); + description.add(SYMBOL_TYPE__N + " Must be a valid Dimension (use ctrl+space for auto complete!)"); + + } else if (k.isAnnotationPresent(RegistryListGenerator.class)) { + String key = "enum-reg-generator"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", new JSONArray(data.getGeneratorLoader().getPossibleKeys())); + definitions.put(key, j); + } + + fancyType = "Iris Generator"; + prop.put("$ref", "#/definitions/" + key); + description.add(SYMBOL_TYPE__N + " Must be a valid Generator (use ctrl+space for auto complete!)"); + + } else if (k.isAnnotationPresent(RegistryListObject.class)) { + String key = "enum-reg-object"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", new JSONArray(data.getObjectLoader().getPossibleKeys())); + definitions.put(key, j); + } + + fancyType = "Iris Object"; + prop.put("$ref", "#/definitions/" + key); + description.add(SYMBOL_TYPE__N + " Must be a valid Object (use ctrl+space for auto complete!)"); + + } else if (k.isAnnotationPresent(RegistryListRegion.class)) { + String key = "enum-reg-region"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", new JSONArray(data.getRegionLoader().getPossibleKeys())); + definitions.put(key, j); + } + + fancyType = "Iris Region"; + prop.put("$ref", "#/definitions/" + key); + description.add(SYMBOL_TYPE__N + " Must be a valid Region (use ctrl+space for auto complete!)"); + + } else if (k.isAnnotationPresent(RegistryListJigsawPiece.class)) { + String key = "enum-reg-structure-piece"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", new JSONArray(data.getJigsawPieceLoader().getPossibleKeys())); + definitions.put(key, j); + } + + fancyType = "Iris Jigsaw Piece"; + prop.put("$ref", "#/definitions/" + key); + description.add(SYMBOL_TYPE__N + " Must be a valid Jigsaw Piece (use ctrl+space for auto complete!)"); + } else if (k.isAnnotationPresent(RegistryListJigsaw.class)) { + String key = "enum-reg-jigsaw"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", new JSONArray(data.getJigsawStructureLoader().getPossibleKeys())); + definitions.put(key, j); + } + + fancyType = "Iris Jigsaw"; + prop.put("$ref", "#/definitions/" + key); + description.add(SYMBOL_TYPE__N + " Must be a valid Jigsaw (use ctrl+space for auto complete!)"); + } else if (k.isAnnotationPresent(RegistryListJigsawPool.class)) { + String key = "enum-reg-structure-pool"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", new JSONArray(data.getJigsawPoolLoader().getPossibleKeys())); + definitions.put(key, j); + } + + fancyType = "Iris Jigsaw Pool"; + prop.put("$ref", "#/definitions/" + key); + description.add(SYMBOL_TYPE__N + " Must be a valid Jigsaw Piece (use ctrl+space for auto complete!)"); + } else if (k.getType().equals(Enchantment.class)) { + String key = "enum-enchantment"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", ENCHANT_TYPES); + definitions.put(key, j); + } + + fancyType = "Enchantment Type"; + prop.put("$ref", "#/definitions/" + key); + description.add(SYMBOL_TYPE__N + " Must be a valid Enchantment Type (use ctrl+space for auto complete!)"); + } else if (k.getType().equals(PotionEffectType.class)) { + String key = "enum-potion-effect-type"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", POTION_TYPES); + definitions.put(key, j); + } + + fancyType = "Potion Effect Type"; + prop.put("$ref", "#/definitions/" + key); + description.add(SYMBOL_TYPE__N + " Must be a valid Potion Effect Type (use ctrl+space for auto complete!)"); + + } else if (k.getType().isEnum()) { + fancyType = k.getType().getSimpleName().replaceAll("\\QIris\\E", ""); + JSONArray a = new JSONArray(); + boolean advanced = k.getType().isAnnotationPresent(Desc.class); + for (Object gg : k.getType().getEnumConstants()) { + if (advanced) { + try { + JSONObject j = new JSONObject(); + String name = ((Enum) gg).name(); + j.put("const", name); + Desc dd = k.getType().getField(name).getAnnotation(Desc.class); + j.put("description", dd == null ? ("No Description for " + name) : dd.value()); + a.put(j); + } catch (Throwable e) { + e.printStackTrace(); + } + } else { + a.put(((Enum) gg).name()); + } + } + + String key = (advanced ? "oneof-" : "") + "enum-" + k.getType().getCanonicalName().replaceAll("\\Q.\\E", "-").toLowerCase(); + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put(advanced ? "oneOf" : "enum", a); + definitions.put(key, j); + } + + prop.put("$ref", "#/definitions/" + key); + description.add(SYMBOL_TYPE__N + " Must be a valid " + k.getType().getSimpleName().replaceAll("\\QIris\\E", "") + " (use ctrl+space for auto complete!)"); + + } + } else if (type.equals("object")) { + fancyType = k.getType().getSimpleName().replaceAll("\\QIris\\E", "") + " (Object)"; + + String key = "obj-" + k.getType().getCanonicalName().replaceAll("\\Q.\\E", "-").toLowerCase(); + + if (!definitions.containsKey(key)) { + definitions.put(key, new JSONObject()); + definitions.put(key, buildProperties(k.getType())); + } + + prop.put("$ref", "#/definitions/" + key); + } else if (type.equals("array")) { + fancyType = "List of Something...?"; + + ArrayType t = k.getDeclaredAnnotation(ArrayType.class); + + if (t != null) { + if (t.min() > 0) { + prop.put("minItems", t.min()); + if (t.min() == 1) { + description.add(SYMBOL_LIMIT__N + " At least one entry must be defined, or just remove this list."); + } else { + description.add(SYMBOL_LIMIT__N + " Requires at least " + t.min() + " entries."); + } + } + + String arrayType = getType(t.type()); + + if (arrayType.equals("integer")) { + fancyType = "List of Integers"; + } else if (arrayType.equals("number")) { + fancyType = "List of Numbers"; + } else if (arrayType.equals("object")) { + fancyType = "List of " + t.type().getSimpleName().replaceAll("\\QIris\\E", "") + "s (Objects)"; + String key = "obj-" + t.type().getCanonicalName().replaceAll("\\Q.\\E", "-").toLowerCase(); + + if (!definitions.containsKey(key)) { + definitions.put(key, new JSONObject()); + definitions.put(key, buildProperties(t.type())); + } + + JSONObject items = new JSONObject(); + items.put("$ref", "#/definitions/" + key); + prop.put("items", items); + } else if (arrayType.equals("string")) { + fancyType = "List of Text"; + + if (k.isAnnotationPresent(RegistryListBiome.class)) { + fancyType = "List of Iris Biomes"; + String key = "enum-reg-biome"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", new JSONArray(data.getBiomeLoader().getPossibleKeys())); + definitions.put(key, j); + } + + JSONObject items = new JSONObject(); + items.put("$ref", "#/definitions/" + key); + prop.put("items", items); + description.add(SYMBOL_TYPE__N + " Must be a valid Biome (use ctrl+space for auto complete!)"); + } else if (k.isAnnotationPresent(RegistryListMythical.class)) { + fancyType = "List of Mythic Mob Types"; + String key = "enum-reg-mythical"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + JSONArray ja = new JSONArray(); + + for (String i : Iris.linkMythicMobs.getMythicMobTypes()) { + ja.put(i); + } + + j.put("enum", ja); + definitions.put(key, j); + } + + JSONObject items = new JSONObject(); + items.put("$ref", "#/definitions/" + key); + prop.put("items", items); + description.add(SYMBOL_TYPE__N + " Must be a valid Mythic Mob Type (use ctrl+space for auto complete!) Configure mob types in the mythic mobs plugin configuration files."); + } else if (k.isAnnotationPresent(RegistryListBlockType.class)) { + fancyType = "List of Block Types"; + String key = "enum-block-type"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + JSONArray ja = new JSONArray(); + + for (String i : data.getBlockLoader().getPossibleKeys()) { + ja.put(i); + } + + for (String i : B.getBlockTypes()) { + ja.put(i); + } + + j.put("enum", ja); + definitions.put(key, j); + } + + JSONObject items = new JSONObject(); + items.put("$ref", "#/definitions/" + key); + prop.put("items", items); + description.add(SYMBOL_TYPE__N + " Must be a valid Block Type (use ctrl+space for auto complete!)"); + } else if (k.isAnnotationPresent(RegistryListItemType.class)) { + fancyType = "List of Item Types"; + String key = "enum-item-type"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", ITEM_TYPES); + definitions.put(key, j); + } + + JSONObject items = new JSONObject(); + items.put("$ref", "#/definitions/" + key); + prop.put("items", items); + description.add(SYMBOL_TYPE__N + " Must be a valid Item Type (use ctrl+space for auto complete!)"); + } else if (k.isAnnotationPresent(RegistryListEntity.class)) { + fancyType = "List of Iris Entities"; + String key = "enum-reg-entity"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", new JSONArray(data.getEntityLoader().getPossibleKeys())); + definitions.put(key, j); + } + + JSONObject items = new JSONObject(); + items.put("$ref", "#/definitions/" + key); + prop.put("items", items); + description.add(SYMBOL_TYPE__N + " Must be a valid Iris Entity (use ctrl+space for auto complete!)"); + } else if (k.isAnnotationPresent(RegistryListFont.class)) { + String key = "enum-font"; + fancyType = "List of Font Families"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", FONT_TYPES); + definitions.put(key, j); + } + + JSONObject items = new JSONObject(); + items.put("$ref", "#/definitions/" + key); + prop.put("items", items); + description.add(SYMBOL_TYPE__N + " Must be a valid Font Family (use ctrl+space for auto complete!)"); + } else if (k.isAnnotationPresent(RegistryListLoot.class)) { + fancyType = "List of Iris Loot Tables"; + String key = "enum-reg-loot-table"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", new JSONArray(data.getLootLoader().getPossibleKeys())); + definitions.put(key, j); + } + + JSONObject items = new JSONObject(); + items.put("$ref", "#/definitions/" + key); + prop.put("items", items); + description.add(SYMBOL_TYPE__N + " Must be a valid Loot Table (use ctrl+space for auto complete!)"); + } else if (k.isAnnotationPresent(RegistryListDimension.class)) { + fancyType = "List of Iris Dimensions"; + String key = "enum-reg-dimension"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", new JSONArray(data.getDimensionLoader().getPossibleKeys())); + definitions.put(key, j); + } + + JSONObject items = new JSONObject(); + items.put("$ref", "#/definitions/" + key); + prop.put("items", items); + description.add(SYMBOL_TYPE__N + " Must be a valid Dimension (use ctrl+space for auto complete!)"); + } else if (k.isAnnotationPresent(RegistryListGenerator.class)) { + fancyType = "List of Iris Generators"; + String key = "enum-reg-generator"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", new JSONArray(data.getGeneratorLoader().getPossibleKeys())); + definitions.put(key, j); + } + + JSONObject items = new JSONObject(); + items.put("$ref", "#/definitions/" + key); + prop.put("items", items); + description.add(SYMBOL_TYPE__N + " Must be a valid Generator (use ctrl+space for auto complete!)"); + } else if (k.isAnnotationPresent(RegistryListObject.class)) { + fancyType = "List of Iris Objects"; + String key = "enum-reg-object"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", new JSONArray(data.getObjectLoader().getPossibleKeys())); + definitions.put(key, j); + } + + JSONObject items = new JSONObject(); + items.put("$ref", "#/definitions/" + key); + prop.put("items", items); + description.add(SYMBOL_TYPE__N + " Must be a valid Object (use ctrl+space for auto complete!)"); + } else if (k.isAnnotationPresent(RegistryListRegion.class)) { + fancyType = "List of Iris Regions"; + String key = "enum-reg-region"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", new JSONArray(data.getRegionLoader().getPossibleKeys())); + definitions.put(key, j); + } + + JSONObject items = new JSONObject(); + items.put("$ref", "#/definitions/" + key); + prop.put("items", items); + description.add(SYMBOL_TYPE__N + " Must be a valid Region (use ctrl+space for auto complete!)"); + } else if (k.isAnnotationPresent(RegistryListJigsawPiece.class)) { + fancyType = "List of Iris Jigsaw Pieces"; + String key = "enum-reg-structure-piece"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", new JSONArray(data.getJigsawPieceLoader().getPossibleKeys())); + definitions.put(key, j); + } + + JSONObject items = new JSONObject(); + items.put("$ref", "#/definitions/" + key); + prop.put("items", items); + description.add(SYMBOL_TYPE__N + " Must be a valid Jigsaw Piece (use ctrl+space for auto complete!)"); + } else if (k.isAnnotationPresent(RegistryListJigsawPool.class)) { + fancyType = "List of Iris Jigsaw Pools"; + String key = "enum-reg-structure-pool"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", new JSONArray(data.getJigsawPoolLoader().getPossibleKeys())); + definitions.put(key, j); + } + + JSONObject items = new JSONObject(); + items.put("$ref", "#/definitions/" + key); + prop.put("items", items); + description.add(SYMBOL_TYPE__N + " Must be a valid Jigsaw Pool (use ctrl+space for auto complete!)"); + } else if (k.isAnnotationPresent(RegistryListJigsaw.class)) { + fancyType = "List of Iris Jigsaw Structures"; + String key = "enum-reg-jigsaw"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", new JSONArray(data.getJigsawStructureLoader().getPossibleKeys())); + definitions.put(key, j); + } + + JSONObject items = new JSONObject(); + items.put("$ref", "#/definitions/" + key); + prop.put("items", items); + description.add(SYMBOL_TYPE__N + " Must be a valid Jigsaw (use ctrl+space for auto complete!)"); + } else if (t.type().equals(Enchantment.class)) { + fancyType = "List of Enchantment Types"; + String key = "enum-enchantment"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", ENCHANT_TYPES); + definitions.put(key, j); + } + + JSONObject items = new JSONObject(); + items.put("$ref", "#/definitions/" + key); + prop.put("items", items); + description.add(SYMBOL_TYPE__N + " Must be a valid Enchantment Type (use ctrl+space for auto complete!)"); + } else if (t.type().equals(PotionEffectType.class)) { + fancyType = "List of Potion Effect Types"; + String key = "enum-potion-effect-type"; + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put("enum", POTION_TYPES); + definitions.put(key, j); + } + + JSONObject items = new JSONObject(); + items.put("$ref", "#/definitions/" + key); + prop.put("items", items); + description.add(SYMBOL_TYPE__N + " Must be a valid Potion Effect Type (use ctrl+space for auto complete!)"); + } else if (t.type().isEnum()) { + fancyType = "List of " + t.type().getSimpleName().replaceAll("\\QIris\\E", "") + "s"; + JSONArray a = new JSONArray(); + boolean advanced = t.type().isAnnotationPresent(Desc.class); + for (Object gg : t.type().getEnumConstants()) { + if (advanced) { + try { + JSONObject j = new JSONObject(); + String name = ((Enum) gg).name(); + j.put("const", name); + Desc dd = t.type().getField(name).getAnnotation(Desc.class); + j.put("description", dd == null ? ("No Description for " + name) : dd.value()); + a.put(j); + } catch (Throwable e) { + e.printStackTrace(); + } + } else { + a.put(((Enum) gg).name()); + } + } + + String key = (advanced ? "oneof-" : "") + "enum-" + t.type().getCanonicalName().replaceAll("\\Q.\\E", "-").toLowerCase(); + + if (!definitions.containsKey(key)) { + JSONObject j = new JSONObject(); + j.put(advanced ? "oneOf" : "enum", a); + definitions.put(key, j); + } + + JSONObject items = new JSONObject(); + items.put("$ref", "#/definitions/" + key); + prop.put("items", items); + description.add(SYMBOL_TYPE__N + " Must be a valid " + t.type().getSimpleName().replaceAll("\\QIris\\E", "") + " (use ctrl+space for auto complete!)"); + } + } + } else { + warnings.add("Undefined array type for field " + k.getName() + " (" + k.getType().getSimpleName() + ") in class " + cl.getSimpleName()); + } + } else { + warnings.add("Unexpected Schema Type: " + type + " for field " + k.getName() + " (" + k.getType().getSimpleName() + ") in class " + cl.getSimpleName()); + } + + KList d = new KList<>(); + d.add(k.getName()); + d.add(getFieldDescription(k)); + d.add(" "); + d.add(fancyType); + d.add(getDescription(k.getType())); + + try { + k.setAccessible(true); + Object value = k.get(cl.newInstance()); + + if (value != null) { + if (value instanceof List) { + d.add("* Default Value is an empty list"); + } else if (!cl.isPrimitive() && !(value instanceof Number) && !(value instanceof String) && !(cl.isEnum())) { + d.add("* Default Value is a default object (create this object to see default properties)"); + } else { + d.add("* Default Value is " + value); + } + } + } catch (Throwable e) { + + } + + description.forEach((g) -> d.add(g.trim())); + prop.put("type", type); + prop.put("description", d.toString("\n")); + + return prop; + } + + private String getType(Class c) { + if (c.equals(int.class) || c.equals(Integer.class) || c.equals(long.class)) { + return "integer"; + } + + if (c.equals(float.class) || c.equals(double.class)) { + return "number"; + } + + if (c.equals(boolean.class)) { + return "boolean"; + } + + if (c.equals(String.class) || c.isEnum() || c.equals(Enchantment.class) || c.equals(PotionEffectType.class)) { + return "string"; + } + + if (c.equals(KList.class)) { + return "array"; + } + + if (c.equals(KMap.class)) { + return "object"; + } + + if (!c.isAnnotationPresent(Desc.class)) { + warnings.addIfMissing("Unsupported Type: " + c.getCanonicalName() + " Did you forget @Desc?"); + } + + return "object"; + } + + private String getFieldDescription(Field r) { + if (r.isAnnotationPresent(Desc.class)) { + return r.getDeclaredAnnotation(Desc.class).value(); + } + + warnings.addIfMissing("Missing @Desc on field " + r.getName() + " (" + r.getType() + ")"); + return "No Field Description"; + } + + private String getDescription(Class r) { + if (r.isAnnotationPresent(Desc.class)) { + return r.getDeclaredAnnotation(Desc.class).value(); + } + + if (!r.isPrimitive() && !r.equals(KList.class) && !r.equals(KMap.class) && r.getCanonicalName().startsWith("com.volmit.")) { + warnings.addIfMissing("Missing @Desc on " + r.getSimpleName()); + } + return ""; + } + + private static JSONArray getEnchantmentTypes() { + JSONArray a = new JSONArray(); + + for (Field gg : Enchantment.class.getDeclaredFields()) { + a.put(gg.getName()); + } + + return a; + } + + private static JSONArray getPotionTypes() { + JSONArray a = new JSONArray(); + + for (PotionEffectType gg : PotionEffectType.values()) { + a.put(gg.getName().toUpperCase().replaceAll("\\Q \\E", "_")); + } + + return a; + } } diff --git a/src/main/java/com/volmit/iris/manager/WandManager.java b/src/main/java/com/volmit/iris/manager/WandManager.java index d99cafb8f..9b1f67c76 100644 --- a/src/main/java/com/volmit/iris/manager/WandManager.java +++ b/src/main/java/com/volmit/iris/manager/WandManager.java @@ -23,312 +23,252 @@ import java.util.Objects; public class WandManager implements Listener { - private static ItemStack wand; - private static ItemStack dust; + private static ItemStack wand; + private static ItemStack dust; - public WandManager() - { - wand = createWand(); - dust = createDust(); - Bukkit.getScheduler().scheduleSyncRepeatingTask(Iris.instance, () -> - { - for(Player i : Bukkit.getOnlinePlayers()) - { - tick(i); - } - }, 0, 5); - } + public WandManager() { + wand = createWand(); + dust = createDust(); + Bukkit.getScheduler().scheduleSyncRepeatingTask(Iris.instance, () -> + { + for (Player i : Bukkit.getOnlinePlayers()) { + tick(i); + } + }, 0, 5); + } - public void tick(Player p) - { - try - { - if(isWand(p.getInventory().getItemInMainHand())) - { - Location[] d = getCuboid(p.getInventory().getItemInMainHand()); - draw(d, p); - } - } + public void tick(Player p) { + try { + if (isWand(p.getInventory().getItemInMainHand())) { + Location[] d = getCuboid(p.getInventory().getItemInMainHand()); + draw(d, p); + } + } catch (Throwable ignored) { - catch(Throwable ignored) - { + } + } - } - } + public void draw(Cuboid d, Player p) { + draw(new Location[]{d.getLowerNE(), d.getUpperSW()}, p); + } - public void draw(Cuboid d, Player p) - { - draw(new Location[] {d.getLowerNE(), d.getUpperSW()}, p); - } + public void draw(Location[] d, Player p) { + Vector gx = Vector.getRandom().subtract(Vector.getRandom()).normalize().clone().multiply(0.65); + d[0].getWorld().spawnParticle(Particle.CRIT_MAGIC, d[0], 1, 0.5 + gx.getX(), 0.5 + gx.getY(), 0.5 + gx.getZ(), 0, null, false); + Vector gxx = Vector.getRandom().subtract(Vector.getRandom()).normalize().clone().multiply(0.65); + d[1].getWorld().spawnParticle(Particle.CRIT, d[1], 1, 0.5 + gxx.getX(), 0.5 + gxx.getY(), 0.5 + gxx.getZ(), 0, null, false); - public void draw(Location[] d, Player p) - { - Vector gx = Vector.getRandom().subtract(Vector.getRandom()).normalize().clone().multiply(0.65); - d[0].getWorld().spawnParticle(Particle.CRIT_MAGIC, d[0], 1, 0.5 + gx.getX(), 0.5 + gx.getY(), 0.5 + gx.getZ(), 0, null, false); - Vector gxx = Vector.getRandom().subtract(Vector.getRandom()).normalize().clone().multiply(0.65); - d[1].getWorld().spawnParticle(Particle.CRIT, d[1], 1, 0.5 + gxx.getX(), 0.5 + gxx.getY(), 0.5 + gxx.getZ(), 0, null, false); + if (!d[0].getWorld().equals(d[1].getWorld())) { + return; + } - if(!d[0].getWorld().equals(d[1].getWorld())) - { - return; - } + if (d[0].distanceSquared(d[1]) > 64 * 64) { + return; + } - if(d[0].distanceSquared(d[1]) > 64 * 64) - { - return; - } + int minx = Math.min(d[0].getBlockX(), d[1].getBlockX()); + int miny = Math.min(d[0].getBlockY(), d[1].getBlockY()); + int minz = Math.min(d[0].getBlockZ(), d[1].getBlockZ()); + int maxx = Math.max(d[0].getBlockX(), d[1].getBlockX()); + int maxy = Math.max(d[0].getBlockY(), d[1].getBlockY()); + int maxz = Math.max(d[0].getBlockZ(), d[1].getBlockZ()); - int minx = Math.min(d[0].getBlockX(), d[1].getBlockX()); - int miny = Math.min(d[0].getBlockY(), d[1].getBlockY()); - int minz = Math.min(d[0].getBlockZ(), d[1].getBlockZ()); - int maxx = Math.max(d[0].getBlockX(), d[1].getBlockX()); - int maxy = Math.max(d[0].getBlockY(), d[1].getBlockY()); - int maxz = Math.max(d[0].getBlockZ(), d[1].getBlockZ()); + for (double j = minx - 1; j < maxx + 1; j += 0.25) { + for (double k = miny - 1; k < maxy + 1; k += 0.25) { + for (double l = minz - 1; l < maxz + 1; l += 0.25) { + if (M.r(0.2)) { + boolean jj = j == minx || j == maxx; + boolean kk = k == miny || k == maxy; + boolean ll = l == minz || l == maxz; - for(double j = minx - 1; j < maxx + 1; j += 0.25) - { - for(double k = miny - 1; k < maxy + 1; k += 0.25) - { - for(double l = minz - 1; l < maxz + 1; l += 0.25) - { - if(M.r(0.2)) - { - boolean jj = j == minx || j == maxx; - boolean kk = k == miny || k == maxy; - boolean ll = l == minz || l == maxz; + if ((jj && kk) || (jj && ll) || (ll && kk)) { + Vector push = new Vector(0, 0, 0); - if((jj && kk) || (jj && ll) || (ll && kk)) - { - Vector push = new Vector(0, 0, 0); + if (j == minx) { + push.add(new Vector(-0.55, 0, 0)); + } - if(j == minx) - { - push.add(new Vector(-0.55, 0, 0)); - } + if (k == miny) { + push.add(new Vector(0, -0.55, 0)); + } - if(k == miny) - { - push.add(new Vector(0, -0.55, 0)); - } + if (l == minz) { + push.add(new Vector(0, 0, -0.55)); + } - if(l == minz) - { - push.add(new Vector(0, 0, -0.55)); - } + if (j == maxx) { + push.add(new Vector(0.55, 0, 0)); + } - if(j == maxx) - { - push.add(new Vector(0.55, 0, 0)); - } + if (k == maxy) { + push.add(new Vector(0, 0.55, 0)); + } - if(k == maxy) - { - push.add(new Vector(0, 0.55, 0)); - } + if (l == maxz) { + push.add(new Vector(0, 0, 0.55)); + } - if(l == maxz) - { - push.add(new Vector(0, 0, 0.55)); - } + Location lv = new Location(d[0].getWorld(), j, k, l).clone().add(0.5, 0.5, 0.5).clone().add(push); + Color color = Color.getHSBColor((float) (0.5f + (Math.sin((j + k + l + (p.getTicksLived() / 2)) / 20f) / 2)), 1, 1); + int r = color.getRed(); + int g = color.getGreen(); + int b = color.getBlue(); + p.spawnParticle(Particle.REDSTONE, lv.getX(), lv.getY(), lv.getZ(), 1, 0, 0, 0, 0, new Particle.DustOptions(org.bukkit.Color.fromRGB(r, g, b), 0.75f)); + } + } + } + } + } + } - Location lv = new Location(d[0].getWorld(), j, k, l).clone().add(0.5, 0.5, 0.5).clone().add(push); - Color color = Color.getHSBColor((float) (0.5f + (Math.sin((j + k + l + (p.getTicksLived() / 2)) / 20f) / 2)), 1, 1); - int r = color.getRed(); - int g = color.getGreen(); - int b = color.getBlue(); - p.spawnParticle(Particle.REDSTONE, lv.getX(), lv.getY(), lv.getZ(), 1, 0, 0, 0, 0, new Particle.DustOptions(org.bukkit.Color.fromRGB(r, g, b), 0.75f)); - } - } - } - } - } - } + @EventHandler + public void on(PlayerInteractEvent e) { + try { + if (isWand(e.getPlayer())) { + if (e.getAction().equals(Action.LEFT_CLICK_BLOCK)) { + e.setCancelled(true); + e.getPlayer().getInventory().setItemInMainHand(update(true, Objects.requireNonNull(e.getClickedBlock()).getLocation(), e.getPlayer().getInventory().getItemInMainHand())); + e.getPlayer().playSound(e.getClickedBlock().getLocation(), Sound.BLOCK_END_PORTAL_FRAME_FILL, 1f, 0.67f); + e.getPlayer().updateInventory(); + } else if (e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { + e.setCancelled(true); + e.getPlayer().getInventory().setItemInMainHand(update(false, Objects.requireNonNull(e.getClickedBlock()).getLocation(), e.getPlayer().getInventory().getItemInMainHand())); + e.getPlayer().playSound(e.getClickedBlock().getLocation(), Sound.BLOCK_END_PORTAL_FRAME_FILL, 1f, 1.17f); + e.getPlayer().updateInventory(); + } + } - @EventHandler - public void on(PlayerInteractEvent e) - { - try - { - if(isWand(e.getPlayer())) - { - if(e.getAction().equals(Action.LEFT_CLICK_BLOCK)) - { - e.setCancelled(true); - e.getPlayer().getInventory().setItemInMainHand(update(true, Objects.requireNonNull(e.getClickedBlock()).getLocation(), e.getPlayer().getInventory().getItemInMainHand())); - e.getPlayer().playSound(e.getClickedBlock().getLocation(), Sound.BLOCK_END_PORTAL_FRAME_FILL, 1f, 0.67f); - e.getPlayer().updateInventory(); - } + if (isDust(e.getPlayer())) { + if (e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { + e.setCancelled(true); + e.getPlayer().playSound(Objects.requireNonNull(e.getClickedBlock()).getLocation(), Sound.ENTITY_ENDER_EYE_DEATH, 2f, 1.97f); + DustRevealer.spawn(e.getClickedBlock(), new MortarSender(e.getPlayer(), Iris.instance.getTag())); - else if(e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) - { - e.setCancelled(true); - e.getPlayer().getInventory().setItemInMainHand(update(false, Objects.requireNonNull(e.getClickedBlock()).getLocation(), e.getPlayer().getInventory().getItemInMainHand())); - e.getPlayer().playSound(e.getClickedBlock().getLocation(), Sound.BLOCK_END_PORTAL_FRAME_FILL, 1f, 1.17f); - e.getPlayer().updateInventory(); - } - } + } + } + } catch (Throwable ignored) { - if(isDust(e.getPlayer())) - { - if(e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) - { - e.setCancelled(true); - e.getPlayer().playSound(Objects.requireNonNull(e.getClickedBlock()).getLocation(), Sound.ENTITY_ENDER_EYE_DEATH, 2f, 1.97f); - DustRevealer.spawn(e.getClickedBlock(), new MortarSender(e.getPlayer(), Iris.instance.getTag())); + } + } - } - } - } + public static void pasteSchematic(IrisObject s, Location at) { + s.place(at); + } - catch(Throwable ignored) - { + public static IrisObject createSchematic(ItemStack wand) { + if (!isWand(wand)) { + return null; + } - } - } + try { + Location[] f = getCuboid(wand); + Cuboid c = new Cuboid(f[0], f[1]); + IrisObject s = new IrisObject(c.getSizeX(), c.getSizeY(), c.getSizeZ()); + for (Block b : c) { + if (b.getType().equals(Material.AIR)) { + continue; + } - public static void pasteSchematic(IrisObject s, Location at) - { - s.place(at); - } + BlockVector bv = b.getLocation().subtract(c.getLowerNE().toVector()).toVector().toBlockVector(); + s.setUnsigned(bv.getBlockX(), bv.getBlockY(), bv.getBlockZ(), b); + } - public static IrisObject createSchematic(ItemStack wand) - { - if(!isWand(wand)) - { - return null; - } + return s; + } catch (Throwable e) { + e.printStackTrace(); + } - try - { - Location[] f = getCuboid(wand); - Cuboid c = new Cuboid(f[0], f[1]); - IrisObject s = new IrisObject(c.getSizeX(), c.getSizeY(), c.getSizeZ()); - for (Block b : c) { - if (b.getType().equals(Material.AIR)) { - continue; - } + return null; + } - BlockVector bv = b.getLocation().subtract(c.getLowerNE().toVector()).toVector().toBlockVector(); - s.setUnsigned(bv.getBlockX(), bv.getBlockY(), bv.getBlockZ(), b); - } + public static Location stringToLocation(String s) { + try { + String[] f = s.split("\\Q in \\E"); + String[] g = f[0].split("\\Q,\\E"); + return new Location(Bukkit.getWorld(f[1]), Integer.parseInt(g[0]), Integer.parseInt(g[1]), Integer.parseInt(g[2])); + } catch (Throwable e) { + return null; + } + } - return s; - } + public static String locationToString(Location s) { + if (s == null) { + return "<#>"; + } - catch(Throwable e) - { - e.printStackTrace(); - } + return s.getBlockX() + "," + s.getBlockY() + "," + s.getBlockZ() + " in " + s.getWorld().getName(); + } - return null; - } + public static ItemStack createWand() { + return createWand(null, null); + } - public static Location stringToLocation(String s) - { - try - { - String[] f = s.split("\\Q in \\E"); - String[] g = f[0].split("\\Q,\\E"); - return new Location(Bukkit.getWorld(f[1]), Integer.parseInt(g[0]), Integer.parseInt(g[1]), Integer.parseInt(g[2])); - } + public static ItemStack createDust() { + ItemStack is = new ItemStack(Material.GLOWSTONE_DUST); + is.addUnsafeEnchantment(Enchantment.ARROW_INFINITE, 1); + ItemMeta im = is.getItemMeta(); + im.setDisplayName(C.BOLD + "" + C.YELLOW + "Dust of Revealing"); + im.setUnbreakable(true); + im.addItemFlags(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_PLACED_ON, ItemFlag.HIDE_POTION_EFFECTS, ItemFlag.HIDE_DESTROYS, ItemFlag.HIDE_ENCHANTS); + im.setLore(new KList().qadd("Right click on a block to reveal it's placement structure!")); + is.setItemMeta(im); - catch(Throwable e) - { - return null; - } - } + return is; + } - public static String locationToString(Location s) - { - if(s == null) - { - return "<#>"; - } + public boolean isDust(Player p) { + ItemStack is = p.getInventory().getItemInMainHand(); + return is != null && isDust(is); + } - return s.getBlockX() + "," + s.getBlockY() + "," + s.getBlockZ() + " in " + s.getWorld().getName(); - } + public boolean isDust(ItemStack is) { + return is.equals(dust); + } - public static ItemStack createWand() - { - return createWand(null, null); - } + public ItemStack update(boolean left, Location a, ItemStack item) { + if (!isWand(item)) { + return item; + } - public static ItemStack createDust() - { - ItemStack is = new ItemStack(Material.GLOWSTONE_DUST); - is.addUnsafeEnchantment(Enchantment.ARROW_INFINITE, 1); - ItemMeta im = is.getItemMeta(); - im.setDisplayName(C.BOLD + "" + C.YELLOW + "Dust of Revealing"); - im.setUnbreakable(true); - im.addItemFlags(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_PLACED_ON, ItemFlag.HIDE_POTION_EFFECTS, ItemFlag.HIDE_DESTROYS, ItemFlag.HIDE_ENCHANTS); - im.setLore(new KList().qadd("Right click on a block to reveal it's placement structure!")); - is.setItemMeta(im); + Location[] f = getCuboid(item); + Location other = left ? f[1] : f[0]; - return is; - } + if (other != null && !other.getWorld().getName().equals(a.getWorld().getName())) { + other = null; + } - public boolean isDust(Player p) - { - ItemStack is = p.getInventory().getItemInMainHand(); - return is != null && isDust(is); - } + return createWand(left ? a : other, left ? other : a); + } - public boolean isDust(ItemStack is) - { - return is.equals(dust); - } + public static ItemStack createWand(Location a, Location b) { + ItemStack is = new ItemStack(Material.BLAZE_ROD); + is.addUnsafeEnchantment(Enchantment.ARROW_INFINITE, 1); + ItemMeta im = is.getItemMeta(); + im.setDisplayName(C.BOLD + "" + C.GOLD + "Wand of Iris"); + im.setUnbreakable(true); + im.addItemFlags(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_PLACED_ON, ItemFlag.HIDE_POTION_EFFECTS, ItemFlag.HIDE_DESTROYS, ItemFlag.HIDE_ENCHANTS); + im.setLore(new KList().add(locationToString(a), locationToString(b))); + is.setItemMeta(im); - public ItemStack update(boolean left, Location a, ItemStack item) - { - if(!isWand(item)) - { - return item; - } + return is; + } - Location[] f = getCuboid(item); - Location other = left ? f[1] : f[0]; + public static Location[] getCuboid(ItemStack is) { + ItemMeta im = is.getItemMeta(); + return new Location[]{stringToLocation(im.getLore().get(0)), stringToLocation(im.getLore().get(1))}; + } - if(other != null && !other.getWorld().getName().equals(a.getWorld().getName())) - { - other = null; - } + public static boolean isWand(Player p) { + ItemStack is = p.getInventory().getItemInMainHand(); + return is != null && isWand(is); + } - return createWand(left ? a : other, left ? other : a); - } - - public static ItemStack createWand(Location a, Location b) - { - ItemStack is = new ItemStack(Material.BLAZE_ROD); - is.addUnsafeEnchantment(Enchantment.ARROW_INFINITE, 1); - ItemMeta im = is.getItemMeta(); - im.setDisplayName(C.BOLD + "" + C.GOLD + "Wand of Iris"); - im.setUnbreakable(true); - im.addItemFlags(ItemFlag.HIDE_ATTRIBUTES, ItemFlag.HIDE_PLACED_ON, ItemFlag.HIDE_POTION_EFFECTS, ItemFlag.HIDE_DESTROYS, ItemFlag.HIDE_ENCHANTS); - im.setLore(new KList().add(locationToString(a), locationToString(b))); - is.setItemMeta(im); - - return is; - } - - public static Location[] getCuboid(ItemStack is) - { - ItemMeta im = is.getItemMeta(); - return new Location[] {stringToLocation(im.getLore().get(0)), stringToLocation(im.getLore().get(1))}; - } - - public static boolean isWand(Player p) - { - ItemStack is = p.getInventory().getItemInMainHand(); - return is != null && isWand(is); - } - - public static boolean isWand(ItemStack is) - { - ItemStack wand = createWand(); - if (is.getItemMeta() == null) return false; - return is.getType().equals(wand.getType()) && - is.getItemMeta().getDisplayName().equals(wand.getItemMeta().getDisplayName()) && - is.getItemMeta().getEnchants().equals(wand.getItemMeta().getEnchants()) && - is.getItemMeta().getItemFlags().equals(wand.getItemMeta().getItemFlags()); - } + public static boolean isWand(ItemStack is) { + ItemStack wand = createWand(); + if (is.getItemMeta() == null) return false; + return is.getType().equals(wand.getType()) && + is.getItemMeta().getDisplayName().equals(wand.getItemMeta().getDisplayName()) && + is.getItemMeta().getEnchants().equals(wand.getItemMeta().getEnchants()) && + is.getItemMeta().getItemFlags().equals(wand.getItemMeta().getItemFlags()); + } } diff --git a/src/main/java/com/volmit/iris/manager/command/CommandIris.java b/src/main/java/com/volmit/iris/manager/command/CommandIris.java index d75111b80..0be3616df 100644 --- a/src/main/java/com/volmit/iris/manager/command/CommandIris.java +++ b/src/main/java/com/volmit/iris/manager/command/CommandIris.java @@ -11,69 +11,65 @@ import com.volmit.iris.util.KList; import com.volmit.iris.util.MortarCommand; import com.volmit.iris.util.MortarSender; -public class CommandIris extends MortarCommand -{ - @Command - private CommandIrisCreate create; +public class CommandIris extends MortarCommand { + @Command + private CommandIrisCreate create; - @Command - private CommandIrisFix fix; + @Command + private CommandIrisFix fix; - @Command - private CommandIrisStudio studio; + @Command + private CommandIrisStudio studio; - @Command - private CommandIrisJigsaw jigsaw; + @Command + private CommandIrisJigsaw jigsaw; - @Command - private CommandIrisObject object; + @Command + private CommandIrisObject object; - @Command - private CommandIrisRegen regen; + @Command + private CommandIrisRegen regen; - @Command - private CommandIrisDownload download; + @Command + private CommandIrisDownload download; - @Command - private CommandIrisUpdateProject updateProject; + @Command + private CommandIrisUpdateProject updateProject; - @Command - private CommandIrisUpdateWorld updateWorld; + @Command + private CommandIrisUpdateWorld updateWorld; - @Command - private CommandIrisWhat what; + @Command + private CommandIrisWhat what; - @Command - private CommandIrisMetrics metrics; + @Command + private CommandIrisMetrics metrics; - @Command - private CommandIrisPregen pregen; + @Command + private CommandIrisPregen pregen; - @Command - private CommandIrisReload reload; + @Command + private CommandIrisReload reload; - public CommandIris() - { - super("iris", "ir", "irs"); - requiresPermission(Iris.perm); - } + public CommandIris() { + super("iris", "ir", "irs"); + requiresPermission(Iris.perm); + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - sender.sendMessage("Iris v" + Iris.instance.getDescription().getVersion() + " by Volmit Software"); - printHelp(sender); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + sender.sendMessage("Iris v" + Iris.instance.getDescription().getVersion() + " by Volmit Software"); + printHelp(sender); + return true; + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - protected String getArgsUsage() - { - return ""; - } + @Override + protected String getArgsUsage() { + return ""; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/CommandIrisDownload.java b/src/main/java/com/volmit/iris/manager/command/CommandIrisDownload.java index d23cf284f..5a6a46e18 100644 --- a/src/main/java/com/volmit/iris/manager/command/CommandIrisDownload.java +++ b/src/main/java/com/volmit/iris/manager/command/CommandIrisDownload.java @@ -3,50 +3,44 @@ package com.volmit.iris.manager.command; import com.volmit.iris.Iris; import com.volmit.iris.util.*; -public class CommandIrisDownload extends MortarCommand -{ - public CommandIrisDownload() - { - super("download", "down", "dl"); - requiresPermission(Iris.perm.studio); - setDescription("Download a project."); - setCategory("Studio"); - } +public class CommandIrisDownload extends MortarCommand { + public CommandIrisDownload() { + super("download", "down", "dl"); + requiresPermission(Iris.perm.studio); + setDescription("Download a project."); + setCategory("Studio"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(args.length < 1) - { - sender.sendMessage("/iris dl " + C.BOLD + ""); - return true; - } + } - boolean trim = false; + @Override + public boolean handle(MortarSender sender, String[] args) { + if (args.length < 1) { + sender.sendMessage("/iris dl " + C.BOLD + ""); + return true; + } - for(String i : args) - { - if(i.equals("-t") || i.equals("--trim")) - { - trim = true; - } - } + boolean trim = false; - boolean btrim = trim; + for (String i : args) { + if (i.equals("-t") || i.equals("--trim")) { + trim = true; + } + } - J.a(() -> Iris.proj.downloadSearch(sender, args[0], btrim)); + boolean btrim = trim; - return true; - } + J.a(() -> Iris.proj.downloadSearch(sender, args[0], btrim)); - @Override - protected String getArgsUsage() - { - return " [-t/--trim]"; - } + return true; + } + + @Override + protected String getArgsUsage() { + return " [-t/--trim]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/CommandIrisMetrics.java b/src/main/java/com/volmit/iris/manager/command/CommandIrisMetrics.java index 148977616..44340e9c4 100644 --- a/src/main/java/com/volmit/iris/manager/command/CommandIrisMetrics.java +++ b/src/main/java/com/volmit/iris/manager/command/CommandIrisMetrics.java @@ -3,64 +3,54 @@ package com.volmit.iris.manager.command; import com.volmit.iris.Iris; import com.volmit.iris.scaffold.IrisWorlds; import com.volmit.iris.scaffold.engine.IrisAccess; -import com.volmit.iris.util.*; +import com.volmit.iris.util.KList; +import com.volmit.iris.util.MortarCommand; +import com.volmit.iris.util.MortarSender; import org.bukkit.World; import org.bukkit.entity.Player; -public class CommandIrisMetrics extends MortarCommand -{ - public CommandIrisMetrics() - { - super("metrics", "stats", "mt"); - setDescription("Get timings for this world"); - requiresPermission(Iris.perm.studio); - setCategory("Metrics"); - } +public class CommandIrisMetrics extends MortarCommand { + public CommandIrisMetrics() { + super("metrics", "stats", "mt"); + setDescription("Get timings for this world"); + requiresPermission(Iris.perm.studio); + setCategory("Metrics"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(sender.isPlayer()) - { - Player p = sender.player(); - World world = p.getWorld(); - if(!IrisWorlds.isIrisWorld(world)) - { - sender.sendMessage("You must be in an iris world."); - return true; - } + } - IrisAccess g = IrisWorlds.access(world); + @Override + public boolean handle(MortarSender sender, String[] args) { + if (sender.isPlayer()) { + Player p = sender.player(); + World world = p.getWorld(); + if (!IrisWorlds.isIrisWorld(world)) { + sender.sendMessage("You must be in an iris world."); + return true; + } - try - { - g.printMetrics(sender); - } + IrisAccess g = IrisWorlds.access(world); - catch(Throwable e) - { - sender.sendMessage("You must be in an iris world."); - } + try { + g.printMetrics(sender); + } catch (Throwable e) { + sender.sendMessage("You must be in an iris world."); + } - return true; - } + return true; + } else { + sender.sendMessage("Players only."); + } - else - { - sender.sendMessage("Players only."); - } + return true; + } - return true; - } - - @Override - protected String getArgsUsage() - { - return ""; - } + @Override + protected String getArgsUsage() { + return ""; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/CommandIrisReload.java b/src/main/java/com/volmit/iris/manager/command/CommandIrisReload.java index c657e922c..41f528a8f 100644 --- a/src/main/java/com/volmit/iris/manager/command/CommandIrisReload.java +++ b/src/main/java/com/volmit/iris/manager/command/CommandIrisReload.java @@ -6,33 +6,29 @@ import com.volmit.iris.util.KList; import com.volmit.iris.util.MortarCommand; import com.volmit.iris.util.MortarSender; -public class CommandIrisReload extends MortarCommand -{ - public CommandIrisReload() - { - super("reload", "rld"); - requiresPermission(Iris.perm.studio); - setDescription("Reload configs"); - setCategory("Studio"); - } +public class CommandIrisReload extends MortarCommand { + public CommandIrisReload() { + super("reload", "rld"); + requiresPermission(Iris.perm.studio); + setDescription("Reload configs"); + setCategory("Studio"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - IrisSettings.invalidate(); - IrisSettings.get(); - sender.sendMessage("settings.json Reloaded"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + IrisSettings.invalidate(); + IrisSettings.get(); + sender.sendMessage("settings.json Reloaded"); + return true; + } - @Override - protected String getArgsUsage() - { - return " [-t/--trim]"; - } + @Override + protected String getArgsUsage() { + return " [-t/--trim]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/CommandIrisUpdateProject.java b/src/main/java/com/volmit/iris/manager/command/CommandIrisUpdateProject.java index 463cb99f5..8280d8f9d 100644 --- a/src/main/java/com/volmit/iris/manager/command/CommandIrisUpdateProject.java +++ b/src/main/java/com/volmit/iris/manager/command/CommandIrisUpdateProject.java @@ -3,38 +3,33 @@ package com.volmit.iris.manager.command; import com.volmit.iris.Iris; import com.volmit.iris.util.*; -public class CommandIrisUpdateProject extends MortarCommand -{ - public CommandIrisUpdateProject() - { - super("update-project", "^project"); - requiresPermission(Iris.perm.studio); - setDescription("Update a project from git."); - setCategory("Studio"); - } +public class CommandIrisUpdateProject extends MortarCommand { + public CommandIrisUpdateProject() { + super("update-project", "^project"); + requiresPermission(Iris.perm.studio); + setDescription("Update a project from git."); + setCategory("Studio"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(args.length < 1) - { - sender.sendMessage("/iris update-project " + C.BOLD + ""); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (args.length < 1) { + sender.sendMessage("/iris update-project " + C.BOLD + ""); + return true; + } - J.a(() -> Iris.proj.downloadSearch(sender, args[0], false, true)); + J.a(() -> Iris.proj.downloadSearch(sender, args[0], false, true)); - return true; - } + return true; + } - @Override - protected String getArgsUsage() - { - return ""; - } + @Override + protected String getArgsUsage() { + return ""; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/PermissionIris.java b/src/main/java/com/volmit/iris/manager/command/PermissionIris.java index 94c7571c9..b47293ce3 100644 --- a/src/main/java/com/volmit/iris/manager/command/PermissionIris.java +++ b/src/main/java/com/volmit/iris/manager/command/PermissionIris.java @@ -3,31 +3,26 @@ package com.volmit.iris.manager.command; import com.volmit.iris.util.MortarPermission; import com.volmit.iris.util.Permission; -public class PermissionIris extends MortarPermission -{ - @Permission - public PermissionIrisStudio studio; - - public PermissionIris() - { - super(); - } +public class PermissionIris extends MortarPermission { + @Permission + public PermissionIrisStudio studio; - @Override - protected String getNode() - { - return "iris"; - } + public PermissionIris() { + super(); + } - @Override - public String getDescription() - { - return "Iris Permissions"; - } + @Override + protected String getNode() { + return "iris"; + } - @Override - public boolean isDefault() - { - return false; - } + @Override + public String getDescription() { + return "Iris Permissions"; + } + + @Override + public boolean isDefault() { + return false; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/PermissionIrisStudio.java b/src/main/java/com/volmit/iris/manager/command/PermissionIrisStudio.java index ecc0d912e..06754b91c 100644 --- a/src/main/java/com/volmit/iris/manager/command/PermissionIrisStudio.java +++ b/src/main/java/com/volmit/iris/manager/command/PermissionIrisStudio.java @@ -2,28 +2,23 @@ package com.volmit.iris.manager.command; import com.volmit.iris.util.MortarPermission; -public class PermissionIrisStudio extends MortarPermission -{ - public PermissionIrisStudio() - { - super(); - } +public class PermissionIrisStudio extends MortarPermission { + public PermissionIrisStudio() { + super(); + } - @Override - protected String getNode() - { - return "studio"; - } + @Override + protected String getNode() { + return "studio"; + } - @Override - public String getDescription() - { - return "Iris Studio Permissions"; - } + @Override + public String getDescription() { + return "Iris Studio Permissions"; + } - @Override - public boolean isDefault() - { - return false; - } + @Override + public boolean isDefault() { + return false; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsaw.java b/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsaw.java index 7af436388..e6e4d0e26 100644 --- a/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsaw.java +++ b/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsaw.java @@ -7,56 +7,50 @@ import com.volmit.iris.util.KList; import com.volmit.iris.util.MortarCommand; import com.volmit.iris.util.MortarSender; -public class CommandIrisJigsaw extends MortarCommand -{ - @Command - private CommandIrisJigsawNew create; +public class CommandIrisJigsaw extends MortarCommand { + @Command + private CommandIrisJigsawNew create; - @Command - private CommandIrisJigsawEdit edit; + @Command + private CommandIrisJigsawEdit edit; - @Command - private CommandIrisJigsawSave save; + @Command + private CommandIrisJigsawSave save; - @Command - private CommandIrisJigsawPlace place; + @Command + private CommandIrisJigsawPlace place; - public CommandIrisJigsaw() - { - super("jigsaw", "jig", "jsw", "j"); - requiresPermission(Iris.perm); - setCategory("Jigsaw"); - setDescription("Iris jigsaw commands"); - } + public CommandIrisJigsaw() { + super("jigsaw", "jig", "jsw", "j"); + requiresPermission(Iris.perm); + setCategory("Jigsaw"); + setDescription("Iris jigsaw commands"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio Jigsaw, please enable studio in Iris/settings.json"); - return true; - } - - if(!sender.isPlayer()) - { - sender.sendMessage("Ingame only"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio Jigsaw, please enable studio in Iris/settings.json"); + return true; + } - sender.sendMessage("Iris Jigsaw Commands:"); - printHelp(sender); - return true; - } + if (!sender.isPlayer()) { + sender.sendMessage("Ingame only"); + return true; + } - @Override - protected String getArgsUsage() - { - return ""; - } + sender.sendMessage("Iris Jigsaw Commands:"); + printHelp(sender); + return true; + } + + @Override + protected String getArgsUsage() { + return ""; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsawEdit.java b/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsawEdit.java index 2bcc14ca7..ff6390fe9 100644 --- a/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsawEdit.java +++ b/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsawEdit.java @@ -11,59 +11,51 @@ import com.volmit.iris.util.MortarSender; import java.io.File; -public class CommandIrisJigsawEdit extends MortarCommand -{ - public CommandIrisJigsawEdit() - { - super("edit", "e", "*"); - requiresPermission(Iris.perm); - setCategory("Jigsaw"); - setDescription("Edit an existing Jigsaw piece"); - } +public class CommandIrisJigsawEdit extends MortarCommand { + public CommandIrisJigsawEdit() { + super("edit", "e", "*"); + requiresPermission(Iris.perm); + setCategory("Jigsaw"); + setDescription("Edit an existing Jigsaw piece"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio Jigsaw, please enable studio in Iris/settings.json"); - return true; - } - - if(!sender.isPlayer()) - { - sender.sendMessage("Ingame only"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio Jigsaw, please enable studio in Iris/settings.json"); + return true; + } - if(args.length < 1) - { - sender.sendMessage(getArgsUsage()); - return true; - } + if (!sender.isPlayer()) { + sender.sendMessage("Ingame only"); + return true; + } - IrisJigsawPiece piece = IrisDataManager.loadAnyJigsawPiece(args[0]); + if (args.length < 1) { + sender.sendMessage(getArgsUsage()); + return true; + } - if(piece != null) - { - File dest = piece.getLoadFile(); - new JigsawEditor(sender.player(), piece, IrisDataManager.loadAnyObject(piece.getObject()), dest); - return true; - } + IrisJigsawPiece piece = IrisDataManager.loadAnyJigsawPiece(args[0]); - sender.sendMessage("Failed to find existing jigsaw piece: " + args[0]); + if (piece != null) { + File dest = piece.getLoadFile(); + new JigsawEditor(sender.player(), piece, IrisDataManager.loadAnyObject(piece.getObject()), dest); + return true; + } - return true; - } + sender.sendMessage("Failed to find existing jigsaw piece: " + args[0]); - @Override - protected String getArgsUsage() - { - return ""; - } + return true; + } + + @Override + protected String getArgsUsage() { + return ""; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsawExit.java b/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsawExit.java index 224a9b488..4ec791390 100644 --- a/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsawExit.java +++ b/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsawExit.java @@ -7,12 +7,8 @@ import com.volmit.iris.util.KList; import com.volmit.iris.util.MortarCommand; import com.volmit.iris.util.MortarSender; -import java.io.File; - -public class CommandIrisJigsawExit extends MortarCommand -{ - public CommandIrisJigsawExit() - { +public class CommandIrisJigsawExit extends MortarCommand { + public CommandIrisJigsawExit() { super("exit", "x", "close", "stop"); requiresPermission(Iris.perm); setCategory("Jigsaw"); @@ -25,24 +21,20 @@ public class CommandIrisJigsawExit extends MortarCommand } @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { sender.sendMessage("To use Iris Studio Jigsaw, please enable studio in Iris/settings.json"); return true; } - if(!sender.isPlayer()) - { + if (!sender.isPlayer()) { sender.sendMessage("Ingame only"); return true; } JigsawEditor editor = JigsawEditor.editors.get(sender.player()); - if(editor == null) - { + if (editor == null) { sender.sendMessage("You don't have any pieces open to close!"); return true; } @@ -52,8 +44,7 @@ public class CommandIrisJigsawExit extends MortarCommand } @Override - protected String getArgsUsage() - { + protected String getArgsUsage() { return ""; } } diff --git a/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsawNew.java b/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsawNew.java index 2de10ab53..7b4f99f47 100644 --- a/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsawNew.java +++ b/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsawNew.java @@ -11,61 +11,54 @@ import com.volmit.iris.util.MortarSender; import java.io.File; -public class CommandIrisJigsawNew extends MortarCommand -{ - public CommandIrisJigsawNew() - { - super("create", "new", "+", "n"); - requiresPermission(Iris.perm); - setCategory("Jigsaw"); - setDescription("Create a new jigsaw piece"); - } +public class CommandIrisJigsawNew extends MortarCommand { + public CommandIrisJigsawNew() { + super("create", "new", "+", "n"); + requiresPermission(Iris.perm); + setCategory("Jigsaw"); + setDescription("Create a new jigsaw piece"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio Jigsaw, please enable studio in Iris/settings.json"); - return true; - } - - if(!sender.isPlayer()) - { - sender.sendMessage("Ingame only"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio Jigsaw, please enable studio in Iris/settings.json"); + return true; + } - if(args.length != 3) - { - sender.sendMessage(getArgsUsage()); - return true; - } + if (!sender.isPlayer()) { + sender.sendMessage("Ingame only"); + return true; + } - IrisObject object = IrisDataManager.loadAnyObject(args[2]); + if (args.length != 3) { + sender.sendMessage(getArgsUsage()); + return true; + } - if (object == null) { - sender.sendMessage("Failed to find existing object: " + args[2]); - return true; - } + IrisObject object = IrisDataManager.loadAnyObject(args[2]); - File dest = Iris.instance.getDataFile("packs", args[1], "jigsaw-pieces", args[0] + ".json"); - new JigsawEditor(sender.player(), null, object, dest); - sender.sendMessage("* Right Click blocks to make them connectors"); - sender.sendMessage("* Right Click connectors to orient them"); - sender.sendMessage("* Shift + Right Click connectors to remove them"); - sender.sendMessage("Remember to use /iris jigsaw save"); - return true; - } + if (object == null) { + sender.sendMessage("Failed to find existing object: " + args[2]); + return true; + } - @Override - protected String getArgsUsage() - { - return " "; - } + File dest = Iris.instance.getDataFile("packs", args[1], "jigsaw-pieces", args[0] + ".json"); + new JigsawEditor(sender.player(), null, object, dest); + sender.sendMessage("* Right Click blocks to make them connectors"); + sender.sendMessage("* Right Click connectors to orient them"); + sender.sendMessage("* Shift + Right Click connectors to remove them"); + sender.sendMessage("Remember to use /iris jigsaw save"); + return true; + } + + @Override + protected String getArgsUsage() { + return " "; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsawPlace.java b/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsawPlace.java index 53ce2314b..a857bb062 100644 --- a/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsawPlace.java +++ b/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsawPlace.java @@ -8,57 +8,50 @@ import com.volmit.iris.object.IrisPosition; import com.volmit.iris.scaffold.jigsaw.PlannedStructure; import com.volmit.iris.util.*; -public class CommandIrisJigsawPlace extends MortarCommand -{ - public CommandIrisJigsawPlace() - { - super("place", "paste", "p"); - requiresPermission(Iris.perm); - setCategory("Jigsaw"); - setDescription("Place a jigsaw structure"); - } +public class CommandIrisJigsawPlace extends MortarCommand { + public CommandIrisJigsawPlace() { + super("place", "paste", "p"); + requiresPermission(Iris.perm); + setCategory("Jigsaw"); + setDescription("Place a jigsaw structure"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio Jigsaw, please enable studio in Iris/settings.json"); - return true; - } - - if(!sender.isPlayer()) - { - sender.sendMessage("Ingame only"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio Jigsaw, please enable studio in Iris/settings.json"); + return true; + } - if(args.length == 0){ - sender.sendMessage("You have to specify a jigsaw structure!"); - return true; - } + if (!sender.isPlayer()) { + sender.sendMessage("Ingame only"); + return true; + } - IrisJigsawStructure str = IrisDataManager.loadAnyJigsawStructure(args[0]); + if (args.length == 0) { + sender.sendMessage("You have to specify a jigsaw structure!"); + return true; + } - if(str != null) - { - PrecisionStopwatch p = PrecisionStopwatch.start(); - PlannedStructure ps = new PlannedStructure(str, new IrisPosition(sender.player().getLocation()), new RNG()); - sender.sendMessage("Generated " + ps.getPieces().size() + " pieces in " + Form.duration(p.getMilliseconds(), 2)); - ps.place(sender.player().getWorld()); - } + IrisJigsawStructure str = IrisDataManager.loadAnyJigsawStructure(args[0]); - return true; - } + if (str != null) { + PrecisionStopwatch p = PrecisionStopwatch.start(); + PlannedStructure ps = new PlannedStructure(str, new IrisPosition(sender.player().getLocation()), new RNG()); + sender.sendMessage("Generated " + ps.getPieces().size() + " pieces in " + Form.duration(p.getMilliseconds(), 2)); + ps.place(sender.player().getWorld()); + } - @Override - protected String getArgsUsage() - { - return ""; - } + return true; + } + + @Override + protected String getArgsUsage() { + return ""; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsawSave.java b/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsawSave.java index 6c3982cf8..bff3de7af 100644 --- a/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsawSave.java +++ b/src/main/java/com/volmit/iris/manager/command/jigsaw/CommandIrisJigsawSave.java @@ -7,51 +7,44 @@ import com.volmit.iris.util.KList; import com.volmit.iris.util.MortarCommand; import com.volmit.iris.util.MortarSender; -public class CommandIrisJigsawSave extends MortarCommand -{ - public CommandIrisJigsawSave() - { - super("save", "s"); - requiresPermission(Iris.perm); - setCategory("Jigsaw"); - setDescription("Save a currently open piece"); - } +public class CommandIrisJigsawSave extends MortarCommand { + public CommandIrisJigsawSave() { + super("save", "s"); + requiresPermission(Iris.perm); + setCategory("Jigsaw"); + setDescription("Save a currently open piece"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio Jigsaw, please enable studio in Iris/settings.json"); - return true; - } - - if(!sender.isPlayer()) - { - sender.sendMessage("Ingame only"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio Jigsaw, please enable studio in Iris/settings.json"); + return true; + } - JigsawEditor editor = JigsawEditor.editors.get(sender.player()); + if (!sender.isPlayer()) { + sender.sendMessage("Ingame only"); + return true; + } - if(editor == null) - { - sender.sendMessage("You don't have any pieces open to save!"); - return true; - } + JigsawEditor editor = JigsawEditor.editors.get(sender.player()); - editor.close(); - return true; - } + if (editor == null) { + sender.sendMessage("You don't have any pieces open to save!"); + return true; + } - @Override - protected String getArgsUsage() - { - return ""; - } + editor.close(); + return true; + } + + @Override + protected String getArgsUsage() { + return ""; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObject.java b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObject.java index 0042de0a0..b9c2c963d 100644 --- a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObject.java +++ b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObject.java @@ -7,71 +7,66 @@ import com.volmit.iris.util.KList; import com.volmit.iris.util.MortarCommand; import com.volmit.iris.util.MortarSender; -public class CommandIrisObject extends MortarCommand -{ - @Command - private CommandIrisObjectWand wand; +public class CommandIrisObject extends MortarCommand { + @Command + private CommandIrisObjectWand wand; - @Command - private CommandIrisObjectDust dust; + @Command + private CommandIrisObjectDust dust; - @Command - private CommandIrisObjectXPY xpy; + @Command + private CommandIrisObjectXPY xpy; - @Command - private CommandIrisObjectXAY xay; + @Command + private CommandIrisObjectXAY xay; - @Command - private CommandIrisObjectShift shift; + @Command + private CommandIrisObjectShift shift; - @Command - private CommandIrisObjectExpand expand; + @Command + private CommandIrisObjectExpand expand; - @Command - private CommandIrisObjectContract contract; + @Command + private CommandIrisObjectContract contract; - @Command - private CommandIrisObjectP1 p1; + @Command + private CommandIrisObjectP1 p1; - @Command - private CommandIrisObjectP2 p2; + @Command + private CommandIrisObjectP2 p2; - @Command - private CommandIrisObjectSave save; + @Command + private CommandIrisObjectSave save; - @Command - private CommandIrisObjectPaste paste; + @Command + private CommandIrisObjectPaste paste; - public CommandIrisObject() - { - super("object", "iob", "o", "obj"); - requiresPermission(Iris.perm); - setCategory("Object"); - setDescription("Object Commands"); - } + public CommandIrisObject() { + super("object", "iob", "o", "obj"); + requiresPermission(Iris.perm); + setCategory("Object"); + setDescription("Object Commands"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); - return true; - } - - sender.sendMessage("Iris Object Commands:"); - printHelp(sender); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); + return true; + } - @Override - protected String getArgsUsage() - { - return "[subcommand]"; - } + sender.sendMessage("Iris Object Commands:"); + printHelp(sender); + return true; + } + + @Override + protected String getArgsUsage() { + return "[subcommand]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectContract.java b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectContract.java index a0132cbdf..fdfa09c21 100644 --- a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectContract.java +++ b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectContract.java @@ -1,71 +1,64 @@ package com.volmit.iris.manager.command.object; +import com.volmit.iris.Iris; +import com.volmit.iris.IrisSettings; +import com.volmit.iris.manager.WandManager; import com.volmit.iris.util.*; import org.bukkit.Location; import org.bukkit.Sound; import org.bukkit.entity.Player; -import com.volmit.iris.Iris; -import com.volmit.iris.IrisSettings; -import com.volmit.iris.manager.WandManager; - -public class CommandIrisObjectContract extends MortarCommand -{ - public CommandIrisObjectContract() - { - super("-"); - requiresPermission(Iris.perm); - setCategory("Object"); - setDescription("Contract a selection based on your looking direction"); - } +public class CommandIrisObjectContract extends MortarCommand { + public CommandIrisObjectContract() { + super("-"); + requiresPermission(Iris.perm); + setCategory("Object"); + setDescription("Contract a selection based on your looking direction"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); - return true; - } - - if(!sender.isPlayer()) - { - sender.sendMessage("You don't have a wand"); - return true; - } + } - Player p = sender.player(); + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); + return true; + } - if(!WandManager.isWand(p)) - { - sender.sendMessage("Ready your Wand."); - return true; - } + if (!sender.isPlayer()) { + sender.sendMessage("You don't have a wand"); + return true; + } - int amt = args.length == 1 ? Integer.valueOf(args[0]) : 1; - Location[] b = WandManager.getCuboid(p.getInventory().getItemInMainHand()); - Location a1 = b[0].clone(); - Location a2 = b[1].clone(); - Cuboid cursor = new Cuboid(a1, a2); - Direction d = Direction.closest(p.getLocation().getDirection()).reverse(); - cursor = cursor.expand(d, -amt); - b[0] = cursor.getLowerNE(); - b[1] = cursor.getUpperSW(); - p.getInventory().setItemInMainHand(WandManager.createWand(b[0], b[1])); - p.updateInventory(); - p.playSound(p.getLocation(), Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 1f, 0.55f); + Player p = sender.player(); - return true; - } + if (!WandManager.isWand(p)) { + sender.sendMessage("Ready your Wand."); + return true; + } - @Override - protected String getArgsUsage() - { - return "[amt]"; - } + int amt = args.length == 1 ? Integer.valueOf(args[0]) : 1; + Location[] b = WandManager.getCuboid(p.getInventory().getItemInMainHand()); + Location a1 = b[0].clone(); + Location a2 = b[1].clone(); + Cuboid cursor = new Cuboid(a1, a2); + Direction d = Direction.closest(p.getLocation().getDirection()).reverse(); + cursor = cursor.expand(d, -amt); + b[0] = cursor.getLowerNE(); + b[1] = cursor.getUpperSW(); + p.getInventory().setItemInMainHand(WandManager.createWand(b[0], b[1])); + p.updateInventory(); + p.playSound(p.getLocation(), Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 1f, 0.55f); + + return true; + } + + @Override + protected String getArgsUsage() { + return "[amt]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectDust.java b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectDust.java index db41a7e8c..b36494922 100644 --- a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectDust.java +++ b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectDust.java @@ -8,45 +8,39 @@ import com.volmit.iris.util.MortarCommand; import com.volmit.iris.util.MortarSender; import org.bukkit.Sound; -public class CommandIrisObjectDust extends MortarCommand -{ - public CommandIrisObjectDust() - { - super("dust", "dst", "d"); - requiresPermission(Iris.perm); - setCategory("Object"); - setDescription("Get a powder that reveals placed objects"); - } +public class CommandIrisObjectDust extends MortarCommand { + public CommandIrisObjectDust() { + super("dust", "dst", "d"); + requiresPermission(Iris.perm); + setCategory("Object"); + setDescription("Get a powder that reveals placed objects"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); - return true; - } - - if(!sender.isPlayer()) - { - sender.sendMessage("You don't have an inventory"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); + return true; + } - sender.player().getInventory().addItem(WandManager.createDust()); - sender.player().playSound(sender.player().getLocation(), Sound.AMBIENT_SOUL_SAND_VALLEY_ADDITIONS, 1f, 1.5f); + if (!sender.isPlayer()) { + sender.sendMessage("You don't have an inventory"); + return true; + } - return true; - } + sender.player().getInventory().addItem(WandManager.createDust()); + sender.player().playSound(sender.player().getLocation(), Sound.AMBIENT_SOUL_SAND_VALLEY_ADDITIONS, 1f, 1.5f); - @Override - protected String getArgsUsage() - { - return "[subcommand]"; - } + return true; + } + + @Override + protected String getArgsUsage() { + return "[subcommand]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectExpand.java b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectExpand.java index 0b9c60c7c..cb206611a 100644 --- a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectExpand.java +++ b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectExpand.java @@ -1,71 +1,64 @@ package com.volmit.iris.manager.command.object; +import com.volmit.iris.Iris; +import com.volmit.iris.IrisSettings; +import com.volmit.iris.manager.WandManager; import com.volmit.iris.util.*; import org.bukkit.Location; import org.bukkit.Sound; import org.bukkit.entity.Player; -import com.volmit.iris.Iris; -import com.volmit.iris.IrisSettings; -import com.volmit.iris.manager.WandManager; - -public class CommandIrisObjectExpand extends MortarCommand -{ - public CommandIrisObjectExpand() - { - super("+"); - requiresPermission(Iris.perm); - setCategory("Object"); - setDescription("Expand based on looking direction"); - } +public class CommandIrisObjectExpand extends MortarCommand { + public CommandIrisObjectExpand() { + super("+"); + requiresPermission(Iris.perm); + setCategory("Object"); + setDescription("Expand based on looking direction"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); - return true; - } - - if(!sender.isPlayer()) - { - sender.sendMessage("You don't have a wand"); - return true; - } + } - Player p = sender.player(); + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); + return true; + } - if(!WandManager.isWand(p)) - { - sender.sendMessage("Ready your Wand."); - return true; - } + if (!sender.isPlayer()) { + sender.sendMessage("You don't have a wand"); + return true; + } - int amt = args.length == 1 ? Integer.valueOf(args[0]) : 1; - Location[] b = WandManager.getCuboid(p.getInventory().getItemInMainHand()); - Location a1 = b[0].clone(); - Location a2 = b[1].clone(); - Cuboid cursor = new Cuboid(a1, a2); - Direction d = Direction.closest(p.getLocation().getDirection()).reverse(); - cursor = cursor.expand(d, amt); - b[0] = cursor.getLowerNE(); - b[1] = cursor.getUpperSW(); - p.getInventory().setItemInMainHand(WandManager.createWand(b[0], b[1])); - p.updateInventory(); - p.playSound(p.getLocation(), Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 1f, 0.55f); + Player p = sender.player(); - return true; - } + if (!WandManager.isWand(p)) { + sender.sendMessage("Ready your Wand."); + return true; + } - @Override - protected String getArgsUsage() - { - return "[amt]"; - } + int amt = args.length == 1 ? Integer.valueOf(args[0]) : 1; + Location[] b = WandManager.getCuboid(p.getInventory().getItemInMainHand()); + Location a1 = b[0].clone(); + Location a2 = b[1].clone(); + Cuboid cursor = new Cuboid(a1, a2); + Direction d = Direction.closest(p.getLocation().getDirection()).reverse(); + cursor = cursor.expand(d, amt); + b[0] = cursor.getLowerNE(); + b[1] = cursor.getUpperSW(); + p.getInventory().setItemInMainHand(WandManager.createWand(b[0], b[1])); + p.updateInventory(); + p.playSound(p.getLocation(), Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 1f, 0.55f); + + return true; + } + + @Override + protected String getArgsUsage() { + return "[amt]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectP1.java b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectP1.java index 28b14b512..b8cbef00b 100644 --- a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectP1.java +++ b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectP1.java @@ -1,80 +1,71 @@ package com.volmit.iris.manager.command.object; -import java.util.Set; - +import com.volmit.iris.Iris; +import com.volmit.iris.IrisSettings; +import com.volmit.iris.manager.WandManager; import com.volmit.iris.util.KList; +import com.volmit.iris.util.MortarCommand; +import com.volmit.iris.util.MortarSender; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; -import com.volmit.iris.Iris; -import com.volmit.iris.IrisSettings; -import com.volmit.iris.manager.WandManager; -import com.volmit.iris.util.MortarCommand; -import com.volmit.iris.util.MortarSender; +import java.util.Set; -public class CommandIrisObjectP1 extends MortarCommand -{ - public CommandIrisObjectP1() - { - super("p1"); - requiresPermission(Iris.perm); - setCategory("Object"); - setDescription("Set point 1 to pos (or look)"); - } +public class CommandIrisObjectP1 extends MortarCommand { + public CommandIrisObjectP1() { + super("p1"); + requiresPermission(Iris.perm); + setCategory("Object"); + setDescription("Set point 1 to pos (or look)"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } - @SuppressWarnings("deprecation") - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); - return true; - } - - if(!sender.isPlayer()) - { - sender.sendMessage("You don't have a wand"); - return true; - } + } - Player p = sender.player(); + @SuppressWarnings("deprecation") + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); + return true; + } - if(!WandManager.isWand(p)) - { - sender.sendMessage("Ready your Wand."); - return true; - } + if (!sender.isPlayer()) { + sender.sendMessage("You don't have a wand"); + return true; + } - ItemStack wand = p.getInventory().getItemInMainHand(); + Player p = sender.player(); - if(WandManager.isWand(wand)) - { - Location[] g = WandManager.getCuboid(wand); - g[0] = p.getLocation().getBlock().getLocation().clone().add(0, -1, 0); - - if(args.length == 1 && args[0].equals("-l")) - { - // TODO: WARNING HEIGHT - g[0] = p.getTargetBlock((Set) null, 256).getLocation().clone(); - } + if (!WandManager.isWand(p)) { + sender.sendMessage("Ready your Wand."); + return true; + } - p.setItemInHand(WandManager.createWand(g[0], g[1])); - } + ItemStack wand = p.getInventory().getItemInMainHand(); - return true; - } + if (WandManager.isWand(wand)) { + Location[] g = WandManager.getCuboid(wand); + g[0] = p.getLocation().getBlock().getLocation().clone().add(0, -1, 0); - @Override - protected String getArgsUsage() - { - return "[-l]"; - } + if (args.length == 1 && args[0].equals("-l")) { + // TODO: WARNING HEIGHT + g[0] = p.getTargetBlock(null, 256).getLocation().clone(); + } + + p.setItemInHand(WandManager.createWand(g[0], g[1])); + } + + return true; + } + + @Override + protected String getArgsUsage() { + return "[-l]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectP2.java b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectP2.java index dfda2a2fb..be87af517 100644 --- a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectP2.java +++ b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectP2.java @@ -1,80 +1,71 @@ package com.volmit.iris.manager.command.object; -import java.util.Set; - +import com.volmit.iris.Iris; +import com.volmit.iris.IrisSettings; +import com.volmit.iris.manager.WandManager; import com.volmit.iris.util.KList; +import com.volmit.iris.util.MortarCommand; +import com.volmit.iris.util.MortarSender; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; -import com.volmit.iris.Iris; -import com.volmit.iris.IrisSettings; -import com.volmit.iris.manager.WandManager; -import com.volmit.iris.util.MortarCommand; -import com.volmit.iris.util.MortarSender; +import java.util.Set; -public class CommandIrisObjectP2 extends MortarCommand -{ - public CommandIrisObjectP2() - { - super("p2"); - requiresPermission(Iris.perm); - setCategory("Object"); - setDescription("Set point 1 to pos (or look)"); - } +public class CommandIrisObjectP2 extends MortarCommand { + public CommandIrisObjectP2() { + super("p2"); + requiresPermission(Iris.perm); + setCategory("Object"); + setDescription("Set point 1 to pos (or look)"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } - @SuppressWarnings("deprecation") - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); - return true; - } - - if(!sender.isPlayer()) - { - sender.sendMessage("You don't have a wand"); - return true; - } + } - Player p = sender.player(); + @SuppressWarnings("deprecation") + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); + return true; + } - if(!WandManager.isWand(p)) - { - sender.sendMessage("Ready your Wand."); - return true; - } + if (!sender.isPlayer()) { + sender.sendMessage("You don't have a wand"); + return true; + } - ItemStack wand = p.getInventory().getItemInMainHand(); + Player p = sender.player(); - if(WandManager.isWand(wand)) - { - Location[] g = WandManager.getCuboid(wand); - g[1] = p.getLocation().getBlock().getLocation().clone().add(0, -1, 0); + if (!WandManager.isWand(p)) { + sender.sendMessage("Ready your Wand."); + return true; + } - if(args.length == 1 && args[0].equals("-l")) - { - // TODO: WARNING HEIGHT - g[1] = p.getTargetBlock((Set) null, 256).getLocation().clone(); - } + ItemStack wand = p.getInventory().getItemInMainHand(); - p.setItemInHand(WandManager.createWand(g[0], g[1])); - } + if (WandManager.isWand(wand)) { + Location[] g = WandManager.getCuboid(wand); + g[1] = p.getLocation().getBlock().getLocation().clone().add(0, -1, 0); - return true; - } + if (args.length == 1 && args[0].equals("-l")) { + // TODO: WARNING HEIGHT + g[1] = p.getTargetBlock(null, 256).getLocation().clone(); + } - @Override - protected String getArgsUsage() - { - return "[-l]"; - } + p.setItemInHand(WandManager.createWand(g[0], g[1])); + } + + return true; + } + + @Override + protected String getArgsUsage() { + return "[-l]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectPaste.java b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectPaste.java index 93a0e2252..00dd0e29f 100644 --- a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectPaste.java +++ b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectPaste.java @@ -18,96 +18,85 @@ import org.bukkit.inventory.ItemStack; import java.io.File; import java.util.Set; -public class CommandIrisObjectPaste extends MortarCommand -{ - public CommandIrisObjectPaste() - { - super("paste", "pasta", "place", "p"); - requiresPermission(Iris.perm); - setCategory("Object"); - setDescription("Paste an object"); - } +public class CommandIrisObjectPaste extends MortarCommand { + public CommandIrisObjectPaste() { + super("paste", "pasta", "place", "p"); + requiresPermission(Iris.perm); + setCategory("Object"); + setDescription("Paste an object"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); - return true; - } + } - if(!sender.isPlayer()) - { - sender.sendMessage("You don't have a wand"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); + return true; + } - if(args.length == 0){ - sender.sendMessage("Please specify the name of of the object want to paste"); - return true; - } + if (!sender.isPlayer()) { + sender.sendMessage("You don't have a wand"); + return true; + } - Player p = sender.player(); - IrisObject obj = IrisDataManager.loadAnyObject(args[0]); + if (args.length == 0) { + sender.sendMessage("Please specify the name of of the object want to paste"); + return true; + } - if(obj == null) - { + Player p = sender.player(); + IrisObject obj = IrisDataManager.loadAnyObject(args[0]); - sender.sendMessage("Can't find " + args[0] + " in the " + ProjectManager.WORKSPACE_NAME + " folder"); - return true; - } + if (obj == null) { - File file = obj.getLoadFile(); - boolean intoWand = false; + sender.sendMessage("Can't find " + args[0] + " in the " + ProjectManager.WORKSPACE_NAME + " folder"); + return true; + } - for(String i : args) - { - if(i.equalsIgnoreCase("-edit")) - { - intoWand = true; - } - } + File file = obj.getLoadFile(); + boolean intoWand = false; - if(file == null || !file.exists()) - { - sender.sendMessage("Can't find " + args[0] + " in the " + ProjectManager.WORKSPACE_NAME + " folder"); - return true; - } + for (String i : args) { + if (i.equalsIgnoreCase("-edit")) { + intoWand = true; + } + } - ItemStack wand = sender.player().getInventory().getItemInMainHand(); + if (file == null || !file.exists()) { + sender.sendMessage("Can't find " + args[0] + " in the " + ProjectManager.WORKSPACE_NAME + " folder"); + return true; + } - IrisObject o = IrisDataManager.loadAnyObject(args[0]); - if(o == null) - { - sender.sendMessage("Error, cant find"); - return true; - } - sender.sendMessage("Loaded " + "objects/" + args[0] + ".iob"); + ItemStack wand = sender.player().getInventory().getItemInMainHand(); - sender.player().getWorld().playSound(sender.player().getLocation(), Sound.BLOCK_ENCHANTMENT_TABLE_USE, 1f, 1.5f); - Location block = sender.player().getTargetBlock((Set) null, 256).getLocation().clone().add(0, 1, 0); + IrisObject o = IrisDataManager.loadAnyObject(args[0]); + if (o == null) { + sender.sendMessage("Error, cant find"); + return true; + } + sender.sendMessage("Loaded " + "objects/" + args[0] + ".iob"); - if(intoWand && WandManager.isWand(wand)) - { - wand = WandManager.createWand(block.clone().subtract(o.getCenter()).add(o.getW() - 1, o.getH(), o.getD() - 1), block.clone().subtract(o.getCenter())); - p.getInventory().setItemInMainHand(wand); - sender.sendMessage("Updated wand for " + "objects/" + args[0] + ".iob"); - } + sender.player().getWorld().playSound(sender.player().getLocation(), Sound.BLOCK_ENCHANTMENT_TABLE_USE, 1f, 1.5f); + Location block = sender.player().getTargetBlock(null, 256).getLocation().clone().add(0, 1, 0); - WandManager.pasteSchematic(o, block); - sender.sendMessage("Placed " + "objects/" + args[0] + ".iob"); + if (intoWand && WandManager.isWand(wand)) { + wand = WandManager.createWand(block.clone().subtract(o.getCenter()).add(o.getW() - 1, o.getH(), o.getD() - 1), block.clone().subtract(o.getCenter())); + p.getInventory().setItemInMainHand(wand); + sender.sendMessage("Updated wand for " + "objects/" + args[0] + ".iob"); + } - return true; - } + WandManager.pasteSchematic(o, block); + sender.sendMessage("Placed " + "objects/" + args[0] + ".iob"); - @Override - protected String getArgsUsage() - { - return "[name] [-edit]"; - } + return true; + } + + @Override + protected String getArgsUsage() { + return "[name] [-edit]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectSave.java b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectSave.java index 5c1f00886..cf11a992e 100644 --- a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectSave.java +++ b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectSave.java @@ -1,100 +1,85 @@ package com.volmit.iris.manager.command.object; -import java.io.File; - -import com.volmit.iris.util.KList; -import org.bukkit.Sound; -import org.bukkit.entity.Player; -import org.bukkit.inventory.ItemStack; - import com.volmit.iris.Iris; import com.volmit.iris.IrisSettings; import com.volmit.iris.manager.WandManager; import com.volmit.iris.object.IrisObject; +import com.volmit.iris.util.KList; import com.volmit.iris.util.MortarCommand; import com.volmit.iris.util.MortarSender; +import org.bukkit.Sound; +import org.bukkit.entity.Player; +import org.bukkit.inventory.ItemStack; -public class CommandIrisObjectSave extends MortarCommand -{ - public CommandIrisObjectSave() - { - super("save", "s"); - requiresPermission(Iris.perm); - setCategory("Object"); - setDescription("Save an object"); - } +import java.io.File; + +public class CommandIrisObjectSave extends MortarCommand { + public CommandIrisObjectSave() { + super("save", "s"); + requiresPermission(Iris.perm); + setCategory("Object"); + setDescription("Save an object"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); - return true; - } - - if(!sender.isPlayer()) - { - sender.sendMessage("You don't have a wand"); - return true; - } + } - if(args.length < 2) - { - sender.sendMessage("/iris o save "); - sender.sendMessage("I.e. /iris o save overworld some-tree/tree1"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); + return true; + } - try - { - boolean overwrite = false; + if (!sender.isPlayer()) { + sender.sendMessage("You don't have a wand"); + return true; + } - for(String i : args) - { - if(i.equals("-o")) - { - overwrite = true; - } - } + if (args.length < 2) { + sender.sendMessage("/iris o save "); + sender.sendMessage("I.e. /iris o save overworld some-tree/tree1"); + return true; + } - Player p = sender.player(); - ItemStack wand = p.getInventory().getItemInMainHand(); - IrisObject o = WandManager.createSchematic(wand); - File file = Iris.proj.getWorkspaceFile(args[0], "objects", args[1] + ".iob"); + try { + boolean overwrite = false; - if(file.exists()) - { - if(!overwrite) - { - sender.sendMessage("File Exists. Overwrite by adding -o"); - return true; - } - } + for (String i : args) { + if (i.equals("-o")) { + overwrite = true; + } + } - o.write(file); - sender.sendMessage("Saved " + args[1]); - p.getWorld().playSound(p.getLocation(), Sound.BLOCK_ENCHANTMENT_TABLE_USE, 1f, 1.5f); - } + Player p = sender.player(); + ItemStack wand = p.getInventory().getItemInMainHand(); + IrisObject o = WandManager.createSchematic(wand); + File file = Iris.proj.getWorkspaceFile(args[0], "objects", args[1] + ".iob"); - catch(Throwable e) - { - sender.sendMessage("Failed to save " + args[1] + ". Are you holding your wand?"); + if (file.exists()) { + if (!overwrite) { + sender.sendMessage("File Exists. Overwrite by adding -o"); + return true; + } + } - e.printStackTrace(); - } + o.write(file); + sender.sendMessage("Saved " + args[1]); + p.getWorld().playSound(p.getLocation(), Sound.BLOCK_ENCHANTMENT_TABLE_USE, 1f, 1.5f); + } catch (Throwable e) { + sender.sendMessage("Failed to save " + args[1] + ". Are you holding your wand?"); - return true; - } + e.printStackTrace(); + } - @Override - protected String getArgsUsage() - { - return "[project] [name]"; - } + return true; + } + + @Override + protected String getArgsUsage() { + return "[project] [name]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectShift.java b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectShift.java index a30274912..edb485664 100644 --- a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectShift.java +++ b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectShift.java @@ -1,72 +1,65 @@ package com.volmit.iris.manager.command.object; +import com.volmit.iris.Iris; +import com.volmit.iris.IrisSettings; +import com.volmit.iris.manager.WandManager; import com.volmit.iris.util.*; import org.bukkit.Location; import org.bukkit.Sound; import org.bukkit.entity.Player; -import com.volmit.iris.Iris; -import com.volmit.iris.IrisSettings; -import com.volmit.iris.manager.WandManager; - -public class CommandIrisObjectShift extends MortarCommand -{ - public CommandIrisObjectShift() - { - super(">"); - requiresPermission(Iris.perm); - setCategory("Object"); - setDescription("Shift selection based on direction"); - } +public class CommandIrisObjectShift extends MortarCommand { + public CommandIrisObjectShift() { + super(">"); + requiresPermission(Iris.perm); + setCategory("Object"); + setDescription("Shift selection based on direction"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); - return true; - } - - if(!sender.isPlayer()) - { - sender.sendMessage("You don't have a wand"); - return true; - } + } - Player p = sender.player(); + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); + return true; + } - if(!WandManager.isWand(p)) - { - sender.sendMessage("Ready your Wand."); - return true; - } + if (!sender.isPlayer()) { + sender.sendMessage("You don't have a wand"); + return true; + } - int amt = args.length == 1 ? Integer.valueOf(args[0]) : 1; - Location[] b = WandManager.getCuboid(p.getInventory().getItemInMainHand()); - Location a1 = b[0].clone(); - Location a2 = b[1].clone(); - Direction d = Direction.closest(p.getLocation().getDirection()).reverse(); - a1.add(d.toVector().multiply(amt)); - a2.add(d.toVector().multiply(amt)); - Cuboid cursor = new Cuboid(a1, a2); - b[0] = cursor.getLowerNE(); - b[1] = cursor.getUpperSW(); - p.getInventory().setItemInMainHand(WandManager.createWand(b[0], b[1])); - p.updateInventory(); - p.playSound(p.getLocation(), Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 1f, 0.55f); + Player p = sender.player(); - return true; - } + if (!WandManager.isWand(p)) { + sender.sendMessage("Ready your Wand."); + return true; + } - @Override - protected String getArgsUsage() - { - return "[amt]"; - } + int amt = args.length == 1 ? Integer.valueOf(args[0]) : 1; + Location[] b = WandManager.getCuboid(p.getInventory().getItemInMainHand()); + Location a1 = b[0].clone(); + Location a2 = b[1].clone(); + Direction d = Direction.closest(p.getLocation().getDirection()).reverse(); + a1.add(d.toVector().multiply(amt)); + a2.add(d.toVector().multiply(amt)); + Cuboid cursor = new Cuboid(a1, a2); + b[0] = cursor.getLowerNE(); + b[1] = cursor.getUpperSW(); + p.getInventory().setItemInMainHand(WandManager.createWand(b[0], b[1])); + p.updateInventory(); + p.playSound(p.getLocation(), Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 1f, 0.55f); + + return true; + } + + @Override + protected String getArgsUsage() { + return "[amt]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectWand.java b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectWand.java index 5f4591de4..7b726b528 100644 --- a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectWand.java +++ b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectWand.java @@ -1,53 +1,47 @@ package com.volmit.iris.manager.command.object; -import com.volmit.iris.util.KList; -import org.bukkit.Sound; - import com.volmit.iris.Iris; import com.volmit.iris.IrisSettings; import com.volmit.iris.manager.WandManager; +import com.volmit.iris.util.KList; import com.volmit.iris.util.MortarCommand; import com.volmit.iris.util.MortarSender; +import org.bukkit.Sound; -public class CommandIrisObjectWand extends MortarCommand -{ - public CommandIrisObjectWand() - { - super("wand", "w"); - requiresPermission(Iris.perm); - setCategory("Object"); - setDescription("Get an Iris Wand for selecting objects"); - } +public class CommandIrisObjectWand extends MortarCommand { + public CommandIrisObjectWand() { + super("wand", "w"); + requiresPermission(Iris.perm); + setCategory("Object"); + setDescription("Get an Iris Wand for selecting objects"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); - return true; - } - - if(!sender.isPlayer()) - { - sender.sendMessage("You don't have an inventory"); - return true; - } + } - sender.player().getInventory().addItem(WandManager.createWand()); - sender.player().playSound(sender.player().getLocation(), Sound.ITEM_ARMOR_EQUIP_NETHERITE, 1f, 1.5f); + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); + return true; + } - return true; - } + if (!sender.isPlayer()) { + sender.sendMessage("You don't have an inventory"); + return true; + } - @Override - protected String getArgsUsage() - { - return "[subcommand]"; - } + sender.player().getInventory().addItem(WandManager.createWand()); + sender.player().playSound(sender.player().getLocation(), Sound.ITEM_ARMOR_EQUIP_NETHERITE, 1f, 1.5f); + + return true; + } + + @Override + protected String getArgsUsage() { + return "[subcommand]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectXAY.java b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectXAY.java index 71349c626..fb83ae370 100644 --- a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectXAY.java +++ b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectXAY.java @@ -1,104 +1,95 @@ package com.volmit.iris.manager.command.object; +import com.volmit.iris.Iris; +import com.volmit.iris.IrisSettings; +import com.volmit.iris.manager.WandManager; +import com.volmit.iris.util.Cuboid; +import com.volmit.iris.util.Cuboid.CuboidDirection; import com.volmit.iris.util.KList; +import com.volmit.iris.util.MortarCommand; +import com.volmit.iris.util.MortarSender; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.util.Vector; -import com.volmit.iris.Iris; -import com.volmit.iris.IrisSettings; -import com.volmit.iris.manager.WandManager; -import com.volmit.iris.util.Cuboid; -import com.volmit.iris.util.MortarCommand; -import com.volmit.iris.util.MortarSender; -import com.volmit.iris.util.Cuboid.CuboidDirection; - -public class CommandIrisObjectXAY extends MortarCommand -{ - public CommandIrisObjectXAY() - { - super("x&y"); - requiresPermission(Iris.perm); - setCategory("Object"); - setDescription("Auto select up, down and out"); - } +public class CommandIrisObjectXAY extends MortarCommand { + public CommandIrisObjectXAY() { + super("x&y"); + requiresPermission(Iris.perm); + setCategory("Object"); + setDescription("Auto select up, down and out"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); - return true; - } - - if(!sender.isPlayer()) - { - sender.sendMessage("You don't have a wand"); - return true; - } + } - Player p = sender.player(); + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); + return true; + } - if(!WandManager.isWand(p)) - { - sender.sendMessage("Ready your Wand."); - return true; - } + if (!sender.isPlayer()) { + sender.sendMessage("You don't have a wand"); + return true; + } - Location[] b = WandManager.getCuboid(p.getInventory().getItemInMainHand()); - Location a1 = b[0].clone(); - Location a2 = b[1].clone(); - Location a1x = b[0].clone(); - Location a2x = b[1].clone(); - Cuboid cursor = new Cuboid(a1, a2); - Cuboid cursorx = new Cuboid(a1, a2); + Player p = sender.player(); - while(!cursor.containsOnly(Material.AIR)) - { - a1.add(new Vector(0, 1, 0)); - a2.add(new Vector(0, 1, 0)); - cursor = new Cuboid(a1, a2); - } + if (!WandManager.isWand(p)) { + sender.sendMessage("Ready your Wand."); + return true; + } - a1.add(new Vector(0, -1, 0)); - a2.add(new Vector(0, -1, 0)); + Location[] b = WandManager.getCuboid(p.getInventory().getItemInMainHand()); + Location a1 = b[0].clone(); + Location a2 = b[1].clone(); + Location a1x = b[0].clone(); + Location a2x = b[1].clone(); + Cuboid cursor = new Cuboid(a1, a2); + Cuboid cursorx = new Cuboid(a1, a2); - while(!cursorx.containsOnly(Material.AIR)) - { - a1x.add(new Vector(0, -1, 0)); - a2x.add(new Vector(0, -1, 0)); - cursorx = new Cuboid(a1x, a2x); - } + while (!cursor.containsOnly(Material.AIR)) { + a1.add(new Vector(0, 1, 0)); + a2.add(new Vector(0, 1, 0)); + cursor = new Cuboid(a1, a2); + } - a1x.add(new Vector(0, 1, 0)); - a2x.add(new Vector(0, 1, 0)); - b[0] = a1; - b[1] = a2x; - cursor = new Cuboid(b[0], b[1]); - cursor = cursor.contract(CuboidDirection.North); - cursor = cursor.contract(CuboidDirection.South); - cursor = cursor.contract(CuboidDirection.East); - cursor = cursor.contract(CuboidDirection.West); - b[0] = cursor.getLowerNE(); - b[1] = cursor.getUpperSW(); - p.getInventory().setItemInMainHand(WandManager.createWand(b[0], b[1])); - p.updateInventory(); - p.playSound(p.getLocation(), Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 1f, 0.55f); + a1.add(new Vector(0, -1, 0)); + a2.add(new Vector(0, -1, 0)); - return true; - } + while (!cursorx.containsOnly(Material.AIR)) { + a1x.add(new Vector(0, -1, 0)); + a2x.add(new Vector(0, -1, 0)); + cursorx = new Cuboid(a1x, a2x); + } - @Override - protected String getArgsUsage() - { - return "[subcommand]"; - } + a1x.add(new Vector(0, 1, 0)); + a2x.add(new Vector(0, 1, 0)); + b[0] = a1; + b[1] = a2x; + cursor = new Cuboid(b[0], b[1]); + cursor = cursor.contract(CuboidDirection.North); + cursor = cursor.contract(CuboidDirection.South); + cursor = cursor.contract(CuboidDirection.East); + cursor = cursor.contract(CuboidDirection.West); + b[0] = cursor.getLowerNE(); + b[1] = cursor.getUpperSW(); + p.getInventory().setItemInMainHand(WandManager.createWand(b[0], b[1])); + p.updateInventory(); + p.playSound(p.getLocation(), Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 1f, 0.55f); + + return true; + } + + @Override + protected String getArgsUsage() { + return "[subcommand]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectXPY.java b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectXPY.java index b2a3b1dcd..209259b92 100644 --- a/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectXPY.java +++ b/src/main/java/com/volmit/iris/manager/command/object/CommandIrisObjectXPY.java @@ -1,92 +1,83 @@ package com.volmit.iris.manager.command.object; +import com.volmit.iris.Iris; +import com.volmit.iris.IrisSettings; +import com.volmit.iris.manager.WandManager; +import com.volmit.iris.util.Cuboid; +import com.volmit.iris.util.Cuboid.CuboidDirection; import com.volmit.iris.util.KList; +import com.volmit.iris.util.MortarCommand; +import com.volmit.iris.util.MortarSender; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.Sound; import org.bukkit.entity.Player; import org.bukkit.util.Vector; -import com.volmit.iris.Iris; -import com.volmit.iris.IrisSettings; -import com.volmit.iris.manager.WandManager; -import com.volmit.iris.util.Cuboid; -import com.volmit.iris.util.MortarCommand; -import com.volmit.iris.util.MortarSender; -import com.volmit.iris.util.Cuboid.CuboidDirection; +public class CommandIrisObjectXPY extends MortarCommand { + public CommandIrisObjectXPY() { + super("x+y"); + requiresPermission(Iris.perm); + setCategory("Object"); + setDescription("Auto select up and out"); + } -public class CommandIrisObjectXPY extends MortarCommand -{ - public CommandIrisObjectXPY() - { - super("x+y"); - requiresPermission(Iris.perm); - setCategory("Object"); - setDescription("Auto select up and out"); - } + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + } - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); + return true; + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio Objects, please enable studio in Iris/settings.json"); - return true; - } - - if(!sender.isPlayer()) - { - sender.sendMessage("You don't have a wand"); - return true; - } + if (!sender.isPlayer()) { + sender.sendMessage("You don't have a wand"); + return true; + } - Player p = sender.player(); + Player p = sender.player(); - if(!WandManager.isWand(p)) - { - sender.sendMessage("Ready your Wand."); - return true; - } - Location[] b = WandManager.getCuboid(p.getInventory().getItemInMainHand()); - b[0].add(new Vector(0, 1, 0)); - b[1].add(new Vector(0, 1, 0)); - Location a1 = b[0].clone(); - Location a2 = b[1].clone(); - Cuboid cursor = new Cuboid(a1, a2); + if (!WandManager.isWand(p)) { + sender.sendMessage("Ready your Wand."); + return true; + } + Location[] b = WandManager.getCuboid(p.getInventory().getItemInMainHand()); + b[0].add(new Vector(0, 1, 0)); + b[1].add(new Vector(0, 1, 0)); + Location a1 = b[0].clone(); + Location a2 = b[1].clone(); + Cuboid cursor = new Cuboid(a1, a2); - while(!cursor.containsOnly(Material.AIR)) - { - a1.add(new Vector(0, 1, 0)); - a2.add(new Vector(0, 1, 0)); - cursor = new Cuboid(a1, a2); - } + while (!cursor.containsOnly(Material.AIR)) { + a1.add(new Vector(0, 1, 0)); + a2.add(new Vector(0, 1, 0)); + cursor = new Cuboid(a1, a2); + } - a1.add(new Vector(0, -1, 0)); - a2.add(new Vector(0, -1, 0)); - b[0] = a1; - a2 = b[1]; - cursor = new Cuboid(a1, a2); - cursor = cursor.contract(CuboidDirection.North); - cursor = cursor.contract(CuboidDirection.South); - cursor = cursor.contract(CuboidDirection.East); - cursor = cursor.contract(CuboidDirection.West); - b[0] = cursor.getLowerNE(); - b[1] = cursor.getUpperSW(); - p.getInventory().setItemInMainHand(WandManager.createWand(b[0], b[1])); - p.updateInventory(); - p.playSound(p.getLocation(), Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 1f, 0.55f); + a1.add(new Vector(0, -1, 0)); + a2.add(new Vector(0, -1, 0)); + b[0] = a1; + a2 = b[1]; + cursor = new Cuboid(a1, a2); + cursor = cursor.contract(CuboidDirection.North); + cursor = cursor.contract(CuboidDirection.South); + cursor = cursor.contract(CuboidDirection.East); + cursor = cursor.contract(CuboidDirection.West); + b[0] = cursor.getLowerNE(); + b[1] = cursor.getUpperSW(); + p.getInventory().setItemInMainHand(WandManager.createWand(b[0], b[1])); + p.updateInventory(); + p.playSound(p.getLocation(), Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 1f, 0.55f); - return true; - } + return true; + } - @Override - protected String getArgsUsage() - { - return "[subcommand]"; - } + @Override + protected String getArgsUsage() { + return "[subcommand]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudio.java b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudio.java index 4d78fe7db..a50f04df8 100644 --- a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudio.java +++ b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudio.java @@ -7,88 +7,83 @@ import com.volmit.iris.util.KList; import com.volmit.iris.util.MortarCommand; import com.volmit.iris.util.MortarSender; -public class CommandIrisStudio extends MortarCommand -{ - @Command - private CommandIrisStudioCreate create; +public class CommandIrisStudio extends MortarCommand { + @Command + private CommandIrisStudioCreate create; - @Command - private CommandIrisStudioOpen open; + @Command + private CommandIrisStudioOpen open; - @Command - private CommandIrisStudioSummon summon; + @Command + private CommandIrisStudioSummon summon; - @Command - private CommandIrisStudioClose close; + @Command + private CommandIrisStudioClose close; - @Command - private CommandIrisStudioPackage pkg; + @Command + private CommandIrisStudioPackage pkg; - @Command - private CommandIrisStudioUpdate update; + @Command + private CommandIrisStudioUpdate update; - @Command - private CommandIrisStudioGoto got0; + @Command + private CommandIrisStudioGoto got0; - @Command - private CommandIrisStudioEditBiome ebiome; + @Command + private CommandIrisStudioEditBiome ebiome; - @Command - private CommandIrisStudioHotload hotload; + @Command + private CommandIrisStudioHotload hotload; - @Command - private CommandIrisStudioExplorer exp; + @Command + private CommandIrisStudioExplorer exp; - @Command - private CommandIrisStudioBeautify beautify; + @Command + private CommandIrisStudioBeautify beautify; - @Command - private CommandIrisStudioProfile profile; + @Command + private CommandIrisStudioProfile profile; - @Command - private CommandIrisStudioExplorerGenerator generator; + @Command + private CommandIrisStudioExplorerGenerator generator; - @Command - private CommandIrisStudioLoot loot; + @Command + private CommandIrisStudioLoot loot; - @Command - private CommandIrisStudioTPStudio tps; + @Command + private CommandIrisStudioTPStudio tps; - @Command - private CommandIrisStudioConvert convert; + @Command + private CommandIrisStudioConvert convert; - @Command - private CommandIrisStudioMap map; + @Command + private CommandIrisStudioMap map; - public CommandIrisStudio() - { - super("studio", "std", "s"); - requiresPermission(Iris.perm.studio); - setCategory("Studio"); - } + public CommandIrisStudio() { + super("studio", "std", "s"); + requiresPermission(Iris.perm.studio); + setCategory("Studio"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); + return true; + } - sender.sendMessage("Iris Studio Commands:"); - printHelp(sender); - return true; - } + sender.sendMessage("Iris Studio Commands:"); + printHelp(sender); + return true; + } - @Override - protected String getArgsUsage() - { - return "[subcommand]"; - } + @Override + protected String getArgsUsage() { + return "[subcommand]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioBeautify.java b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioBeautify.java index 5b3d8752e..623fef310 100644 --- a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioBeautify.java +++ b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioBeautify.java @@ -3,94 +3,73 @@ package com.volmit.iris.manager.command.studio; import com.volmit.iris.Iris; import com.volmit.iris.IrisSettings; import com.volmit.iris.util.*; -import org.bukkit.Bukkit; -import org.bukkit.World; -import org.bukkit.command.CommandSender; -import org.bukkit.entity.Player; import java.io.File; -import java.io.IOException; -public class CommandIrisStudioBeautify extends MortarCommand -{ - public CommandIrisStudioBeautify() - { - super("beautify", "prettify"); - requiresPermission(Iris.perm.studio); - setDescription("Prettify the project by cleaning up json."); - setCategory("Studio"); - } +public class CommandIrisStudioBeautify extends MortarCommand { + public CommandIrisStudioBeautify() { + super("beautify", "prettify"); + requiresPermission(Iris.perm.studio); + setDescription("Prettify the project by cleaning up json."); + setCategory("Studio"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); + return true; + } - File clean = null; + File clean = null; - if(args.length == 0) - { - if(!Iris.proj.isProjectOpen()) - { - sender.sendMessage("No open project. Either use /iris std beautify or have a project open."); - return true; - } + if (args.length == 0) { + if (!Iris.proj.isProjectOpen()) { + sender.sendMessage("No open project. Either use /iris std beautify or have a project open."); + return true; + } - clean = Iris.proj.getActiveProject().getPath(); - } + clean = Iris.proj.getActiveProject().getPath(); + } else { + clean = Iris.instance.getDataFolder("packs", args[0]); - else - { - clean = Iris.instance.getDataFolder("packs", args[0]); + if (!clean.exists()) { + sender.sendMessage("Not a valid project."); + return true; + } + } - if(!clean.exists()) - { - sender.sendMessage("Not a valid project."); - return true; - } - } + sender.sendMessage("Cleaned " + Form.f(clean(sender, clean)) + " JSON Files"); - sender.sendMessage("Cleaned " + Form.f(clean(sender, clean)) + " JSON Files"); + return true; + } - return true; - } + private int clean(MortarSender s, File clean) { + int c = 0; + if (clean.isDirectory()) { + for (File i : clean.listFiles()) { + c += clean(s, i); + } + } else if (clean.getName().endsWith(".json")) { + try { + IO.writeAll(clean, new JSONObject(IO.readAll(clean)).toString(4)); + } catch (Throwable e) { + Iris.error("Failed to beautify " + clean.getAbsolutePath() + " You may have errors in your json!"); + } - private int clean(MortarSender s, File clean) { - int c = 0; - if(clean.isDirectory()) - { - for(File i : clean.listFiles()) - { - c+=clean(s, i); - } - } + c++; + } - else if(clean.getName().endsWith(".json")) - { - try { - IO.writeAll(clean, new JSONObject(IO.readAll(clean)).toString(4)); - } catch (Throwable e) { - Iris.error("Failed to beautify " + clean.getAbsolutePath() + " You may have errors in your json!"); - } + return c; + } - c++; - } - - return c; - } - - @Override - protected String getArgsUsage() - { - return "[project]"; - } + @Override + protected String getArgsUsage() { + return "[project]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioClose.java b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioClose.java index 99e545957..749eb8838 100644 --- a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioClose.java +++ b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioClose.java @@ -1,85 +1,69 @@ package com.volmit.iris.manager.command.studio; +import com.volmit.iris.Iris; +import com.volmit.iris.IrisSettings; import com.volmit.iris.util.KList; +import com.volmit.iris.util.MortarCommand; +import com.volmit.iris.util.MortarSender; import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.entity.Player; -import com.volmit.iris.Iris; -import com.volmit.iris.IrisSettings; -import com.volmit.iris.util.MortarCommand; -import com.volmit.iris.util.MortarSender; +public class CommandIrisStudioClose extends MortarCommand { + public CommandIrisStudioClose() { + super("close", "x"); + requiresPermission(Iris.perm.studio); + setDescription("Close the existing dimension"); + setCategory("Studio"); + } -public class CommandIrisStudioClose extends MortarCommand -{ - public CommandIrisStudioClose() - { - super("close", "x"); - requiresPermission(Iris.perm.studio); - setDescription("Close the existing dimension"); - setCategory("Studio"); - } + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + } - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); + return true; + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); - return true; - } + if (!Iris.proj.isProjectOpen()) { + sender.sendMessage("No open projects."); + return true; + } - if(!Iris.proj.isProjectOpen()) - { - sender.sendMessage("No open projects."); - return true; - } + if (sender.isPlayer()) { + World f = null; - if(sender.isPlayer()) - { - World f = null; + for (World i : Bukkit.getWorlds()) { + if (i.getWorldFolder().getAbsolutePath().equals(Iris.proj.getActiveProject().getActiveProvider().getTarget().getWorld().getWorldFolder().getAbsolutePath())) { + continue; + } - for(World i : Bukkit.getWorlds()) - { - if(i.getWorldFolder().getAbsolutePath().equals(Iris.proj.getActiveProject().getActiveProvider().getTarget().getWorld().getWorldFolder().getAbsolutePath())) - { - continue; - } + f = i; + break; + } - f = i; - break; - } + if (f == null) { + for (Player i : Iris.proj.getActiveProject().getActiveProvider().getTarget().getWorld().getPlayers()) { + i.kickPlayer("Project Closing, No other world to put you in. Rejoin Please!"); + } + } else { + for (Player i : Iris.proj.getActiveProject().getActiveProvider().getTarget().getWorld().getPlayers()) { + i.teleport(f.getSpawnLocation()); + } + } + } - if(f == null) - { - for(Player i : Iris.proj.getActiveProject().getActiveProvider().getTarget().getWorld().getPlayers()) - { - i.kickPlayer("Project Closing, No other world to put you in. Rejoin Please!"); - } - } + Iris.proj.close(); + sender.sendMessage("Projects Closed & Caches Cleared!"); + return true; + } - else - { - for(Player i : Iris.proj.getActiveProject().getActiveProvider().getTarget().getWorld().getPlayers()) - { - i.teleport(f.getSpawnLocation()); - } - } - } - - Iris.proj.close(); - sender.sendMessage("Projects Closed & Caches Cleared!"); - return true; - } - - @Override - protected String getArgsUsage() - { - return ""; - } + @Override + protected String getArgsUsage() { + return ""; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioConvert.java b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioConvert.java index 87aaeed80..14ecdf360 100644 --- a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioConvert.java +++ b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioConvert.java @@ -6,37 +6,32 @@ import com.volmit.iris.util.KList; import com.volmit.iris.util.MortarCommand; import com.volmit.iris.util.MortarSender; -public class CommandIrisStudioConvert extends MortarCommand -{ - public CommandIrisStudioConvert() - { - super("convert", "cvt"); - requiresPermission(Iris.perm.studio); - setDescription("Convert .ewg schematics into Iris (.iob) files"); - setCategory("Studio"); - } +public class CommandIrisStudioConvert extends MortarCommand { + public CommandIrisStudioConvert() { + super("convert", "cvt"); + requiresPermission(Iris.perm.studio); + setDescription("Convert .ewg schematics into Iris (.iob) files"); + setCategory("Studio"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); + return true; + } - Iris.convert.check(sender); - return true; - } + Iris.convert.check(sender); + return true; + } - @Override - protected String getArgsUsage() - { - return ""; - } + @Override + protected String getArgsUsage() { + return ""; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioCreate.java b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioCreate.java index 972c374aa..c8a4b1f93 100644 --- a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioCreate.java +++ b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioCreate.java @@ -7,63 +7,51 @@ import com.volmit.iris.util.KList; import com.volmit.iris.util.MortarCommand; import com.volmit.iris.util.MortarSender; -public class CommandIrisStudioCreate extends MortarCommand -{ - public CommandIrisStudioCreate() - { - super("create", "new", "+"); - requiresPermission(Iris.perm.studio); - setDescription("Create a new project & open it."); - setCategory("Studio"); - } +public class CommandIrisStudioCreate extends MortarCommand { + public CommandIrisStudioCreate() { + super("create", "new", "+"); + requiresPermission(Iris.perm.studio); + setDescription("Create a new project & open it."); + setCategory("Studio"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); + return true; + } - if(args.length < 1) - { - sender.sendMessage("Please use a lowercase name with hyphens (-) for spaces."); - sender.sendMessage("I.e. /iris std new " + C.BOLD + "aether"); - return true; - } + if (args.length < 1) { + sender.sendMessage("Please use a lowercase name with hyphens (-) for spaces."); + sender.sendMessage("I.e. /iris std new " + C.BOLD + "aether"); + return true; + } - String template = null; + String template = null; - for(String i : args) - { - if(i.startsWith("template=")) - { - template = i.split("\\Q=\\E")[1]; - } - } + for (String i : args) { + if (i.startsWith("template=")) { + template = i.split("\\Q=\\E")[1]; + } + } - if(template != null) - { - Iris.proj.create(sender, args[0], template); - } + if (template != null) { + Iris.proj.create(sender, args[0], template); + } else { + Iris.proj.create(sender, args[0]); + } - else - { - Iris.proj.create(sender, args[0]); - } + return true; + } - return true; - } - - @Override - protected String getArgsUsage() - { - return "[dimension] [template=]"; - } + @Override + protected String getArgsUsage() { + return "[dimension] [template=]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioEditBiome.java b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioEditBiome.java index 6b0ae1ce2..ff76c050c 100644 --- a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioEditBiome.java +++ b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioEditBiome.java @@ -10,65 +10,51 @@ import org.bukkit.entity.Player; import java.awt.*; import java.io.File; -public class CommandIrisStudioEditBiome extends MortarCommand -{ - public CommandIrisStudioEditBiome() - { - super("editbiome", "ebiome", "eb"); - setDescription("Open this biome file in vscode"); - requiresPermission(Iris.perm.studio); - setCategory("Studio"); - } +public class CommandIrisStudioEditBiome extends MortarCommand { + public CommandIrisStudioEditBiome() { + super("editbiome", "ebiome", "eb"); + setDescription("Open this biome file in vscode"); + requiresPermission(Iris.perm.studio); + setCategory("Studio"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); + return true; + } - if(!Iris.proj.isProjectOpen()) - { - sender.sendMessage("There is not a studio currently loaded."); - return true; - } + if (!Iris.proj.isProjectOpen()) { + sender.sendMessage("There is not a studio currently loaded."); + return true; + } - if(sender.isPlayer()) - { - Player p = sender.player(); + if (sender.isPlayer()) { + Player p = sender.player(); - try - { - File f = Iris.proj.getActiveProject().getActiveProvider().getBiome(p.getLocation().getBlockX(), p.getLocation().getBlockY(), p.getLocation().getBlockZ()).getLoadFile(); - Desktop.getDesktop().open(f); - } + try { + File f = Iris.proj.getActiveProject().getActiveProvider().getBiome(p.getLocation().getBlockX(), p.getLocation().getBlockY(), p.getLocation().getBlockZ()).getLoadFile(); + Desktop.getDesktop().open(f); + } catch (Throwable e) { + sender.sendMessage("Cant find the file. Are you in an Iris Studio world?"); + } - catch(Throwable e) - { - sender.sendMessage("Cant find the file. Are you in an Iris Studio world?"); - } + return true; + } else { + sender.sendMessage("Players only."); + } - return true; - } + return true; + } - else - { - sender.sendMessage("Players only."); - } - - return true; - } - - @Override - protected String getArgsUsage() - { - return "[width]"; - } + @Override + protected String getArgsUsage() { + return "[width]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioExplorer.java b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioExplorer.java index 5b9b39d18..d0ca08f8b 100644 --- a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioExplorer.java +++ b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioExplorer.java @@ -8,55 +8,45 @@ import com.volmit.iris.util.KList; import com.volmit.iris.util.MortarCommand; import com.volmit.iris.util.MortarSender; -public class CommandIrisStudioExplorer extends MortarCommand -{ - @Command - private CommandIrisStudioExplorerGenerator generator; +public class CommandIrisStudioExplorer extends MortarCommand { + @Command + private CommandIrisStudioExplorerGenerator generator; - public CommandIrisStudioExplorer() - { - super("noise", "nmap"); - setDescription("Explore different noise generators visually"); - requiresPermission(Iris.perm.studio); - setCategory("World"); - } + public CommandIrisStudioExplorer() { + super("noise", "nmap"); + setDescription("Explore different noise generators visually"); + requiresPermission(Iris.perm.studio); + setCategory("World"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(args.length != 0) - { - printHelp(sender); - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (args.length != 0) { + printHelp(sender); + } else { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); + return true; + } - else - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); - return true; - } + if (!IrisSettings.get().isUseServerLaunchedGuis()) { + sender.sendMessage("To use Iris Guis, please enable serverLaunchedGuis in Iris/settings.json"); + return true; + } - if(!IrisSettings.get().isUseServerLaunchedGuis()) - { - sender.sendMessage("To use Iris Guis, please enable serverLaunchedGuis in Iris/settings.json"); - return true; - } + NoiseExplorer.launch(); + sender.sendMessage("Opening Noise Explorer!"); + } + return true; + } - NoiseExplorer.launch(); - sender.sendMessage("Opening Noise Explorer!"); - } - return true; - } - - @Override - protected String getArgsUsage() - { - return ""; - } + @Override + protected String getArgsUsage() { + return ""; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioExplorerGenerator.java b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioExplorerGenerator.java index 6ea191336..21f71ee75 100644 --- a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioExplorerGenerator.java +++ b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioExplorerGenerator.java @@ -10,75 +10,62 @@ import com.volmit.iris.util.MortarCommand; import com.volmit.iris.util.MortarSender; import com.volmit.iris.util.RNG; -public class CommandIrisStudioExplorerGenerator extends MortarCommand -{ - public CommandIrisStudioExplorerGenerator() - { - super("generator", "gen", "g"); - setDescription("Preview created noise noises generators"); - requiresPermission(Iris.perm.studio); - setCategory("World"); - } +public class CommandIrisStudioExplorerGenerator extends MortarCommand { + public CommandIrisStudioExplorerGenerator() { + super("generator", "gen", "g"); + setDescription("Preview created noise noises generators"); + requiresPermission(Iris.perm.studio); + setCategory("World"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); + return true; + } - if(!IrisSettings.get().isUseServerLaunchedGuis()) - { - sender.sendMessage("To use Iris Guis, please enable serverLaunchedGuis in Iris/settings.json"); - return true; - } + if (!IrisSettings.get().isUseServerLaunchedGuis()) { + sender.sendMessage("To use Iris Guis, please enable serverLaunchedGuis in Iris/settings.json"); + return true; + } - if (args.length == 0) - { - sender.sendMessage("Specify a generator to preview"); - return true; - } + if (args.length == 0) { + sender.sendMessage("Specify a generator to preview"); + return true; + } - IrisGenerator generator; - long seed = 12345; + IrisGenerator generator; + long seed = 12345; - if (Iris.proj.isProjectOpen()) - { - generator = Iris.proj.getActiveProject().getActiveProvider().getData().getGeneratorLoader().load(args[0]); - seed = Iris.proj.getActiveProject().getActiveProvider().getTarget().getWorld().getSeed(); - } - else - { - generator = IrisDataManager.loadAnyGenerator(args[0]); - } + if (Iris.proj.isProjectOpen()) { + generator = Iris.proj.getActiveProject().getActiveProvider().getData().getGeneratorLoader().load(args[0]); + seed = Iris.proj.getActiveProject().getActiveProvider().getTarget().getWorld().getSeed(); + } else { + generator = IrisDataManager.loadAnyGenerator(args[0]); + } - if (generator != null) - { - long finalSeed = seed; - NoiseExplorer.launch((x, z) -> - generator.getHeight(x, z, new RNG(finalSeed).nextParallelRNG(3245).lmax()), "Gen: " + generator.getLoadKey()); + if (generator != null) { + long finalSeed = seed; + NoiseExplorer.launch((x, z) -> + generator.getHeight(x, z, new RNG(finalSeed).nextParallelRNG(3245).lmax()), "Gen: " + generator.getLoadKey()); - sender.sendMessage("Opening Noise Explorer for gen " + generator.getLoadKey() + " (" + generator.getLoader().getDataFolder().getName() + ")"); - return true; - } - else - { - sender.sendMessage("Invalid Generator"); - } + sender.sendMessage("Opening Noise Explorer for gen " + generator.getLoadKey() + " (" + generator.getLoader().getDataFolder().getName() + ")"); + return true; + } else { + sender.sendMessage("Invalid Generator"); + } - return true; - } + return true; + } - @Override - protected String getArgsUsage() - { - return "[generator]"; - } + @Override + protected String getArgsUsage() { + return "[generator]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioGoto.java b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioGoto.java index e143dddf3..d9945b78a 100644 --- a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioGoto.java +++ b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioGoto.java @@ -16,93 +16,73 @@ import java.io.File; import java.util.ArrayList; import java.util.List; -public class CommandIrisStudioGoto extends MortarCommand -{ - public CommandIrisStudioGoto() - { - super("goto", "find", "g", "tp"); - setDescription("Find any region or biome"); - requiresPermission(Iris.perm.studio); - setCategory("World"); - } +public class CommandIrisStudioGoto extends MortarCommand { + public CommandIrisStudioGoto() { + super("goto", "find", "g", "tp"); + setDescription("Find any region or biome"); + requiresPermission(Iris.perm.studio); + setCategory("World"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { - if(args.length == 0 && sender.isPlayer() && IrisWorlds.isIrisWorld(sender.player().getWorld())) - { - IrisDataManager data = IrisWorlds.access(sender.player().getWorld()).getData(); - if (data == null){ - sender.sendMessage("Issue when loading tab completions. No data found (?)"); - } else { - list.add(data.getBiomeLoader().getPossibleKeys()); - list.add(data.getRegionLoader().getPossibleKeys()); - //TODO: Remove comment here -> list.add(data.getObjectLoader().getPossibleKeys()); - } - } - } + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { + if (args.length == 0 && sender.isPlayer() && IrisWorlds.isIrisWorld(sender.player().getWorld())) { + IrisDataManager data = IrisWorlds.access(sender.player().getWorld()).getData(); + if (data == null) { + sender.sendMessage("Issue when loading tab completions. No data found (?)"); + } else { + list.add(data.getBiomeLoader().getPossibleKeys()); + list.add(data.getRegionLoader().getPossibleKeys()); + //TODO: Remove comment here -> list.add(data.getObjectLoader().getPossibleKeys()); + } + } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - try - { - if(args.length < 1) - { - sender.sendMessage("/iris std goto " + getArgsUsage()); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + try { + if (args.length < 1) { + sender.sendMessage("/iris std goto " + getArgsUsage()); + return true; + } - if(sender.isPlayer()) - { - Player p = sender.player(); - World world = p.getWorld(); + if (sender.isPlayer()) { + Player p = sender.player(); + World world = p.getWorld(); - if(!IrisWorlds.isIrisWorld(world)) - { - sender.sendMessage("You must be in an iris world."); - return true; - } + if (!IrisWorlds.isIrisWorld(world)) { + sender.sendMessage("You must be in an iris world."); + return true; + } - IrisAccess g = IrisWorlds.access(world); - IrisBiome b = IrisDataManager.loadAnyBiome(args[0]); - IrisRegion r = IrisDataManager.loadAnyRegion(args[0]); - IrisObject o = IrisDataManager.loadAnyObject(args[0]); + IrisAccess g = IrisWorlds.access(world); + IrisBiome b = IrisDataManager.loadAnyBiome(args[0]); + IrisRegion r = IrisDataManager.loadAnyRegion(args[0]); + IrisObject o = IrisDataManager.loadAnyObject(args[0]); - if(b != null) - { - J.a(() -> { - Location l = g.lookForBiome(b, 10000, (v) -> sender.sendMessage("Looking for " + C.BOLD + C.WHITE + b.getName() + C.RESET + C.GRAY + ": Checked " + Form.f(v) + " Places")); + if (b != null) { + J.a(() -> { + Location l = g.lookForBiome(b, 10000, (v) -> sender.sendMessage("Looking for " + C.BOLD + C.WHITE + b.getName() + C.RESET + C.GRAY + ": Checked " + Form.f(v) + " Places")); - if(l == null) - { - sender.sendMessage("Couldn't find " + b.getName() + "."); - } + if (l == null) { + sender.sendMessage("Couldn't find " + b.getName() + "."); + } else { + sender.sendMessage("Found " + b.getName() + "!"); + J.s(() -> sender.player().teleport(l)); + } + }); + } else if (r != null) { + J.a(() -> { + Location l = g.lookForRegion(r, 60000, (v) -> sender.sendMessage(C.BOLD + "" + C.WHITE + r.getName() + C.RESET + C.GRAY + ": Checked " + Form.f(v) + " Places")); - else - { - sender.sendMessage("Found " + b.getName() + "!"); - J.s(() -> sender.player().teleport(l)); - } - }); - } - - else if(r != null) - { - J.a(() -> { - Location l = g.lookForRegion(r, 60000, (v) -> sender.sendMessage(C.BOLD +""+ C.WHITE + r.getName() + C.RESET + C.GRAY + ": Checked " + Form.f(v) + " Places")); - - if(l == null) - { - sender.sendMessage("Couldn't find " + r.getName() + "."); - } - - else - { - sender.sendMessage("Found " + r.getName() + "!"); - J.s(() -> sender.player().teleport(l)); - } - }); - } + if (l == null) { + sender.sendMessage("Couldn't find " + r.getName() + "."); + } else { + sender.sendMessage("Found " + r.getName() + "!"); + J.s(() -> sender.player().teleport(l)); + } + }); + } /* TODO: Fix this shit else if (o != null) { @@ -126,50 +106,42 @@ public class CommandIrisStudioGoto extends MortarCommand }); }*/ - else - { - sender.sendMessage(args[0] + " is not a biome or region in this dimension. (Biome teleportation works best!"); - } + else { + sender.sendMessage(args[0] + " is not a biome or region in this dimension. (Biome teleportation works best!"); + } - return true; - } + return true; + } else { + sender.sendMessage("Players only."); + } + } catch (Throwable e) { + Iris.error("Failed goto!"); + e.printStackTrace(); + sender.sendMessage("We cant seem to aquire a lock on the biome cache. Please report the error in the console to our github. Thanks!"); + } - else - { - sender.sendMessage("Players only."); - } - } + return true; + } - catch(Throwable e) - { - Iris.error("Failed goto!"); - e.printStackTrace(); - sender.sendMessage("We cant seem to aquire a lock on the biome cache. Please report the error in the console to our github. Thanks!"); - } + @Override + protected String getArgsUsage() { + return "[biome/region]"; + } - return true; - } + private List listf(String directoryName) { + File directory = new File(directoryName); + List files = new ArrayList<>(); - @Override - protected String getArgsUsage() - { - return "[biome/region]"; - } - - private List listf(String directoryName) { - File directory = new File(directoryName); - List files = new ArrayList<>(); - - // Get all files from a directory. - File[] fList = directory.listFiles(); - if(fList != null) - for (File file : fList) { - if (file.isFile()) { - files.add(file); - } else if (file.isDirectory()) { - files.addAll(listf(file.getAbsolutePath())); - } - } - return files; - } + // Get all files from a directory. + File[] fList = directory.listFiles(); + if (fList != null) + for (File file : fList) { + if (file.isFile()) { + files.add(file); + } else if (file.isDirectory()) { + files.addAll(listf(file.getAbsolutePath())); + } + } + return files; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioHotload.java b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioHotload.java index 7caae5c2e..c79e3f291 100644 --- a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioHotload.java +++ b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioHotload.java @@ -9,56 +9,47 @@ import com.volmit.iris.util.MortarSender; import org.bukkit.World; import org.bukkit.entity.Player; -public class CommandIrisStudioHotload extends MortarCommand -{ - public CommandIrisStudioHotload() - { - super("hotload", "hot", "h", "reload"); - setDescription("Force a hotload"); - requiresPermission(Iris.perm.studio); - setCategory("World"); - } +public class CommandIrisStudioHotload extends MortarCommand { + public CommandIrisStudioHotload() { + super("hotload", "hot", "h", "reload"); + setDescription("Force a hotload"); + requiresPermission(Iris.perm.studio); + setCategory("World"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); - return true; - } + } - if(sender.isPlayer()) - { - Player p = sender.player(); - World world = p.getWorld(); - if(!IrisWorlds.isIrisWorld(world)) - { - sender.sendMessage("You must be in an iris world."); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); + return true; + } - IrisWorlds.access(world).hotload(); - sender.sendMessage("Hotloaded!"); - return true; - } + if (sender.isPlayer()) { + Player p = sender.player(); + World world = p.getWorld(); + if (!IrisWorlds.isIrisWorld(world)) { + sender.sendMessage("You must be in an iris world."); + return true; + } - else - { - sender.sendMessage("Players only."); - } + IrisWorlds.access(world).hotload(); + sender.sendMessage("Hotloaded!"); + return true; + } else { + sender.sendMessage("Players only."); + } - return true; - } + return true; + } - @Override - protected String getArgsUsage() - { - return ""; - } + @Override + protected String getArgsUsage() { + return ""; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioLoot.java b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioLoot.java index 3ffebd7fe..cf5de89d5 100644 --- a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioLoot.java +++ b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioLoot.java @@ -2,7 +2,6 @@ package com.volmit.iris.manager.command.studio; import com.volmit.iris.Iris; import com.volmit.iris.IrisSettings; -import com.volmit.iris.manager.IrisDataManager; import com.volmit.iris.object.InventorySlotType; import com.volmit.iris.object.IrisLootTable; import com.volmit.iris.scaffold.IrisWorlds; @@ -13,113 +12,93 @@ import org.bukkit.entity.Player; import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; -public class CommandIrisStudioLoot extends MortarCommand -{ - public CommandIrisStudioLoot() - { - super("loot"); - setDescription("Show loot if a chest were right here"); - requiresPermission(Iris.perm.studio); - setCategory("Loot"); - } +public class CommandIrisStudioLoot extends MortarCommand { + public CommandIrisStudioLoot() { + super("loot"); + setDescription("Show loot if a chest were right here"); + requiresPermission(Iris.perm.studio); + setCategory("Loot"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); + return true; + } - if(sender.isPlayer()) - { - Player p = sender.player(); - IrisAccess prov = IrisWorlds.access(sender.player().getWorld()); + if (sender.isPlayer()) { + Player p = sender.player(); + IrisAccess prov = IrisWorlds.access(sender.player().getWorld()); - if (!Iris.proj.isProjectOpen()) - { - sender.sendMessage("You can only use /iris studio loot in a studio world of iris."); - return true; - } + if (!Iris.proj.isProjectOpen()) { + sender.sendMessage("You can only use /iris studio loot in a studio world of iris."); + return true; + } - KList tables = prov.getCompound().getEngine(p.getLocation().getBlockY()).getLootTables(RNG.r, p.getLocation().getBlock()); - Inventory inv = Bukkit.createInventory(null, 27 * 2); + KList tables = prov.getCompound().getEngine(p.getLocation().getBlockY()).getLootTables(RNG.r, p.getLocation().getBlock()); + Inventory inv = Bukkit.createInventory(null, 27 * 2); - try - { - Iris.proj.getActiveProject().getActiveProvider().getCompound().getEngine(p.getLocation().getBlockY()).addItems(true, inv, RNG.r, tables, InventorySlotType.STORAGE, p.getLocation().getBlockX(), p.getLocation().getBlockY(), p.getLocation().getBlockZ(), 1); - } + try { + Iris.proj.getActiveProject().getActiveProvider().getCompound().getEngine(p.getLocation().getBlockY()).addItems(true, inv, RNG.r, tables, InventorySlotType.STORAGE, p.getLocation().getBlockX(), p.getLocation().getBlockY(), p.getLocation().getBlockZ(), 1); + } catch (Throwable e) { + sender.sendMessage("You can only use /iris loot in a studio world of iris."); + return true; + } - catch(Throwable e) - { - sender.sendMessage("You can only use /iris loot in a studio world of iris."); - return true; - } + p.openInventory(inv); - p.openInventory(inv); + for (IrisLootTable i : tables) { + sender.sendMessage("- " + i.getName()); + } - for(IrisLootTable i : tables) - { - sender.sendMessage("- " + i.getName()); - } + boolean ffast = false; + boolean fadd = false; - boolean ffast = false; - boolean fadd = false; + for (String i : args) { + if (i.equals("--fast")) { + ffast = true; + } - for(String i : args) - { - if(i.equals("--fast")) - { - ffast = true; - } + if (i.equals("--add")) { + fadd = true; + } + } - if(i.equals("--add")) - { - fadd = true; - } - } + boolean fast = ffast; + boolean add = fadd; + O ta = new O(); + ta.set(-1); - boolean fast = ffast; - boolean add = fadd; - O ta = new O(); - ta.set(-1); + ta.set(Bukkit.getScheduler().scheduleSyncRepeatingTask(Iris.instance, () -> + { + if (!p.getOpenInventory().getType().equals(InventoryType.CHEST)) { + Bukkit.getScheduler().cancelTask(ta.get()); + return; + } - ta.set(Bukkit.getScheduler().scheduleSyncRepeatingTask(Iris.instance, () -> - { - if(!p.getOpenInventory().getType().equals(InventoryType.CHEST)) - { - Bukkit.getScheduler().cancelTask(ta.get()); - return; - } + if (!add) { + inv.clear(); + } - if(!add) - { - inv.clear(); - } + Iris.proj.getActiveProject().getActiveProvider().getCompound().getEngine(p.getLocation().getBlockY()).addItems(true, inv, new RNG(RNG.r.imax()), tables, InventorySlotType.STORAGE, p.getLocation().getBlockX(), p.getLocation().getBlockY(), p.getLocation().getBlockZ(), 1); + }, 0, fast ? 5 : 35)); - Iris.proj.getActiveProject().getActiveProvider().getCompound().getEngine(p.getLocation().getBlockY()).addItems(true, inv, new RNG(RNG.r.imax()), tables, InventorySlotType.STORAGE, p.getLocation().getBlockX(), p.getLocation().getBlockY(), p.getLocation().getBlockZ(), 1); - }, 0, fast ? 5 : 35)); + return true; + } else { + sender.sendMessage("Players only."); + } - return true; - } + return true; + } - else - { - sender.sendMessage("Players only."); - } - - return true; - } - - @Override - protected String getArgsUsage() - { - return "[width]"; - } + @Override + protected String getArgsUsage() { + return "[width]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioMap.java b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioMap.java index f98f0b919..ba78cca1d 100644 --- a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioMap.java +++ b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioMap.java @@ -9,57 +9,47 @@ import com.volmit.iris.util.KList; import com.volmit.iris.util.MortarCommand; import com.volmit.iris.util.MortarSender; -public class CommandIrisStudioMap extends MortarCommand -{ - public CommandIrisStudioMap() - { - super("map", "render"); - setDescription("Render a map (gui outside of mc)"); - requiresPermission(Iris.perm.studio); - setCategory("World"); - } +public class CommandIrisStudioMap extends MortarCommand { + public CommandIrisStudioMap() { + super("map", "render"); + setDescription("Render a map (gui outside of mc)"); + requiresPermission(Iris.perm.studio); + setCategory("World"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); + return true; + } - if(!IrisSettings.get().isUseServerLaunchedGuis()) - { - sender.sendMessage("To use Iris Guis, please enable serverLaunchedGuis in Iris/settings.json"); - return true; - } + if (!IrisSettings.get().isUseServerLaunchedGuis()) { + sender.sendMessage("To use Iris Guis, please enable serverLaunchedGuis in Iris/settings.json"); + return true; + } - try - { - IrisAccess g = Iris.proj.getActiveProject().getActiveProvider(); - IrisVision.launch(g, 0); - sender.sendMessage("Opening Map!"); - } + try { + IrisAccess g = Iris.proj.getActiveProject().getActiveProvider(); + IrisVision.launch(g, 0); + sender.sendMessage("Opening Map!"); + } catch (Throwable e) { + IrisAccess g = IrisWorlds.access(sender.player().getWorld()); + IrisVision.launch(g, 0); + sender.sendMessage("Opening Map!"); + } - catch(Throwable e) - { - IrisAccess g = IrisWorlds.access(sender.player().getWorld()); - IrisVision.launch(g, 0); - sender.sendMessage("Opening Map!"); - } + return true; + } - return true; - } - - @Override - protected String getArgsUsage() - { - return ""; - } + @Override + protected String getArgsUsage() { + return ""; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioOpen.java b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioOpen.java index 927c3ed61..441b884e3 100644 --- a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioOpen.java +++ b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioOpen.java @@ -6,43 +6,37 @@ import com.volmit.iris.util.KList; import com.volmit.iris.util.MortarCommand; import com.volmit.iris.util.MortarSender; -public class CommandIrisStudioOpen extends MortarCommand -{ - public CommandIrisStudioOpen() - { - super("open", "o"); - requiresPermission(Iris.perm.studio); - setDescription("Create a new temporary world to design a dimension."); - setCategory("Studio"); - } +public class CommandIrisStudioOpen extends MortarCommand { + public CommandIrisStudioOpen() { + super("open", "o"); + requiresPermission(Iris.perm.studio); + setDescription("Create a new temporary world to design a dimension."); + setCategory("Studio"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); - return true; - } - - if(args.length < 1) - { - sender.sendMessage("/iris std open (file name without .json)"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); + return true; + } - Iris.proj.open(sender, args[0]); - return true; - } + if (args.length < 1) { + sender.sendMessage("/iris std open (file name without .json)"); + return true; + } - @Override - protected String getArgsUsage() - { - return "[dimension]"; - } + Iris.proj.open(sender, args[0]); + return true; + } + + @Override + protected String getArgsUsage() { + return "[dimension]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioPackage.java b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioPackage.java index d1cc8eed8..27a601543 100644 --- a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioPackage.java +++ b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioPackage.java @@ -7,59 +7,51 @@ import com.volmit.iris.util.KList; import com.volmit.iris.util.MortarCommand; import com.volmit.iris.util.MortarSender; -public class CommandIrisStudioPackage extends MortarCommand -{ - public CommandIrisStudioPackage() - { - super("package", "pkg"); - requiresPermission(Iris.perm.studio); - setDescription("Package your dimension into a compressed format."); - setCategory("Studio"); - } +public class CommandIrisStudioPackage extends MortarCommand { + public CommandIrisStudioPackage() { + super("package", "pkg"); + requiresPermission(Iris.perm.studio); + setDescription("Package your dimension into a compressed format."); + setCategory("Studio"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); - return true; - } - - if(args.length == 0) - { - sender.sendMessage("/iris std package [-o] [-m]"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); + return true; + } - J.a(() -> - { - boolean o = false; - boolean m = true; + if (args.length == 0) { + sender.sendMessage("/iris std package [-o] [-m]"); + return true; + } - for(String i : args) - { - if(i.equalsIgnoreCase("-o")) - { - o = true; - } - } + J.a(() -> + { + boolean o = false; + boolean m = true; - String dim = args[0]; - Iris.proj.compilePackage(sender, dim, o, m); - }); + for (String i : args) { + if (i.equalsIgnoreCase("-o")) { + o = true; + } + } - return true; - } + String dim = args[0]; + Iris.proj.compilePackage(sender, dim, o, m); + }); - @Override - protected String getArgsUsage() - { - return "[dimension] [-o] [-m]"; - } + return true; + } + + @Override + protected String getArgsUsage() { + return "[dimension] [-o] [-m]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioProfile.java b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioProfile.java index d29d0583a..91e0c7741 100644 --- a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioProfile.java +++ b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioProfile.java @@ -11,266 +11,235 @@ import com.volmit.iris.util.*; import java.io.File; import java.io.IOException; -public class CommandIrisStudioProfile extends MortarCommand -{ - public CommandIrisStudioProfile() - { - super("profile", "blame"); - requiresPermission(Iris.perm.studio); - setDescription("Profile the specified project"); - setCategory("Studio"); - } +public class CommandIrisStudioProfile extends MortarCommand { + public CommandIrisStudioProfile() { + super("profile", "blame"); + requiresPermission(Iris.perm.studio); + setDescription("Profile the specified project"); + setCategory("Studio"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); + return true; + } - J.a(() -> { - File f = null; - File report = Iris.instance.getDataFile("profile.txt"); - KList v = new KList<>(); - if(args.length == 0) - { - if(!Iris.proj.isProjectOpen()) - { - sender.sendMessage("No open project. Either use /iris std beautify or have a project open."); - return; - } + J.a(() -> { + File f = null; + File report = Iris.instance.getDataFile("profile.txt"); + KList v = new KList<>(); + if (args.length == 0) { + if (!Iris.proj.isProjectOpen()) { + sender.sendMessage("No open project. Either use /iris std beautify or have a project open."); + return; + } - f = Iris.proj.getActiveProject().getPath(); - } + f = Iris.proj.getActiveProject().getPath(); + } else { + f = Iris.instance.getDataFolder("packs", args[0]); - else - { - f = Iris.instance.getDataFolder("packs", args[0]); + if (!f.exists()) { + sender.sendMessage("Not a valid project."); + return; + } + } - if(!f.exists()) - { - sender.sendMessage("Not a valid project."); - return; - } - } + IrisProject p = new IrisProject(f); + IrisDataManager data = new IrisDataManager(f); + KMap styleTimings = new KMap<>(); + KMap interpolatorTimings = new KMap<>(); + KMap generatorTimings = new KMap<>(); + KMap biomeTimings = new KMap<>(); + KMap regionTimings = new KMap<>(); - IrisProject p = new IrisProject(f); - IrisDataManager data = new IrisDataManager(f); - KMap styleTimings = new KMap<>(); - KMap interpolatorTimings = new KMap<>(); - KMap generatorTimings = new KMap<>(); - KMap biomeTimings = new KMap<>(); - KMap regionTimings = new KMap<>(); - - sender.sendMessage("Calculating Performance Metrics for Noise Generators..."); + sender.sendMessage("Calculating Performance Metrics for Noise Generators..."); - for(NoiseStyle i : NoiseStyle.values()) - { - CNG c = i.create(new RNG(i.hashCode())); + for (NoiseStyle i : NoiseStyle.values()) { + CNG c = i.create(new RNG(i.hashCode())); - for(int j = 0; j < 30000; j++) - { - c.noise(j, j + 1000, j * j); - c.noise(j, -j); - } + for (int j = 0; j < 30000; j++) { + c.noise(j, j + 1000, j * j); + c.noise(j, -j); + } - PrecisionStopwatch px = PrecisionStopwatch.start(); + PrecisionStopwatch px = PrecisionStopwatch.start(); - for(int j = 0; j < 1000000; j++) - { - c.noise(j, j + 1000, j * j); - c.noise(j, -j); - } + for (int j = 0; j < 1000000; j++) { + c.noise(j, j + 1000, j * j); + c.noise(j, -j); + } - styleTimings.put(i, px.getMilliseconds()); - } + styleTimings.put(i, px.getMilliseconds()); + } - v.add("Noise Style Performance Impacts: "); + v.add("Noise Style Performance Impacts: "); - for(NoiseStyle i : styleTimings.sortKNumber()) - { - v.add(i.name() +": "+ styleTimings.get(i)); - } + for (NoiseStyle i : styleTimings.sortKNumber()) { + v.add(i.name() + ": " + styleTimings.get(i)); + } - v.add(""); + v.add(""); - sender.sendMessage("Calculating Interpolator Timings..."); + sender.sendMessage("Calculating Interpolator Timings..."); - for(InterpolationMethod i : InterpolationMethod.values()) - { - IrisInterpolator in = new IrisInterpolator(); - in.setFunction(i); - in.setHorizontalScale(8); + for (InterpolationMethod i : InterpolationMethod.values()) { + IrisInterpolator in = new IrisInterpolator(); + in.setFunction(i); + in.setHorizontalScale(8); - NoiseProvider np = new NoiseProvider() { - @Override - public double noise(double x, double z) { - return Math.random(); - } - }; + NoiseProvider np = new NoiseProvider() { + @Override + public double noise(double x, double z) { + return Math.random(); + } + }; - for(int j = 0; j < 3000; j++) - { - in.interpolate(j, -j, np); - } + for (int j = 0; j < 3000; j++) { + in.interpolate(j, -j, np); + } - PrecisionStopwatch px = PrecisionStopwatch.start(); + PrecisionStopwatch px = PrecisionStopwatch.start(); - for(int j = 0; j < 100000; j++) - { - in.interpolate(j + 10000, -j - 100000, np); - } + for (int j = 0; j < 100000; j++) { + in.interpolate(j + 10000, -j - 100000, np); + } - interpolatorTimings.put(i, px.getMilliseconds()); - } + interpolatorTimings.put(i, px.getMilliseconds()); + } - v.add("Noise Interpolator Performance Impacts: "); + v.add("Noise Interpolator Performance Impacts: "); - for(InterpolationMethod i : interpolatorTimings.sortKNumber()) - { - v.add(i.name() +": "+ interpolatorTimings.get(i)); - } + for (InterpolationMethod i : interpolatorTimings.sortKNumber()) { + v.add(i.name() + ": " + interpolatorTimings.get(i)); + } - v.add(""); + v.add(""); - sender.sendMessage("Processing Generator Scores: "); + sender.sendMessage("Processing Generator Scores: "); - KMap> btx = new KMap<>(); + KMap> btx = new KMap<>(); - for(String i : data.getGeneratorLoader().getPossibleKeys()) - { - KList vv = new KList<>(); - IrisGenerator g = data.getGeneratorLoader().load(i); - KList composites = g.getAllComposites(); - double score = 0; - int m = 0; - for(IrisNoiseGenerator j : composites) - { - m++; - score += styleTimings.get(j.getStyle().getStyle()); - vv.add("Composite Noise Style " + m + " " + j.getStyle().getStyle().name() + ": " + styleTimings.get(j.getStyle().getStyle())); - } + for (String i : data.getGeneratorLoader().getPossibleKeys()) { + KList vv = new KList<>(); + IrisGenerator g = data.getGeneratorLoader().load(i); + KList composites = g.getAllComposites(); + double score = 0; + int m = 0; + for (IrisNoiseGenerator j : composites) { + m++; + score += styleTimings.get(j.getStyle().getStyle()); + vv.add("Composite Noise Style " + m + " " + j.getStyle().getStyle().name() + ": " + styleTimings.get(j.getStyle().getStyle())); + } - score += interpolatorTimings.get(g.getInterpolator().getFunction()); - vv.add("Interpolator " + g.getInterpolator().getFunction().name() + ": " + interpolatorTimings.get(g.getInterpolator().getFunction())); - generatorTimings.put(i, score); - btx.put(i, vv); - } + score += interpolatorTimings.get(g.getInterpolator().getFunction()); + vv.add("Interpolator " + g.getInterpolator().getFunction().name() + ": " + interpolatorTimings.get(g.getInterpolator().getFunction())); + generatorTimings.put(i, score); + btx.put(i, vv); + } - v.add("Project Generator Performance Impacts: "); + v.add("Project Generator Performance Impacts: "); - for(String i : generatorTimings.sortKNumber()) - { - v.add(i + ": " + generatorTimings.get(i)); + for (String i : generatorTimings.sortKNumber()) { + v.add(i + ": " + generatorTimings.get(i)); - btx.get(i).forEach((ii) -> v.add(" " + ii)); - } + btx.get(i).forEach((ii) -> v.add(" " + ii)); + } - v.add(""); + v.add(""); - KMap> bt = new KMap<>(); + KMap> bt = new KMap<>(); - for(String i : data.getBiomeLoader().getPossibleKeys()) - { - KList vv = new KList<>(); - IrisBiome b = data.getBiomeLoader().load(i); - double score = 0; + for (String i : data.getBiomeLoader().getPossibleKeys()) { + KList vv = new KList<>(); + IrisBiome b = data.getBiomeLoader().load(i); + double score = 0; - int m = 0; - for(IrisBiomePaletteLayer j : b.getLayers()) - { - m++; - score += styleTimings.get(j.getStyle().getStyle()); - vv.add("Palette Layer " + m + ": " + styleTimings.get(j.getStyle().getStyle())); - } + int m = 0; + for (IrisBiomePaletteLayer j : b.getLayers()) { + m++; + score += styleTimings.get(j.getStyle().getStyle()); + vv.add("Palette Layer " + m + ": " + styleTimings.get(j.getStyle().getStyle())); + } - score += styleTimings.get(b.getBiomeStyle().getStyle()); - vv.add("Biome Style: " + styleTimings.get(b.getBiomeStyle().getStyle())); - score += styleTimings.get(b.getChildStyle().getStyle()); - vv.add("Child Style: " + styleTimings.get(b.getChildStyle().getStyle())); - biomeTimings.put(i, score); - bt.put(i, vv); - } + score += styleTimings.get(b.getBiomeStyle().getStyle()); + vv.add("Biome Style: " + styleTimings.get(b.getBiomeStyle().getStyle())); + score += styleTimings.get(b.getChildStyle().getStyle()); + vv.add("Child Style: " + styleTimings.get(b.getChildStyle().getStyle())); + biomeTimings.put(i, score); + bt.put(i, vv); + } - v.add("Project Biome Performance Impacts: "); + v.add("Project Biome Performance Impacts: "); - for(String i : biomeTimings.sortKNumber()) - { - v.add(i + ": " + biomeTimings.get(i)); + for (String i : biomeTimings.sortKNumber()) { + v.add(i + ": " + biomeTimings.get(i)); - bt.get(i).forEach((ff) -> v.add(" " + ff)); - } + bt.get(i).forEach((ff) -> v.add(" " + ff)); + } - v.add(""); + v.add(""); - for(String i : data.getRegionLoader().getPossibleKeys()) - { - IrisRegion b = data.getRegionLoader().load(i); - double score = 0; + for (String i : data.getRegionLoader().getPossibleKeys()) { + IrisRegion b = data.getRegionLoader().load(i); + double score = 0; - score += styleTimings.get(b.getLakeStyle().getStyle()); - score += styleTimings.get(b.getRiverStyle().getStyle()); - regionTimings.put(i, score); - } + score += styleTimings.get(b.getLakeStyle().getStyle()); + score += styleTimings.get(b.getRiverStyle().getStyle()); + regionTimings.put(i, score); + } - v.add("Project Region Performance Impacts: "); + v.add("Project Region Performance Impacts: "); - for(String i : regionTimings.sortKNumber()) - { - v.add(i + ": " + regionTimings.get(i)); - } + for (String i : regionTimings.sortKNumber()) { + v.add(i + ": " + regionTimings.get(i)); + } - v.add(""); + v.add(""); - double m = 0; - for(double i : biomeTimings.v()) - { - m+=i; - } - m/=biomeTimings.size(); - double mm = 0; - for(double i : generatorTimings.v()) - { - mm+=i; - } - mm/=generatorTimings.size(); - m+=mm; - double mmm = 0; - for(double i : regionTimings.v()) - { - mmm+=i; - } - mmm/=regionTimings.size(); - m+=mmm; + double m = 0; + for (double i : biomeTimings.v()) { + m += i; + } + m /= biomeTimings.size(); + double mm = 0; + for (double i : generatorTimings.v()) { + mm += i; + } + mm /= generatorTimings.size(); + m += mm; + double mmm = 0; + for (double i : regionTimings.v()) { + mmm += i; + } + mmm /= regionTimings.size(); + m += mmm; - v.add("Average Score: " + m); - sender.sendMessage("Score: " + Form.duration(m, 0)); + v.add("Average Score: " + m); + sender.sendMessage("Score: " + Form.duration(m, 0)); - try { - IO.writeAll(report, v.toString("\n")); - } catch (IOException e) { - e.printStackTrace(); - } + try { + IO.writeAll(report, v.toString("\n")); + } catch (IOException e) { + e.printStackTrace(); + } - sender.sendMessage("Done! " + report.getPath()); - }); + sender.sendMessage("Done! " + report.getPath()); + }); + return true; + } - return true; - } - - @Override - protected String getArgsUsage() - { - return "[project]"; - } + @Override + protected String getArgsUsage() { + return "[project]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioSummon.java b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioSummon.java index 426d6c5f5..0b0accbc7 100644 --- a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioSummon.java +++ b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioSummon.java @@ -13,75 +13,59 @@ import org.bukkit.Location; import org.bukkit.World; import org.bukkit.entity.Player; -public class CommandIrisStudioSummon extends MortarCommand -{ - public CommandIrisStudioSummon() - { - super("summon", "spawnmob"); - setDescription("Spawn an Iris entity"); - requiresPermission(Iris.perm.studio); - setCategory("Summon"); - } +public class CommandIrisStudioSummon extends MortarCommand { + public CommandIrisStudioSummon() { + super("summon", "spawnmob"); + setDescription("Spawn an Iris entity"); + requiresPermission(Iris.perm.studio); + setCategory("Summon"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); + return true; + } - if(sender.isPlayer()) - { - Player p = sender.player(); - World world = p.getWorld(); - if(!IrisWorlds.isIrisWorld(world)) - { - sender.sendMessage("You must be in an iris world."); - return true; - } + if (sender.isPlayer()) { + Player p = sender.player(); + World world = p.getWorld(); + if (!IrisWorlds.isIrisWorld(world)) { + sender.sendMessage("You must be in an iris world."); + return true; + } - IrisAccess g = IrisWorlds.access(world); - if(args.length == 0) - { - for(String i : g.getData().getEntityLoader().getPossibleKeys()) - { - sender.sendMessage("- " + i); - } - } + IrisAccess g = IrisWorlds.access(world); + if (args.length == 0) { + for (String i : g.getData().getEntityLoader().getPossibleKeys()) { + sender.sendMessage("- " + i); + } + } else { + IrisEntity e = g.getData().getEntityLoader().load(args[0]); - else - { - IrisEntity e = g.getData().getEntityLoader().load(args[0]); + if (e == null) { + sender.sendMessage("Couldnt find entity " + args[0] + ". Use '/iris std summon' to see a list of iris entities."); + return true; + } - if(e == null) - { - sender.sendMessage("Couldnt find entity " + args[0] + ". Use '/iris std summon' to see a list of iris entities."); - return true; - } + Location vl = sender.player().getLocation().clone().add(0, 3, 0); + e.spawn((Engine) g.getEngineAccess(vl.getBlockY()), vl); + } + } else { + sender.sendMessage("Players only."); + } - Location vl = sender.player().getLocation().clone().add(0, 3, 0); - e.spawn((Engine) g.getEngineAccess(vl.getBlockY()), vl); - } - } + return true; + } - else - { - sender.sendMessage("Players only."); - } - - return true; - } - - @Override - protected String getArgsUsage() - { - return ""; - } + @Override + protected String getArgsUsage() { + return ""; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioTPStudio.java b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioTPStudio.java index 24a2e7e87..2da7c274a 100644 --- a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioTPStudio.java +++ b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioTPStudio.java @@ -7,59 +7,49 @@ import com.volmit.iris.util.MortarCommand; import com.volmit.iris.util.MortarSender; import org.bukkit.GameMode; -public class CommandIrisStudioTPStudio extends MortarCommand -{ - public CommandIrisStudioTPStudio() - { - super("tps", "stp", "tpstudio"); - requiresPermission(Iris.perm.studio); - setDescription("Go to the spawn of the currently open studio world."); - setCategory("Studio"); - } +public class CommandIrisStudioTPStudio extends MortarCommand { + public CommandIrisStudioTPStudio() { + super("tps", "stp", "tpstudio"); + requiresPermission(Iris.perm.studio); + setDescription("Go to the spawn of the currently open studio world."); + setCategory("Studio"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); + return true; + } - if(!sender.isPlayer()){ - sender.sendMessage("Cannot be ran by console."); - return true; - } + if (!sender.isPlayer()) { + sender.sendMessage("Cannot be ran by console."); + return true; + } - if(!Iris.proj.isProjectOpen()) - { - sender.sendMessage("There is not a studio currently loaded."); - return true; - } + if (!Iris.proj.isProjectOpen()) { + sender.sendMessage("There is not a studio currently loaded."); + return true; + } - try - { - sender.sendMessage("Teleporting you to the active studio world."); - sender.player().teleport(Iris.proj.getActiveProject().getActiveProvider().getTarget().getWorld().getSpawnLocation()); - sender.player().setGameMode(GameMode.SPECTATOR); - } + try { + sender.sendMessage("Teleporting you to the active studio world."); + sender.player().teleport(Iris.proj.getActiveProject().getActiveProvider().getTarget().getWorld().getSpawnLocation()); + sender.player().setGameMode(GameMode.SPECTATOR); + } catch (Throwable e) { + sender.sendMessage("Failed to teleport to the studio world. Try re-opening the project."); + } - catch(Throwable e) - { - sender.sendMessage("Failed to teleport to the studio world. Try re-opening the project."); - } + return true; + } - return true; - } - - @Override - protected String getArgsUsage() - { - return ""; - } + @Override + protected String getArgsUsage() { + return ""; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioUpdate.java b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioUpdate.java index 3cbb432cc..84bce9e66 100644 --- a/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioUpdate.java +++ b/src/main/java/com/volmit/iris/manager/command/studio/CommandIrisStudioUpdate.java @@ -7,52 +7,42 @@ import com.volmit.iris.util.KList; import com.volmit.iris.util.MortarCommand; import com.volmit.iris.util.MortarSender; -public class CommandIrisStudioUpdate extends MortarCommand -{ - public CommandIrisStudioUpdate() - { - super("update", "upd", "u"); - requiresPermission(Iris.perm.studio); - setDescription("Update your dimension project."); - setCategory("Studio"); - } +public class CommandIrisStudioUpdate extends MortarCommand { + public CommandIrisStudioUpdate() { + super("update", "upd", "u"); + requiresPermission(Iris.perm.studio); + setDescription("Update your dimension project."); + setCategory("Studio"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(!IrisSettings.get().isStudio()) - { - sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (!IrisSettings.get().isStudio()) { + sender.sendMessage("To use Iris Studio, please enable studio in Iris/settings.json"); + return true; + } - if(args.length == 0) - { - sender.sendMessage("/iris std package "); - return true; - } + if (args.length == 0) { + sender.sendMessage("/iris std package "); + return true; + } - if(new IrisProject(Iris.proj.getWorkspaceFolder(args[0])).updateWorkspace()) - { - sender.sendMessage("Updated Code Workspace for " + args[0]); - } + if (new IrisProject(Iris.proj.getWorkspaceFolder(args[0])).updateWorkspace()) { + sender.sendMessage("Updated Code Workspace for " + args[0]); + } else { + sender.sendMessage("Invalid project: " + args[0] + ". Try deleting the code-workspace file and try again."); + } - else - { - sender.sendMessage("Invalid project: " + args[0] + ". Try deleting the code-workspace file and try again."); - } + return true; + } - return true; - } - - @Override - protected String getArgsUsage() - { - return "[dimension]"; - } + @Override + protected String getArgsUsage() { + return "[dimension]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/what/CommandIrisWhat.java b/src/main/java/com/volmit/iris/manager/command/what/CommandIrisWhat.java index e8d2327f1..fe0bbd9bb 100644 --- a/src/main/java/com/volmit/iris/manager/command/what/CommandIrisWhat.java +++ b/src/main/java/com/volmit/iris/manager/command/what/CommandIrisWhat.java @@ -6,45 +6,41 @@ import com.volmit.iris.util.KList; import com.volmit.iris.util.MortarCommand; import com.volmit.iris.util.MortarSender; -public class CommandIrisWhat extends MortarCommand -{ - @Command - private CommandIrisWhatBlock block; +public class CommandIrisWhat extends MortarCommand { + @Command + private CommandIrisWhatBlock block; - @Command - private CommandIrisWhatHand hand; + @Command + private CommandIrisWhatHand hand; - @Command - private CommandIrisWhatBiome biome; + @Command + private CommandIrisWhatBiome biome; - @Command - private CommandIrisWhatObjects objects; + @Command + private CommandIrisWhatObjects objects; - public CommandIrisWhat() - { - super("what", "w", "?"); - setDescription("Get timings for this world"); - requiresPermission(Iris.perm.studio); - setCategory("Wut"); - setDescription("Figure out what stuff is"); - } + public CommandIrisWhat() { + super("what", "w", "?"); + setDescription("Get timings for this world"); + requiresPermission(Iris.perm.studio); + setCategory("Wut"); + setDescription("Figure out what stuff is"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - sender.sendMessage("Iris 'What' Commands:"); - printHelp(sender); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + sender.sendMessage("Iris 'What' Commands:"); + printHelp(sender); + return true; + } - @Override - protected String getArgsUsage() - { - return ""; - } + @Override + protected String getArgsUsage() { + return ""; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/what/CommandIrisWhatBiome.java b/src/main/java/com/volmit/iris/manager/command/what/CommandIrisWhatBiome.java index 22f5e5d39..fc22eb4f0 100644 --- a/src/main/java/com/volmit/iris/manager/command/what/CommandIrisWhatBiome.java +++ b/src/main/java/com/volmit/iris/manager/command/what/CommandIrisWhatBiome.java @@ -8,91 +8,57 @@ import com.volmit.iris.scaffold.engine.IrisAccess; import com.volmit.iris.util.KList; import com.volmit.iris.util.MortarCommand; import com.volmit.iris.util.MortarSender; -import net.minecraft.core.BlockPosition; -import net.minecraft.core.IRegistry; -import net.minecraft.core.IRegistryCustom; -import net.minecraft.core.IRegistryWritable; -import net.minecraft.data.RegistryGeneration; -import net.minecraft.data.worldgen.biome.BiomeRegistry; -import net.minecraft.resources.MinecraftKey; -import net.minecraft.resources.ResourceKey; -import net.minecraft.server.commands.CommandLocateBiome; -import net.minecraft.server.level.WorldServer; -import net.minecraft.world.level.biome.BiomeBase; import org.bukkit.World; import org.bukkit.block.Biome; -import org.bukkit.craftbukkit.libs.it.unimi.dsi.fastutil.ints.Int2ObjectMap; -import org.bukkit.craftbukkit.v1_17_R1.CraftWorld; -import org.bukkit.craftbukkit.v1_17_R1.block.CraftBlock; import org.bukkit.entity.Player; -import java.lang.reflect.Field; -import java.util.Map; +public class CommandIrisWhatBiome extends MortarCommand { + public CommandIrisWhatBiome() { + super("biome", "bi", "b"); + setDescription("Get the biome data you are in."); + requiresPermission(Iris.perm.studio); + setCategory("Wut"); + setDescription("What biome am I in"); + } -public class CommandIrisWhatBiome extends MortarCommand -{ - public CommandIrisWhatBiome() - { - super("biome", "bi", "b"); - setDescription("Get the biome data you are in."); - requiresPermission(Iris.perm.studio); - setCategory("Wut"); - setDescription("What biome am I in"); - } + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + } - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (sender.isPlayer()) { + Player p = sender.player(); + World w = p.getWorld(); - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(sender.isPlayer()) - { - Player p = sender.player(); - World w = p.getWorld(); + try { - try - { + IrisAccess g = IrisWorlds.access(w); + assert g != null; + IrisBiome b = g.getBiome(p.getLocation().getBlockX(), p.getLocation().getBlockY(), p.getLocation().getBlockZ()); + sender.sendMessage("IBiome: " + b.getLoadKey() + " (" + b.getDerivative().name() + ")"); - IrisAccess g = IrisWorlds.access(w); - assert g != null; - IrisBiome b = g.getBiome(p.getLocation().getBlockX(), p.getLocation().getBlockY(), p.getLocation().getBlockZ()); - sender.sendMessage("IBiome: " + b.getLoadKey() + " (" + b.getDerivative().name() + ")"); + } catch (Throwable e) { + sender.sendMessage("Non-Iris Biome: " + p.getLocation().getBlock().getBiome().name()); - } + if (p.getLocation().getBlock().getBiome().equals(Biome.CUSTOM)) { + try { + sender.sendMessage("Data Pack Biome: " + INMS.get().getTrueBiomeBaseKey(p.getLocation()) + " (ID: " + INMS.get().getTrueBiomeBaseId(INMS.get().getTrueBiomeBase(p.getLocation())) + ")"); + } catch (Throwable ex) { - catch(Throwable e) - { - sender.sendMessage("Non-Iris Biome: " + p.getLocation().getBlock().getBiome().name()); + } + } + } + } else { + sender.sendMessage("Players only."); + } - if(p.getLocation().getBlock().getBiome().equals(Biome.CUSTOM)) - { - try - { - sender.sendMessage("Data Pack Biome: " + INMS.get().getTrueBiomeBaseKey(p.getLocation()) + " (ID: " + INMS.get().getTrueBiomeBaseId(INMS.get().getTrueBiomeBase(p.getLocation())) + ")"); - } + return true; + } - catch(Throwable ex) - { - - } - } - } - } - - else - { - sender.sendMessage("Players only."); - } - - return true; - } - - @Override - protected String getArgsUsage() - { - return ""; - } + @Override + protected String getArgsUsage() { + return ""; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/what/CommandIrisWhatBlock.java b/src/main/java/com/volmit/iris/manager/command/what/CommandIrisWhatBlock.java index 3faf70dd6..528d79faf 100644 --- a/src/main/java/com/volmit/iris/manager/command/what/CommandIrisWhatBlock.java +++ b/src/main/java/com/volmit/iris/manager/command/what/CommandIrisWhatBlock.java @@ -1,90 +1,78 @@ package com.volmit.iris.manager.command.what; +import com.volmit.iris.Iris; import com.volmit.iris.util.*; import org.bukkit.FluidCollisionMode; import org.bukkit.block.data.BlockData; import org.bukkit.entity.Player; -import com.volmit.iris.Iris; +public class CommandIrisWhatBlock extends MortarCommand { + public CommandIrisWhatBlock() { + super("block", "l", "bl"); + setDescription("Get the block data for looking."); + requiresPermission(Iris.perm.studio); + setCategory("Wut"); + setDescription("WAILA, WAWLA etc"); + } -public class CommandIrisWhatBlock extends MortarCommand -{ - public CommandIrisWhatBlock() - { - super("block", "l", "bl"); - setDescription("Get the block data for looking."); - requiresPermission(Iris.perm.studio); - setCategory("Wut"); - setDescription("WAILA, WAWLA etc"); - } + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + } - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (sender.isPlayer()) { + BlockData bd; + Player p = sender.player(); + try { + bd = p.getTargetBlockExact(128, FluidCollisionMode.NEVER).getBlockData(); + } catch (NullPointerException e) { + sender.sendMessage("Please look at any block, not at the sky"); + bd = null; + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(sender.isPlayer()) - { - BlockData bd; - Player p = sender.player(); - try - { - bd = p.getTargetBlockExact(128, FluidCollisionMode.NEVER).getBlockData(); - } - catch (NullPointerException e) - { - sender.sendMessage("Please look at any block, not at the sky"); - bd = null; - } + if (bd != null) { + sender.sendMessage("Material: " + C.GREEN + bd.getMaterial().name()); + sender.sendMessage("Full: " + C.WHITE + bd.getAsString(true)); - if(bd != null) { - sender.sendMessage("Material: " + C.GREEN + bd.getMaterial().name()); - sender.sendMessage("Full: " + C.WHITE + bd.getAsString(true)); + if (B.isStorage(bd)) { + sender.sendMessage(C.YELLOW + "* Storage Block (Loot Capable)"); + } - if (B.isStorage(bd)) { - sender.sendMessage(C.YELLOW + "* Storage Block (Loot Capable)"); - } + if (B.isLit(bd)) { + sender.sendMessage(C.YELLOW + "* Lit Block (Light Capable)"); + } - if (B.isLit(bd)) { - sender.sendMessage(C.YELLOW + "* Lit Block (Light Capable)"); - } + if (B.isFoliage(bd)) { + sender.sendMessage(C.YELLOW + "* Foliage Block"); + } - if (B.isFoliage(bd)) { - sender.sendMessage(C.YELLOW + "* Foliage Block"); - } + if (B.isDecorant(bd)) { + sender.sendMessage(C.YELLOW + "* Decorant Block"); + } - if (B.isDecorant(bd)) { - sender.sendMessage(C.YELLOW + "* Decorant Block"); - } + if (B.isFluid(bd)) { + sender.sendMessage(C.YELLOW + "* Fluid Block"); + } - if (B.isFluid(bd)) { - sender.sendMessage(C.YELLOW + "* Fluid Block"); - } + if (B.isFoliagePlantable(bd)) { + sender.sendMessage(C.YELLOW + "* Plantable Foliage Block"); + } - if (B.isFoliagePlantable(bd)) { - sender.sendMessage(C.YELLOW + "* Plantable Foliage Block"); - } + if (B.isSolid(bd)) { + sender.sendMessage(C.YELLOW + "* Solid Block"); + } + } + } else { + sender.sendMessage("Players only."); + } - if (B.isSolid(bd)) { - sender.sendMessage(C.YELLOW + "* Solid Block"); - } - } - } + return true; + } - else - { - sender.sendMessage("Players only."); - } - - return true; - } - - @Override - protected String getArgsUsage() - { - return ""; - } + @Override + protected String getArgsUsage() { + return ""; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/what/CommandIrisWhatHand.java b/src/main/java/com/volmit/iris/manager/command/what/CommandIrisWhatHand.java index fe9d8f1f6..07c0346da 100644 --- a/src/main/java/com/volmit/iris/manager/command/what/CommandIrisWhatHand.java +++ b/src/main/java/com/volmit/iris/manager/command/what/CommandIrisWhatHand.java @@ -1,70 +1,57 @@ package com.volmit.iris.manager.command.what; +import com.volmit.iris.Iris; +import com.volmit.iris.util.C; import com.volmit.iris.util.KList; +import com.volmit.iris.util.MortarCommand; +import com.volmit.iris.util.MortarSender; import org.bukkit.Material; import org.bukkit.block.data.BlockData; import org.bukkit.entity.Player; -import com.volmit.iris.Iris; -import com.volmit.iris.util.C; -import com.volmit.iris.util.MortarCommand; -import com.volmit.iris.util.MortarSender; +public class CommandIrisWhatHand extends MortarCommand { + public CommandIrisWhatHand() { + super("hand", "h"); + setDescription("Get the block data for holding."); + requiresPermission(Iris.perm.studio); + setCategory("Wut"); + setDescription("What block am I holding"); + } -public class CommandIrisWhatHand extends MortarCommand -{ - public CommandIrisWhatHand() - { - super("hand", "h"); - setDescription("Get the block data for holding."); - requiresPermission(Iris.perm.studio); - setCategory("Wut"); - setDescription("What block am I holding"); - } + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + } - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (sender.isPlayer()) { + Player p = sender.player(); + try { + BlockData bd = p.getInventory().getItemInMainHand().getType().createBlockData(); + if (!bd.getMaterial().equals(Material.AIR)) { + sender.sendMessage("Material: " + C.GREEN + bd.getMaterial().name()); + sender.sendMessage("Full: " + C.WHITE + bd.getAsString(true)); + } else { + sender.sendMessage("Please hold a block/item"); + } + } catch (Throwable e) { + Material bd = p.getInventory().getItemInMainHand().getType(); + if (!bd.equals(Material.AIR)) { + sender.sendMessage("Material: " + C.GREEN + bd.name()); + } else { + sender.sendMessage("Please hold a block/item"); + } + } + } else { + sender.sendMessage("Players only."); + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(sender.isPlayer()) - { - Player p = sender.player(); - try - { - BlockData bd = p.getInventory().getItemInMainHand().getType().createBlockData(); - if(!bd.getMaterial().equals(Material.AIR)) { - sender.sendMessage("Material: " + C.GREEN + bd.getMaterial().name()); - sender.sendMessage("Full: " + C.WHITE + bd.getAsString(true)); - } else { - sender.sendMessage("Please hold a block/item"); - } - } + return true; + } - catch(Throwable e) - { - Material bd = p.getInventory().getItemInMainHand().getType(); - if(!bd.equals(Material.AIR)) { - sender.sendMessage("Material: " + C.GREEN + bd.name()); - } else { - sender.sendMessage("Please hold a block/item"); - } - } - } - - else - { - sender.sendMessage("Players only."); - } - - return true; - } - - @Override - protected String getArgsUsage() - { - return ""; - } + @Override + protected String getArgsUsage() { + return ""; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/what/CommandIrisWhatObjects.java b/src/main/java/com/volmit/iris/manager/command/what/CommandIrisWhatObjects.java index 13ebf9f9f..15e498d28 100644 --- a/src/main/java/com/volmit/iris/manager/command/what/CommandIrisWhatObjects.java +++ b/src/main/java/com/volmit/iris/manager/command/what/CommandIrisWhatObjects.java @@ -23,253 +23,207 @@ import java.time.temporal.ChronoUnit; import java.util.Date; import java.util.Objects; -public class CommandIrisWhatObjects extends MortarCommand -{ - public CommandIrisWhatObjects() - { - super("objects", "o", "obj", "capture", "capt"); - setDescription("Capture nearby information to help with reporting problems"); - requiresPermission(Iris.perm.studio); - setCategory("World"); - } +public class CommandIrisWhatObjects extends MortarCommand { + public CommandIrisWhatObjects() { + super("objects", "o", "obj", "capture", "capt"); + setDescription("Capture nearby information to help with reporting problems"); + requiresPermission(Iris.perm.studio); + setCategory("World"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(sender.isPlayer()) - { - Player p = sender.player(); - World world = p.getWorld(); + @Override + public boolean handle(MortarSender sender, String[] args) { + if (sender.isPlayer()) { + Player p = sender.player(); + World world = p.getWorld(); - if(!IrisWorlds.isIrisWorld(world)) - { - sender.sendMessage("You must be in an iris world."); - return true; - } + if (!IrisWorlds.isIrisWorld(world)) { + sender.sendMessage("You must be in an iris world."); + return true; + } - IrisAccess g = IrisWorlds.access(world); - KList chunks = new KList<>(); - int bx = p.getLocation().getChunk().getX(); - int bz = p.getLocation().getChunk().getZ(); + IrisAccess g = IrisWorlds.access(world); + KList chunks = new KList<>(); + int bx = p.getLocation().getChunk().getX(); + int bz = p.getLocation().getChunk().getZ(); - try - { - Location l = p.getTargetBlockExact(48, FluidCollisionMode.NEVER).getLocation(); + try { + Location l = p.getTargetBlockExact(48, FluidCollisionMode.NEVER).getLocation(); - if(l != null) - { - int cx = l.getChunk().getX(); - int cz = l.getChunk().getZ(); - new Spiraler(3, 3, (x, z) -> chunks.addIfMissing(world.getChunkAt(x + cx, z + cz))).drain(); - } - } + if (l != null) { + int cx = l.getChunk().getX(); + int cz = l.getChunk().getZ(); + new Spiraler(3, 3, (x, z) -> chunks.addIfMissing(world.getChunkAt(x + cx, z + cz))).drain(); + } + } catch (Throwable e) { - catch(Throwable e) - { + } - } + new Spiraler(3, 3, (x, z) -> chunks.addIfMissing(world.getChunkAt(x + bx, z + bz))).drain(); + sender.sendMessage("Capturing IGenData from " + chunks.size() + " nearby chunks."); + try { + File ff = Iris.instance.getDataFile("reports/" + M.ms() + ".txt"); + PrintWriter pw = new PrintWriter(ff); + pw.println("=== Iris Chunk Report ==="); + pw.println("== General Info =="); + pw.println("Iris Version: " + Iris.instance.getDescription().getVersion()); + pw.println("Bukkit Version: " + Bukkit.getBukkitVersion()); + pw.println("MC Version: " + Bukkit.getVersion()); + pw.println("PaperSpigot: " + (PaperLib.isPaper() ? "Yup!" : "Nope!")); + pw.println("Report Captured At: " + new Date()); + pw.println("Chunks: (" + chunks.size() + "): "); - new Spiraler(3, 3, (x, z) -> chunks.addIfMissing(world.getChunkAt(x + bx, z + bz))).drain(); - sender.sendMessage("Capturing IGenData from " + chunks.size() + " nearby chunks."); - try - { - File ff = Iris.instance.getDataFile("reports/" + M.ms() + ".txt"); - PrintWriter pw = new PrintWriter(ff); - pw.println("=== Iris Chunk Report ==="); - pw.println("== General Info =="); - pw.println("Iris Version: " + Iris.instance.getDescription().getVersion()); - pw.println("Bukkit Version: " + Bukkit.getBukkitVersion()); - pw.println("MC Version: " + Bukkit.getVersion()); - pw.println("PaperSpigot: " + (PaperLib.isPaper() ? "Yup!" : "Nope!")); - pw.println("Report Captured At: " + new Date().toString()); - pw.println("Chunks: (" + chunks.size() + "): "); + for (Chunk i : chunks) { + pw.println("- [" + i.getX() + ", " + i.getZ() + "]"); + } - for(Chunk i : chunks) - { - pw.println("- [" + i.getX() + ", " + i.getZ() + "]"); - } + int regions = 0; + long size = 0; + String age = "No idea..."; - int regions = 0; - long size = 0; - String age = "No idea..."; + try { + for (File i : Objects.requireNonNull(new File(world.getWorldFolder(), "region").listFiles())) { + if (i.isFile()) { + size += i.length(); + } + } + } catch (Throwable ignored) { - try - { - for(File i : Objects.requireNonNull(new File(world.getWorldFolder(), "region").listFiles())) - { - if(i.isFile()) - { - size += i.length(); - } - } - } + } - catch(Throwable ignored) - { + try { + FileTime creationTime = (FileTime) Files.getAttribute(world.getWorldFolder().toPath(), "creationTime"); + age = hrf(Duration.of(M.ms() - creationTime.toMillis(), ChronoUnit.MILLIS)); + } catch (IOException ignored) { - } + } - try - { - FileTime creationTime = (FileTime) Files.getAttribute(world.getWorldFolder().toPath(), "creationTime"); - age = hrf(Duration.of(M.ms() - creationTime.toMillis(), ChronoUnit.MILLIS)); - } - catch(IOException ignored) - { + KList biomes = new KList<>(); + KList caveBiomes = new KList<>(); + KMap>> objects = new KMap<>(); - } + for (Chunk i : chunks) { + for (int j = 0; j < 16; j += 3) { - KList biomes = new KList<>(); - KList caveBiomes = new KList<>(); - KMap>> objects = new KMap<>(); + for (int k = 0; k < 16; k += 3) { - for(Chunk i : chunks) - { - for(int j = 0; j < 16; j += 3) - { + assert g != null; + IrisBiome bb = g.getBiome((i.getX() * 16) + j, (i.getZ() * 16) + k); + IrisBiome bxf = g.getCaveBiome((i.getX() * 16) + j, (i.getZ() * 16) + k); + biomes.addIfMissing(bb.getName() + " [" + Form.capitalize(bb.getInferredType().name().toLowerCase()) + "] " + " (" + bb.getLoadFile().getName() + ")"); + caveBiomes.addIfMissing(bxf.getName() + " (" + bxf.getLoadFile().getName() + ")"); + exportObjects(bb, pw, g, objects); + exportObjects(bxf, pw, g, objects); + } + } + } - for(int k = 0; k < 16; k += 3) - { + regions = Objects.requireNonNull(new File(world.getWorldFolder().getPath() + "/region").list()).length; - assert g != null; - IrisBiome bb = g.getBiome((i.getX() * 16) + j, (i.getZ() * 16) + k); - IrisBiome bxf = g.getCaveBiome((i.getX() * 16) + j, (i.getZ() * 16) + k); - biomes.addIfMissing(bb.getName() + " [" + Form.capitalize(bb.getInferredType().name().toLowerCase()) + "] " + " (" + bb.getLoadFile().getName() + ")"); - caveBiomes.addIfMissing(bxf.getName() + " (" + bxf.getLoadFile().getName() + ")"); - exportObjects(bb, pw, g, objects); - exportObjects(bxf, pw, g, objects); - } - } - } + pw.println(); + pw.println("== World Info =="); + pw.println("World Name: " + world.getName()); + pw.println("Age: " + age); + pw.println("Folder: " + world.getWorldFolder().getPath()); + pw.println("Regions: " + Form.f(regions)); + pw.println("Chunks: max. " + Form.f(regions * 32 * 32)); + pw.println("World Size: min. " + Form.fileSize(size)); + pw.println(); + pw.println("== Biome Info =="); + pw.println("Found " + biomes.size() + " Biome(s): "); - regions = Objects.requireNonNull(new File(world.getWorldFolder().getPath() + "/region").list()).length; + for (String i : biomes) { + pw.println("- " + i); + } + pw.println(); - pw.println(); - pw.println("== World Info =="); - pw.println("World Name: " + world.getName()); - pw.println("Age: " + age); - pw.println("Folder: " + world.getWorldFolder().getPath()); - pw.println("Regions: " + Form.f(regions)); - pw.println("Chunks: max. " + Form.f(regions * 32 * 32)); - pw.println("World Size: min. " + Form.fileSize(size)); - pw.println(); - pw.println("== Biome Info =="); - pw.println("Found " + biomes.size() + " Biome(s): "); + pw.println("== Object Info =="); - for(String i : biomes) - { - pw.println("- " + i); - } - pw.println(); + for (String i : objects.k()) { + pw.println("- " + i); - pw.println("== Object Info =="); + for (String j : objects.get(i).k()) { + pw.println(" @ " + j); - for(String i : objects.k()) - { - pw.println("- " + i); + for (String k : objects.get(i).get(j)) { + pw.println(" * " + k); + } + } + } - for(String j : objects.get(i).k()) - { - pw.println(" @ " + j); + pw.println(); + pw.close(); - for(String k : objects.get(i).get(j)) - { - pw.println(" * " + k); - } - } - } + sender.sendMessage("Reported to: " + ff.getPath()); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } - pw.println(); - pw.close(); + return true; + } else { + sender.sendMessage("Players only."); + } - sender.sendMessage("Reported to: " + ff.getPath()); - } + return true; + } - catch(FileNotFoundException e) - { - e.printStackTrace(); - } + private void exportObjects(IrisBiome bb, PrintWriter pw, IrisAccess g, KMap>> objects) { + String n1 = bb.getName() + " [" + Form.capitalize(bb.getInferredType().name().toLowerCase()) + "] " + " (" + bb.getLoadFile().getName() + ")"; + int m = 0; + KSet stop = new KSet<>(); + for (IrisObjectPlacement f : bb.getObjects()) { + m++; + String n2 = "Placement #" + m + " (" + f.getPlace().size() + " possible objects)"; - return true; - } + for (String i : f.getPlace()) { + String nn3 = i + ": [ERROR] Failed to find object!"; - else - { - sender.sendMessage("Players only."); - } + try { + if (stop.contains(i)) { + continue; + } - return true; - } + File ff = g.getData().getObjectLoader().findFile(i); + BlockVector sz = IrisObject.sampleSize(ff); + nn3 = i + ": size=[" + sz.getBlockX() + "," + sz.getBlockY() + "," + sz.getBlockZ() + "] location=[" + ff.getPath() + "]"; + stop.add(i); + } catch (Throwable ignored) { - private void exportObjects(IrisBiome bb, PrintWriter pw, IrisAccess g, KMap>> objects) - { - String n1 = bb.getName() + " [" + Form.capitalize(bb.getInferredType().name().toLowerCase()) + "] " + " (" + bb.getLoadFile().getName() + ")"; - int m = 0; - KSet stop = new KSet<>(); - for(IrisObjectPlacement f : bb.getObjects()) - { - m++; - String n2 = "Placement #" + m + " (" + f.getPlace().size() + " possible objects)"; + } - for(String i : f.getPlace()) - { - String nn3 = i + ": [ERROR] Failed to find object!"; + String n3 = nn3; - try - { - if(stop.contains(i)) - { - continue; - } + objects.compute(n1, (k1, v1) -> + { + if (v1 == null) { + return new KMap<>(); + } - File ff = g.getData().getObjectLoader().findFile(i); - BlockVector sz = IrisObject.sampleSize(ff); - nn3 = i + ": size=[" + sz.getBlockX() + "," + sz.getBlockY() + "," + sz.getBlockZ() + "] location=[" + ff.getPath() + "]"; - stop.add(i); - } + return v1; + }).compute(n2, (k, v) -> + { + if (v == null) { + return new KList().qaddIfMissing(n3); + } - catch(Throwable ignored) - { + v.addIfMissing(n3); + return v; + }); + } + } + } - } + public static String hrf(Duration duration) { + return duration.toString().substring(2).replaceAll("(\\d[HMS])(?!$)", "$1 ").toLowerCase(); + } - String n3 = nn3; - - objects.compute(n1, (k1, v1) -> - { - if(v1 == null) - { - return new KMap<>(); - } - - return v1; - }).compute(n2, (k, v) -> - { - if(v == null) - { - return new KList().qaddIfMissing(n3); - } - - v.addIfMissing(n3); - return v; - }); - } - } - } - - public static String hrf(Duration duration) - { - return duration.toString().substring(2).replaceAll("(\\d[HMS])(?!$)", "$1 ").toLowerCase(); - } - - @Override - protected String getArgsUsage() - { - return "[thread-count]"; - } + @Override + protected String getArgsUsage() { + return "[thread-count]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/world/CommandIrisCreate.java b/src/main/java/com/volmit/iris/manager/command/world/CommandIrisCreate.java index 4d7d0a15a..47a2cdbfd 100644 --- a/src/main/java/com/volmit/iris/manager/command/world/CommandIrisCreate.java +++ b/src/main/java/com/volmit/iris/manager/command/world/CommandIrisCreate.java @@ -2,7 +2,6 @@ package com.volmit.iris.manager.command.world; import com.volmit.iris.Iris; import com.volmit.iris.IrisSettings; -import com.volmit.iris.generator.IrisWorldManager; import com.volmit.iris.manager.IrisDataManager; import com.volmit.iris.manager.link.MultiverseCoreLink; import com.volmit.iris.nms.INMS; @@ -16,273 +15,243 @@ import org.bukkit.World; import org.bukkit.WorldCreator; import java.io.File; -import java.util.Locale; import java.util.Random; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReference; -import java.util.concurrent.atomic.AtomicReferenceArray; -public class CommandIrisCreate extends MortarCommand -{ - public CommandIrisCreate() - { - super("create", "c", "cr", "new", "+"); - requiresPermission(Iris.perm.studio); - setCategory("Create"); - setDescription("Create a new Iris World!"); - } +public class CommandIrisCreate extends MortarCommand { + public CommandIrisCreate() { + super("create", "c", "cr", "new", "+"); + requiresPermission(Iris.perm.studio); + setCategory("Create"); + setDescription("Create a new Iris World!"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { - if (args.length == 0 || args[args.length - 1].equals("")) { //They are about to type a new argument - list.addAll(getBase(args)); - return; - } + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { + if (args.length == 0 || args[args.length - 1].equals("")) { //They are about to type a new argument + list.addAll(getBase(args)); + return; + } - String[] split = args[args.length - 1].split("\\Q=\\E"); - if (split.length == 0) { //They haven't typed the = yet so just keep the options there - list.addAll(getBase(args)); - return; - } + String[] split = args[args.length - 1].split("\\Q=\\E"); + if (split.length == 0) { //They haven't typed the = yet so just keep the options there + list.addAll(getBase(args)); + return; + } - String pre = split[0].toLowerCase(); + String pre = split[0].toLowerCase(); - if (pre.equals("type")) { - for (String s : Iris.proj.getListing(true).keySet()) { - list.add("type=" + s); - } - if (!list.contains("type=overworld")) { - list.contains("type=overworld"); - } - } else if (pre.equals("seed")) { - list.add("seed=1337"); - list.add("seed=" + new Random().nextInt()); - list.add("seed=random"); - } else if (pre.equals("pregen")) { - list.add("500"); - list.add("1000"); - list.add("2000"); - list.add("5k"); - list.add("10k"); - list.add("25k"); - } - } + if (pre.equals("type")) { + for (String s : Iris.proj.getListing(true).keySet()) { + list.add("type=" + s); + } + if (!list.contains("type=overworld")) { + list.contains("type=overworld"); + } + } else if (pre.equals("seed")) { + list.add("seed=1337"); + list.add("seed=" + new Random().nextInt()); + list.add("seed=random"); + } else if (pre.equals("pregen")) { + list.add("500"); + list.add("1000"); + list.add("2000"); + list.add("5k"); + list.add("10k"); + list.add("25k"); + } + } - private KList getBase(String[] args) { - KList list = new KList<>(); - boolean seed = true; - boolean type = true; - boolean pregen = true; + private KList getBase(String[] args) { + KList list = new KList<>(); + boolean seed = true; + boolean type = true; + boolean pregen = true; - for (String s : args) { - if (s.toLowerCase().startsWith("seed=")) seed = false; - else if (s.toLowerCase().startsWith("type=")) type = false; - else if (s.toLowerCase().startsWith("pregen=")) pregen = false; - } + for (String s : args) { + if (s.toLowerCase().startsWith("seed=")) seed = false; + else if (s.toLowerCase().startsWith("type=")) type = false; + else if (s.toLowerCase().startsWith("pregen=")) pregen = false; + } - if (seed) list.add("seed="); - if (type) list.add("type="); - if (pregen) list.add("pregen="); - return list; - } + if (seed) list.add("seed="); + if (type) list.add("type="); + if (pregen) list.add("pregen="); + return list; + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(args.length < 1) - { - sender.sendMessage("/iris create [type=overworld] [seed=1337] [pregen=5000]"); - return true; - } - Random random = new Random(); - String worldName = args[0]; - String type = IrisSettings.get().getGenerator().getDefaultWorldType(); - long seed = random.nextLong(); //Random seed when creating a world - AtomicInteger pregen = new AtomicInteger(256); - boolean multiverse = Iris.linkMultiverseCore.supported(); + @Override + public boolean handle(MortarSender sender, String[] args) { + if (args.length < 1) { + sender.sendMessage("/iris create [type=overworld] [seed=1337] [pregen=5000]"); + return true; + } + Random random = new Random(); + String worldName = args[0]; + String type = IrisSettings.get().getGenerator().getDefaultWorldType(); + long seed = random.nextLong(); //Random seed when creating a world + AtomicInteger pregen = new AtomicInteger(256); + boolean multiverse = Iris.linkMultiverseCore.supported(); - for(String i : args) - { - type = i.startsWith("type=") ? i.split("\\Q=\\E")[1] : type; - seed = i.startsWith("seed=") ? (i.split("\\Q=\\E")[1].equalsIgnoreCase("random") ? random.nextLong() : Long.valueOf(i.split("\\Q=\\E")[1])) : seed; - pregen.set(i.startsWith("pregen=") ? getVal(i.split("\\Q=\\E")[1]) : pregen.get()); - } + for (String i : args) { + type = i.startsWith("type=") ? i.split("\\Q=\\E")[1] : type; + seed = i.startsWith("seed=") ? (i.split("\\Q=\\E")[1].equalsIgnoreCase("random") ? random.nextLong() : Long.valueOf(i.split("\\Q=\\E")[1])) : seed; + pregen.set(i.startsWith("pregen=") ? getVal(i.split("\\Q=\\E")[1]) : pregen.get()); + } - Iris.linkMultiverseCore.assignWorldType(worldName, type); - final AtomicReference world = new AtomicReference<>(); - IrisDimension dim; - File folder = new File(worldName); + Iris.linkMultiverseCore.assignWorldType(worldName, type); + final AtomicReference world = new AtomicReference<>(); + IrisDimension dim; + File folder = new File(worldName); - Runnable onDone = () -> { + Runnable onDone = () -> { - sender.sendMessage(worldName + " Spawn Area generated."); - sender.sendMessage("You must remember to either have multiverse installed or use the Bukkit method, otherwise the world will go corrupt!"); - sender.sendMessage("Wiki: https://volmitsoftware.gitbook.io/iris/getting-started"); + sender.sendMessage(worldName + " Spawn Area generated."); + sender.sendMessage("You must remember to either have multiverse installed or use the Bukkit method, otherwise the world will go corrupt!"); + sender.sendMessage("Wiki: https://volmitsoftware.gitbook.io/iris/getting-started"); - O b = new O(); - b.set(true); + O b = new O(); + b.set(true); - if(sender.isPlayer()) - { - try - { - sender.player().teleport(world.get().getSpawnLocation()); - } + if (sender.isPlayer()) { + try { + sender.player().teleport(world.get().getSpawnLocation()); + } catch (Throwable e) { - catch(Throwable e) - { + } + } - } - } + if (pregen.get() > 0) { + b.set(false); + int size = pregen.get(); + size *= 2; + sender.sendMessage("Pregenerating " + worldName + " " + size + " x " + size); + sender.sendMessage("Expect server lag during this time. Use '/iris pregen stop' to cancel"); - if(pregen.get() > 0) - { - b.set(false); - int size = pregen.get(); - size *= 2; - sender.sendMessage("Pregenerating " + worldName + " " + size + " x " + size); - sender.sendMessage("Expect server lag during this time. Use '/iris pregen stop' to cancel"); + new Pregenerator(world.get(), size, () -> + { + b.set(true); + }); + } - new Pregenerator(world.get(), size, () -> - { - b.set(true); - }); - } - - World ww = world.get(); - if (ww == null){ - sender.sendMessage("World not created, can not finish"); - return; - } - J.a(() -> - { - while(!b.get()) - { - J.sleep(1000); - } + World ww = world.get(); + if (ww == null) { + sender.sendMessage("World not created, can not finish"); + return; + } + J.a(() -> + { + while (!b.get()) { + J.sleep(1000); + } - Bukkit.getScheduler().scheduleSyncDelayedTask(Iris.instance, () -> - { - ww.save(); - sender.sendMessage("All Done!"); - }); - }); - }; + Bukkit.getScheduler().scheduleSyncDelayedTask(Iris.instance, () -> + { + ww.save(); + sender.sendMessage("All Done!"); + }); + }); + }; - if(multiverse) - { - dim = IrisDataManager.loadAnyDimension(type); + if (multiverse) { + dim = IrisDataManager.loadAnyDimension(type); - if(dim == null) - { - sender.sendMessage("Cant find dimension type: " + type + ". Did you forget to /ir download " + type + "?"); - return true; - } + if (dim == null) { + sender.sendMessage("Cant find dimension type: " + type + ". Did you forget to /ir download " + type + "?"); + return true; + } - if(dim.getEnvironment() == null) - { - dim.setEnvironment(World.Environment.NORMAL); - } + if (dim.getEnvironment() == null) { + dim.setEnvironment(World.Environment.NORMAL); + } - if(Iris.linkMultiverseCore == null) - { - Iris.linkMultiverseCore = new MultiverseCoreLink(); - } + if (Iris.linkMultiverseCore == null) { + Iris.linkMultiverseCore = new MultiverseCoreLink(); + } - String command = "mv create " + worldName + " " + Iris.linkMultiverseCore.envName(dim.getEnvironment()); - command += " -s " + seed; - command += " -g Iris:" + dim.getLoadKey(); - sender.sendMessage("Delegating " + command); - Bukkit.dispatchCommand(sender, command); - world.set(Bukkit.getWorld(worldName)); - onDone.run(); - } - else - { - if(folder.exists()) - { - sender.sendMessage("That world folder already exists!"); - return true; - } + String command = "mv create " + worldName + " " + Iris.linkMultiverseCore.envName(dim.getEnvironment()); + command += " -s " + seed; + command += " -g Iris:" + dim.getLoadKey(); + sender.sendMessage("Delegating " + command); + Bukkit.dispatchCommand(sender, command); + world.set(Bukkit.getWorld(worldName)); + onDone.run(); + } else { + if (folder.exists()) { + sender.sendMessage("That world folder already exists!"); + return true; + } - File iris = new File(folder, "iris"); - iris.mkdirs(); + File iris = new File(folder, "iris"); + iris.mkdirs(); - dim = Iris.proj.installIntoWorld(sender, type, folder); + dim = Iris.proj.installIntoWorld(sender, type, folder); - WorldCreator wc = new IrisWorldCreator().dimension(dim.getLoadKey()).name(worldName) - .productionMode().seed(seed).create(); + WorldCreator wc = new IrisWorldCreator().dimension(dim.getLoadKey()).name(worldName) + .productionMode().seed(seed).create(); - J.s(() -> { - sender.sendMessage("Generating with " + Iris.getThreadCount() + " threads per chunk"); - O done = new O<>(); - done.set(false); + J.s(() -> { + sender.sendMessage("Generating with " + Iris.getThreadCount() + " threads per chunk"); + O done = new O<>(); + done.set(false); - J.a(() -> - { - double last = 0; - int req = 800; - while(!done.get()) - { - boolean derp = false; - double v = (double) ((IrisAccess) wc.generator()).getGenerated() / (double) req; + J.a(() -> + { + double last = 0; + int req = 800; + while (!done.get()) { + boolean derp = false; + double v = (double) ((IrisAccess) wc.generator()).getGenerated() / (double) req; - if(last > v || v > 1) - { - derp = true; - v = last; - } + if (last > v || v > 1) { + derp = true; + v = last; + } else { + last = v; + } - else - { - last = v; - } + sender.sendMessage("Generating " + Form.pc(v) + (derp ? " (Waiting on Server...)" : "")); + J.sleep(3000); + } + }); - sender.sendMessage("Generating " + Form.pc(v) + (derp ? " (Waiting on Server...)" : "")); - J.sleep(3000); - } - }); + World w = INMS.get().createWorld(wc); + world.set(w); - World w = INMS.get().createWorld(wc); - world.set(w); + J.a(() -> { + new Pregenerator(w, pregen.get() * 2); + }); - J.a(() -> { - new Pregenerator(w, pregen.get() * 2); - }); - - done.set(true); - }); - } + done.set(true); + }); + } - return true; - } + return true; + } - private int getVal(String arg) { + private int getVal(String arg) { - if(arg.toLowerCase().endsWith("c") || arg.toLowerCase().endsWith("chunks")) - { - return Integer.parseInt(arg.toLowerCase().replaceAll("\\Qc\\E", "").replaceAll("\\Qchunks\\E", "")) * 16; - } + if (arg.toLowerCase().endsWith("c") || arg.toLowerCase().endsWith("chunks")) { + return Integer.parseInt(arg.toLowerCase().replaceAll("\\Qc\\E", "").replaceAll("\\Qchunks\\E", "")) * 16; + } - if(arg.toLowerCase().endsWith("r") || arg.toLowerCase().endsWith("regions")) - { - return Integer.parseInt(arg.toLowerCase().replaceAll("\\Qr\\E", "").replaceAll("\\Qregions\\E", "")) * 512; - } + if (arg.toLowerCase().endsWith("r") || arg.toLowerCase().endsWith("regions")) { + return Integer.parseInt(arg.toLowerCase().replaceAll("\\Qr\\E", "").replaceAll("\\Qregions\\E", "")) * 512; + } - if(arg.toLowerCase().endsWith("k")) - { - return Integer.parseInt(arg.toLowerCase().replaceAll("\\Qk\\E", "")) * 1000; - } + if (arg.toLowerCase().endsWith("k")) { + return Integer.parseInt(arg.toLowerCase().replaceAll("\\Qk\\E", "")) * 1000; + } - return Integer.parseInt(arg.toLowerCase()); - } + return Integer.parseInt(arg.toLowerCase()); + } - @Override - protected String getArgsUsage() - { - return " [type=overworld] [seed=1337] [pregen=5000]"; - } + @Override + protected String getArgsUsage() { + return " [type=overworld] [seed=1337] [pregen=5000]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/world/CommandIrisFix.java b/src/main/java/com/volmit/iris/manager/command/world/CommandIrisFix.java index 6c883fefd..3cb98b5a2 100644 --- a/src/main/java/com/volmit/iris/manager/command/world/CommandIrisFix.java +++ b/src/main/java/com/volmit/iris/manager/command/world/CommandIrisFix.java @@ -7,63 +7,50 @@ import com.volmit.iris.util.*; import java.util.concurrent.atomic.AtomicInteger; -public class CommandIrisFix extends MortarCommand -{ - public CommandIrisFix() - { - super("fix"); - requiresPermission(Iris.perm.studio); - setDescription("Fix nearby chunks"); - setCategory("Studio"); - } +public class CommandIrisFix extends MortarCommand { + public CommandIrisFix() { + super("fix"); + requiresPermission(Iris.perm.studio); + setDescription("Fix nearby chunks"); + setCategory("Studio"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - try - { - IrisAccess a = IrisWorlds.access(sender.player().getWorld()); - if(a.getCompound().getSize() > 1) - { - sender.sendMessage("Cant fix engine composite worlds!"); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + try { + IrisAccess a = IrisWorlds.access(sender.player().getWorld()); + if (a.getCompound().getSize() > 1) { + sender.sendMessage("Cant fix engine composite worlds!"); + return true; + } - int viewDistance = args.length > 0 ? Integer.valueOf(args[0]) : -1; - if(viewDistance <=1) - { - J.a(() -> { - int fixed = a.getCompound().getDefaultEngine().getFramework().getEngineParallax().repairChunk(sender.player().getLocation().getChunk()); - sender.sendMessage("Fixed " + Form.f(fixed) + " blocks!"); - }); - } + int viewDistance = args.length > 0 ? Integer.valueOf(args[0]) : -1; + if (viewDistance <= 1) { + J.a(() -> { + int fixed = a.getCompound().getDefaultEngine().getFramework().getEngineParallax().repairChunk(sender.player().getLocation().getChunk()); + sender.sendMessage("Fixed " + Form.f(fixed) + " blocks!"); + }); + } else { + AtomicInteger v = new AtomicInteger(); + J.a(() -> { + new Spiraler(viewDistance, viewDistance, (x, z) -> v.set(v.get() + a.getCompound().getDefaultEngine().getFramework().getEngineParallax().repairChunk(sender.player().getWorld().getChunkAt(x, z)))).drain(); + sender.sendMessage("Fixed " + Form.f(v.get()) + " blocks in " + (viewDistance * viewDistance) + " chunks!"); + }); + } + } catch (Throwable e) { + sender.sendMessage("Not a valid Iris World (or bad argument)"); + } - else - { - AtomicInteger v = new AtomicInteger(); - J.a(() -> { - new Spiraler(viewDistance, viewDistance, (x,z) -> v.set(v.get() + a.getCompound().getDefaultEngine().getFramework().getEngineParallax().repairChunk(sender.player().getWorld().getChunkAt(x, z)))).drain(); - sender.sendMessage("Fixed " + Form.f(v.get()) + " blocks in " + (viewDistance * viewDistance) + " chunks!"); - }); - } - } + return true; + } - catch(Throwable e) - { - sender.sendMessage("Not a valid Iris World (or bad argument)"); - } - - return true; - } - - @Override - protected String getArgsUsage() - { - return "[view-distance]"; - } + @Override + protected String getArgsUsage() { + return "[view-distance]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/world/CommandIrisPregen.java b/src/main/java/com/volmit/iris/manager/command/world/CommandIrisPregen.java index 7f86dccb1..7b9ea39be 100644 --- a/src/main/java/com/volmit/iris/manager/command/world/CommandIrisPregen.java +++ b/src/main/java/com/volmit/iris/manager/command/world/CommandIrisPregen.java @@ -11,161 +11,136 @@ import org.bukkit.entity.Player; import java.awt.*; -public class CommandIrisPregen extends MortarCommand -{ - public CommandIrisPregen() - { - super("pregen", "preg", "p"); - setDescription( - "Pregen this world with optional parameters: " + - "\n'1k' = 1000 by 1000 blocks, '1c' = 1 by 1 chunks, and '1r' = 32 by 32 chunks." + - "\nIf you are using the console or want to pregen a world you're not in:" + - "\nalso specify the name of the world. E.g. /ir pregen 5k world" - ); - requiresPermission(Iris.perm.studio); - setCategory("Pregen"); - } +public class CommandIrisPregen extends MortarCommand { + public CommandIrisPregen() { + super("pregen", "preg", "p"); + setDescription( + "Pregen this world with optional parameters: " + + "\n'1k' = 1000 by 1000 blocks, '1c' = 1 by 1 chunks, and '1r' = 32 by 32 chunks." + + "\nIf you are using the console or want to pregen a world you're not in:" + + "\nalso specify the name of the world. E.g. /ir pregen 5k world" + ); + requiresPermission(Iris.perm.studio); + setCategory("Pregen"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { - list.add("stop"); - list.add("pause"); - list.add("resume"); - list.add("500"); - list.add("1000"); - list.add("10k"); - list.add("25k"); - list.add("10c"); - list.add("25c"); - list.add("5r"); - list.add("10r"); - for (World w : Bukkit.getServer().getWorlds()){ - list.add(w.getName()); - } - } + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { + list.add("stop"); + list.add("pause"); + list.add("resume"); + list.add("500"); + list.add("1000"); + list.add("10k"); + list.add("25k"); + list.add("10c"); + list.add("25c"); + list.add("5r"); + list.add("10r"); + for (World w : Bukkit.getServer().getWorlds()) { + list.add(w.getName()); + } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(args.length == 0) - { - sender.sendMessage("/iris pregen "); - return true; - } + @Override + public boolean handle(MortarSender sender, String[] args) { + if (args.length == 0) { + sender.sendMessage("/iris pregen "); + return true; + } - if(args[0].equalsIgnoreCase("stop") || args[0].equalsIgnoreCase("x")) - { - if (Pregenerator.shutdownInstance()) { - sender.sendMessage("Stopped Pregen."); - } else - { - sender.sendMessage("No Active Pregens."); - } - return true; - } - else if(args[0].equalsIgnoreCase("pause") || args[0].equalsIgnoreCase("resume")) - { - if(Pregenerator.getInstance() != null) - { - Pregenerator.pauseResume(); + if (args[0].equalsIgnoreCase("stop") || args[0].equalsIgnoreCase("x")) { + if (Pregenerator.shutdownInstance()) { + sender.sendMessage("Stopped Pregen."); + } else { + sender.sendMessage("No Active Pregens."); + } + return true; + } else if (args[0].equalsIgnoreCase("pause") || args[0].equalsIgnoreCase("resume")) { + if (Pregenerator.getInstance() != null) { + Pregenerator.pauseResume(); - if(Pregenerator.isPaused()) - { - sender.sendMessage("Pregen Paused"); - } + if (Pregenerator.isPaused()) { + sender.sendMessage("Pregen Paused"); + } else { + sender.sendMessage("Pregen Resumed"); + } + } else { + sender.sendMessage("No Active Pregens"); + } - else - { - sender.sendMessage("Pregen Resumed"); - } - } + return true; + } else if (sender.isPlayer()) { + Player p = sender.player(); + World world; + if (args.length != 2) { + world = p.getWorld(); + } else { + try { + world = Bukkit.getWorld(args[1]); + } catch (Exception e) { + sender.sendMessage("Could not find specified world"); + sender.sendMessage("Please doublecheck your command. E.g. /ir pregen 5k world"); + return true; + } + } + try { + new Pregenerator(world, getVal(args[0]) * 2); + } catch (NumberFormatException e) { + sender.sendMessage("Invalid argument in command"); + return true; + } catch (NullPointerException e) { + e.printStackTrace(); + sender.sendMessage("No radius specified (check error in console)"); + } catch (HeadlessException e) { + sender.sendMessage("If you are seeing this and are using a hosted server, please turn off 'useServerLaunchedGUIs' in the settings"); + } - else - { - sender.sendMessage("No Active Pregens"); - } + return true; + } else { + if (args.length < 1) { + sender.sendMessage("Please specify the radius of the pregen and the name of the world. E.g. /ir pregen 5k world"); + return true; + } + if (args.length < 2) { + sender.sendMessage("Please specify the name of the world after the command. E.g. /ir pregen 5k world"); + return true; + } + World world = Bukkit.getWorld(args[1]); + try { + new Pregenerator(world, getVal(args[0]) * 2); + } catch (NumberFormatException e) { + sender.sendMessage("Invalid argument in command"); + return true; + } catch (NullPointerException e) { + sender.sendMessage("Not all required parameters specified"); + } catch (HeadlessException e) { + sender.sendMessage("If you are seeing this and are using a hosted server, please turn off 'useServerLaunchedGUIs' in the settings"); + } - return true; - } + return true; + } + } - else if(sender.isPlayer()) - { - Player p = sender.player(); - World world; - if (args.length != 2) { - world = p.getWorld(); - } else { - try { - world = Bukkit.getWorld(args[1]); - } catch (Exception e){ - sender.sendMessage("Could not find specified world"); - sender.sendMessage("Please doublecheck your command. E.g. /ir pregen 5k world"); - return true; - } - } - try { - new Pregenerator(world, getVal(args[0]) * 2); - } catch (NumberFormatException e){ - sender.sendMessage("Invalid argument in command"); - return true; - } catch (NullPointerException e){ - e.printStackTrace(); - sender.sendMessage("No radius specified (check error in console)"); - } catch (HeadlessException e){ - sender.sendMessage("If you are seeing this and are using a hosted server, please turn off 'useServerLaunchedGUIs' in the settings"); - } + private int getVal(String arg) { - return true; - } - else - { - if (args.length < 1){ - sender.sendMessage("Please specify the radius of the pregen and the name of the world. E.g. /ir pregen 5k world"); - return true; - } - if (args.length < 2){ - sender.sendMessage("Please specify the name of the world after the command. E.g. /ir pregen 5k world"); - return true; - } - World world = Bukkit.getWorld(args[1]); - try { - new Pregenerator(world, getVal(args[0]) * 2); - } catch (NumberFormatException e){ - sender.sendMessage("Invalid argument in command"); - return true; - } catch (NullPointerException e){ - sender.sendMessage("Not all required parameters specified"); - } catch (HeadlessException e){ - sender.sendMessage("If you are seeing this and are using a hosted server, please turn off 'useServerLaunchedGUIs' in the settings"); - } + if (arg.toLowerCase().endsWith("c") || arg.toLowerCase().endsWith("chunks")) { + return Integer.parseInt(arg.toLowerCase().replaceAll("\\Qc\\E", "").replaceAll("\\Qchunks\\E", "")) * 16; + } - return true; - } - } + if (arg.toLowerCase().endsWith("r") || arg.toLowerCase().endsWith("regions")) { + return Integer.parseInt(arg.toLowerCase().replaceAll("\\Qr\\E", "").replaceAll("\\Qregions\\E", "")) * 512; + } - private int getVal(String arg) { + if (arg.toLowerCase().endsWith("k")) { + return Integer.parseInt(arg.toLowerCase().replaceAll("\\Qk\\E", "")) * 1000; + } - if(arg.toLowerCase().endsWith("c") || arg.toLowerCase().endsWith("chunks")) - { - return Integer.parseInt(arg.toLowerCase().replaceAll("\\Qc\\E", "").replaceAll("\\Qchunks\\E", "")) * 16; - } + return Integer.parseInt(arg.toLowerCase()); + } - if(arg.toLowerCase().endsWith("r") || arg.toLowerCase().endsWith("regions")) - { - return Integer.parseInt(arg.toLowerCase().replaceAll("\\Qr\\E", "").replaceAll("\\Qregions\\E", "")) * 512; - } - - if(arg.toLowerCase().endsWith("k")) - { - return Integer.parseInt(arg.toLowerCase().replaceAll("\\Qk\\E", "")) * 1000; - } - - return Integer.parseInt(arg.toLowerCase()); - } - - @Override - protected String getArgsUsage() - { - return "[radius]"; - } + @Override + protected String getArgsUsage() { + return "[radius]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/world/CommandIrisRegen.java b/src/main/java/com/volmit/iris/manager/command/world/CommandIrisRegen.java index e271af18e..c0d894651 100644 --- a/src/main/java/com/volmit/iris/manager/command/world/CommandIrisRegen.java +++ b/src/main/java/com/volmit/iris/manager/command/world/CommandIrisRegen.java @@ -5,26 +5,23 @@ import com.volmit.iris.util.KList; import com.volmit.iris.util.MortarCommand; import com.volmit.iris.util.MortarSender; -public class CommandIrisRegen extends MortarCommand -{ - public CommandIrisRegen() - { - super("regen"); - setDescription("Regenerate chunks around you (iris worlds only)"); - requiresPermission(Iris.perm.studio); - setCategory("Regen"); - } +public class CommandIrisRegen extends MortarCommand { + public CommandIrisRegen() { + super("regen"); + setDescription("Regenerate chunks around you (iris worlds only)"); + requiresPermission(Iris.perm.studio); + setCategory("Regen"); + } - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - } + } - @Override - public boolean handle(MortarSender sender, String[] args) - { - sender.sendMessage("Iris' /regen command is currently disabled due to maintenance. Apologies."); - return true; + @Override + public boolean handle(MortarSender sender, String[] args) { + sender.sendMessage("Iris' /regen command is currently disabled due to maintenance. Apologies."); + return true; /* This is commented yes try { @@ -67,11 +64,10 @@ public class CommandIrisRegen extends MortarCommand return true; */ - } + } - @Override - protected String getArgsUsage() - { - return "[size]"; - } + @Override + protected String getArgsUsage() { + return "[size]"; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/world/CommandIrisUpdateWorld.java b/src/main/java/com/volmit/iris/manager/command/world/CommandIrisUpdateWorld.java index 1ab7d4ff9..36f84dd3e 100644 --- a/src/main/java/com/volmit/iris/manager/command/world/CommandIrisUpdateWorld.java +++ b/src/main/java/com/volmit/iris/manager/command/world/CommandIrisUpdateWorld.java @@ -1,65 +1,57 @@ package com.volmit.iris.manager.command.world; -import java.io.File; - import com.volmit.iris.Iris; import com.volmit.iris.util.*; -public class CommandIrisUpdateWorld extends MortarCommand -{ - public CommandIrisUpdateWorld() - { - super("update-world", "^world"); - requiresPermission(Iris.perm.studio); - setDescription("Update a world from a project."); - setCategory("Studio"); - } +import java.io.File; - @Override - public void addTabOptions(MortarSender sender, String[] args, KList list) { +public class CommandIrisUpdateWorld extends MortarCommand { + public CommandIrisUpdateWorld() { + super("update-world", "^world"); + requiresPermission(Iris.perm.studio); + setDescription("Update a world from a project."); + setCategory("Studio"); + } - } + @Override + public void addTabOptions(MortarSender sender, String[] args, KList list) { - @Override - public boolean handle(MortarSender sender, String[] args) - { - if(args.length < 2) - { - sender.sendMessage("/iris update-world " + C.BOLD + " "); - return true; - } + } - boolean fresh = false; + @Override + public boolean handle(MortarSender sender, String[] args) { + if (args.length < 2) { + sender.sendMessage("/iris update-world " + C.BOLD + " "); + return true; + } - for(String i : args) - { - if(i.equalsIgnoreCase("--fresh-download")) - { - fresh = true; - } - } + boolean fresh = false; - boolean bfre = fresh; + for (String i : args) { + if (i.equalsIgnoreCase("--fresh-download")) { + fresh = true; + } + } - J.a(() -> - { - File folder = new File(args[0]); - folder.mkdirs(); + boolean bfre = fresh; - if(bfre) - { - Iris.proj.downloadSearch(sender, args[1], false, true); - } + J.a(() -> + { + File folder = new File(args[0]); + folder.mkdirs(); - Iris.proj.installIntoWorld(sender, args[1], folder); - }); + if (bfre) { + Iris.proj.downloadSearch(sender, args[1], false, true); + } - return true; - } + Iris.proj.installIntoWorld(sender, args[1], folder); + }); - @Override - protected String getArgsUsage() - { - return " "; - } + return true; + } + + @Override + protected String getArgsUsage() { + return " "; + } } diff --git a/src/main/java/com/volmit/iris/manager/command/world/CommandLocate.java b/src/main/java/com/volmit/iris/manager/command/world/CommandLocate.java index 39efdbf8f..c7382ef09 100644 --- a/src/main/java/com/volmit/iris/manager/command/world/CommandLocate.java +++ b/src/main/java/com/volmit/iris/manager/command/world/CommandLocate.java @@ -12,15 +12,15 @@ import org.bukkit.event.player.PlayerCommandPreprocessEvent; import java.util.Arrays; -public class CommandLocate extends MortarCommand implements Listener -{ +public class CommandLocate extends MortarCommand implements Listener { CommandLocate instance; + @EventHandler public void onPlayerCommandPreprocess(final PlayerCommandPreprocessEvent event) { - if (IrisWorlds.isIrisWorld(event.getPlayer().getWorld())){ + if (IrisWorlds.isIrisWorld(event.getPlayer().getWorld())) { // Make sure the command starts with /locate and does not locate stronghold - if (event.getMessage().contains("/locate") && event.getMessage().contains("stronghold")){ + if (event.getMessage().contains("/locate") && event.getMessage().contains("stronghold")) { return; } if (event.getMessage().contains("/locate")) { @@ -31,16 +31,14 @@ public class CommandLocate extends MortarCommand implements Listener } } - public CommandLocate() - { + public CommandLocate() { super("locate"); requiresPermission(Iris.perm); this.instance = this; } @Override - public boolean handle(MortarSender sender, String[] args) - { + public boolean handle(MortarSender sender, String[] args) { Bukkit.dispatchCommand(sender, "/ir std goto " + Arrays.toString(args)); return true; } @@ -51,8 +49,7 @@ public class CommandLocate extends MortarCommand implements Listener } @Override - protected String getArgsUsage() - { + protected String getArgsUsage() { return "[biome/region/structure]"; } } diff --git a/src/main/java/com/volmit/iris/manager/edit/BlockEditor.java b/src/main/java/com/volmit/iris/manager/edit/BlockEditor.java index 29a208321..1f7239850 100644 --- a/src/main/java/com/volmit/iris/manager/edit/BlockEditor.java +++ b/src/main/java/com/volmit/iris/manager/edit/BlockEditor.java @@ -1,26 +1,25 @@ package com.volmit.iris.manager.edit; -import java.io.Closeable; - import org.bukkit.block.Biome; import org.bukkit.block.data.BlockData; -public interface BlockEditor extends Closeable -{ - public long last(); +import java.io.Closeable; - public void set(int x, int y, int z, BlockData d); +public interface BlockEditor extends Closeable { + long last(); - public BlockData get(int x, int y, int z); - - public void setBiome(int x, int z, Biome b); + void set(int x, int y, int z, BlockData d); - public void setBiome(int x, int y, int z, Biome b); + BlockData get(int x, int y, int z); - @Override - public void close(); + void setBiome(int x, int z, Biome b); - public Biome getBiome(int x, int y, int z); + void setBiome(int x, int y, int z, Biome b); - public Biome getBiome(int x, int z); + @Override + void close(); + + Biome getBiome(int x, int y, int z); + + Biome getBiome(int x, int z); } diff --git a/src/main/java/com/volmit/iris/manager/edit/BlockSignal.java b/src/main/java/com/volmit/iris/manager/edit/BlockSignal.java index 318604cbd..f1b6a6a7c 100644 --- a/src/main/java/com/volmit/iris/manager/edit/BlockSignal.java +++ b/src/main/java/com/volmit/iris/manager/edit/BlockSignal.java @@ -1,7 +1,7 @@ package com.volmit.iris.manager.edit; -import com.volmit.iris.util.J; import com.volmit.iris.scaffold.parallel.MultiBurst; +import com.volmit.iris.util.J; import com.volmit.iris.util.SR; import org.bukkit.Location; import org.bukkit.block.Block; @@ -11,18 +11,15 @@ import org.bukkit.entity.Player; import org.bukkit.util.Vector; public class BlockSignal { - public static void of(Block block, int ticks) - { + public static void of(Block block, int ticks) { new BlockSignal(block, ticks); } - public static void of(Block block) - { + public static void of(Block block) { of(block, 100); } - public static Runnable forever(Block block) - { + public static Runnable forever(Block block) { Location tg = block.getLocation().clone().add(0.5, 0, 0.5).clone(); FallingBlock e = block.getWorld().spawnFallingBlock(tg.clone(), block.getBlockData()); e.setGravity(false); @@ -38,8 +35,7 @@ public class BlockSignal { new SR(20) { @Override public void run() { - if(e.isDead()) - { + if (e.isDead()) { cancel(); return; } @@ -55,16 +51,14 @@ public class BlockSignal { BlockData type = block.getBlockData(); MultiBurst.burst.lazy(() -> { - for(Player i : block.getWorld().getPlayers()) - { + for (Player i : block.getWorld().getPlayers()) { i.sendBlockChange(block.getLocation(), block.getBlockData()); } }); }; } - public BlockSignal(Block block, int ticks) - { + public BlockSignal(Block block, int ticks) { Location tg = block.getLocation().clone().add(0.5, 0, 0.5).clone(); FallingBlock e = block.getWorld().spawnFallingBlock(tg.clone(), block.getBlockData()); e.setGravity(false); @@ -81,8 +75,7 @@ public class BlockSignal { BlockData type = block.getBlockData(); MultiBurst.burst.lazy(() -> { - for(Player i : block.getWorld().getPlayers()) - { + for (Player i : block.getWorld().getPlayers()) { i.sendBlockChange(block.getLocation(), block.getBlockData()); } }); diff --git a/src/main/java/com/volmit/iris/manager/edit/BukkitBlockEditor.java b/src/main/java/com/volmit/iris/manager/edit/BukkitBlockEditor.java index 6f1e04a3c..26c6ee9ca 100644 --- a/src/main/java/com/volmit/iris/manager/edit/BukkitBlockEditor.java +++ b/src/main/java/com/volmit/iris/manager/edit/BukkitBlockEditor.java @@ -1,67 +1,56 @@ package com.volmit.iris.manager.edit; +import com.volmit.iris.util.M; import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.block.data.BlockData; -import com.volmit.iris.util.M; +public class BukkitBlockEditor implements BlockEditor { + private final World world; -public class BukkitBlockEditor implements BlockEditor -{ - private final World world; + public BukkitBlockEditor(World world) { + this.world = world; + } - public BukkitBlockEditor(World world) - { - this.world = world; - } + @Override + public void set(int x, int y, int z, BlockData d) { + world.getBlockAt(x, y, z).setBlockData(d, false); + } - @Override - public void set(int x, int y, int z, BlockData d) - { - world.getBlockAt(x, y, z).setBlockData(d, false); - } + @Override + public BlockData get(int x, int y, int z) { + return world.getBlockAt(x, y, z).getBlockData(); + } - @Override - public BlockData get(int x, int y, int z) - { - return world.getBlockAt(x, y, z).getBlockData(); - } + @Override + public void close() { - @Override - public void close() - { + } - } + @Override + public long last() { + return M.ms(); + } - @Override - public long last() - { - return M.ms(); - } + @SuppressWarnings("deprecation") + @Override + public void setBiome(int x, int z, Biome b) { + world.setBiome(x, z, b); + } - @SuppressWarnings("deprecation") - @Override - public void setBiome(int x, int z, Biome b) - { - world.setBiome(x, z, b); - } + @Override + public void setBiome(int x, int y, int z, Biome b) { + world.setBiome(x, y, z, b); + } - @Override - public void setBiome(int x, int y, int z, Biome b) - { - world.setBiome(x, y, z, b); - } + @Override + public Biome getBiome(int x, int y, int z) { + return world.getBiome(x, y, z); + } - @Override - public Biome getBiome(int x, int y, int z) - { - return world.getBiome(x, y, z); - } - - @SuppressWarnings("deprecation") - @Override - public Biome getBiome(int x, int z) - { - return world.getBiome(x, z); - } + @SuppressWarnings("deprecation") + @Override + public Biome getBiome(int x, int z) { + return world.getBiome(x, z); + } } diff --git a/src/main/java/com/volmit/iris/manager/edit/DustRevealer.java b/src/main/java/com/volmit/iris/manager/edit/DustRevealer.java index f37e4ece7..76223d193 100644 --- a/src/main/java/com/volmit/iris/manager/edit/DustRevealer.java +++ b/src/main/java/com/volmit/iris/manager/edit/DustRevealer.java @@ -16,17 +16,14 @@ public class DustRevealer { private final String key; private final KList hits; - public static void spawn(Block block, MortarSender sender) - { + public static void spawn(Block block, MortarSender sender) { World world = block.getWorld(); IrisAccess access = IrisWorlds.access(world); - if(access != null) - { + if (access != null) { ParallaxAccess a = access.getEngineAccess(block.getY()).getParallaxAccess(); - if(a.getObject(block.getX(), block.getY(), block.getZ()) != null) - { + if (a.getObject(block.getX(), block.getY(), block.getZ()) != null) { sender.sendMessage("Found object " + a.getObject(block.getX(), block.getY(), block.getZ())); J.a(() -> { new DustRevealer(a, world, new BlockPosition(block.getX(), block.getY(), block.getZ()), a.getObject(block.getX(), block.getY(), block.getZ()), new KList<>()); @@ -64,27 +61,23 @@ public class DustRevealer { is(new BlockPosition(block.getX(), block.getY() + 1, block.getZ() + 1)); is(new BlockPosition(block.getX(), block.getY() - 1, block.getZ() - 1)); is(new BlockPosition(block.getX(), block.getY() - 1, block.getZ() + 1)); - is(new BlockPosition(block.getX()-1, block.getY() + 1, block.getZ() - 1)); - is(new BlockPosition(block.getX()-1, block.getY() + 1, block.getZ() + 1)); - is(new BlockPosition(block.getX()-1, block.getY() - 1, block.getZ() - 1)); - is(new BlockPosition(block.getX()-1, block.getY() - 1, block.getZ() + 1)); - is(new BlockPosition(block.getX()+1, block.getY() + 1, block.getZ() - 1)); - is(new BlockPosition(block.getX()+1, block.getY() + 1, block.getZ() + 1)); - is(new BlockPosition(block.getX()+1, block.getY() - 1, block.getZ() - 1)); - is(new BlockPosition(block.getX()+1, block.getY() - 1, block.getZ() + 1)); - } - - catch(Throwable e) - { + is(new BlockPosition(block.getX() - 1, block.getY() + 1, block.getZ() - 1)); + is(new BlockPosition(block.getX() - 1, block.getY() + 1, block.getZ() + 1)); + is(new BlockPosition(block.getX() - 1, block.getY() - 1, block.getZ() - 1)); + is(new BlockPosition(block.getX() - 1, block.getY() - 1, block.getZ() + 1)); + is(new BlockPosition(block.getX() + 1, block.getY() + 1, block.getZ() - 1)); + is(new BlockPosition(block.getX() + 1, block.getY() + 1, block.getZ() + 1)); + is(new BlockPosition(block.getX() + 1, block.getY() - 1, block.getZ() - 1)); + is(new BlockPosition(block.getX() + 1, block.getY() - 1, block.getZ() + 1)); + } catch (Throwable e) { e.printStackTrace(); } }); - }, RNG.r.i(3,6)); + }, RNG.r.i(3, 6)); } private boolean is(BlockPosition a) { - if(isValidTry(a) && parallax.getObject(a.getX(), a.getY(), a.getZ()) != null && parallax.getObject(a.getX(), a.getY(), a.getZ()).equals(key)) - { + if (isValidTry(a) && parallax.getObject(a.getX(), a.getY(), a.getZ()) != null && parallax.getObject(a.getX(), a.getY(), a.getZ()).equals(key)) { hits.add(a); new DustRevealer(parallax, world, a, key, hits); return true; @@ -93,8 +86,7 @@ public class DustRevealer { return false; } - private boolean isValidTry(BlockPosition b) - { + private boolean isValidTry(BlockPosition b) { return !hits.contains(b); } } diff --git a/src/main/java/com/volmit/iris/manager/edit/JigsawEditor.java b/src/main/java/com/volmit/iris/manager/edit/JigsawEditor.java index e0eb53c8a..454efe088 100644 --- a/src/main/java/com/volmit/iris/manager/edit/JigsawEditor.java +++ b/src/main/java/com/volmit/iris/manager/edit/JigsawEditor.java @@ -32,10 +32,8 @@ public class JigsawEditor implements Listener { private final KMap falling = new KMap<>(); private final ChronoLatch cl = new ChronoLatch(100); - public JigsawEditor(Player player, IrisJigsawPiece piece, IrisObject object, File saveLocation) - { - if(editors.containsKey(player)) - { + public JigsawEditor(Player player, IrisJigsawPiece piece, IrisObject object, File saveLocation) { + if (editors.containsKey(player)) { editors.get(player).close(); } @@ -47,36 +45,27 @@ public class JigsawEditor implements Listener { this.targetSaveLocation = saveLocation; this.piece = piece == null ? new IrisJigsawPiece() : piece; this.piece.setObject(object.getLoadKey()); - cuboid = new Cuboid(origin.clone(), origin.clone().add(object.getW()-1, object.getH()-1, object.getD()-1)); + cuboid = new Cuboid(origin.clone(), origin.clone().add(object.getW() - 1, object.getH() - 1, object.getD() - 1)); ticker = J.sr(this::onTick, 0); object.placeCenterY(origin); Iris.instance.registerListener(this); } @EventHandler - public void on(PlayerMoveEvent e) - { - if(e.getPlayer().equals(player)) - { - try - { + public void on(PlayerMoveEvent e) { + if (e.getPlayer().equals(player)) { + try { target = player.getTargetBlockExact(7).getLocation(); - } - - catch(Throwable ex) - { + } catch (Throwable ex) { target = player.getLocation(); return; } - if(cuboid.contains(target)) - { - for(IrisPosition i : falling.k()) - { + if (cuboid.contains(target)) { + for (IrisPosition i : falling.k()) { Location at = toLocation(i); - if(at.equals(target)) - { + if (at.equals(target)) { falling.remove(i).run(); } } @@ -84,8 +73,7 @@ public class JigsawEditor implements Listener { } } - public Location toLocation(IrisPosition i) - { + public Location toLocation(IrisPosition i) { return origin.clone() .add(new Vector(i.getX(), i.getY(), i.getZ())) .add(object.getCenter()) @@ -93,50 +81,37 @@ public class JigsawEditor implements Listener { .getLocation(); } - public IrisPosition toPosition(Location l) - { + public IrisPosition toPosition(Location l) { return new IrisPosition(l.clone().getBlock().getLocation() .subtract(origin.clone()) .subtract(object.getCenter()) - .add(1,1,1) + .add(1, 1, 1) .toVector()); } @EventHandler - public void on(PlayerInteractEvent e) - { - if(e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) - { - if(e.getClickedBlock() != null && cuboid.contains(e.getClickedBlock().getLocation()) && e.getPlayer().equals(player)) - { + public void on(PlayerInteractEvent e) { + if (e.getAction().equals(Action.RIGHT_CLICK_BLOCK)) { + if (e.getClickedBlock() != null && cuboid.contains(e.getClickedBlock().getLocation()) && e.getPlayer().equals(player)) { IrisPosition pos = toPosition(e.getClickedBlock().getLocation()); IrisJigsawPieceConnector connector = null; - for(IrisJigsawPieceConnector i : piece.getConnectors()) - { - if(i.getPosition().equals(pos)) - { + for (IrisJigsawPieceConnector i : piece.getConnectors()) { + if (i.getPosition().equals(pos)) { connector = i; break; } } - if(!player.isSneaking() && connector == null) - { + if (!player.isSneaking() && connector == null) { connector = new IrisJigsawPieceConnector(); connector.setDirection(IrisDirection.getDirection(e.getBlockFace())); connector.setPosition(pos); piece.getConnectors().add(connector); player.playSound(e.getClickedBlock().getLocation(), Sound.ENTITY_ITEM_FRAME_ADD_ITEM, 1f, 1f); - } - - else if(player.isSneaking() && connector != null) - { + } else if (player.isSneaking() && connector != null) { piece.getConnectors().remove(connector); player.playSound(e.getClickedBlock().getLocation(), Sound.ENTITY_ITEM_FRAME_REMOVE_ITEM, 1f, 1f); - } - - else if(connector != null && !player.isSneaking()) - { + } else if (connector != null && !player.isSneaking()) { connector.setDirection(IrisDirection.getDirection(e.getBlockFace())); player.playSound(e.getClickedBlock().getLocation(), Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 1f, 1f); } @@ -144,8 +119,7 @@ public class JigsawEditor implements Listener { } } - public void close() - { + public void close() { exit(); try { IO.writeAll(targetSaveLocation, new JSONObject(new Gson().toJson(piece)).toString(4)); @@ -154,8 +128,7 @@ public class JigsawEditor implements Listener { } } - public void exit() - { + public void exit() { J.car(ticker); Iris.instance.unregisterListener(this); object.unplaceCenterY(origin); @@ -163,18 +136,14 @@ public class JigsawEditor implements Listener { falling.v().forEach(Runnable::run); } - public void onTick() - { - if(cl.flip()) - { + public void onTick() { + if (cl.flip()) { Iris.wand.draw(cuboid, player); - f: for(IrisPosition i : falling.k()) - { - for(IrisJigsawPieceConnector j : piece.getConnectors()) - { - if(j.getPosition().equals(i)) - { + f: + for (IrisPosition i : falling.k()) { + for (IrisJigsawPieceConnector j : piece.getConnectors()) { + if (j.getPosition().equals(i)) { continue f; } } @@ -182,28 +151,23 @@ public class JigsawEditor implements Listener { falling.remove(i).run(); } - for(IrisJigsawPieceConnector i : piece.getConnectors()) - { + for (IrisJigsawPieceConnector i : piece.getConnectors()) { IrisPosition pos = i.getPosition(); Location at = toLocation(pos); Vector dir = i.getDirection().toVector().clone(); - for(int ix = 0; ix < RNG.r.i(1, 3); ix++) - { + for (int ix = 0; ix < RNG.r.i(1, 3); ix++) { at.getWorld().spawnParticle(Particle.SOUL_FIRE_FLAME, at.clone().getBlock().getLocation().add(0.25, 0.25, 0.25).add(RNG.r.d(0.5), RNG.r.d(0.5), RNG.r.d(0.5)), 0, dir.getX(), dir.getY(), dir.getZ(), 0.092 + RNG.r.d(-0.03, 0.08)); } - if(at.getBlock().getLocation().equals(target)) - { + if (at.getBlock().getLocation().equals(target)) { continue; } - if(!falling.containsKey(pos)) - { - if(at.getBlock().getType().isAir()) - { + if (!falling.containsKey(pos)) { + if (at.getBlock().getType().isAir()) { at.getBlock().setType(Material.STONE); } diff --git a/src/main/java/com/volmit/iris/manager/edit/WEBlockEditor.java b/src/main/java/com/volmit/iris/manager/edit/WEBlockEditor.java index 5c939a47c..9066c172a 100644 --- a/src/main/java/com/volmit/iris/manager/edit/WEBlockEditor.java +++ b/src/main/java/com/volmit/iris/manager/edit/WEBlockEditor.java @@ -1,9 +1,5 @@ package com.volmit.iris.manager.edit; -import org.bukkit.World; -import org.bukkit.block.Biome; -import org.bukkit.block.data.BlockData; - import com.sk89q.worldedit.EditSession; import com.sk89q.worldedit.WorldEdit; import com.sk89q.worldedit.bukkit.BukkitAdapter; @@ -11,66 +7,59 @@ import com.sk89q.worldedit.math.BlockVector2; import com.sk89q.worldedit.math.BlockVector3; import com.sk89q.worldedit.world.biome.BiomeTypes; import com.volmit.iris.util.M; +import org.bukkit.World; +import org.bukkit.block.Biome; +import org.bukkit.block.data.BlockData; -public class WEBlockEditor implements BlockEditor -{ - private final World world; - private final EditSession es; - private long last; +public class WEBlockEditor implements BlockEditor { + private final World world; + private final EditSession es; + private final long last; - public WEBlockEditor(World world) - { - last = M.ms(); - this.world = world; - es = WorldEdit.getInstance().newEditSessionBuilder().world(BukkitAdapter.adapt(world)).build(); - } + public WEBlockEditor(World world) { + last = M.ms(); + this.world = world; + es = WorldEdit.getInstance().newEditSessionBuilder().world(BukkitAdapter.adapt(world)).build(); + } - @SuppressWarnings("deprecation") - public void setBiome(int x, int z, Biome b) - { - es.setBiome(BlockVector2.at(x, z), BiomeTypes.get("minecraft:" + b.name().toLowerCase())); - } + @SuppressWarnings("deprecation") + public void setBiome(int x, int z, Biome b) { + es.setBiome(BlockVector2.at(x, z), BiomeTypes.get("minecraft:" + b.name().toLowerCase())); + } - public void setBiome(int x, int y, int z, Biome b) - { - es.setBiome(BlockVector3.at(x, y, z), BiomeTypes.get("minecraft:" + b.name().toLowerCase())); - } + public void setBiome(int x, int y, int z, Biome b) { + es.setBiome(BlockVector3.at(x, y, z), BiomeTypes.get("minecraft:" + b.name().toLowerCase())); + } - @Override - public void set(int x, int y, int z, BlockData d) - { - es.rawSetBlock(BlockVector3.at(x, y, z), BukkitAdapter.adapt(d)); - } + @Override + public void set(int x, int y, int z, BlockData d) { + es.rawSetBlock(BlockVector3.at(x, y, z), BukkitAdapter.adapt(d)); + } - @Override - public BlockData get(int x, int y, int z) - { - return world.getBlockAt(x, y, z).getBlockData(); - } + @Override + public BlockData get(int x, int y, int z) { + return world.getBlockAt(x, y, z).getBlockData(); + } - @Override - public void close() - { - es.close(); - return; - } + @Override + public void close() { + es.close(); + return; + } - @Override - public long last() - { - return last; - } + @Override + public long last() { + return last; + } - @Override - public Biome getBiome(int x, int y, int z) - { - return world.getBiome(x, y, z); - } + @Override + public Biome getBiome(int x, int y, int z) { + return world.getBiome(x, y, z); + } - @SuppressWarnings("deprecation") - @Override - public Biome getBiome(int x, int z) - { - return world.getBiome(x, z); - } + @SuppressWarnings("deprecation") + @Override + public Biome getBiome(int x, int z) { + return world.getBiome(x, z); + } } diff --git a/src/main/java/com/volmit/iris/manager/gui/IrisRenderer.java b/src/main/java/com/volmit/iris/manager/gui/IrisRenderer.java index 3b4dc367b..7800b45df 100644 --- a/src/main/java/com/volmit/iris/manager/gui/IrisRenderer.java +++ b/src/main/java/com/volmit/iris/manager/gui/IrisRenderer.java @@ -1,40 +1,35 @@ package com.volmit.iris.manager.gui; -import java.awt.image.BufferedImage; - import com.volmit.iris.scaffold.engine.Engine; import com.volmit.iris.util.IrisInterpolation; import org.bukkit.Material; -public class IrisRenderer -{ - private Renderer renderer; +import java.awt.image.BufferedImage; - public IrisRenderer(Renderer renderer) - { - this.renderer = renderer; - } +public class IrisRenderer { + private final Renderer renderer; - public BufferedImage render(double sx, double sz, double size, int resolution) - { - BufferedImage image = new BufferedImage(resolution, resolution, BufferedImage.TYPE_INT_RGB); - double x, z; - int i, j; - for(i = 0; i < resolution; i++) - { - x = IrisInterpolation.lerp(sx, sx + size, (double) i / (double) (resolution)); + public IrisRenderer(Renderer renderer) { + this.renderer = renderer; + } - for(j = 0; j < resolution; j++) - { - z = IrisInterpolation.lerp(sz, sz + size, (double) j / (double) (resolution)); - image.setRGB(i, j, renderer.draw(x, z).getRGB()); - } - } + public BufferedImage render(double sx, double sz, double size, int resolution) { + BufferedImage image = new BufferedImage(resolution, resolution, BufferedImage.TYPE_INT_RGB); + double x, z; + int i, j; + for (i = 0; i < resolution; i++) { + x = IrisInterpolation.lerp(sx, sx + size, (double) i / (double) (resolution)); - return image; - } + for (j = 0; j < resolution; j++) { + z = IrisInterpolation.lerp(sz, sz + size, (double) j / (double) (resolution)); + image.setRGB(i, j, renderer.draw(x, z).getRGB()); + } + } + + return image; + } public void set(double worldX, double worldZ) { - ((Engine)renderer).getWorld().getBlockAt((int)worldX, 20, (int)worldZ).setType(Material.DIAMOND_BLOCK); + ((Engine) renderer).getWorld().getBlockAt((int) worldX, 20, (int) worldZ).setType(Material.DIAMOND_BLOCK); } } diff --git a/src/main/java/com/volmit/iris/manager/gui/IrisVision.java b/src/main/java/com/volmit/iris/manager/gui/IrisVision.java index ab5a0c7e5..aec1110c6 100644 --- a/src/main/java/com/volmit/iris/manager/gui/IrisVision.java +++ b/src/main/java/com/volmit/iris/manager/gui/IrisVision.java @@ -21,337 +21,288 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; -public class IrisVision extends JPanel implements MouseWheelListener -{ - private static final long serialVersionUID = 2094606939770332040L; - private IrisRenderer renderer; - private int posX = 0; - private World world; - private int posZ = 0; - private double scale = 128; - private double mscale = 1D; - private int w = 0; - private int h = 0; - private double lx = Double.MAX_VALUE; - private double lz = Double.MAX_VALUE; - private double ox = 0; - private double oz = 0; - private double oxp = 0; - private double ozp = 0; - double tfps = 240D; - private RollingSequence rs = new RollingSequence(512); - private O m = new O<>(); - private int tid = 0; - private KMap positions = new KMap<>(); - private KMap fastpositions = new KMap<>(); - private KSet working = new KSet<>(); - private KSet workingfast = new KSet<>(); - private final ExecutorService e = Executors.newFixedThreadPool(8, new ThreadFactory() - { - @Override - public Thread newThread(Runnable r) - { - tid++; - Thread t = new Thread(r); - t.setName("Iris HD Renderer " + tid); - t.setPriority(Thread.MIN_PRIORITY); - t.setUncaughtExceptionHandler((et, e) -> - { - Iris.info("Exception encountered in " + et.getName()); - e.printStackTrace(); - }); +public class IrisVision extends JPanel implements MouseWheelListener { + private static final long serialVersionUID = 2094606939770332040L; + private IrisRenderer renderer; + private int posX = 0; + private World world; + private int posZ = 0; + private double scale = 128; + private double mscale = 1D; + private int w = 0; + private int h = 0; + private double lx = Double.MAX_VALUE; + private double lz = Double.MAX_VALUE; + private double ox = 0; + private double oz = 0; + private double oxp = 0; + private double ozp = 0; + double tfps = 240D; + private final RollingSequence rs = new RollingSequence(512); + private final O m = new O<>(); + private int tid = 0; + private final KMap positions = new KMap<>(); + private final KMap fastpositions = new KMap<>(); + private final KSet working = new KSet<>(); + private final KSet workingfast = new KSet<>(); + private final ExecutorService e = Executors.newFixedThreadPool(8, new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + tid++; + Thread t = new Thread(r); + t.setName("Iris HD Renderer " + tid); + t.setPriority(Thread.MIN_PRIORITY); + t.setUncaughtExceptionHandler((et, e) -> + { + Iris.info("Exception encountered in " + et.getName()); + e.printStackTrace(); + }); - return t; - } - }); + return t; + } + }); - private final ExecutorService eh = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new ThreadFactory() - { - @Override - public Thread newThread(Runnable r) - { - tid++; - Thread t = new Thread(r); - t.setName("Iris Renderer " + tid); - t.setPriority(Thread.NORM_PRIORITY); - t.setUncaughtExceptionHandler((et, e) -> - { - Iris.info("Exception encountered in " + et.getName()); - e.printStackTrace(); - }); + private final ExecutorService eh = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors(), new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + tid++; + Thread t = new Thread(r); + t.setName("Iris Renderer " + tid); + t.setPriority(Thread.NORM_PRIORITY); + t.setUncaughtExceptionHandler((et, e) -> + { + Iris.info("Exception encountered in " + et.getName()); + e.printStackTrace(); + }); - return t; - } - }); + return t; + } + }); - public IrisVision() - { - m.set(8); - renderer = new IrisRenderer(null); - rs.put(1); - addMouseWheelListener((MouseWheelListener) this); - addMouseMotionListener(new MouseMotionListener() - { - @Override - public void mouseMoved(MouseEvent e) - { - Point cp = e.getPoint(); - lx = (cp.getX()); - lz = (cp.getY()); - } + public IrisVision() { + m.set(8); + renderer = new IrisRenderer(null); + rs.put(1); + addMouseWheelListener(this); + addMouseMotionListener(new MouseMotionListener() { + @Override + public void mouseMoved(MouseEvent e) { + Point cp = e.getPoint(); + lx = (cp.getX()); + lz = (cp.getY()); + } - @Override - public void mouseDragged(MouseEvent e) - { - Point cp = e.getPoint(); - ox += (lx - cp.getX()) * scale; - oz += (lz - cp.getY()) * scale; - lx = cp.getX(); - lz = cp.getY(); - } - }); - } + @Override + public void mouseDragged(MouseEvent e) { + Point cp = e.getPoint(); + ox += (lx - cp.getX()) * scale; + oz += (lz - cp.getY()) * scale; + lx = cp.getX(); + lz = cp.getY(); + } + }); + } - public BufferedImage getTile(KSet fg, int div, int x, int z, O m) - { - BlockPosition key = new BlockPosition((int) mscale, Math.floorDiv(x, div), Math.floorDiv(z, div)); - fg.add(key); + public BufferedImage getTile(KSet fg, int div, int x, int z, O m) { + BlockPosition key = new BlockPosition((int) mscale, Math.floorDiv(x, div), Math.floorDiv(z, div)); + fg.add(key); - if(positions.containsKey(key)) - { - return positions.get(key); - } + if (positions.containsKey(key)) { + return positions.get(key); + } - if(fastpositions.containsKey(key)) - { - if(!working.contains(key) && working.size() < 9) - { - m.set(m.get() - 1); + if (fastpositions.containsKey(key)) { + if (!working.contains(key) && working.size() < 9) { + m.set(m.get() - 1); - if(m.get() >= 0) - { - working.add(key); - double mk = mscale; - double mkd = scale; - e.submit(() -> - { - PrecisionStopwatch ps = PrecisionStopwatch.start(); - BufferedImage b = renderer.render(x * mscale, z * mscale, div * mscale, div); - rs.put(ps.getMilliseconds()); - working.remove(key); + if (m.get() >= 0) { + working.add(key); + double mk = mscale; + double mkd = scale; + e.submit(() -> + { + PrecisionStopwatch ps = PrecisionStopwatch.start(); + BufferedImage b = renderer.render(x * mscale, z * mscale, div * mscale, div); + rs.put(ps.getMilliseconds()); + working.remove(key); - if(mk == mscale && mkd == scale) - { - positions.put(key, b); - } - }); - } - } + if (mk == mscale && mkd == scale) { + positions.put(key, b); + } + }); + } + } - return fastpositions.get(key); - } + return fastpositions.get(key); + } - if(workingfast.contains(key)) - { - return null; - } + if (workingfast.contains(key)) { + return null; + } - m.set(m.get() - 1); + m.set(m.get() - 1); - if(m.get() >= 0) - { - workingfast.add(key); - double mk = mscale; - double mkd = scale; - eh.submit(() -> - { - PrecisionStopwatch ps = PrecisionStopwatch.start(); - BufferedImage b = renderer.render(x * mscale, z * mscale, div * mscale, div / 12); - rs.put(ps.getMilliseconds()); - workingfast.remove(key); + if (m.get() >= 0) { + workingfast.add(key); + double mk = mscale; + double mkd = scale; + eh.submit(() -> + { + PrecisionStopwatch ps = PrecisionStopwatch.start(); + BufferedImage b = renderer.render(x * mscale, z * mscale, div * mscale, div / 12); + rs.put(ps.getMilliseconds()); + workingfast.remove(key); - if(mk == mscale && mkd == scale) - { - fastpositions.put(key, b); - } - }); - } - return null; - } + if (mk == mscale && mkd == scale) { + fastpositions.put(key, b); + } + }); + } + return null; + } - private double getWorldX(double screenX) - { - return (screenX + oxp) * mscale; - } + private double getWorldX(double screenX) { + return (screenX + oxp) * mscale; + } - private double getWorldZ(double screenZ) - { - return (screenZ + ozp) * mscale; - } + private double getWorldZ(double screenZ) { + return (screenZ + ozp) * mscale; + } - private double getScreenX(double x) - { - return (oxp + x) / mscale; - } + private double getScreenX(double x) { + return (oxp + x) / mscale; + } - private double getScreenZ(double z) - { - return (ozp + z) / mscale; - } + private double getScreenZ(double z) { + return (ozp + z) / mscale; + } - @Override - public void paint(Graphics gx) - { - if(ox < oxp) - { - oxp -= Math.abs(ox - oxp) * 0.36; - } + @Override + public void paint(Graphics gx) { + if (ox < oxp) { + oxp -= Math.abs(ox - oxp) * 0.36; + } - if(ox > oxp) - { - oxp += Math.abs(oxp - ox) * 0.36; - } + if (ox > oxp) { + oxp += Math.abs(oxp - ox) * 0.36; + } - if(oz < ozp) - { - ozp -= Math.abs(oz - ozp) * 0.36; - } + if (oz < ozp) { + ozp -= Math.abs(oz - ozp) * 0.36; + } - if(oz > ozp) - { - ozp += Math.abs(ozp - oz) * 0.36; - } + if (oz > ozp) { + ozp += Math.abs(ozp - oz) * 0.36; + } - PrecisionStopwatch p = PrecisionStopwatch.start(); - Graphics2D g = (Graphics2D) gx; - w = getWidth(); - h = getHeight(); - double vscale = scale; - scale = w / 16D; + PrecisionStopwatch p = PrecisionStopwatch.start(); + Graphics2D g = (Graphics2D) gx; + w = getWidth(); + h = getHeight(); + double vscale = scale; + scale = w / 16D; - if(scale != vscale) - { - positions.clear(); - } + if (scale != vscale) { + positions.clear(); + } - KSet gg = new KSet<>(); - int iscale = (int) scale; - g.setColor(Color.white); - g.clearRect(0, 0, w, h); - posX = (int) oxp; - posZ = (int) ozp; - m.set(3); + KSet gg = new KSet<>(); + int iscale = (int) scale; + g.setColor(Color.white); + g.clearRect(0, 0, w, h); + posX = (int) oxp; + posZ = (int) ozp; + m.set(3); - for(int r = 0; r < Math.max(w, h); r += iscale) - { - for(int i = -iscale; i < w + iscale; i += iscale) - { - for(int j = -iscale; j < h + iscale; j += iscale) - { - int a = i - (w / 2); - int b = j - (h / 2); - if(a * a + b * b <= r * r) - { - BufferedImage t = getTile(gg, iscale, Math.floorDiv((posX / iscale) + i, iscale) * iscale, Math.floorDiv((posZ / iscale) + j, iscale) * iscale, m); + for (int r = 0; r < Math.max(w, h); r += iscale) { + for (int i = -iscale; i < w + iscale; i += iscale) { + for (int j = -iscale; j < h + iscale; j += iscale) { + int a = i - (w / 2); + int b = j - (h / 2); + if (a * a + b * b <= r * r) { + BufferedImage t = getTile(gg, iscale, Math.floorDiv((posX / iscale) + i, iscale) * iscale, Math.floorDiv((posZ / iscale) + j, iscale) * iscale, m); - if(t != null) - { - g.drawImage(t, i - ((posX / iscale) % (iscale)), j - ((posZ / iscale) % (iscale)), (int) (iscale), (int) (iscale), new ImageObserver() - { - @Override - public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) - { - return true; - } - }); - } - } - } - } - } + if (t != null) { + g.drawImage(t, i - ((posX / iscale) % (iscale)), j - ((posZ / iscale) % (iscale)), iscale, iscale, new ImageObserver() { + @Override + public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { + return true; + } + }); + } + } + } + } + } - p.end(); + p.end(); - for(BlockPosition i : positions.k()) - { - if(!gg.contains(i)) - { - positions.remove(i); - } - } + for (BlockPosition i : positions.k()) { + if (!gg.contains(i)) { + positions.remove(i); + } + } - for(Player i : world.getPlayers()) - { - g.setColor(Color.getHSBColor(RNG.r.f(), 1f, 1f)); - g.drawRect((int)getScreenX(i.getLocation().getX()), (int)getScreenZ(i.getLocation().getZ()), 4, 4); - } + for (Player i : world.getPlayers()) { + g.setColor(Color.getHSBColor(RNG.r.f(), 1f, 1f)); + g.drawRect((int) getScreenX(i.getLocation().getX()), (int) getScreenZ(i.getLocation().getZ()), 4, 4); + } - if(!isVisible()) - { - return; - } + if (!isVisible()) { + return; + } - if(!getParent().isVisible()) - { - return; - } + if (!getParent().isVisible()) { + return; + } - if(!getParent().getParent().isVisible()) - { - return; - } + if (!getParent().getParent().isVisible()) { + return; + } - J.a(() -> - { - J.sleep((long) 1); - repaint(); - }); - } + J.a(() -> + { + J.sleep(1); + repaint(); + }); + } - private static void createAndShowGUI(Renderer r, int s, World world) - { - JFrame frame = new JFrame("Vision"); - IrisVision nv = new IrisVision(); - nv.world = world; - nv.renderer = new IrisRenderer(r); - frame.add(nv); - frame.setSize(1440, 820); - frame.setVisible(true); - File file = Iris.getCached("Iris Icon", "https://raw.githubusercontent.com/VolmitSoftware/Iris/master/icon.png"); + private static void createAndShowGUI(Renderer r, int s, World world) { + JFrame frame = new JFrame("Vision"); + IrisVision nv = new IrisVision(); + nv.world = world; + nv.renderer = new IrisRenderer(r); + frame.add(nv); + frame.setSize(1440, 820); + frame.setVisible(true); + File file = Iris.getCached("Iris Icon", "https://raw.githubusercontent.com/VolmitSoftware/Iris/master/icon.png"); - if(file != null) - { - try - { - frame.setIconImage(ImageIO.read(file)); - } + if (file != null) { + try { + frame.setIconImage(ImageIO.read(file)); + } catch (IOException e) { - catch(IOException e) - { + } + } + } - } - } - } + public static void launch(IrisAccess g, int i) { + J.a(() -> + { + createAndShowGUI((x, z) -> g.getEngineAccess(i).draw(x, z), i, g.getCompound().getWorld()); + }); + } - public static void launch(IrisAccess g, int i) { - J.a(() -> - { - createAndShowGUI((x, z) -> g.getEngineAccess(i).draw(x, z), i, g.getCompound().getWorld()); - }); - } + public void mouseWheelMoved(MouseWheelEvent e) { + int notches = e.getWheelRotation(); + if (e.isControlDown()) { + return; + } - public void mouseWheelMoved(MouseWheelEvent e) - { - int notches = e.getWheelRotation(); - if(e.isControlDown()) - { - return; - } - - Iris.info("Blocks/Pixel: " + (mscale) + ", Blocks Wide: " + (w * mscale)); - positions.clear(); - fastpositions.clear(); - mscale = mscale + ((0.044 * mscale) * notches); - mscale = mscale < 0.00001 ? 0.00001 : mscale; - } + Iris.info("Blocks/Pixel: " + (mscale) + ", Blocks Wide: " + (w * mscale)); + positions.clear(); + fastpositions.clear(); + mscale = mscale + ((0.044 * mscale) * notches); + mscale = mscale < 0.00001 ? 0.00001 : mscale; + } } diff --git a/src/main/java/com/volmit/iris/manager/gui/NoiseExplorer.java b/src/main/java/com/volmit/iris/manager/gui/NoiseExplorer.java index 21e14897e..a2a539dc0 100644 --- a/src/main/java/com/volmit/iris/manager/gui/NoiseExplorer.java +++ b/src/main/java/com/volmit/iris/manager/gui/NoiseExplorer.java @@ -1,359 +1,292 @@ package com.volmit.iris.manager.gui; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.EventQueue; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseMotionListener; -import java.awt.event.MouseWheelEvent; -import java.awt.event.MouseWheelListener; -import java.io.File; -import java.io.IOException; -import java.util.concurrent.locks.ReentrantLock; - -import javax.imageio.ImageIO; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JFrame; -import javax.swing.JLayeredPane; -import javax.swing.JPanel; -import javax.swing.JViewport; - import com.volmit.iris.Iris; import com.volmit.iris.generator.noise.CNG; import com.volmit.iris.object.NoiseStyle; -import com.volmit.iris.util.Function2; -import com.volmit.iris.util.GroupedExecutor; -import com.volmit.iris.util.J; -import com.volmit.iris.util.KList; -import com.volmit.iris.util.M; -import com.volmit.iris.util.PrecisionStopwatch; -import com.volmit.iris.util.RNG; -import com.volmit.iris.util.RollingSequence; +import com.volmit.iris.util.*; -public class NoiseExplorer extends JPanel implements MouseWheelListener -{ +import javax.imageio.ImageIO; +import javax.swing.*; +import java.awt.Dimension; +import java.awt.*; +import java.awt.event.*; +import java.io.File; +import java.io.IOException; +import java.util.concurrent.locks.ReentrantLock; - private static final long serialVersionUID = 2094606939770332040L; +public class NoiseExplorer extends JPanel implements MouseWheelListener { - static JComboBox combo; - RollingSequence r = new RollingSequence(90); - boolean colorMode = true; - double scale = 1; - static boolean hd = false; - static double ascale = 10; - CNG cng = NoiseStyle.STATIC.create(new RNG(RNG.r.nextLong())); - GroupedExecutor gx = new GroupedExecutor(Runtime.getRuntime().availableProcessors(), Thread.MAX_PRIORITY, "Iris Renderer"); - ReentrantLock l = new ReentrantLock(); - int[][] co; - int w = 0; - int h = 0; - Function2 generator; - static double oxp = 0; - static double ozp = 0; - double ox = 0; //Offset X - double oz = 0; //Offset Y - double mx = 0; - double mz = 0; - static double mxx = 0; - static double mzz = 0; - static boolean down = false; - double lx = Double.MAX_VALUE; //MouseX - double lz = Double.MAX_VALUE; //MouseY - double t; - double tz; + private static final long serialVersionUID = 2094606939770332040L; - public NoiseExplorer() - { - addMouseWheelListener(this); - addMouseMotionListener(new MouseMotionListener() - { - @Override - public void mouseMoved(MouseEvent e) - { - Point cp = e.getPoint(); + static JComboBox combo; + RollingSequence r = new RollingSequence(90); + boolean colorMode = true; + double scale = 1; + static boolean hd = false; + static double ascale = 10; + CNG cng = NoiseStyle.STATIC.create(new RNG(RNG.r.nextLong())); + GroupedExecutor gx = new GroupedExecutor(Runtime.getRuntime().availableProcessors(), Thread.MAX_PRIORITY, "Iris Renderer"); + ReentrantLock l = new ReentrantLock(); + int[][] co; + int w = 0; + int h = 0; + Function2 generator; + static double oxp = 0; + static double ozp = 0; + double ox = 0; //Offset X + double oz = 0; //Offset Y + double mx = 0; + double mz = 0; + static double mxx = 0; + static double mzz = 0; + static boolean down = false; + double lx = Double.MAX_VALUE; //MouseX + double lz = Double.MAX_VALUE; //MouseY + double t; + double tz; - lx = (cp.getX()); - lz = (cp.getY()); - mx = lx; - mz = lz; - } + public NoiseExplorer() { + addMouseWheelListener(this); + addMouseMotionListener(new MouseMotionListener() { + @Override + public void mouseMoved(MouseEvent e) { + Point cp = e.getPoint(); - @Override - public void mouseDragged(MouseEvent e) - { - Point cp = e.getPoint(); - ox += (lx - cp.getX()) * scale; - oz += (lz - cp.getY()) * scale; - lx = cp.getX(); - lz = cp.getY(); - } - }); - } + lx = (cp.getX()); + lz = (cp.getY()); + mx = lx; + mz = lz; + } - public void mouseWheelMoved(MouseWheelEvent e) - { + @Override + public void mouseDragged(MouseEvent e) { + Point cp = e.getPoint(); + ox += (lx - cp.getX()) * scale; + oz += (lz - cp.getY()) * scale; + lx = cp.getX(); + lz = cp.getY(); + } + }); + } - int notches = e.getWheelRotation(); - if(e.isControlDown()) - { - t = t + ((0.0025 * t) * notches); - return; - } + public void mouseWheelMoved(MouseWheelEvent e) { - scale = scale + ((0.044 * scale) * notches); - scale = Math.max(scale, 0.00001); - } + int notches = e.getWheelRotation(); + if (e.isControlDown()) { + t = t + ((0.0025 * t) * notches); + return; + } - @Override - public void paint(Graphics g) - { - if(scale < ascale) - { - ascale -= Math.abs(scale - ascale) * 0.16; - } + scale = scale + ((0.044 * scale) * notches); + scale = Math.max(scale, 0.00001); + } - if(scale > ascale) - { - ascale += Math.abs(ascale - scale) * 0.16; - } + @Override + public void paint(Graphics g) { + if (scale < ascale) { + ascale -= Math.abs(scale - ascale) * 0.16; + } - if(t < tz) - { - tz -= Math.abs(t - tz) * 0.29; - } + if (scale > ascale) { + ascale += Math.abs(ascale - scale) * 0.16; + } - if(t > tz) - { - tz += Math.abs(tz - t) * 0.29; - } + if (t < tz) { + tz -= Math.abs(t - tz) * 0.29; + } - if(ox < oxp) - { - oxp -= Math.abs(ox - oxp) * 0.16; - } + if (t > tz) { + tz += Math.abs(tz - t) * 0.29; + } - if(ox > oxp) - { - oxp += Math.abs(oxp - ox) * 0.16; - } + if (ox < oxp) { + oxp -= Math.abs(ox - oxp) * 0.16; + } - if(oz < ozp) - { - ozp -= Math.abs(oz - ozp) * 0.16; - } + if (ox > oxp) { + oxp += Math.abs(oxp - ox) * 0.16; + } - if(oz > ozp) - { - ozp += Math.abs(ozp - oz) * 0.16; - } + if (oz < ozp) { + ozp -= Math.abs(oz - ozp) * 0.16; + } - if(mx < mxx) - { - mxx -= Math.abs(mx - mxx) * 0.16; - } + if (oz > ozp) { + ozp += Math.abs(ozp - oz) * 0.16; + } - if(mx > mxx) - { - mxx += Math.abs(mxx - mx) * 0.16; - } + if (mx < mxx) { + mxx -= Math.abs(mx - mxx) * 0.16; + } - if(mz < mzz) - { - mzz -= Math.abs(mz - mzz) * 0.16; - } + if (mx > mxx) { + mxx += Math.abs(mxx - mx) * 0.16; + } - if(mz > mzz) - { - mzz += Math.abs(mzz - mz) * 0.16; - } + if (mz < mzz) { + mzz -= Math.abs(mz - mzz) * 0.16; + } - PrecisionStopwatch p = PrecisionStopwatch.start(); - int accuracy = hd ? 1 : M.clip((r.getAverage() / 6D), 1D, 128D).intValue(); - accuracy = down ? accuracy * 4 : accuracy; - int v = 1000; + if (mz > mzz) { + mzz += Math.abs(mzz - mz) * 0.16; + } - if(g instanceof Graphics2D) - { - Graphics2D gg = (Graphics2D) g; + PrecisionStopwatch p = PrecisionStopwatch.start(); + int accuracy = hd ? 1 : M.clip((r.getAverage() / 6D), 1D, 128D).intValue(); + accuracy = down ? accuracy * 4 : accuracy; + int v = 1000; - if(getParent().getWidth() != w || getParent().getHeight() != h) - { - w = getParent().getWidth(); - h = getParent().getHeight(); - co = null; - } + if (g instanceof Graphics2D) { + Graphics2D gg = (Graphics2D) g; - if(co == null) - { - co = new int[w][h]; - } + if (getParent().getWidth() != w || getParent().getHeight() != h) { + w = getParent().getWidth(); + h = getParent().getHeight(); + co = null; + } - for(int x = 0; x < w; x += accuracy) - { - int xx = x; + if (co == null) { + co = new int[w][h]; + } - for(int z = 0; z < h; z += accuracy) - { - int zz = z; - gx.queue("a", () -> - { - double n = generator != null ? generator.apply((xx * ascale) + oxp, (zz * ascale) + ozp) : cng.noise((xx * ascale) + oxp, tz, (zz * ascale) + ozp); + for (int x = 0; x < w; x += accuracy) { + int xx = x; - if(n > 1 || n < 0) - { - return; - } + for (int z = 0; z < h; z += accuracy) { + int zz = z; + gx.queue("a", () -> + { + double n = generator != null ? generator.apply((xx * ascale) + oxp, (zz * ascale) + ozp) : cng.noise((xx * ascale) + oxp, tz, (zz * ascale) + ozp); - Color color = colorMode ? Color.getHSBColor((float) (n), 1f - (float) (n * n * n * n * n * n), 1f - (float) n) : Color.getHSBColor(0f, 0f, (float) n); - int rgb = color.getRGB(); - co[xx][zz] = rgb; - }); - } + if (n > 1 || n < 0) { + return; + } - gx.waitFor("a"); + Color color = colorMode ? Color.getHSBColor((float) (n), 1f - (float) (n * n * n * n * n * n), 1f - (float) n) : Color.getHSBColor(0f, 0f, (float) n); + int rgb = color.getRGB(); + co[xx][zz] = rgb; + }); + } - if(hd && p.getMilliseconds() > v) - { - break; - } - } + gx.waitFor("a"); - for(int x = 0; x < getParent().getWidth(); x += accuracy) - { - for(int z = 0; z < getParent().getHeight(); z += accuracy) - { - gg.setColor(new Color(co[x][z])); - gg.fillRect(x, z, accuracy, accuracy); - } - } - } + if (hd && p.getMilliseconds() > v) { + break; + } + } - p.end(); + for (int x = 0; x < getParent().getWidth(); x += accuracy) { + for (int z = 0; z < getParent().getHeight(); z += accuracy) { + gg.setColor(new Color(co[x][z])); + gg.fillRect(x, z, accuracy, accuracy); + } + } + } - t += 1D; - r.put(p.getMilliseconds()); + p.end(); - if(!isVisible()) - { - return; - } + t += 1D; + r.put(p.getMilliseconds()); - if(!getParent().isVisible()) - { - return; - } + if (!isVisible()) { + return; + } - if(!getParent().getParent().isVisible()) - { - return; - } + if (!getParent().isVisible()) { + return; + } - EventQueue.invokeLater(() -> - { - J.sleep((long) Math.max(0, 32 - r.getAverage())); - repaint(); - }); - } + if (!getParent().getParent().isVisible()) { + return; + } - private static void createAndShowGUI(Function2 gen, String genName) - { - JFrame frame = new JFrame("Noise Explorer: " + genName); - NoiseExplorer nv = new NoiseExplorer(); - frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); - JLayeredPane pane = new JLayeredPane(); - nv.setSize(new Dimension(1440, 820)); - pane.add(nv, 1, 0); - nv.generator = gen; - frame.add(pane); - File file = Iris.getCached("Iris Icon", "https://raw.githubusercontent.com/VolmitSoftware/Iris/master/icon.png"); + EventQueue.invokeLater(() -> + { + J.sleep((long) Math.max(0, 32 - r.getAverage())); + repaint(); + }); + } - if(file != null) - { - try - { - frame.setIconImage(ImageIO.read(file)); - } - catch(IOException ignored) { } - } - frame.setSize(1440, 820); - frame.setVisible(true); - } + private static void createAndShowGUI(Function2 gen, String genName) { + JFrame frame = new JFrame("Noise Explorer: " + genName); + NoiseExplorer nv = new NoiseExplorer(); + frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); + JLayeredPane pane = new JLayeredPane(); + nv.setSize(new Dimension(1440, 820)); + pane.add(nv, 1, 0); + nv.generator = gen; + frame.add(pane); + File file = Iris.getCached("Iris Icon", "https://raw.githubusercontent.com/VolmitSoftware/Iris/master/icon.png"); - private static void createAndShowGUI() - { - JFrame frame = new JFrame("Noise Explorer"); - NoiseExplorer nv = new NoiseExplorer(); - frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); - KList li = new KList(NoiseStyle.values()).toStringList(); - combo = new JComboBox(li.toArray(new String[li.size()])); - combo.setSelectedItem("STATIC"); - combo.setFocusable(false); - combo.addActionListener(e -> { - @SuppressWarnings("unchecked") - String b = (String) (((JComboBox) e.getSource()).getSelectedItem()); - NoiseStyle s = NoiseStyle.valueOf(b); - nv.cng = s.create(RNG.r.nextParallelRNG(RNG.r.imax())); - }); + if (file != null) { + try { + frame.setIconImage(ImageIO.read(file)); + } catch (IOException ignored) { + } + } + frame.setSize(1440, 820); + frame.setVisible(true); + } - combo.setSize(500, 30); - JLayeredPane pane = new JLayeredPane(); - nv.setSize(new Dimension(1440, 820)); - pane.add(nv, 1, 0); - pane.add(combo, 2, 0); - frame.add(pane); - File file = Iris.getCached("Iris Icon", "https://raw.githubusercontent.com/VolmitSoftware/Iris/master/icon.png"); + private static void createAndShowGUI() { + JFrame frame = new JFrame("Noise Explorer"); + NoiseExplorer nv = new NoiseExplorer(); + frame.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE); + KList li = new KList(NoiseStyle.values()).toStringList(); + combo = new JComboBox(li.toArray(new String[li.size()])); + combo.setSelectedItem("STATIC"); + combo.setFocusable(false); + combo.addActionListener(e -> { + @SuppressWarnings("unchecked") + String b = (String) (((JComboBox) e.getSource()).getSelectedItem()); + NoiseStyle s = NoiseStyle.valueOf(b); + nv.cng = s.create(RNG.r.nextParallelRNG(RNG.r.imax())); + }); - if(file != null) - { - try - { - frame.setIconImage(ImageIO.read(file)); - } - catch(IOException ignored) { } - } - frame.setSize(1440, 820); - frame.setVisible(true); - } + combo.setSize(500, 30); + JLayeredPane pane = new JLayeredPane(); + nv.setSize(new Dimension(1440, 820)); + pane.add(nv, 1, 0); + pane.add(combo, 2, 0); + frame.add(pane); + File file = Iris.getCached("Iris Icon", "https://raw.githubusercontent.com/VolmitSoftware/Iris/master/icon.png"); - public static void launch(Function2 gen, String genName) - { - EventQueue.invokeLater(() -> createAndShowGUI(gen, genName)); - } + if (file != null) { + try { + frame.setIconImage(ImageIO.read(file)); + } catch (IOException ignored) { + } + } + frame.setSize(1440, 820); + frame.setVisible(true); + } - public static void launch() - { - EventQueue.invokeLater(() -> createAndShowGUI()); - } + public static void launch(Function2 gen, String genName) { + EventQueue.invokeLater(() -> createAndShowGUI(gen, genName)); + } - static class HandScrollListener extends MouseAdapter - { - private static final Point pp = new Point(); + public static void launch() { + EventQueue.invokeLater(() -> createAndShowGUI()); + } - @Override - public void mouseDragged(MouseEvent e) - { - JViewport vport = (JViewport) e.getSource(); - JComponent label = (JComponent) vport.getView(); - Point cp = e.getPoint(); - Point vp = vport.getViewPosition(); - vp.translate(pp.x - cp.x, pp.y - cp.y); - label.scrollRectToVisible(new Rectangle(vp, vport.getSize())); + static class HandScrollListener extends MouseAdapter { + private static final Point pp = new Point(); - pp.setLocation(cp); - } + @Override + public void mouseDragged(MouseEvent e) { + JViewport vport = (JViewport) e.getSource(); + JComponent label = (JComponent) vport.getView(); + Point cp = e.getPoint(); + Point vp = vport.getViewPosition(); + vp.translate(pp.x - cp.x, pp.y - cp.y); + label.scrollRectToVisible(new Rectangle(vp, vport.getSize())); - @Override - public void mousePressed(MouseEvent e) - { - pp.setLocation(e.getPoint()); - } - } + pp.setLocation(cp); + } + + @Override + public void mousePressed(MouseEvent e) { + pp.setLocation(e.getPoint()); + } + } } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/manager/gui/Renderer.java b/src/main/java/com/volmit/iris/manager/gui/Renderer.java index 4a89c1f3d..6e78906c2 100644 --- a/src/main/java/com/volmit/iris/manager/gui/Renderer.java +++ b/src/main/java/com/volmit/iris/manager/gui/Renderer.java @@ -1,9 +1,8 @@ package com.volmit.iris.manager.gui; -import java.awt.Color; +import java.awt.*; @FunctionalInterface -public interface Renderer -{ - public Color draw(double x, double z); +public interface Renderer { + Color draw(double x, double z); } diff --git a/src/main/java/com/volmit/iris/manager/gui/TileRender.java b/src/main/java/com/volmit/iris/manager/gui/TileRender.java index 4c1062efc..a2d2efdfa 100644 --- a/src/main/java/com/volmit/iris/manager/gui/TileRender.java +++ b/src/main/java/com/volmit/iris/manager/gui/TileRender.java @@ -7,8 +7,7 @@ import java.awt.image.BufferedImage; @Builder @Data -public class TileRender -{ +public class TileRender { private BufferedImage image; private int quality; } diff --git a/src/main/java/com/volmit/iris/manager/link/BKLink.java b/src/main/java/com/volmit/iris/manager/link/BKLink.java index 461577c81..1b6374975 100644 --- a/src/main/java/com/volmit/iris/manager/link/BKLink.java +++ b/src/main/java/com/volmit/iris/manager/link/BKLink.java @@ -6,33 +6,24 @@ import org.bukkit.block.Block; import org.bukkit.block.data.BlockData; import org.bukkit.plugin.Plugin; -public class BKLink -{ - public BKLink() - { +public class BKLink { + public BKLink() { - } + } - public void updateBlock(Block b) { - BlockData d = b.getBlockData(); - b.setType(Material.AIR, false); - b.setBlockData(d, true); - } + public void updateBlock(Block b) { + BlockData d = b.getBlockData(); + b.setType(Material.AIR, false); + b.setBlockData(d, true); + } - public boolean supported() - { - return getBK() != null; - } + public boolean supported() { + return getBK() != null; + } - public Plugin getBK() - { - Plugin p = Bukkit.getPluginManager().getPlugin("BKCommonLib"); + public Plugin getBK() { + Plugin p = Bukkit.getPluginManager().getPlugin("BKCommonLib"); - if(p == null) - { - return null; - } - - return p; - } + return p; + } } diff --git a/src/main/java/com/volmit/iris/manager/link/CitizensLink.java b/src/main/java/com/volmit/iris/manager/link/CitizensLink.java index 5aaf227ec..799c6677e 100644 --- a/src/main/java/com/volmit/iris/manager/link/CitizensLink.java +++ b/src/main/java/com/volmit/iris/manager/link/CitizensLink.java @@ -3,39 +3,30 @@ package com.volmit.iris.manager.link; import org.bukkit.Bukkit; import org.bukkit.plugin.Plugin; -public class CitizensLink -{ - public CitizensLink() - { +public class CitizensLink { + public CitizensLink() { - } + } - public boolean supported() - { - return getCitizens() != null; - } + public boolean supported() { + return getCitizens() != null; + } - // public Entity spawn(EntityType type, String npcType, Location a) - // { - // if(!supported()) - // { - // return null; - // } - // - // NPC npc = CitizensAPI.getNPCRegistry().createNPC(type, ""); - // npc.spawn(a); - // return npc.getEntity(); - // } + // public Entity spawn(EntityType type, String npcType, Location a) + // { + // if(!supported()) + // { + // return null; + // } + // + // NPC npc = CitizensAPI.getNPCRegistry().createNPC(type, ""); + // npc.spawn(a); + // return npc.getEntity(); + // } - public Plugin getCitizens() - { - Plugin p = Bukkit.getPluginManager().getPlugin("Citizens"); + public Plugin getCitizens() { + Plugin p = Bukkit.getPluginManager().getPlugin("Citizens"); - if(p == null) - { - return null; - } - - return p; - } + return p; + } } diff --git a/src/main/java/com/volmit/iris/manager/link/MultiverseCoreLink.java b/src/main/java/com/volmit/iris/manager/link/MultiverseCoreLink.java index 2010a33ad..d1d6f3996 100644 --- a/src/main/java/com/volmit/iris/manager/link/MultiverseCoreLink.java +++ b/src/main/java/com/volmit/iris/manager/link/MultiverseCoreLink.java @@ -11,151 +11,114 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.Map; -public class MultiverseCoreLink -{ - private final KMap worldNameTypes = new KMap<>(); +public class MultiverseCoreLink { + private final KMap worldNameTypes = new KMap<>(); - public MultiverseCoreLink() - { + public MultiverseCoreLink() { - } + } - public boolean addWorld(String worldName, IrisDimension dim, String seed) - { - if(!supported()) - { - return false; - } + public boolean addWorld(String worldName, IrisDimension dim, String seed) { + if (!supported()) { + return false; + } - try - { - Plugin p = getMultiverse(); - Object mvWorldManager = p.getClass().getDeclaredMethod("getMVWorldManager").invoke(p); - Method m = mvWorldManager.getClass().getDeclaredMethod("addWorld", + try { + Plugin p = getMultiverse(); + Object mvWorldManager = p.getClass().getDeclaredMethod("getMVWorldManager").invoke(p); + Method m = mvWorldManager.getClass().getDeclaredMethod("addWorld", - String.class, World.Environment.class, String.class, WorldType.class, Boolean.class, String.class, boolean.class); - boolean b = (boolean) m.invoke(mvWorldManager, worldName, dim.getEnvironment(), seed, WorldType.NORMAL, false, "Iris", false); - saveConfig(); - return b; - } + String.class, World.Environment.class, String.class, WorldType.class, Boolean.class, String.class, boolean.class); + boolean b = (boolean) m.invoke(mvWorldManager, worldName, dim.getEnvironment(), seed, WorldType.NORMAL, false, "Iris", false); + saveConfig(); + return b; + } catch (Throwable e) { + e.printStackTrace(); + } - catch(Throwable e) - { - e.printStackTrace(); - } + return false; + } - return false; - } + @SuppressWarnings("unchecked") + public Map getList() { + try { + Plugin p = getMultiverse(); + Object mvWorldManager = p.getClass().getDeclaredMethod("getMVWorldManager").invoke(p); + Field f = mvWorldManager.getClass().getDeclaredField("worldsFromTheConfig"); + f.setAccessible(true); + return (Map) f.get(mvWorldManager); + } catch (Throwable e) { + e.printStackTrace(); + } - @SuppressWarnings("unchecked") - public Map getList() - { - try - { - Plugin p = getMultiverse(); - Object mvWorldManager = p.getClass().getDeclaredMethod("getMVWorldManager").invoke(p); - Field f = mvWorldManager.getClass().getDeclaredField("worldsFromTheConfig"); - f.setAccessible(true); - return (Map) f.get(mvWorldManager); - } + return null; + } - catch(Throwable e) - { - e.printStackTrace(); - } + public void removeFromConfig(World world) { + if (!supported()) { + return; + } - return null; - } + getList().remove(world.getName()); + saveConfig(); + } - public void removeFromConfig(World world) - { - if(!supported()) - { - return; - } + public void removeFromConfig(String world) { + if (!supported()) { + return; + } - getList().remove(world.getName()); - saveConfig(); - } + getList().remove(world); + saveConfig(); + } - public void removeFromConfig(String world) - { - if(!supported()) - { - return; - } + public void saveConfig() { + try { + Plugin p = getMultiverse(); + Object mvWorldManager = p.getClass().getDeclaredMethod("getMVWorldManager").invoke(p); + mvWorldManager.getClass().getDeclaredMethod("saveWorldsConfig").invoke(mvWorldManager); + } catch (Throwable e) { + e.printStackTrace(); + } + } - getList().remove(world); - saveConfig(); - } + public void assignWorldType(String worldName, String type) { + worldNameTypes.put(worldName, type); + } - public void saveConfig() - { - try - { - Plugin p = getMultiverse(); - Object mvWorldManager = p.getClass().getDeclaredMethod("getMVWorldManager").invoke(p); - mvWorldManager.getClass().getDeclaredMethod("saveWorldsConfig").invoke(mvWorldManager); - } + public String getWorldNameType(String worldName, String defaultType) { + try { + String t = worldNameTypes.get(worldName); + return t == null ? defaultType : t; + } catch (Throwable e) { + return defaultType; + } + } - catch(Throwable e) - { - e.printStackTrace(); - } - } + public boolean supported() { + return getMultiverse() != null; + } - public void assignWorldType(String worldName, String type) - { - worldNameTypes.put(worldName, type); - } + public Plugin getMultiverse() { + Plugin p = Bukkit.getPluginManager().getPlugin("Multiverse-Core"); - public String getWorldNameType(String worldName, String defaultType) - { - try - { - String t = worldNameTypes.get(worldName); - return t == null ? defaultType : t; - } + return p; + } - catch(Throwable e) - { - return defaultType; - } - } + public String envName(World.Environment environment) { + if (environment == null) { + return "normal"; + } - public boolean supported() - { - return getMultiverse() != null; - } + switch (environment) { + case NORMAL: + return "normal"; + case NETHER: + return "nether"; + case THE_END: + return "end"; + } - public Plugin getMultiverse() - { - Plugin p = Bukkit.getPluginManager().getPlugin("Multiverse-Core"); - - if(p == null) - { - return null; - } - - return p; - } - - public String envName(World.Environment environment) { - if(environment == null) - { - return "normal"; - } - - switch(environment) - { - case NORMAL: - return "normal"; - case NETHER: - return "nether"; - case THE_END: - return "end"; - } - - return environment.toString().toLowerCase(); - } + return environment.toString().toLowerCase(); + } } diff --git a/src/main/java/com/volmit/iris/manager/link/MythicMobsLink.java b/src/main/java/com/volmit/iris/manager/link/MythicMobsLink.java index 2d5dd9d53..8402dc36f 100644 --- a/src/main/java/com/volmit/iris/manager/link/MythicMobsLink.java +++ b/src/main/java/com/volmit/iris/manager/link/MythicMobsLink.java @@ -1,64 +1,48 @@ package com.volmit.iris.manager.link; +import com.volmit.iris.util.KList; +import io.lumine.xikage.mythicmobs.MythicMobs; +import io.lumine.xikage.mythicmobs.mobs.MythicMob; import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.entity.Entity; import org.bukkit.plugin.Plugin; -import com.volmit.iris.util.KList; +public class MythicMobsLink { + public MythicMobsLink() { -import io.lumine.xikage.mythicmobs.MythicMobs; -import io.lumine.xikage.mythicmobs.mobs.MythicMob; + } -public class MythicMobsLink -{ - public MythicMobsLink() - { + public boolean supported() { + return getMythicMobs() != null; + } - } + public Entity spawn(String name, Location a) { + if (!supported()) { + return null; + } - public boolean supported() - { - return getMythicMobs() != null; - } + MythicMobs m = (MythicMobs) getMythicMobs(); + return m.getMobManager().spawnMob(name, a).getEntity().getBukkitEntity(); + } - public Entity spawn(String name, Location a) - { - if(!supported()) - { - return null; - } + public String[] getMythicMobTypes() { + KList v = new KList<>(); - MythicMobs m = (MythicMobs) getMythicMobs(); - return m.getMobManager().spawnMob(name, a).getEntity().getBukkitEntity(); - } + if (supported()) { + MythicMobs m = (MythicMobs) getMythicMobs(); - public String[] getMythicMobTypes() - { - KList v = new KList<>(); + for (MythicMob i : m.getMobManager().getMobTypes()) { + v.add(i.getInternalName()); + } + } - if(supported()) - { - MythicMobs m = (MythicMobs) getMythicMobs(); + return v.toArray(new String[v.size()]); + } - for(MythicMob i : m.getMobManager().getMobTypes()) - { - v.add(i.getInternalName()); - } - } + public Plugin getMythicMobs() { + Plugin p = Bukkit.getPluginManager().getPlugin("MythicMobs"); - return v.toArray(new String[v.size()]); - } - - public Plugin getMythicMobs() - { - Plugin p = Bukkit.getPluginManager().getPlugin("MythicMobs"); - - if(p == null) - { - return null; - } - - return p; - } + return p; + } } diff --git a/src/main/java/com/volmit/iris/manager/report/Report.java b/src/main/java/com/volmit/iris/manager/report/Report.java index 17d725297..56eeee6c7 100644 --- a/src/main/java/com/volmit/iris/manager/report/Report.java +++ b/src/main/java/com/volmit/iris/manager/report/Report.java @@ -2,22 +2,18 @@ package com.volmit.iris.manager.report; import lombok.Builder; -import java.io.File; - @Builder -public class Report -{ +public class Report { @Builder.Default - private ReportType type = ReportType.NOTICE; + private final ReportType type = ReportType.NOTICE; @Builder.Default - private String title = "Problem..."; + private final String title = "Problem..."; @Builder.Default - private String message = "No Message"; + private final String message = "No Message"; @Builder.Default - private String suggestion = "No Suggestion"; + private final String suggestion = "No Suggestion"; - public String toString() - { + public String toString() { return type.toString() + ": " + title + ": " + message + ": Suggestion: " + suggestion; } } diff --git a/src/main/java/com/volmit/iris/nms/INMS.java b/src/main/java/com/volmit/iris/nms/INMS.java index c63b99ea0..0cab540a4 100644 --- a/src/main/java/com/volmit/iris/nms/INMS.java +++ b/src/main/java/com/volmit/iris/nms/INMS.java @@ -7,66 +7,51 @@ import com.volmit.iris.nms.v1X.NMSBinding1X; import com.volmit.iris.util.KMap; import org.bukkit.Bukkit; -public class INMS -{ - //@builder - private static final KMap> bindings = new KMap>() - .qput("v1_17_R1", NMSBinding17_1.class) - ; - //@done - private static final INMSBinding binding = bind(); +public class INMS { + //@builder + private static final KMap> bindings = new KMap>() + .qput("v1_17_R1", NMSBinding17_1.class); + //@done + private static final INMSBinding binding = bind(); - public static INMSBinding get() - { - return binding; - } + public static INMSBinding get() { + return binding; + } - public static final String getNMSTag() - { - if(IrisSettings.get().getGeneral().isDisableNMS()) - { - return "BUKKIT"; - } + public static final String getNMSTag() { + if (IrisSettings.get().getGeneral().isDisableNMS()) { + return "BUKKIT"; + } - try - { - return Bukkit.getServer().getClass().getCanonicalName().split("\\Q.\\E")[3]; - } + try { + return Bukkit.getServer().getClass().getCanonicalName().split("\\Q.\\E")[3]; + } catch (Throwable e) { + Iris.error("Failed to determine server nms version!"); + e.printStackTrace(); + } - catch(Throwable e) - { - Iris.error("Failed to determine server nms version!"); - e.printStackTrace(); - } + return "BUKKIT"; + } - return "BUKKIT"; - } + private static final INMSBinding bind() { + String code = getNMSTag(); + Iris.info("Locating NMS Binding for " + code); - private static final INMSBinding bind() - { - String code = getNMSTag(); - Iris.info("Locating NMS Binding for " + code); + if (bindings.containsKey(code)) { + try { + INMSBinding b = bindings.get(code).getConstructor().newInstance(); + Iris.info("Craftbukkit " + code + " <-> " + b.getClass().getSimpleName() + " Successfully Bound"); - if(bindings.containsKey(code)) - { - try - { - INMSBinding b = bindings.get(code).getConstructor().newInstance(); - Iris.info("Craftbukkit " + code + " <-> " + b.getClass().getSimpleName() + " Successfully Bound"); + return b; + } catch (Throwable e) { + e.printStackTrace(); + } + } - return b; - } + Iris.info("Craftbukkit " + code + " <-> " + NMSBinding1X.class.getSimpleName() + " Successfully Bound"); + Iris.warn("Note: Some features of Iris may not work the same since you are on an unsupported version of Minecraft."); + Iris.warn("Note: If this is a new version, expect an update soon."); - catch(Throwable e) - { - e.printStackTrace(); - } - } - - Iris.info("Craftbukkit " + code + " <-> " + NMSBinding1X.class.getSimpleName() + " Successfully Bound"); - Iris.warn("Note: Some features of Iris may not work the same since you are on an unsupported version of Minecraft."); - Iris.warn("Note: If this is a new version, expect an update soon."); - - return new NMSBinding1X(); - } + return new NMSBinding1X(); + } } diff --git a/src/main/java/com/volmit/iris/nms/INMSBinding.java b/src/main/java/com/volmit/iris/nms/INMSBinding.java index 4cc662d51..6d98793d1 100644 --- a/src/main/java/com/volmit/iris/nms/INMSBinding.java +++ b/src/main/java/com/volmit/iris/nms/INMSBinding.java @@ -5,30 +5,28 @@ import org.bukkit.World; import org.bukkit.WorldCreator; import org.bukkit.block.Biome; -public interface INMSBinding -{ - public Object getBiomeBaseFromId(int id); +public interface INMSBinding { + Object getBiomeBaseFromId(int id); - public int getTrueBiomeBaseId(Object biomeBase); + int getTrueBiomeBaseId(Object biomeBase); - public Object getTrueBiomeBase(Location location); + Object getTrueBiomeBase(Location location); - public String getTrueBiomeBaseKey(Location location); + String getTrueBiomeBaseKey(Location location); - public Object getCustomBiomeBaseFor(String mckey); + Object getCustomBiomeBaseFor(String mckey); - public String getKeyForBiomeBase(Object biomeBase); + String getKeyForBiomeBase(Object biomeBase); - public Object getBiomeBase(World world, Biome biome); + Object getBiomeBase(World world, Biome biome); - public Object getBiomeBase(Object registry, Biome biome); + Object getBiomeBase(Object registry, Biome biome); - public boolean isBukkit(); + boolean isBukkit(); int getBiomeId(Biome biome); - default World createWorld(WorldCreator c) - { - return c.createWorld(); - } + default World createWorld(WorldCreator c) { + return c.createWorld(); + } } diff --git a/src/main/java/com/volmit/iris/nms/v17_1/NMSBinding17_1.java b/src/main/java/com/volmit/iris/nms/v17_1/NMSBinding17_1.java index aad74905c..d6823c2b7 100644 --- a/src/main/java/com/volmit/iris/nms/v17_1/NMSBinding17_1.java +++ b/src/main/java/com/volmit/iris/nms/v17_1/NMSBinding17_1.java @@ -1,15 +1,11 @@ package com.volmit.iris.nms.v17_1; -import com.volmit.iris.Iris; import com.volmit.iris.nms.INMSBinding; import com.volmit.iris.util.KMap; import net.minecraft.core.IRegistry; import net.minecraft.core.IRegistryWritable; -import net.minecraft.data.worldgen.biome.BiomeRegistry; import net.minecraft.resources.MinecraftKey; import net.minecraft.resources.ResourceKey; -import net.minecraft.server.MinecraftServer; -import net.minecraft.server.level.WorldServer; import net.minecraft.world.level.biome.BiomeBase; import org.bukkit.Bukkit; import org.bukkit.Location; @@ -17,154 +13,143 @@ import org.bukkit.World; import org.bukkit.block.Biome; import org.bukkit.craftbukkit.v1_17_R1.CraftServer; import org.bukkit.craftbukkit.v1_17_R1.CraftWorld; + import java.lang.reflect.Field; import java.lang.reflect.Method; -public class NMSBinding17_1 implements INMSBinding -{ - private final KMap baseBiomeCache = new KMap<>(); +public class NMSBinding17_1 implements INMSBinding { + private final KMap baseBiomeCache = new KMap<>(); - private IRegistryWritable getCustomBiomeRegistry() - { - return ((CraftServer)Bukkit.getServer()).getHandle().getServer().getCustomRegistry().b(IRegistry.aO); - } + private IRegistryWritable getCustomBiomeRegistry() { + return ((CraftServer) Bukkit.getServer()).getHandle().getServer().getCustomRegistry().b(IRegistry.aO); + } - @Override - public Object getBiomeBaseFromId(int id) { - return getCustomBiomeRegistry().fromId(id); - } + @Override + public Object getBiomeBaseFromId(int id) { + return getCustomBiomeRegistry().fromId(id); + } - @Override - public int getTrueBiomeBaseId(Object biomeBase) { - return getCustomBiomeRegistry().getId((BiomeBase)biomeBase); - } + @Override + public int getTrueBiomeBaseId(Object biomeBase) { + return getCustomBiomeRegistry().getId((BiomeBase) biomeBase); + } - @Override - public Object getTrueBiomeBase(Location location) { - return ((CraftWorld)location.getWorld()).getHandle().getBiome(location.getBlockX(), location.getBlockY(), location.getBlockZ()); - } + @Override + public Object getTrueBiomeBase(Location location) { + return ((CraftWorld) location.getWorld()).getHandle().getBiome(location.getBlockX(), location.getBlockY(), location.getBlockZ()); + } - @Override - public String getTrueBiomeBaseKey(Location location) { - return getKeyForBiomeBase(getTrueBiomeBase(location)); - } + @Override + public String getTrueBiomeBaseKey(Location location) { + return getKeyForBiomeBase(getTrueBiomeBase(location)); + } - @Override - public Object getCustomBiomeBaseFor(String mckey) { - return getCustomBiomeRegistry().d(ResourceKey.a(IRegistry.aO, new MinecraftKey(mckey))); - } + @Override + public Object getCustomBiomeBaseFor(String mckey) { + return getCustomBiomeRegistry().d(ResourceKey.a(IRegistry.aO, new MinecraftKey(mckey))); + } - @Override - public String getKeyForBiomeBase(Object biomeBase) { - return getCustomBiomeRegistry().c((BiomeBase)biomeBase).get().a().toString(); - } + @Override + public String getKeyForBiomeBase(Object biomeBase) { + return getCustomBiomeRegistry().c((BiomeBase) biomeBase).get().a().toString(); + } - @Override - public Object getBiomeBase(World world, Biome biome) - { - return getBiomeBase(((CraftWorld)world).getHandle().t().d(IRegistry.aO), biome); - } + @Override + public Object getBiomeBase(World world, Biome biome) { + return getBiomeBase(((CraftWorld) world).getHandle().t().d(IRegistry.aO), biome); + } - private Class[] classify(Object...par) - { - Class[] g = new Class[par.length]; - for(int i = 0; i < g.length; i++) - { - g[i] = par[i].getClass(); - } + private Class[] classify(Object... par) { + Class[] g = new Class[par.length]; + for (int i = 0; i < g.length; i++) { + g[i] = par[i].getClass(); + } - return g; - } + return g; + } - private T invoke(Object from, String name, Object...par) - { - try { - Method f = from.getClass().getDeclaredMethod(name, classify(par)); - f.setAccessible(true); - return (T) f.invoke(from, par); - } catch (Throwable e) { - e.printStackTrace(); - } + private T invoke(Object from, String name, Object... par) { + try { + Method f = from.getClass().getDeclaredMethod(name, classify(par)); + f.setAccessible(true); + return (T) f.invoke(from, par); + } catch (Throwable e) { + e.printStackTrace(); + } - return null; - } + return null; + } - private T invokeStatic(Class from, String name, Object...par) - { - try { - Method f = from.getDeclaredMethod(name, classify(par)); - f.setAccessible(true); - return (T) f.invoke(null, par); - } catch (Throwable e) { - e.printStackTrace(); - } + private T invokeStatic(Class from, String name, Object... par) { + try { + Method f = from.getDeclaredMethod(name, classify(par)); + f.setAccessible(true); + return (T) f.invoke(null, par); + } catch (Throwable e) { + e.printStackTrace(); + } - return null; - } + return null; + } - private T getField(Object from, String name) - { - try { - Field f = from.getClass().getDeclaredField(name); - f.setAccessible(true); - return (T) f.get(from); - } catch (Throwable e) { - e.printStackTrace(); - } + private T getField(Object from, String name) { + try { + Field f = from.getClass().getDeclaredField(name); + f.setAccessible(true); + return (T) f.get(from); + } catch (Throwable e) { + e.printStackTrace(); + } - return null; - } + return null; + } - private T getStaticField(Class t, String name) - { - try { - Field f = t.getDeclaredField(name); - f.setAccessible(true); - return (T) f.get(null); - } catch (Throwable e) { - e.printStackTrace(); - } + private T getStaticField(Class t, String name) { + try { + Field f = t.getDeclaredField(name); + f.setAccessible(true); + return (T) f.get(null); + } catch (Throwable e) { + e.printStackTrace(); + } - return null; - } + return null; + } - @Override - public Object getBiomeBase(Object registry, Biome biome) { - Object v = baseBiomeCache.get(biome); + @Override + public Object getBiomeBase(Object registry, Biome biome) { + Object v = baseBiomeCache.get(biome); - if(v != null) - { - return v; - } - v = org.bukkit.craftbukkit.v1_17_R1.block.CraftBlock.biomeToBiomeBase((IRegistry) registry, biome); - if (v == null) { - // Ok so there is this new biome name called "CUSTOM" in Paper's new releases. - // But, this does NOT exist within CraftBukkit which makes it return an error. - // So, we will just return the ID that the plains biome returns instead. - return org.bukkit.craftbukkit.v1_17_R1.block.CraftBlock.biomeToBiomeBase((IRegistry) registry, Biome.PLAINS); - } - baseBiomeCache.put(biome, v); - return v; - } + if (v != null) { + return v; + } + v = org.bukkit.craftbukkit.v1_17_R1.block.CraftBlock.biomeToBiomeBase((IRegistry) registry, biome); + if (v == null) { + // Ok so there is this new biome name called "CUSTOM" in Paper's new releases. + // But, this does NOT exist within CraftBukkit which makes it return an error. + // So, we will just return the ID that the plains biome returns instead. + return org.bukkit.craftbukkit.v1_17_R1.block.CraftBlock.biomeToBiomeBase((IRegistry) registry, Biome.PLAINS); + } + baseBiomeCache.put(biome, v); + return v; + } - @Override - public int getBiomeId(Biome biome) { - for(World i : Bukkit.getWorlds()) - { - if(i.getEnvironment().equals(World.Environment.NORMAL)) - { + @Override + public int getBiomeId(Biome biome) { + for (World i : Bukkit.getWorlds()) { + if (i.getEnvironment().equals(World.Environment.NORMAL)) { - IRegistry registry = ((CraftWorld)i).getHandle().t().d(IRegistry.aO); + IRegistry registry = ((CraftWorld) i).getHandle().t().d(IRegistry.aO); - return registry.getId((BiomeBase) getBiomeBase(registry, biome)); - } - } + return registry.getId((BiomeBase) getBiomeBase(registry, biome)); + } + } - return biome.ordinal(); - } + return biome.ordinal(); + } - @Override - public boolean isBukkit() { - return false; - } + @Override + public boolean isBukkit() { + return false; + } } diff --git a/src/main/java/com/volmit/iris/nms/v1X/NMSBinding1X.java b/src/main/java/com/volmit/iris/nms/v1X/NMSBinding1X.java index 60a95880c..3369dc926 100644 --- a/src/main/java/com/volmit/iris/nms/v1X/NMSBinding1X.java +++ b/src/main/java/com/volmit/iris/nms/v1X/NMSBinding1X.java @@ -5,55 +5,53 @@ import org.bukkit.Location; import org.bukkit.World; import org.bukkit.block.Biome; -public class NMSBinding1X implements INMSBinding -{ - @Override - public Object getBiomeBaseFromId(int id) { - return null; - } +public class NMSBinding1X implements INMSBinding { + @Override + public Object getBiomeBaseFromId(int id) { + return null; + } - @Override - public int getTrueBiomeBaseId(Object biomeBase) { - return 0; - } + @Override + public int getTrueBiomeBaseId(Object biomeBase) { + return 0; + } - @Override - public Object getTrueBiomeBase(Location location) { - return null; - } + @Override + public Object getTrueBiomeBase(Location location) { + return null; + } - @Override - public String getTrueBiomeBaseKey(Location location) { - return null; - } + @Override + public String getTrueBiomeBaseKey(Location location) { + return null; + } - @Override - public Object getCustomBiomeBaseFor(String mckey) { - return null; - } + @Override + public Object getCustomBiomeBaseFor(String mckey) { + return null; + } - @Override - public String getKeyForBiomeBase(Object biomeBase) { - return null; - } + @Override + public String getKeyForBiomeBase(Object biomeBase) { + return null; + } - public Object getBiomeBase(World world, Biome biome) - { - return null; - } + public Object getBiomeBase(World world, Biome biome) { + return null; + } - @Override - public Object getBiomeBase(Object registry, Biome biome) { - return null; - } + @Override + public Object getBiomeBase(Object registry, Biome biome) { + return null; + } - @Override - public boolean isBukkit() { - return true; - } + @Override + public boolean isBukkit() { + return true; + } - @Override - public int getBiomeId(Biome biome) { - return biome.ordinal(); - } + @Override + public int getBiomeId(Biome biome) { + return biome.ordinal(); + } } diff --git a/src/main/java/com/volmit/iris/object/CarvingMode.java b/src/main/java/com/volmit/iris/object/CarvingMode.java index a28d9472f..49c8ce3c5 100644 --- a/src/main/java/com/volmit/iris/object/CarvingMode.java +++ b/src/main/java/com/volmit/iris/object/CarvingMode.java @@ -4,27 +4,24 @@ import com.volmit.iris.util.Desc; import com.volmit.iris.util.DontObfuscate; @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)") - @DontObfuscate - SURFACE_ONLY, +public enum CarvingMode { + @Desc("Only place this object on surfaces (NOT under carvings)") + @DontObfuscate + SURFACE_ONLY, - @Desc("Only place this object under carvings (NOT on the surface)") - @DontObfuscate - CARVING_ONLY, + @Desc("Only place this object under carvings (NOT on the surface)") + @DontObfuscate + CARVING_ONLY, - @Desc("This object can place anywhere") - @DontObfuscate - ANYWHERE; + @Desc("This object can place anywhere") + @DontObfuscate + ANYWHERE; - public boolean supportsCarving() - { - return this.equals(ANYWHERE) || this.equals(CARVING_ONLY); - } + public boolean supportsCarving() { + return this.equals(ANYWHERE) || this.equals(CARVING_ONLY); + } - public boolean supportsSurface() - { - return this.equals(ANYWHERE) || this.equals(SURFACE_ONLY); - } + public boolean supportsSurface() { + return this.equals(ANYWHERE) || this.equals(SURFACE_ONLY); + } } diff --git a/src/main/java/com/volmit/iris/object/DecorationPart.java b/src/main/java/com/volmit/iris/object/DecorationPart.java index 044759299..29dc2c747 100644 --- a/src/main/java/com/volmit/iris/object/DecorationPart.java +++ b/src/main/java/com/volmit/iris/object/DecorationPart.java @@ -4,25 +4,24 @@ import com.volmit.iris.util.Desc; import com.volmit.iris.util.DontObfuscate; @Desc("Represents a location where decorations should go") -public enum DecorationPart -{ - @Desc("The default, decorate anywhere") - @DontObfuscate - NONE, +public enum DecorationPart { + @Desc("The default, decorate anywhere") + @DontObfuscate + NONE, - @Desc("Targets shore lines (typically for sugar cane)") - @DontObfuscate - SHORE_LINE, + @Desc("Targets shore lines (typically for sugar cane)") + @DontObfuscate + SHORE_LINE, - @Desc("Target sea surfaces (typically for lilypads)") - @DontObfuscate - SEA_SURFACE, + @Desc("Target sea surfaces (typically for lilypads)") + @DontObfuscate + SEA_SURFACE, - @Desc("Targets the sea floor (entire placement must be bellow sea level)") - @DontObfuscate - SEA_FLOOR, + @Desc("Targets the sea floor (entire placement must be bellow sea level)") + @DontObfuscate + SEA_FLOOR, - @Desc("Decorates on cave & carving ceilings or underside of overhangs") - @DontObfuscate - CEILING, + @Desc("Decorates on cave & carving ceilings or underside of overhangs") + @DontObfuscate + CEILING, } diff --git a/src/main/java/com/volmit/iris/object/FontStyle.java b/src/main/java/com/volmit/iris/object/FontStyle.java index f28e2217c..fe871ab07 100644 --- a/src/main/java/com/volmit/iris/object/FontStyle.java +++ b/src/main/java/com/volmit/iris/object/FontStyle.java @@ -4,17 +4,16 @@ import com.volmit.iris.util.Desc; import com.volmit.iris.util.DontObfuscate; @Desc("Represents a basic font style to apply to a font family") -public enum FontStyle -{ - @Desc("Plain old text") - @DontObfuscate - PLAIN, +public enum FontStyle { + @Desc("Plain old text") + @DontObfuscate + PLAIN, - @Desc("Italicized Text") - @DontObfuscate - ITALIC, + @Desc("Italicized Text") + @DontObfuscate + ITALIC, - @Desc("Bold Text") - @DontObfuscate - BOLD, + @Desc("Bold Text") + @DontObfuscate + BOLD, } diff --git a/src/main/java/com/volmit/iris/object/InferredType.java b/src/main/java/com/volmit/iris/object/InferredType.java index 93e5caa4c..1ecd02a54 100644 --- a/src/main/java/com/volmit/iris/object/InferredType.java +++ b/src/main/java/com/volmit/iris/object/InferredType.java @@ -4,33 +4,32 @@ import com.volmit.iris.util.Desc; import com.volmit.iris.util.DontObfuscate; @Desc("Represents a biome type") -public enum InferredType -{ - @Desc("Represents any shore biome type") - @DontObfuscate - SHORE, +public enum InferredType { + @Desc("Represents any shore biome type") + @DontObfuscate + SHORE, - @Desc("Represents any land biome type") - @DontObfuscate - LAND, + @Desc("Represents any land biome type") + @DontObfuscate + LAND, - @Desc("Represents any sea biome type") - @DontObfuscate - SEA, + @Desc("Represents any sea biome type") + @DontObfuscate + SEA, - @Desc("Represents any cave biome type") - @DontObfuscate - CAVE, + @Desc("Represents any cave biome type") + @DontObfuscate + CAVE, - @Desc("Represents any river biome type") - @DontObfuscate - RIVER, + @Desc("Represents any river biome type") + @DontObfuscate + RIVER, - @Desc("Represents any lake biome type") - @DontObfuscate - LAKE, + @Desc("Represents any lake biome type") + @DontObfuscate + LAKE, - @Desc("Defers the type to whatever another biome type that already exists is.") - @DontObfuscate - DEFER; + @Desc("Defers the type to whatever another biome type that already exists is.") + @DontObfuscate + DEFER } diff --git a/src/main/java/com/volmit/iris/object/InterpolationMethod.java b/src/main/java/com/volmit/iris/object/InterpolationMethod.java index 2f7a8291f..386696fba 100644 --- a/src/main/java/com/volmit/iris/object/InterpolationMethod.java +++ b/src/main/java/com/volmit/iris/object/InterpolationMethod.java @@ -4,115 +4,113 @@ import com.volmit.iris.util.Desc; import com.volmit.iris.util.DontObfuscate; @Desc("An interpolation method (or function) is simply a method of smoothing a position based on surrounding points on a grid. Bicubic for example is smoother, but has 4 times the checks than Bilinear for example. Try using BILINEAR_STARCAST_9 for beautiful results.") -public enum InterpolationMethod -{ - @Desc("No interpolation. Nearest Neighbor (bad for terrain, great for performance).") - @DontObfuscate - NONE, +public enum InterpolationMethod { + @Desc("No interpolation. Nearest Neighbor (bad for terrain, great for performance).") + @DontObfuscate + NONE, - @Desc("Uses 4 nearby points in a square to calculate a 2d slope. Very fast but creates square artifacts. See: https://en.wikipedia.org/wiki/Bilinear_interpolation") - @DontObfuscate - BILINEAR, + @Desc("Uses 4 nearby points in a square to calculate a 2d slope. Very fast but creates square artifacts. See: https://en.wikipedia.org/wiki/Bilinear_interpolation") + @DontObfuscate + BILINEAR, - @Desc("Starcast is Iris's own creation. It uses raytrace checks to find a horizontal boundary nearby. 3 Checks in a circle. Typically starcast is used with another interpolation method. See BILINEAR_STARCAST_9 For example. Starcast is meant to 'break up' large, abrupt cliffs to make cheap interpolation smoother.") - @DontObfuscate - STARCAST_3, + @Desc("Starcast is Iris's own creation. It uses raytrace checks to find a horizontal boundary nearby. 3 Checks in a circle. Typically starcast is used with another interpolation method. See BILINEAR_STARCAST_9 For example. Starcast is meant to 'break up' large, abrupt cliffs to make cheap interpolation smoother.") + @DontObfuscate + STARCAST_3, - @Desc("Starcast is Iris's own creation. It uses raytrace checks to find a horizontal boundary nearby. 6 Checks in a circle. Typically starcast is used with another interpolation method. See BILINEAR_STARCAST_9 For example. Starcast is meant to 'break up' large, abrupt cliffs to make cheap interpolation smoother.") - @DontObfuscate - STARCAST_6, + @Desc("Starcast is Iris's own creation. It uses raytrace checks to find a horizontal boundary nearby. 6 Checks in a circle. Typically starcast is used with another interpolation method. See BILINEAR_STARCAST_9 For example. Starcast is meant to 'break up' large, abrupt cliffs to make cheap interpolation smoother.") + @DontObfuscate + STARCAST_6, - @Desc("Starcast is Iris's own creation. It uses raytrace checks to find a horizontal boundary nearby. 9 Checks in a circle. Typically starcast is used with another interpolation method. See BILINEAR_STARCAST_9 For example. Starcast is meant to 'break up' large, abrupt cliffs to make cheap interpolation smoother.") - @DontObfuscate - STARCAST_9, + @Desc("Starcast is Iris's own creation. It uses raytrace checks to find a horizontal boundary nearby. 9 Checks in a circle. Typically starcast is used with another interpolation method. See BILINEAR_STARCAST_9 For example. Starcast is meant to 'break up' large, abrupt cliffs to make cheap interpolation smoother.") + @DontObfuscate + STARCAST_9, - @Desc("Starcast is Iris's own creation. It uses raytrace checks to find a horizontal boundary nearby. 12 Checks in a circle. Typically starcast is used with another interpolation method. See BILINEAR_STARCAST_9 For example. Starcast is meant to 'break up' large, abrupt cliffs to make cheap interpolation smoother.") - @DontObfuscate - STARCAST_12, + @Desc("Starcast is Iris's own creation. It uses raytrace checks to find a horizontal boundary nearby. 12 Checks in a circle. Typically starcast is used with another interpolation method. See BILINEAR_STARCAST_9 For example. Starcast is meant to 'break up' large, abrupt cliffs to make cheap interpolation smoother.") + @DontObfuscate + STARCAST_12, - @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with bilinear.") - @DontObfuscate - BILINEAR_STARCAST_3, + @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with bilinear.") + @DontObfuscate + BILINEAR_STARCAST_3, - @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with bilinear.") - @DontObfuscate - BILINEAR_STARCAST_6, + @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with bilinear.") + @DontObfuscate + BILINEAR_STARCAST_6, - @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with bilinear.") - @DontObfuscate - BILINEAR_STARCAST_9, + @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with bilinear.") + @DontObfuscate + BILINEAR_STARCAST_9, - @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with bilinear.") - @DontObfuscate - BILINEAR_STARCAST_12, + @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with bilinear.") + @DontObfuscate + BILINEAR_STARCAST_12, - @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with hermite.") - @DontObfuscate - HERMITE_STARCAST_3, + @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with hermite.") + @DontObfuscate + HERMITE_STARCAST_3, - @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with hermite.") - @DontObfuscate - HERMITE_STARCAST_6, + @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with hermite.") + @DontObfuscate + HERMITE_STARCAST_6, - @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with hermite.") - @DontObfuscate - HERMITE_STARCAST_9, + @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with hermite.") + @DontObfuscate + HERMITE_STARCAST_9, - @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with hermite.") - @DontObfuscate - HERMITE_STARCAST_12, + @Desc("Uses starcast to break up the abrupt sharp cliffs, then smooths the rest out with hermite.") + @DontObfuscate + HERMITE_STARCAST_12, - @Desc("Uses bilinear but on a bezier curve. See: https://en.wikipedia.org/wiki/Bezier_curve") - @DontObfuscate - BILINEAR_BEZIER, + @Desc("Uses bilinear but on a bezier curve. See: https://en.wikipedia.org/wiki/Bezier_curve") + @DontObfuscate + BILINEAR_BEZIER, - @Desc("Uses Bilinear but with parametric curves alpha 2.") - @DontObfuscate - BILINEAR_PARAMETRIC_2, + @Desc("Uses Bilinear but with parametric curves alpha 2.") + @DontObfuscate + BILINEAR_PARAMETRIC_2, - @Desc("Uses Bilinear but with parametric curves alpha 4.") - @DontObfuscate - BILINEAR_PARAMETRIC_4, + @Desc("Uses Bilinear but with parametric curves alpha 4.") + @DontObfuscate + BILINEAR_PARAMETRIC_4, - @Desc("Uses Bilinear but with parametric curves alpha 1.5.") - @DontObfuscate - BILINEAR_PARAMETRIC_1_5, + @Desc("Uses Bilinear but with parametric curves alpha 1.5.") + @DontObfuscate + BILINEAR_PARAMETRIC_1_5, - @Desc("Bicubic noise creates 4, 4-point splines for a total of 16 checks. Bcubic can go higher than expected and lower than expected right before a large change in slope.") - @DontObfuscate - BICUBIC, + @Desc("Bicubic noise creates 4, 4-point splines for a total of 16 checks. Bcubic can go higher than expected and lower than expected right before a large change in slope.") + @DontObfuscate + BICUBIC, - @Desc("Hermite is similar to bicubic, but faster and it can be tuned a little bit") - @DontObfuscate - HERMITE, + @Desc("Hermite is similar to bicubic, but faster and it can be tuned a little bit") + @DontObfuscate + HERMITE, - @Desc("Essentially bicubic with zero tension") - @DontObfuscate - CATMULL_ROM_SPLINE, + @Desc("Essentially bicubic with zero tension") + @DontObfuscate + CATMULL_ROM_SPLINE, - @Desc("Essentially bicubic with max tension") - @DontObfuscate - HERMITE_TENSE, + @Desc("Essentially bicubic with max tension") + @DontObfuscate + HERMITE_TENSE, - @Desc("Hermite is similar to bicubic, this variant reduces the dimple artifacts of bicubic") - @DontObfuscate - HERMITE_LOOSE, + @Desc("Hermite is similar to bicubic, this variant reduces the dimple artifacts of bicubic") + @DontObfuscate + HERMITE_LOOSE, - @Desc("Hermite is similar to bicubic, this variant reduces the dimple artifacts of bicubic") - @DontObfuscate - HERMITE_LOOSE_HALF_POSITIVE_BIAS, + @Desc("Hermite is similar to bicubic, this variant reduces the dimple artifacts of bicubic") + @DontObfuscate + HERMITE_LOOSE_HALF_POSITIVE_BIAS, - @Desc("Hermite is similar to bicubic, this variant reduces the dimple artifacts of bicubic") - @DontObfuscate - HERMITE_LOOSE_HALF_NEGATIVE_BIAS, + @Desc("Hermite is similar to bicubic, this variant reduces the dimple artifacts of bicubic") + @DontObfuscate + HERMITE_LOOSE_HALF_NEGATIVE_BIAS, - @Desc("Hermite is similar to bicubic, this variant reduces the dimple artifacts of bicubic") - @DontObfuscate - HERMITE_LOOSE_FULL_POSITIVE_BIAS, + @Desc("Hermite is similar to bicubic, this variant reduces the dimple artifacts of bicubic") + @DontObfuscate + HERMITE_LOOSE_FULL_POSITIVE_BIAS, - @Desc("Hermite is similar to bicubic, this variant reduces the dimple artifacts of bicubic") - @DontObfuscate - HERMITE_LOOSE_FULL_NEGATIVE_BIAS, + @Desc("Hermite is similar to bicubic, this variant reduces the dimple artifacts of bicubic") + @DontObfuscate + HERMITE_LOOSE_FULL_NEGATIVE_BIAS, - ; } diff --git a/src/main/java/com/volmit/iris/object/InventorySlotType.java b/src/main/java/com/volmit/iris/object/InventorySlotType.java index 26221b0e3..93b180be2 100644 --- a/src/main/java/com/volmit/iris/object/InventorySlotType.java +++ b/src/main/java/com/volmit/iris/object/InventorySlotType.java @@ -4,25 +4,24 @@ import com.volmit.iris.util.Desc; import com.volmit.iris.util.DontObfuscate; @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.") - @DontObfuscate - STORAGE, +public enum InventorySlotType { + @Desc("Typically the one you want to go with. Storage represnents most slots in inventories.") + @DontObfuscate + STORAGE, - @Desc("Used for the fuel slot in Furnaces, Blast furnaces, smokers etc.") - @DontObfuscate - FUEL, + @Desc("Used for the fuel slot in Furnaces, Blast furnaces, smokers etc.") + @DontObfuscate + FUEL, - @Desc("Used for the cook slot in furnaces") - @DontObfuscate - FURNACE, + @Desc("Used for the cook slot in furnaces") + @DontObfuscate + FURNACE, - @Desc("Used for the cook slot in blast furnaces") - @DontObfuscate - BLAST_FURNACE, + @Desc("Used for the cook slot in blast furnaces") + @DontObfuscate + BLAST_FURNACE, - @Desc("Used for the cook slot in smokers") - @DontObfuscate - SMOKER, + @Desc("Used for the cook slot in smokers") + @DontObfuscate + SMOKER, } diff --git a/src/main/java/com/volmit/iris/object/IrisAttributeModifier.java b/src/main/java/com/volmit/iris/object/IrisAttributeModifier.java index 9fdbd8772..1ab25d8a6 100644 --- a/src/main/java/com/volmit/iris/object/IrisAttributeModifier.java +++ b/src/main/java/com/volmit/iris/object/IrisAttributeModifier.java @@ -1,83 +1,70 @@ package com.volmit.iris.object; +import com.volmit.iris.util.*; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; 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.meta.ItemMeta; -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.MaxNumber; -import com.volmit.iris.util.MinNumber; -import com.volmit.iris.util.RNG; -import com.volmit.iris.util.Required; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; - @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 -{ - @Required - - @DontObfuscate - @Desc("The Attribute type. 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 Attribute attribute = null; +public class IrisAttributeModifier { + @Required - @MinNumber(2) - @Required - - @DontObfuscate - @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 = ""; + @DontObfuscate + @Desc("The Attribute type. 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 Attribute attribute = null; - @DontObfuscate - - @Desc("The application operation (add number is default). 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 Operation operation = Operation.ADD_NUMBER; + @MinNumber(2) + @Required - @DontObfuscate - - @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; + @DontObfuscate + @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 = ""; - - @DontObfuscate - @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; + @DontObfuscate - @MinNumber(0) - @MaxNumber(1) - - @DontObfuscate - @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; + @Desc("The application operation (add number is default). 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 Operation operation = Operation.ADD_NUMBER; - public void apply(RNG rng, ItemMeta meta) - { - if(rng.nextDouble() < getChance()) - { - meta.addAttributeModifier(getAttribute(), new AttributeModifier(getName(), getAmount(rng), getOperation())); - } - } + @DontObfuscate - public void apply(RNG rng, Attributable meta) - { - if(rng.nextDouble() < getChance()) - { - meta.getAttribute(getAttribute()).addModifier(new AttributeModifier(getName(), getAmount(rng), getOperation())); - } - } + @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; - public double getAmount(RNG rng) - { - return rng.d(getMinAmount(), getMaxAmount()); - } + + @DontObfuscate + @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) + + @DontObfuscate + @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()) { + meta.addAttributeModifier(getAttribute(), new AttributeModifier(getName(), getAmount(rng), getOperation())); + } + } + + public void apply(RNG rng, Attributable meta) { + if (rng.nextDouble() < getChance()) { + meta.getAttribute(getAttribute()).addModifier(new AttributeModifier(getName(), getAmount(rng), getOperation())); + } + } + + public double getAmount(RNG rng) { + return rng.d(getMinAmount(), getMaxAmount()); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisAxisRotationClamp.java b/src/main/java/com/volmit/iris/object/IrisAxisRotationClamp.java index 074f729aa..2e94b491d 100644 --- a/src/main/java/com/volmit/iris/object/IrisAxisRotationClamp.java +++ b/src/main/java/com/volmit/iris/object/IrisAxisRotationClamp.java @@ -1,13 +1,6 @@ package com.volmit.iris.object; -import com.volmit.iris.util.DependsOn; -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.M; -import com.volmit.iris.util.MaxNumber; -import com.volmit.iris.util.MinNumber; -import com.volmit.iris.util.Required; - +import com.volmit.iris.util.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -18,77 +11,68 @@ import lombok.experimental.Accessors; @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 -{ - @DontObfuscate - @Desc("Should this axis be rotated at all?") - private boolean enabled = false; +public class IrisAxisRotationClamp { + @DontObfuscate + @Desc("Should this axis be rotated at all?") + private boolean enabled = false; - private transient boolean forceLock = false; + private transient boolean forceLock = false; - @Required - @DependsOn({"max"}) - @MinNumber(-360) - @MaxNumber(360) - @DontObfuscate - @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({"max"}) + @MinNumber(-360) + @MaxNumber(360) + @DontObfuscate + @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) - @DontObfuscate - @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"}) + @MinNumber(-360) + @MaxNumber(360) + @DontObfuscate + @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) - @DontObfuscate - @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; + @Required + @DependsOn({"min", "max"}) + @MinNumber(0) + @MaxNumber(360) + @DontObfuscate + @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 void minMax(double fd) { + min = fd; + max = fd; + forceLock = true; + } - public boolean isUnlimited() - { - return min == max && min == 0; - } + public boolean isUnlimited() { + return min == max && min == 0; + } - public boolean isLocked() - { - return min == max && !isUnlimited(); - } + public boolean isLocked() { + return min == max && !isUnlimited(); + } - public double getRadians(int rng) - { - if(forceLock) - { - return Math.toRadians(max); - } + public double getRadians(int rng) { + if (forceLock) { + return Math.toRadians(max); + } - if(isUnlimited()) - { - if(interval < 1) - { - interval = 1; - } + if (isUnlimited()) { + if (interval < 1) { + interval = 1; + } - return Math.toRadians(((double) interval * (Math.ceil(Math.abs((rng % 360D) / (double) interval)))) % 360D); - } + return Math.toRadians((interval * (Math.ceil(Math.abs((rng % 360D) / interval)))) % 360D); + } - if(min == max && min != 0) - { - return Math.toRadians(max); - } + if (min == max && min != 0) { + return Math.toRadians(max); + } - return Math.toRadians(M.clip(((double) interval * (Math.ceil(Math.abs((rng % 360D) / (double) interval)))) % 360D, Math.min(min, max), Math.max(min, 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/com/volmit/iris/object/IrisBiome.java b/src/main/java/com/volmit/iris/object/IrisBiome.java index 2094a6b19..962f83cc1 100644 --- a/src/main/java/com/volmit/iris/object/IrisBiome.java +++ b/src/main/java/com/volmit/iris/object/IrisBiome.java @@ -1,9 +1,9 @@ package com.volmit.iris.object; import com.volmit.iris.generator.IrisComplex; -import com.volmit.iris.scaffold.cache.AtomicCache; import com.volmit.iris.generator.noise.CNG; import com.volmit.iris.manager.IrisDataManager; +import com.volmit.iris.scaffold.cache.AtomicCache; import com.volmit.iris.scaffold.data.DataProvider; import com.volmit.iris.scaffold.engine.IrisAccess; import com.volmit.iris.util.*; @@ -24,13 +24,12 @@ import java.awt.*; @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 -{ - @MinNumber(2) - @Required - @DontObfuscate - @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 = "A Biome"; +public class IrisBiome extends IrisRegistrant implements IRare { + @MinNumber(2) + @Required + @DontObfuscate + @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 = "A Biome"; /* Needs to be implemented but it's not @DontObfuscate @@ -38,634 +37,547 @@ public class IrisBiome extends IrisRegistrant implements IRare private IrisMaterialPalette fluidPalette = new IrisMaterialPalette().qclear().qadd("void_air"); */ - @DontObfuscate - @Desc("Entity spawns to override or add to this biome. Anytime an entity spawns, it has a chance to be replaced as one of these overrides.") - @ArrayType(min = 1, type = IrisEntitySpawnOverride.class) - private KList entitySpawnOverrides = new KList<>(); - - @DontObfuscate - @Desc("Add random chances for terrain features") - @ArrayType(min = 1, type = IrisFeaturePotential.class) - private KList features = new KList<>(); - - @DontObfuscate - @Desc("Entity spawns during generation") - @ArrayType(min = 1, type = IrisEntityInitialSpawn.class) - private KList entityInitialSpawns = new KList<>(); - - @ArrayType(min = 1, type = IrisEffect.class) - @DontObfuscate - @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<>(); - - @DontObfuscate - @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) - @DontObfuscate - @Desc("Define custom block drops for this biome") - private KList blockDrops = new KList<>(); - - @DontObfuscate - @Desc("Reference loot tables in this area") - private IrisLootReference loot = new IrisLootReference(); - - @MinNumber(0.0001) - @DontObfuscate - @DependsOn({"biomeStyle", "biomeZoom", "biomeScatter"}) - @Desc("This zooms in the biome colors if multiple derivatives are chosen") - private double biomeZoom = 1; - - @DontObfuscate - @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; - - @DontObfuscate - @Desc("The max layers to iterate below the surface for locked layer biomes (mesa).") - private int lockLayersMax = 7; - - @MinNumber(1) - @MaxNumber(512) - @DontObfuscate - @Desc("The rarity of this biome (integer)") - private int rarity = 1; - - @DontObfuscate - @Desc("A color for visualizing this biome with a color. I.e. #F13AF5. This will show up on the map.") - private IrisColor color = null; - - @Required - @DontObfuscate - @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 Biome derivative = Biome.THE_VOID; - - @Required - @DontObfuscate - @Desc("Override the derivative when vanilla places structures to this derivative. This is useful for example if you have an ocean biome, but you have set the derivative to desert to get a brown-ish color. To prevent desert structures from spawning on top of your ocean, you can set your vanillaDerivative to ocean, to allow for vanilla structures. Not defining this value will simply select the derivative.") - private Biome vanillaDerivative = null; - - @ArrayType(min = 1, type = Biome.class) - @DontObfuscate - @Desc("You can instead specify multiple biome derivatives to randomly scatter colors in this biome") - private KList biomeScatter = new KList<>(); - - @ArrayType(min = 1, type = Biome.class) - @DontObfuscate - @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<>(); - - @DontObfuscate - @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; - - @DontObfuscate - @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(); - - @RegistryListBiome - @ArrayType(min = 1, type = String.class) - @DontObfuscate - @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 9 biomes down the tree.") - private KList children = new KList<>(); - - @ArrayType(min = 1, type = IrisJigsawStructurePlacement.class) - @DontObfuscate - @Desc("Jigsaw structures") - private KList jigsawStructures = new KList<>(); - - @RegistryListBiome - @DontObfuscate - @Desc("The carving biome. If specified the biome will be used when under a carving instead of this current biome.") - private String carvingBiome = ""; - - @DontObfuscate - @Desc("The default slab if iris decides to place a slab in this biome. Default is no slab.") - private IrisBiomePaletteLayer slab = new IrisBiomePaletteLayer().zero(); - - @DontObfuscate - @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(min = 1, type = IrisBiomePaletteLayer.class) - @DontObfuscate - @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(min = 1, type = IrisBiomePaletteLayer.class) - @DontObfuscate - @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 seaLayers = new KList(); - - @ArrayType(min = 1, type = IrisDecorator.class) - @DontObfuscate - @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) - @DontObfuscate - @Desc("Objects define what schematics (iob files) iris will place in this biome") - private KList objects = new KList(); - - @Required - @ArrayType(min = 1, type = IrisBiomeGeneratorLink.class) - @DontObfuscate - @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) - @DontObfuscate - @Desc("Define biome deposit generators that add onto the existing regional and global deposit generators") - private KList deposits = new KList<>(); - - private transient InferredType inferredType; - - 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<>(false); - private final transient AtomicCache> carveObjectsCache = new AtomicCache<>(false); - private final transient AtomicCache cacheColor = new AtomicCache<>(true); - private final transient AtomicCache childrenCell = new AtomicCache<>(); - private final transient AtomicCache biomeGenerator = new AtomicCache<>(); - private final transient AtomicCache maxHeight = 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<>(); - - public Biome getVanillaDerivative() - { - return vanillaDerivative == null ? derivative : vanillaDerivative; - } - - public double getGenLinkMax(String loadKey) - { - Integer v = genCacheMax.aquire(() -> - { - KMap l = new KMap<>(); - - for(IrisBiomeGeneratorLink i : getGenerators()) - { - l.put(i.getGenerator(), i.getMax()); - } - - return l; - }).get(loadKey); - - return v == null ? 0 : v; - } - - public double getGenLinkMin(String loadKey) - { - Integer v = genCacheMin.aquire(() -> - { - KMap l = new KMap<>(); - - for(IrisBiomeGeneratorLink i : getGenerators()) - { - l.put(i.getGenerator(), i.getMin()); - } - - return l; - }).get(loadKey); - - return v == null ? 0 : v; - } - - public IrisBiomeGeneratorLink getGenLink(String loadKey) - { - return genCache.aquire(() -> - { - KMap l = new KMap<>(); - - for(IrisBiomeGeneratorLink i : getGenerators()) - { - l.put(i.getGenerator(), i); - } - - return l; - }).get(loadKey); - } - - public IrisBiome getRealCarvingBiome(IrisDataManager 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(IrisAccess 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, 255)); - } - - public CNG getBiomeGenerator(RNG random) - { - return biomeGenerator.aquire(() -> - { - return biomeStyle.create(random.nextParallelRNG(213949 + 228888 + getRarity() + getName().length())); - }); - } - - public CNG getChildrenGenerator(RNG random, int sig, double scale) - { - return childrenCell.aquire(() -> getChildStyle().create(random.nextParallelRNG(sig * 2137)).bake().scale(scale).bake()); - } - - public KList generateLayers(double wx, double wz, RNG random, int maxDepth, int height, IrisDataManager rdata, IrisComplex complex) - { - if(isLockLayers()) - { - return generateLockedLayers(wx, wz, random, maxDepth, height, rdata, complex); - } - - KList data = new KList<>(); - - if(maxDepth <= 0) - { - return data; - } - - for(int i = 0; i < layers.size(); i++) - { - CNG hgen = getLayerHeightGenerators(random, rdata).get(i); - double d = hgen.fit(layers.get(i).getMinHeight(), layers.get(i).getMaxHeight(), wx / layers.get(i).getZoom(), wz / layers.get(i).getZoom()); - - IrisSlopeClip sc = getLayers().get(i).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(getLayers().get(i).get(random.nextParallelRNG(i + j), (wx + j) / layers.get(i).getZoom(), j, (wz - j) / layers.get(i).getZoom(), rdata)); - } - - catch(Throwable e) - { - e.printStackTrace(); - } - } - - if(data.size() >= maxDepth) - { - break; - } - } - - return data; - } - - public KList generateLockedLayers(double wx, double wz, RNG random, int maxDepthf, int height, IrisDataManager rdata, IrisComplex complex) - { - KList data = new KList<>(); - KList real = new KList<>(); - int maxDepth = Math.min(maxDepthf, getLockLayersMax()); - if(maxDepth <= 0) - { - return data; - } - - for(int i = 0; i < layers.size(); i++) - { - CNG hgen = getLayerHeightGenerators(random, rdata).get(i); - double d = hgen.fit(layers.get(i).getMinHeight(), layers.get(i).getMaxHeight(), wx / layers.get(i).getZoom(), wz / layers.get(i).getZoom()); - - IrisSlopeClip sc = getLayers().get(i).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(getLayers().get(i).get(random.nextParallelRNG(i + j), (wx + j) / layers.get(i).getZoom(), j, (wz - j) / layers.get(i).getZoom(), rdata)); - } - - catch(Throwable e) - { - e.printStackTrace(); - } - } - } - - if(data.isEmpty()) - { - return real; - } - - for(int i = 0; i < maxDepth; i++) - { - int offset = (255 - height) - i; - int index = offset % data.size(); - real.add(data.get(index < 0 ? 0 : index)); - } - - return real; - } - - private int getMaxHeight() - { - return maxHeight.aquire(() -> - { - int maxHeight = 0; - - for(IrisBiomeGeneratorLink i : getGenerators()) - { - maxHeight += i.getMax(); - } - - return maxHeight; - }); - } - - public IrisBiome infer(InferredType t, InferredType type) - { - setInferredType(t.equals(InferredType.DEFER) ? type : t); - return this; - } - - public KList generateSeaLayers(double wx, double wz, RNG random, int maxDepth, IrisDataManager rdata) - { - KList data = new KList<>(); - - for(int i = 0; i < seaLayers.size(); i++) - { - CNG hgen = getLayerSeaHeightGenerators(random, rdata).get(i); - int d = hgen.fit(seaLayers.get(i).getMinHeight(), seaLayers.get(i).getMaxHeight(), wx / seaLayers.get(i).getZoom(), wz / seaLayers.get(i).getZoom()); - - if(d < 0) - { - continue; - } - - for(int j = 0; j < d; j++) - { - if(data.size() >= maxDepth) - { - break; - } - - try - { - data.add(getSeaLayers().get(i).get(random.nextParallelRNG(i + j), (wx + j) / seaLayers.get(i).getZoom(), j, (wz - j) / seaLayers.get(i).getZoom(), rdata)); - } - - catch(Throwable e) - { - e.printStackTrace(); - } - } - - if(data.size() >= maxDepth) - { - break; - } - } - - return data; - } - - public KList getLayerHeightGenerators(RNG rng, IrisDataManager rdata) - { - return layerHeightGenerators.aquire(() -> - { - KList layerHeightGenerators = new KList<>(); - - int m = 7235; - - for(IrisBiomePaletteLayer i : getLayers()) - { - layerHeightGenerators.add(i.getHeightGenerator(rng.nextParallelRNG((m++) * m * m * m), rdata)); - } - - return layerHeightGenerators; - }); - } - - public KList getLayerSeaHeightGenerators(RNG rng, IrisDataManager data) - { - return layerSeaHeightGenerators.aquire(() -> - { - KList layerSeaHeightGenerators = new KList<>(); - - int m = 7735; - - for(IrisBiomePaletteLayer i : getSeaLayers()) - { - layerSeaHeightGenerators.add(i.getHeightGenerator(rng.nextParallelRNG((m++) * m * m * m), data)); - } - - return layerSeaHeightGenerators; - }); - } - - 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 isLake() - { - if(inferredType == null) - { - return false; - } - return inferredType.equals(InferredType.LAKE); - } - - public boolean isRiver() - { - if(inferredType == null) - { - return false; - } - return inferredType.equals(InferredType.RIVER); - } - - public boolean isAquatic() - { - return isSea() || isLake() || isRiver(); - } - - public boolean isShore() - { - if(inferredType == null) - { - return false; - } - return inferredType.equals(InferredType.SHORE); - } - - public Biome getSkyBiome(RNG rng, double x, double y, double z) - { - if(biomeSkyScatter.size() == 1) - { - return biomeSkyScatter.get(0); - } - - if(biomeSkyScatter.isEmpty()) - { - return getGroundBiome(rng, x, y, z); - } - - return biomeSkyScatter.get(getBiomeGenerator(rng).fit(0, biomeSkyScatter.size() - 1, 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); - int l = limit; - m.addAll(b.getAllChildren(g, l)); - } - } - - return new KList(m); - } - - public Biome getGroundBiome(RNG rng, double x, double y, double z) - { - if(biomeScatter.isEmpty()) - { - return getDerivative(); - } - - if(biomeScatter.size() == 1) - { - return biomeScatter.get(0); - } - - return getBiomeGenerator(rng).fit(biomeScatter, x, y, z); - } - - public BlockData getSurfaceBlock(int x, int z, RNG rng, IrisDataManager idm) - { - if(getLayers().isEmpty()) - { - return B.get("AIR"); - } - - return getLayers().get(0).get(rng, x, 0, z, idm); - } + @DontObfuscate + @Desc("Entity spawns to override or add to this biome. Anytime an entity spawns, it has a chance to be replaced as one of these overrides.") + @ArrayType(min = 1, type = IrisEntitySpawnOverride.class) + private KList entitySpawnOverrides = new KList<>(); + + @DontObfuscate + @Desc("Add random chances for terrain features") + @ArrayType(min = 1, type = IrisFeaturePotential.class) + private KList features = new KList<>(); + + @DontObfuscate + @Desc("Entity spawns during generation") + @ArrayType(min = 1, type = IrisEntityInitialSpawn.class) + private KList entityInitialSpawns = new KList<>(); + + @ArrayType(min = 1, type = IrisEffect.class) + @DontObfuscate + @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<>(); + + @DontObfuscate + @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) + @DontObfuscate + @Desc("Define custom block drops for this biome") + private KList blockDrops = new KList<>(); + + @DontObfuscate + @Desc("Reference loot tables in this area") + private IrisLootReference loot = new IrisLootReference(); + + @MinNumber(0.0001) + @DontObfuscate + @DependsOn({"biomeStyle", "biomeZoom", "biomeScatter"}) + @Desc("This zooms in the biome colors if multiple derivatives are chosen") + private double biomeZoom = 1; + + @DontObfuscate + @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; + + @DontObfuscate + @Desc("The max layers to iterate below the surface for locked layer biomes (mesa).") + private int lockLayersMax = 7; + + @MinNumber(1) + @MaxNumber(512) + @DontObfuscate + @Desc("The rarity of this biome (integer)") + private int rarity = 1; + + @DontObfuscate + @Desc("A color for visualizing this biome with a color. I.e. #F13AF5. This will show up on the map.") + private IrisColor color = null; + + @Required + @DontObfuscate + @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 Biome derivative = Biome.THE_VOID; + + @Required + @DontObfuscate + @Desc("Override the derivative when vanilla places structures to this derivative. This is useful for example if you have an ocean biome, but you have set the derivative to desert to get a brown-ish color. To prevent desert structures from spawning on top of your ocean, you can set your vanillaDerivative to ocean, to allow for vanilla structures. Not defining this value will simply select the derivative.") + private Biome vanillaDerivative = null; + + @ArrayType(min = 1, type = Biome.class) + @DontObfuscate + @Desc("You can instead specify multiple biome derivatives to randomly scatter colors in this biome") + private KList biomeScatter = new KList<>(); + + @ArrayType(min = 1, type = Biome.class) + @DontObfuscate + @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<>(); + + @DontObfuscate + @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; + + @DontObfuscate + @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(); + + @RegistryListBiome + @ArrayType(min = 1, type = String.class) + @DontObfuscate + @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 9 biomes down the tree.") + private KList children = new KList<>(); + + @ArrayType(min = 1, type = IrisJigsawStructurePlacement.class) + @DontObfuscate + @Desc("Jigsaw structures") + private KList jigsawStructures = new KList<>(); + + @RegistryListBiome + @DontObfuscate + @Desc("The carving biome. If specified the biome will be used when under a carving instead of this current biome.") + private String carvingBiome = ""; + + @DontObfuscate + @Desc("The default slab if iris decides to place a slab in this biome. Default is no slab.") + private IrisBiomePaletteLayer slab = new IrisBiomePaletteLayer().zero(); + + @DontObfuscate + @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(min = 1, type = IrisBiomePaletteLayer.class) + @DontObfuscate + @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(min = 1, type = IrisBiomePaletteLayer.class) + @DontObfuscate + @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 seaLayers = new KList(); + + @ArrayType(min = 1, type = IrisDecorator.class) + @DontObfuscate + @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) + @DontObfuscate + @Desc("Objects define what schematics (iob files) iris will place in this biome") + private KList objects = new KList(); + + @Required + @ArrayType(min = 1, type = IrisBiomeGeneratorLink.class) + @DontObfuscate + @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) + @DontObfuscate + @Desc("Define biome deposit generators that add onto the existing regional and global deposit generators") + private KList deposits = new KList<>(); + + private transient InferredType inferredType; + + 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<>(false); + private final transient AtomicCache> carveObjectsCache = new AtomicCache<>(false); + private final transient AtomicCache cacheColor = new AtomicCache<>(true); + private final transient AtomicCache childrenCell = new AtomicCache<>(); + private final transient AtomicCache biomeGenerator = new AtomicCache<>(); + private final transient AtomicCache maxHeight = 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<>(); + + public Biome getVanillaDerivative() { + return vanillaDerivative == null ? derivative : vanillaDerivative; + } + + public double getGenLinkMax(String loadKey) { + Integer v = genCacheMax.aquire(() -> + { + KMap l = new KMap<>(); + + for (IrisBiomeGeneratorLink i : getGenerators()) { + l.put(i.getGenerator(), i.getMax()); + } + + return l; + }).get(loadKey); + + return v == null ? 0 : v; + } + + public double getGenLinkMin(String loadKey) { + Integer v = genCacheMin.aquire(() -> + { + KMap l = new KMap<>(); + + for (IrisBiomeGeneratorLink i : getGenerators()) { + l.put(i.getGenerator(), i.getMin()); + } + + return l; + }).get(loadKey); + + return v == null ? 0 : v; + } + + public IrisBiomeGeneratorLink getGenLink(String loadKey) { + return genCache.aquire(() -> + { + KMap l = new KMap<>(); + + for (IrisBiomeGeneratorLink i : getGenerators()) { + l.put(i.getGenerator(), i); + } + + return l; + }).get(loadKey); + } + + public IrisBiome getRealCarvingBiome(IrisDataManager 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(IrisAccess 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, 255)); + } + + public CNG getBiomeGenerator(RNG random) { + return biomeGenerator.aquire(() -> + { + return biomeStyle.create(random.nextParallelRNG(213949 + 228888 + getRarity() + getName().length())); + }); + } + + public CNG getChildrenGenerator(RNG random, int sig, double scale) { + return childrenCell.aquire(() -> getChildStyle().create(random.nextParallelRNG(sig * 2137)).bake().scale(scale).bake()); + } + + public KList generateLayers(double wx, double wz, RNG random, int maxDepth, int height, IrisDataManager rdata, IrisComplex complex) { + if (isLockLayers()) { + return generateLockedLayers(wx, wz, random, maxDepth, height, rdata, complex); + } + + KList data = new KList<>(); + + if (maxDepth <= 0) { + return data; + } + + for (int i = 0; i < layers.size(); i++) { + CNG hgen = getLayerHeightGenerators(random, rdata).get(i); + double d = hgen.fit(layers.get(i).getMinHeight(), layers.get(i).getMaxHeight(), wx / layers.get(i).getZoom(), wz / layers.get(i).getZoom()); + + IrisSlopeClip sc = getLayers().get(i).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(getLayers().get(i).get(random.nextParallelRNG(i + j), (wx + j) / layers.get(i).getZoom(), j, (wz - j) / layers.get(i).getZoom(), rdata)); + } catch (Throwable e) { + e.printStackTrace(); + } + } + + if (data.size() >= maxDepth) { + break; + } + } + + return data; + } + + public KList generateLockedLayers(double wx, double wz, RNG random, int maxDepthf, int height, IrisDataManager rdata, IrisComplex complex) { + KList data = new KList<>(); + KList real = new KList<>(); + int maxDepth = Math.min(maxDepthf, getLockLayersMax()); + if (maxDepth <= 0) { + return data; + } + + for (int i = 0; i < layers.size(); i++) { + CNG hgen = getLayerHeightGenerators(random, rdata).get(i); + double d = hgen.fit(layers.get(i).getMinHeight(), layers.get(i).getMaxHeight(), wx / layers.get(i).getZoom(), wz / layers.get(i).getZoom()); + + IrisSlopeClip sc = getLayers().get(i).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(getLayers().get(i).get(random.nextParallelRNG(i + j), (wx + j) / layers.get(i).getZoom(), j, (wz - j) / layers.get(i).getZoom(), rdata)); + } catch (Throwable e) { + e.printStackTrace(); + } + } + } + + if (data.isEmpty()) { + return real; + } + + for (int i = 0; i < maxDepth; i++) { + int offset = (255 - height) - i; + int index = offset % data.size(); + real.add(data.get(index < 0 ? 0 : index)); + } + + return real; + } + + private int getMaxHeight() { + return maxHeight.aquire(() -> + { + int maxHeight = 0; + + for (IrisBiomeGeneratorLink i : getGenerators()) { + maxHeight += i.getMax(); + } + + return maxHeight; + }); + } + + public IrisBiome infer(InferredType t, InferredType type) { + setInferredType(t.equals(InferredType.DEFER) ? type : t); + return this; + } + + public KList generateSeaLayers(double wx, double wz, RNG random, int maxDepth, IrisDataManager rdata) { + KList data = new KList<>(); + + for (int i = 0; i < seaLayers.size(); i++) { + CNG hgen = getLayerSeaHeightGenerators(random, rdata).get(i); + int d = hgen.fit(seaLayers.get(i).getMinHeight(), seaLayers.get(i).getMaxHeight(), wx / seaLayers.get(i).getZoom(), wz / seaLayers.get(i).getZoom()); + + if (d < 0) { + continue; + } + + for (int j = 0; j < d; j++) { + if (data.size() >= maxDepth) { + break; + } + + try { + data.add(getSeaLayers().get(i).get(random.nextParallelRNG(i + j), (wx + j) / seaLayers.get(i).getZoom(), j, (wz - j) / seaLayers.get(i).getZoom(), rdata)); + } catch (Throwable e) { + e.printStackTrace(); + } + } + + if (data.size() >= maxDepth) { + break; + } + } + + return data; + } + + public KList getLayerHeightGenerators(RNG rng, IrisDataManager rdata) { + return layerHeightGenerators.aquire(() -> + { + KList layerHeightGenerators = new KList<>(); + + int m = 7235; + + for (IrisBiomePaletteLayer i : getLayers()) { + layerHeightGenerators.add(i.getHeightGenerator(rng.nextParallelRNG((m++) * m * m * m), rdata)); + } + + return layerHeightGenerators; + }); + } + + public KList getLayerSeaHeightGenerators(RNG rng, IrisDataManager data) { + return layerSeaHeightGenerators.aquire(() -> + { + KList layerSeaHeightGenerators = new KList<>(); + + int m = 7735; + + for (IrisBiomePaletteLayer i : getSeaLayers()) { + layerSeaHeightGenerators.add(i.getHeightGenerator(rng.nextParallelRNG((m++) * m * m * m), data)); + } + + return layerSeaHeightGenerators; + }); + } + + 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 isLake() { + if (inferredType == null) { + return false; + } + return inferredType.equals(InferredType.LAKE); + } + + public boolean isRiver() { + if (inferredType == null) { + return false; + } + return inferredType.equals(InferredType.RIVER); + } + + public boolean isAquatic() { + return isSea() || isLake() || isRiver(); + } + + public boolean isShore() { + if (inferredType == null) { + return false; + } + return inferredType.equals(InferredType.SHORE); + } + + public Biome getSkyBiome(RNG rng, double x, double y, double z) { + if (biomeSkyScatter.size() == 1) { + return biomeSkyScatter.get(0); + } + + if (biomeSkyScatter.isEmpty()) { + return getGroundBiome(rng, x, y, z); + } + + return biomeSkyScatter.get(getBiomeGenerator(rng).fit(0, biomeSkyScatter.size() - 1, 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); + int l = limit; + m.addAll(b.getAllChildren(g, l)); + } + } + + return new KList(m); + } + + public Biome getGroundBiome(RNG rng, double x, double y, double z) { + if (biomeScatter.isEmpty()) { + return getDerivative(); + } + + if (biomeScatter.size() == 1) { + return biomeScatter.get(0); + } + + return getBiomeGenerator(rng).fit(biomeScatter, x, y, z); + } + + public BlockData getSurfaceBlock(int x, int z, RNG rng, IrisDataManager idm) { + if (getLayers().isEmpty()) { + return B.get("AIR"); + } + + return getLayers().get(0).get(rng, x, 0, z, idm); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisBiomeGeneratorLink.java b/src/main/java/com/volmit/iris/object/IrisBiomeGeneratorLink.java index 35fb81e29..eda606f21 100644 --- a/src/main/java/com/volmit/iris/object/IrisBiomeGeneratorLink.java +++ b/src/main/java/com/volmit/iris/object/IrisBiomeGeneratorLink.java @@ -13,53 +13,49 @@ import lombok.experimental.Accessors; @AllArgsConstructor @Desc("This represents a link to a generator for a biome") @Data -public class IrisBiomeGeneratorLink -{ +public class IrisBiomeGeneratorLink { - @RegistryListGenerator - @DontObfuscate - @Desc("The generator id") - private String generator = "default"; + @RegistryListGenerator + @DontObfuscate + @Desc("The generator id") + private String generator = "default"; - @DependsOn({"min", "max"}) - @Required - @MinNumber(-256) // TODO: WARNING HEIGHT - @MaxNumber(256) // TODO: WARNING HEIGHT - @DontObfuscate - @Desc("The min block value (value + fluidHeight)") - private int min = 0; + @DependsOn({"min", "max"}) + @Required + @MinNumber(-256) // TODO: WARNING HEIGHT + @MaxNumber(256) // TODO: WARNING HEIGHT + @DontObfuscate + @Desc("The min block value (value + fluidHeight)") + private int min = 0; - @DependsOn({"min", "max"}) - @Required - @MinNumber(-256) // TODO: WARNING HEIGHT - @MaxNumber(256) // TODO: WARNING HEIGHT - @DontObfuscate - @Desc("The max block value (value + fluidHeight)") - private int max = 0; + @DependsOn({"min", "max"}) + @Required + @MinNumber(-256) // TODO: WARNING HEIGHT + @MaxNumber(256) // TODO: WARNING HEIGHT + @DontObfuscate + @Desc("The max block value (value + fluidHeight)") + private int max = 0; - private final transient AtomicCache gen = new AtomicCache<>(); + private final transient AtomicCache gen = new AtomicCache<>(); - public IrisGenerator getCachedGenerator(DataProvider g) - { - return gen.aquire(() -> - { - IrisGenerator gen = g.getData().getGeneratorLoader().load(getGenerator()); + public IrisGenerator getCachedGenerator(DataProvider g) { + return gen.aquire(() -> + { + IrisGenerator gen = g.getData().getGeneratorLoader().load(getGenerator()); - if(gen == null) - { - gen = new IrisGenerator(); - } + if (gen == null) { + gen = new IrisGenerator(); + } - return gen; - }); - } + 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; + 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); - } + return IrisInterpolation.lerp(min, max, g); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisBiomeMutation.java b/src/main/java/com/volmit/iris/object/IrisBiomeMutation.java index 11d54eb2a..211f5de6a 100644 --- a/src/main/java/com/volmit/iris/object/IrisBiomeMutation.java +++ b/src/main/java/com/volmit/iris/object/IrisBiomeMutation.java @@ -1,18 +1,8 @@ package com.volmit.iris.object; import com.volmit.iris.scaffold.cache.AtomicCache; -import com.volmit.iris.util.ArrayType; -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.KList; -import com.volmit.iris.util.KSet; -import com.volmit.iris.util.MaxNumber; -import com.volmit.iris.util.MinNumber; -import com.volmit.iris.util.RegistryListBiome; -import com.volmit.iris.util.RegistryListObject; -import com.volmit.iris.util.Required; - import com.volmit.iris.scaffold.data.DataProvider; +import com.volmit.iris.util.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -23,93 +13,75 @@ import lombok.experimental.Accessors; @AllArgsConstructor @Desc("A biome mutation if a condition is met") @Data -public class IrisBiomeMutation -{ +public class IrisBiomeMutation { - @RegistryListBiome - @Required - @ArrayType(min = 1, type = String.class) - @DontObfuscate - @Desc("One of The following biomes or regions must show up") - private KList sideA = new KList<>(); + @RegistryListBiome + @Required + @ArrayType(min = 1, type = String.class) + @DontObfuscate + @Desc("One of The following biomes or regions must show up") + private KList sideA = new KList<>(); - @RegistryListBiome - @Required - @ArrayType(min = 1, type = String.class) - @DontObfuscate - @Desc("One of The following biomes or regions must show up") - private KList sideB = new KList<>(); + @RegistryListBiome + @Required + @ArrayType(min = 1, type = String.class) + @DontObfuscate + @Desc("One of The following biomes or regions must show up") + private KList sideB = new KList<>(); - @Required - @MinNumber(1) - @MaxNumber(1024) - @DontObfuscate - @Desc("The scan radius for placing this mutator") - private int radius = 16; + @Required + @MinNumber(1) + @MaxNumber(1024) + @DontObfuscate + @Desc("The scan radius for placing this mutator") + private int radius = 16; - @Required - @MinNumber(1) - @MaxNumber(32) - @DontObfuscate - @Desc("How many tries per chunk to check for this mutation") - private int checks = 2; + @Required + @MinNumber(1) + @MaxNumber(32) + @DontObfuscate + @Desc("How many tries per chunk to check for this mutation") + private int checks = 2; - @RegistryListObject - @ArrayType(min = 1, type = IrisObjectPlacement.class) - @DontObfuscate - @Desc("Objects define what schematics (iob files) iris will place in this biome mutation") - private KList objects = new KList(); + @RegistryListObject + @ArrayType(min = 1, type = IrisObjectPlacement.class) + @DontObfuscate + @Desc("Objects define what schematics (iob files) iris will place in this biome mutation") + private KList objects = new KList(); - private final transient AtomicCache> sideACache = new AtomicCache<>(); - private final transient AtomicCache> sideBCache = new AtomicCache<>(); + private final transient AtomicCache> sideACache = new AtomicCache<>(); + private final transient AtomicCache> sideBCache = new AtomicCache<>(); - public KList getRealSideA(DataProvider xg) - { - return sideACache.aquire(() -> processList(xg, getSideA())); - } + public KList getRealSideA(DataProvider xg) { + return sideACache.aquire(() -> processList(xg, getSideA())); + } - public KList getRealSideB(DataProvider xg) - { - return sideBCache.aquire(() -> processList(xg, getSideB())); - } + public KList getRealSideB(DataProvider xg) { + return sideBCache.aquire(() -> processList(xg, getSideB())); + } - public KList processList(DataProvider xg, KList s) - { - KSet r = new KSet<>(); + public KList processList(DataProvider xg, KList s) { + KSet r = new KSet<>(); - for(String i : s) - { - String q = i; + for (String i : s) { + String q = i; - if(q.startsWith("^")) - { - r.addAll(xg.getData().getRegionLoader().load(q.substring(1)).getLandBiomes()); - continue; - } + if (q.startsWith("^")) { + r.addAll(xg.getData().getRegionLoader().load(q.substring(1)).getLandBiomes()); + continue; + } else if (q.startsWith("*")) { + String name = q.substring(1); + r.addAll(xg.getData().getBiomeLoader().load(name).getAllChildren(xg, 7)); + } else if (q.startsWith("!")) { + r.remove(q.substring(1)); + } else if (q.startsWith("!*")) { + String name = q.substring(2); + r.removeAll(xg.getData().getBiomeLoader().load(name).getAllChildren(xg, 7)); + } else { + r.add(q); + } + } - else if(q.startsWith("*")) - { - String name = q.substring(1); - r.addAll(xg.getData().getBiomeLoader().load(name).getAllChildren(xg, 7)); - } - - else if(q.startsWith("!")) - { - r.remove(q.substring(1)); - } - - else if(q.startsWith("!*")) - { - String name = q.substring(2); - r.removeAll(xg.getData().getBiomeLoader().load(name).getAllChildren(xg, 7)); - } - - else - { - r.add(q); - } - } - - return new KList(r); - } + return new KList(r); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisBiomePaletteLayer.java b/src/main/java/com/volmit/iris/object/IrisBiomePaletteLayer.java index 563d50176..8a61e269a 100644 --- a/src/main/java/com/volmit/iris/object/IrisBiomePaletteLayer.java +++ b/src/main/java/com/volmit/iris/object/IrisBiomePaletteLayer.java @@ -1,18 +1,9 @@ package com.volmit.iris.object; -import com.volmit.iris.scaffold.cache.AtomicCache; -import com.volmit.iris.manager.IrisDataManager; import com.volmit.iris.generator.noise.CNG; -import com.volmit.iris.util.ArrayType; -import com.volmit.iris.util.DependsOn; -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.KList; -import com.volmit.iris.util.MaxNumber; -import com.volmit.iris.util.MinNumber; -import com.volmit.iris.util.RNG; -import com.volmit.iris.util.Required; - +import com.volmit.iris.manager.IrisDataManager; +import com.volmit.iris.scaffold.cache.AtomicCache; +import com.volmit.iris.util.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -24,105 +15,93 @@ import org.bukkit.block.data.BlockData; @AllArgsConstructor @Desc("A layer of surface / subsurface material in biomes") @Data -public class IrisBiomePaletteLayer -{ - @DontObfuscate - @Desc("The style of noise") - private IrisGeneratorStyle style = NoiseStyle.STATIC.style(); +public class IrisBiomePaletteLayer { + @DontObfuscate + @Desc("The style of noise") + private IrisGeneratorStyle style = NoiseStyle.STATIC.style(); - @DependsOn({"minHeight", "maxHeight"}) - @MinNumber(0) - @MaxNumber(256) // TODO: WARNING HEIGHT - @DontObfuscate - @Desc("The min thickness of this layer") - private int minHeight = 1; + @DependsOn({"minHeight", "maxHeight"}) + @MinNumber(0) + @MaxNumber(256) // TODO: WARNING HEIGHT + @DontObfuscate + @Desc("The min thickness of this layer") + private int minHeight = 1; - @DependsOn({"minHeight", "maxHeight"}) - @MinNumber(1) - @MaxNumber(256) // TODO: WARNING HEIGHT - @DontObfuscate - @Desc("The max thickness of this layer") - private int maxHeight = 1; + @DependsOn({"minHeight", "maxHeight"}) + @MinNumber(1) + @MaxNumber(256) // TODO: WARNING HEIGHT + @DontObfuscate + @Desc("The max thickness of this layer") + private int maxHeight = 1; - @DontObfuscate - @Desc("If set, this layer will change size depending on the slope. If in bounds, the layer will get larger (taller) the closer to the center of this slope clip it is. If outside of the slipe's bounds, this layer will not show.") - private IrisSlopeClip slopeCondition = new IrisSlopeClip(); + @DontObfuscate + @Desc("If set, this layer will change size depending on the slope. If in bounds, the layer will get larger (taller) the closer to the center of this slope clip it is. If outside of the slipe's bounds, this layer will not show.") + private IrisSlopeClip slopeCondition = new IrisSlopeClip(); - @MinNumber(0.0001) - @DontObfuscate - @Desc("The terrain zoom mostly for zooming in on a wispy palette") - private double zoom = 5; + @MinNumber(0.0001) + @DontObfuscate + @Desc("The terrain zoom mostly for zooming in on a wispy palette") + private double zoom = 5; - @Required - @ArrayType(min = 1, type = IrisBlockData.class) - @DontObfuscate - @Desc("The palette of blocks to be used in this layer") - private KList palette = new KList().qadd(new IrisBlockData("GRASS_BLOCK")); + @Required + @ArrayType(min = 1, type = IrisBlockData.class) + @DontObfuscate + @Desc("The palette of blocks to be used in this layer") + private KList palette = new KList().qadd(new IrisBlockData("GRASS_BLOCK")); - private final transient AtomicCache> blockData = new AtomicCache<>(); - private final transient AtomicCache layerGenerator = new AtomicCache<>(); - private final transient AtomicCache heightGenerator = new AtomicCache<>(); + private final transient AtomicCache> blockData = new AtomicCache<>(); + private final transient AtomicCache layerGenerator = new AtomicCache<>(); + private final transient AtomicCache heightGenerator = new AtomicCache<>(); - public CNG getHeightGenerator(RNG rng, IrisDataManager data) - { - return heightGenerator.aquire(() -> CNG.signature(rng.nextParallelRNG(minHeight * maxHeight + getBlockData(data).size()))); - } + public CNG getHeightGenerator(RNG rng, IrisDataManager data) { + return heightGenerator.aquire(() -> CNG.signature(rng.nextParallelRNG(minHeight * maxHeight + getBlockData(data).size()))); + } - public BlockData get(RNG rng, double x, double y, double z, IrisDataManager data) - { - if(getBlockData(data).isEmpty()) - { - return null; - } + public BlockData get(RNG rng, double x, double y, double z, IrisDataManager data) { + if (getBlockData(data).isEmpty()) { + return null; + } - if(getBlockData(data).size() == 1) - { - return getBlockData(data).get(0); - } + if (getBlockData(data).size() == 1) { + return getBlockData(data).get(0); + } - return getLayerGenerator(rng, data).fit(getBlockData(data), x / zoom, y / zoom, z / zoom); - } + return getLayerGenerator(rng, data).fit(getBlockData(data), x / zoom, y / zoom, z / zoom); + } - public CNG getLayerGenerator(RNG rng, IrisDataManager data) - { - return layerGenerator.aquire(() -> - { - RNG rngx = rng.nextParallelRNG(minHeight + maxHeight + getBlockData(data).size()); - return style.create(rngx); - }); - } + public CNG getLayerGenerator(RNG rng, IrisDataManager data) { + return layerGenerator.aquire(() -> + { + RNG rngx = rng.nextParallelRNG(minHeight + maxHeight + getBlockData(data).size()); + return style.create(rngx); + }); + } - public KList add(String b) - { - palette.add(new IrisBlockData(b)); + public KList add(String b) { + palette.add(new IrisBlockData(b)); - return palette; - } + return palette; + } - public KList getBlockData(IrisDataManager data) - { - return blockData.aquire(() -> - { - KList blockData = new KList<>(); - for(IrisBlockData ix : palette) - { - BlockData bx = ix.getBlockData(data); - if(bx != null) - { - for(int i = 0; i < ix.getWeight(); i++) - { - blockData.add(bx); - } - } - } + public KList getBlockData(IrisDataManager data) { + return blockData.aquire(() -> + { + KList blockData = new KList<>(); + for (IrisBlockData ix : palette) { + BlockData bx = ix.getBlockData(data); + if (bx != null) { + for (int i = 0; i < ix.getWeight(); i++) { + blockData.add(bx); + } + } + } - return blockData; - }); - } + return blockData; + }); + } - public IrisBiomePaletteLayer zero() - { - palette.clear(); - return this; - } + public IrisBiomePaletteLayer zero() { + palette.clear(); + return this; + } } diff --git a/src/main/java/com/volmit/iris/object/IrisBlockData.java b/src/main/java/com/volmit/iris/object/IrisBlockData.java index 4aae16cb1..08c136705 100644 --- a/src/main/java/com/volmit/iris/object/IrisBlockData.java +++ b/src/main/java/com/volmit/iris/object/IrisBlockData.java @@ -1,18 +1,9 @@ package com.volmit.iris.object; import com.volmit.iris.Iris; -import com.volmit.iris.scaffold.cache.AtomicCache; import com.volmit.iris.manager.IrisDataManager; -import com.volmit.iris.util.B; -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.KList; -import com.volmit.iris.util.KMap; -import com.volmit.iris.util.MaxNumber; -import com.volmit.iris.util.MinNumber; -import com.volmit.iris.util.RegistryListBlockType; -import com.volmit.iris.util.Required; - +import com.volmit.iris.scaffold.cache.AtomicCache; +import com.volmit.iris.util.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; @@ -26,218 +17,176 @@ import org.bukkit.block.data.BlockData; @Desc("Represents Block Data") @Data @EqualsAndHashCode(callSuper = false) -public class IrisBlockData extends IrisRegistrant -{ - @RegistryListBlockType - @Required - @DontObfuscate - @Desc("The block to use") - private String block = "air"; +public class IrisBlockData extends IrisRegistrant { + @RegistryListBlockType + @Required + @DontObfuscate + @Desc("The block to use") + private String block = "air"; - @Desc("Debug this block by printing it to the console when it's used") - @DontObfuscate - private boolean debug = false; + @Desc("Debug this block by printing it to the console when it's used") + @DontObfuscate + private boolean debug = false; - @DontObfuscate - @Desc("The resource key. Typically Minecraft") - private String key = "minecraft"; + @DontObfuscate + @Desc("The resource key. Typically Minecraft") + private String key = "minecraft"; - @MinNumber(1) - @MaxNumber(1000) - @DontObfuscate - @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; + @MinNumber(1) + @MaxNumber(1000) + @DontObfuscate + @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; - @DontObfuscate - @Desc("If the block cannot be created on this version, Iris will attempt to use this backup block data instead.") - private IrisBlockData backup = null; + @DontObfuscate + @Desc("If the block cannot be created on this version, Iris will attempt to use this backup block data instead.") + private IrisBlockData backup = null; - @DontObfuscate - @Desc("Optional properties for this block data such as 'waterlogged': true") - private KMap data = new KMap<>(); + @DontObfuscate + @Desc("Optional properties for this block data such as 'waterlogged': true") + private KMap data = new KMap<>(); - private final transient AtomicCache blockdata = new AtomicCache<>(); - private final transient AtomicCache realProperties = new AtomicCache<>(); + private final transient AtomicCache blockdata = new AtomicCache<>(); + private final transient AtomicCache realProperties = new AtomicCache<>(); - public IrisBlockData(String b) - { - this.block = b; - } + public IrisBlockData(String b) { + this.block = b; + } - public String computeProperties(KMap data) - { - if(data.isEmpty()) - { - return ""; - } + public String computeProperties(KMap data) { + if (data.isEmpty()) { + return ""; + } - KList r = new KList<>(); + KList r = new KList<>(); - for(String i : data.keySet()) - { - r.add(i + "=" + filter(data.get(i).toString())); - } + for (String i : data.keySet()) { + r.add(i + "=" + filter(data.get(i).toString())); + } - return "[" + r.toString(",") + "]"; - } + return "[" + r.toString(",") + "]"; + } - public String computeProperties() - { - return computeProperties(getData()); - } + public String computeProperties() { + return computeProperties(getData()); + } - public BlockData getBlockData(IrisDataManager data) - { - return blockdata.aquire(() -> - { - BlockData b = null; + public BlockData getBlockData(IrisDataManager data) { + return blockdata.aquire(() -> + { + BlockData b = null; - IrisBlockData customData = data.getBlockLoader().load(getBlock(), false); + IrisBlockData customData = data.getBlockLoader().load(getBlock(), false); - if(customData != null) - { - b = customData.getBlockData(data); + if (customData != null) { + b = customData.getBlockData(data); - if(b != null) - { - b = b.clone(); + if (b != null) { + b = b.clone(); - String st = b.getAsString(true); + String st = b.getAsString(true); - if(st.contains("[")) - { - st = st.split("\\Q[\\E")[0]; - } + if (st.contains("[")) { + st = st.split("\\Q[\\E")[0]; + } - KMap cdata = customData.getData().copy(); + KMap cdata = customData.getData().copy(); - for(String i : getData().keySet()) - { - cdata.put(i, getData().get(i)); - } + for (String i : getData().keySet()) { + cdata.put(i, getData().get(i)); + } - String sx = getKey() + ":" + st.split("\\Q:\\E")[1] + computeProperties(cdata); + String sx = getKey() + ":" + st.split("\\Q:\\E")[1] + computeProperties(cdata); - if(debug) - { - Iris.warn("Debug block data " + sx + " (CUSTOM)"); - } + if (debug) { + Iris.warn("Debug block data " + sx + " (CUSTOM)"); + } - BlockData bx = B.get(sx); + BlockData bx = B.get(sx); - if(bx != null) - { - return bx; - } + if (bx != null) { + return bx; + } - if(b != null) - { - return b; - } - } - } + if (b != null) { + return b; + } + } + } - String ss = getKey() + ":" + getBlock() + computeProperties(); - b = B.get(ss); + String ss = getKey() + ":" + getBlock() + computeProperties(); + b = B.get(ss); - if(debug) - { - Iris.warn("Debug block data " + ss); - } + if (debug) { + Iris.warn("Debug block data " + ss); + } - if(b != null) - { - return b; - } + if (b != null) { + return b; + } - if(backup != null) - { - return backup.getBlockData(data); - } + if (backup != null) { + return backup.getBlockData(data); + } - return B.get("AIR"); - }); - } + return B.get("AIR"); + }); + } - public static IrisBlockData from(String j) - { - IrisBlockData b = new IrisBlockData(); - String m = j.toLowerCase().trim(); + public static IrisBlockData from(String j) { + IrisBlockData b = new IrisBlockData(); + String m = j.toLowerCase().trim(); - if(m.contains(":")) - { - b.setKey(m.split("\\Q:\\E")[0]); - String v = m.split("\\Q:\\E")[1]; + if (m.contains(":")) { + b.setKey(m.split("\\Q:\\E")[0]); + String v = m.split("\\Q:\\E")[1]; - 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 (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")); - } + if (rp.contains(",")) { + props.add(rp.split("\\Q,\\E")); + } else { + props.add(rp); + } - 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); + } + } else { + b.setBlock(m); + } - for(String i : props) - { - Object kg = filter(i.split("\\Q=\\E")[1]); - b.data.put(i.split("\\Q=\\E")[0], kg); - } - } + return b; + } - else - { - b.setBlock(v); - } - } + private static Object filter(String string) { + if (string.equals("true")) { + return true; + } - else - { - b.setBlock(m); - } + if (string.equals("false")) { + return false; + } - return b; - } + try { + return Integer.valueOf(string); + } catch (Throwable e) { - private static Object filter(String string) - { - if(string.equals("true")) - { - return true; - } + } - if(string.equals("false")) - { - return false; - } + try { + return Double.valueOf(string).intValue(); + } catch (Throwable e) { - try - { - return Integer.valueOf(string); - } + } - catch(Throwable e) - { - - } - - try - { - return Double.valueOf(string).intValue(); - } - - catch(Throwable e) - { - - } - - return string; - } + return string; + } } diff --git a/src/main/java/com/volmit/iris/object/IrisBlockDrops.java b/src/main/java/com/volmit/iris/object/IrisBlockDrops.java index a6b6b4c3d..9f8edc7dd 100644 --- a/src/main/java/com/volmit/iris/object/IrisBlockDrops.java +++ b/src/main/java/com/volmit/iris/object/IrisBlockDrops.java @@ -1,91 +1,75 @@ package com.volmit.iris.object; -import org.bukkit.block.data.BlockData; -import org.bukkit.inventory.ItemStack; - -import com.volmit.iris.scaffold.cache.AtomicCache; import com.volmit.iris.manager.IrisDataManager; -import com.volmit.iris.util.ArrayType; -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.KList; -import com.volmit.iris.util.RNG; -import com.volmit.iris.util.Required; - +import com.volmit.iris.scaffold.cache.AtomicCache; +import com.volmit.iris.util.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; +import org.bukkit.block.data.BlockData; +import org.bukkit.inventory.ItemStack; @Accessors(chain = true) @NoArgsConstructor @AllArgsConstructor @Desc("Represents a block drop list") @Data -public class IrisBlockDrops -{ - @Required - @ArrayType(min = 1, type = IrisBlockData.class) - @Desc("The blocks that drop loot") - private KList blocks = new KList(); +public class IrisBlockDrops { + @Required + @ArrayType(min = 1, type = IrisBlockData.class) + @Desc("The blocks that drop loot") + private KList blocks = new KList(); - @DontObfuscate - @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; + @DontObfuscate + @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; - @DontObfuscate - @Desc("Add in specific items to drop") - @ArrayType(min = 1, type = IrisLoot.class) - private KList drops = new KList<>(); + @DontObfuscate + @Desc("Add in specific items to drop") + @ArrayType(min = 1, type = IrisLoot.class) + private KList drops = new KList<>(); - @DontObfuscate - @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; + @DontObfuscate + @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; - @DontObfuscate - @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; + @DontObfuscate + @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; - private final transient AtomicCache> data = new AtomicCache<>(); + private final transient AtomicCache> data = new AtomicCache<>(); - public boolean shouldDropFor(BlockData data, IrisDataManager rdata) - { - KList list = this.data.aquire(() -> - { - KList b = new KList<>(); + public boolean shouldDropFor(BlockData data, IrisDataManager rdata) { + KList list = this.data.aquire(() -> + { + KList b = new KList<>(); - for(IrisBlockData i : getBlocks()) - { - BlockData dd = i.getBlockData(rdata); + for (IrisBlockData i : getBlocks()) { + BlockData dd = i.getBlockData(rdata); - if(dd != null) - { - b.add(dd); - } - } + if (dd != null) { + b.add(dd); + } + } - return b.removeDuplicates(); - }); + return b.removeDuplicates(); + }); - for(BlockData i : list) - { - if(exactBlocks ? i.equals(data) : i.getMaterial().equals(data.getMaterial())) - { - return true; - } - } + for (BlockData i : list) { + if (exactBlocks ? i.equals(data) : i.getMaterial().equals(data.getMaterial())) { + return true; + } + } - return false; - } + return false; + } - public void fillDrops(boolean debug, KList d) - { - for(IrisLoot i : getDrops()) - { - if(RNG.r.i(1, i.getRarity()) == i.getRarity()) - { - d.add(i.get(debug, RNG.r)); - } - } - } + public void fillDrops(boolean debug, KList d) { + for (IrisLoot i : getDrops()) { + if (RNG.r.i(1, i.getRarity()) == i.getRarity()) { + d.add(i.get(debug, RNG.r)); + } + } + } } diff --git a/src/main/java/com/volmit/iris/object/IrisCarveLayer.java b/src/main/java/com/volmit/iris/object/IrisCarveLayer.java index f97cdb9d2..b03e524e8 100644 --- a/src/main/java/com/volmit/iris/object/IrisCarveLayer.java +++ b/src/main/java/com/volmit/iris/object/IrisCarveLayer.java @@ -1,16 +1,8 @@ package com.volmit.iris.object; -import com.volmit.iris.scaffold.cache.AtomicCache; import com.volmit.iris.generator.noise.CNG; -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.IrisInterpolation; -import com.volmit.iris.util.M; -import com.volmit.iris.util.MaxNumber; -import com.volmit.iris.util.MinNumber; -import com.volmit.iris.util.RNG; -import com.volmit.iris.util.Required; - +import com.volmit.iris.scaffold.cache.AtomicCache; +import com.volmit.iris.util.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -21,70 +13,61 @@ import lombok.experimental.Accessors; @AllArgsConstructor @Desc("Translate objects") @Data -public class IrisCarveLayer -{ - @Required - @DontObfuscate - @Desc("The 4d slope this carve layer follows") - private IrisGeneratorStyle style = new IrisGeneratorStyle(); +public class IrisCarveLayer { + @Required + @DontObfuscate + @Desc("The 4d slope this carve layer follows") + private IrisGeneratorStyle style = new IrisGeneratorStyle(); - @MaxNumber(512) - @MinNumber(-128) - @DontObfuscate - @Desc("The max height") - private int maxHeight = 220; + @MaxNumber(512) + @MinNumber(-128) + @DontObfuscate + @Desc("The max height") + private int maxHeight = 220; - @MinNumber(0.0) - @MaxNumber(1.0) - @DontObfuscate - @Desc("The full percentage means the 4D opacity of this carver will decay from 100% to 0% at the min & max vertical ranges. Setting the percent to 1.0 will make a very drastic & charp change at the edge of the vertical min & max. Where as 0.15 means only 15% of the vertical range will actually be 100% opacity.") - private double fullPercent = 0.5; + @MinNumber(0.0) + @MaxNumber(1.0) + @DontObfuscate + @Desc("The full percentage means the 4D opacity of this carver will decay from 100% to 0% at the min & max vertical ranges. Setting the percent to 1.0 will make a very drastic & charp change at the edge of the vertical min & max. Where as 0.15 means only 15% of the vertical range will actually be 100% opacity.") + private double fullPercent = 0.5; - @MaxNumber(512) - @MinNumber(-128) - @DontObfuscate - @Desc("The min height") - private int minHeight = 147; + @MaxNumber(512) + @MinNumber(-128) + @DontObfuscate + @Desc("The min height") + private int minHeight = 147; - @MaxNumber(1) - @MinNumber(0) - @DontObfuscate - @Desc("The threshold used as: \n\ncarved = noise(x,y,z) > threshold") - private double threshold = 0.5; + @MaxNumber(1) + @MinNumber(0) + @DontObfuscate + @Desc("The threshold used as: \n\ncarved = noise(x,y,z) > threshold") + private double threshold = 0.5; - private final transient AtomicCache cng = new AtomicCache<>(); + private final transient AtomicCache cng = new AtomicCache<>(); - public boolean isCarved(RNG rng, double x, double y, double z) - { - if(y > getMaxHeight() || y < getMinHeight()) - { - return false; - } + public boolean isCarved(RNG rng, double x, double y, double z) { + if (y > getMaxHeight() || y < getMinHeight()) { + return false; + } - double opacity = Math.pow(IrisInterpolation.sinCenter(M.lerpInverse(getMinHeight(), getMaxHeight(), y)), 4); - return cng.aquire(() -> getStyle().create(rng.nextParallelRNG(-2340 * getMaxHeight() * getMinHeight()))).fitDouble(0D, 1D, x, y, z) * opacity > getThreshold(); - } + double opacity = Math.pow(IrisInterpolation.sinCenter(M.lerpInverse(getMinHeight(), getMaxHeight(), y)), 4); + return cng.aquire(() -> getStyle().create(rng.nextParallelRNG(-2340 * getMaxHeight() * getMinHeight()))).fitDouble(0D, 1D, x, y, z) * opacity > getThreshold(); + } - public boolean isCarved2(RNG rng, double x, double y, double z) - { - if(y > getMaxHeight() || y < getMinHeight()) - { - return false; - } + public boolean isCarved2(RNG rng, double x, double y, double z) { + if (y > getMaxHeight() || y < getMinHeight()) { + return false; + } - double innerRange = fullPercent * (maxHeight - minHeight); - double opacity = 1D; + double innerRange = fullPercent * (maxHeight - minHeight); + double opacity = 1D; - if(y <= minHeight+innerRange) - { - opacity = IrisInterpolation.bezier(M.lerpInverse(getMinHeight(), minHeight+innerRange, y)); - } + if (y <= minHeight + innerRange) { + opacity = IrisInterpolation.bezier(M.lerpInverse(getMinHeight(), minHeight + innerRange, y)); + } else if (y >= maxHeight - innerRange) { + opacity = IrisInterpolation.bezier(1D - M.lerpInverse(maxHeight - innerRange, getMaxHeight(), y)); + } - else if(y >=maxHeight - innerRange) - { - opacity = IrisInterpolation.bezier(1D - M.lerpInverse(maxHeight-innerRange, getMaxHeight(), y)); - } - - return cng.aquire(() -> getStyle().create(rng.nextParallelRNG(-2340 * getMaxHeight() * getMinHeight()))).fitDouble(0D, 1D, x, y, z) * opacity > getThreshold(); - } + return cng.aquire(() -> getStyle().create(rng.nextParallelRNG(-2340 * getMaxHeight() * getMinHeight()))).fitDouble(0D, 1D, x, y, z) * opacity > getThreshold(); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisCaveFluid.java b/src/main/java/com/volmit/iris/object/IrisCaveFluid.java index e955b4ea0..24c670cb6 100644 --- a/src/main/java/com/volmit/iris/object/IrisCaveFluid.java +++ b/src/main/java/com/volmit/iris/object/IrisCaveFluid.java @@ -1,14 +1,8 @@ package com.volmit.iris.object; -import com.volmit.iris.scaffold.cache.AtomicCache; import com.volmit.iris.manager.IrisDataManager; -import com.volmit.iris.util.B; -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.MaxNumber; -import com.volmit.iris.util.MinNumber; -import com.volmit.iris.util.Required; - +import com.volmit.iris.scaffold.cache.AtomicCache; +import com.volmit.iris.util.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -20,43 +14,39 @@ import org.bukkit.block.data.BlockData; @AllArgsConstructor @Desc("Translate objects") @Data -public class IrisCaveFluid -{ - @Required - @MaxNumber(255) - @MinNumber(0) - @DontObfuscate - @Desc("The fluid height of the cave") - private int fluidHeight = 35; +public class IrisCaveFluid { + @Required + @MaxNumber(255) + @MinNumber(0) + @DontObfuscate + @Desc("The fluid height of the cave") + private int fluidHeight = 35; - @DontObfuscate - @Desc("Insead of fluidHeight & below being fluid, turning inverse height on will simply spawn fluid in this cave layer from min(max_height, cave_height) to the fluid height. Basically, fluid will spawn above the fluidHeight value instead of below the fluidHeight.") - private boolean inverseHeight = false; + @DontObfuscate + @Desc("Insead of fluidHeight & below being fluid, turning inverse height on will simply spawn fluid in this cave layer from min(max_height, cave_height) to the fluid height. Basically, fluid will spawn above the fluidHeight value instead of below the fluidHeight.") + private boolean inverseHeight = false; - @Required - @DontObfuscate - @Desc("The fluid type that should spawn here") - private IrisBlockData fluidType = new IrisBlockData("CAVE_AIR"); + @Required + @DontObfuscate + @Desc("The fluid type that should spawn here") + private IrisBlockData fluidType = new IrisBlockData("CAVE_AIR"); - private final transient AtomicCache fluidData = new AtomicCache<>(); + private final transient AtomicCache fluidData = new AtomicCache<>(); - public boolean hasFluid(IrisDataManager rdata) - { - return !B.isAir(getFluid(rdata)); - } + public boolean hasFluid(IrisDataManager rdata) { + return !B.isAir(getFluid(rdata)); + } - public BlockData getFluid(IrisDataManager rdata) - { - return fluidData.aquire(() -> - { - BlockData b = getFluidType().getBlockData(rdata); + public BlockData getFluid(IrisDataManager rdata) { + return fluidData.aquire(() -> + { + BlockData b = getFluidType().getBlockData(rdata); - if(b != null) - { - return b; - } + if (b != null) { + return b; + } - return B.get("CAVE_AIR"); - }); - } + return B.get("CAVE_AIR"); + }); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisCaveLayer.java b/src/main/java/com/volmit/iris/object/IrisCaveLayer.java index d99a18016..74bde0b8f 100644 --- a/src/main/java/com/volmit/iris/object/IrisCaveLayer.java +++ b/src/main/java/com/volmit/iris/object/IrisCaveLayer.java @@ -4,7 +4,6 @@ import com.volmit.iris.util.Desc; import com.volmit.iris.util.DontObfuscate; import com.volmit.iris.util.MinNumber; import com.volmit.iris.util.Required; - import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -15,34 +14,33 @@ import lombok.experimental.Accessors; @AllArgsConstructor @Desc("Translate objects") @Data -public class IrisCaveLayer -{ - @Required - @DontObfuscate - @Desc("The vertical slope this cave layer follows") - private IrisShapedGeneratorStyle verticalSlope = new IrisShapedGeneratorStyle(); +public class IrisCaveLayer { + @Required + @DontObfuscate + @Desc("The vertical slope this cave layer follows") + private IrisShapedGeneratorStyle verticalSlope = new IrisShapedGeneratorStyle(); - @Required - @DontObfuscate - @Desc("The horizontal slope this cave layer follows") - private IrisShapedGeneratorStyle horizontalSlope = new IrisShapedGeneratorStyle(); + @Required + @DontObfuscate + @Desc("The horizontal slope this cave layer follows") + private IrisShapedGeneratorStyle horizontalSlope = new IrisShapedGeneratorStyle(); - @DontObfuscate - @Desc("If defined, a cave fluid will fill this cave below (or above) the specified fluidHeight in this object.") - private IrisCaveFluid fluid = new IrisCaveFluid(); + @DontObfuscate + @Desc("If defined, a cave fluid will fill this cave below (or above) the specified fluidHeight in this object.") + private IrisCaveFluid fluid = new IrisCaveFluid(); - @MinNumber(0.001) - @DontObfuscate - @Desc("The cave zoom. Higher values makes caves spread out further and branch less often, but are thicker.") - private double caveZoom = 1D; + @MinNumber(0.001) + @DontObfuscate + @Desc("The cave zoom. Higher values makes caves spread out further and branch less often, but are thicker.") + private double caveZoom = 1D; - @MinNumber(0.001) - @DontObfuscate - @Desc("The cave thickness.") - private double caveThickness = 1D; + @MinNumber(0.001) + @DontObfuscate + @Desc("The cave thickness.") + private double caveThickness = 1D; - @DontObfuscate - @Desc("If set to true, this cave layer can break the surface") - private boolean canBreakSurface = false; + @DontObfuscate + @Desc("If set to true, this cave layer can break the surface") + private boolean canBreakSurface = false; } diff --git a/src/main/java/com/volmit/iris/object/IrisColor.java b/src/main/java/com/volmit/iris/object/IrisColor.java index c990b6c8e..9da4c7f1c 100644 --- a/src/main/java/com/volmit/iris/object/IrisColor.java +++ b/src/main/java/com/volmit/iris/object/IrisColor.java @@ -15,83 +15,75 @@ import java.awt.*; @NoArgsConstructor @Desc("Represents a color") @Data -public class IrisColor -{ - @DontObfuscate - @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; +public class IrisColor { + @DontObfuscate + @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; - @DontObfuscate - @MaxNumber(255) - @MinNumber(0) - @Desc("Represents the red channel. Only define this if you are not defining the hex value.") - private int red = 0; + @DontObfuscate + @MaxNumber(255) + @MinNumber(0) + @Desc("Represents the red channel. Only define this if you are not defining the hex value.") + private int red = 0; - @DontObfuscate - @MaxNumber(255) - @MinNumber(0) - @Desc("Represents the green channel. Only define this if you are not defining the hex value.") - private int green = 0; + @DontObfuscate + @MaxNumber(255) + @MinNumber(0) + @Desc("Represents the green channel. Only define this if you are not defining the hex value.") + private int green = 0; - @DontObfuscate - @MaxNumber(255) - @MinNumber(0) - @Desc("Represents the blue channel. Only define this if you are not defining the hex value.") - private int blue = 0; + @DontObfuscate + @MaxNumber(255) + @MinNumber(0) + @Desc("Represents the blue channel. Only define this if you are not defining the hex value.") + private int blue = 0; - private final transient AtomicCache color = new AtomicCache<>(); + private final transient AtomicCache color = new AtomicCache<>(); - public Color getColor() - { - return color.aquire(() -> { - if(hex != null) - { - String v = (hex.startsWith("#") ? hex : "#" + hex).trim(); - try - { - return Color.decode(v); - } + public Color getColor() { + return color.aquire(() -> { + if (hex != null) { + String v = (hex.startsWith("#") ? hex : "#" + hex).trim(); + try { + return Color.decode(v); + } catch (Throwable e) { - catch(Throwable e) - { + } + } - } - } + return new Color(red, green, blue); + }); + } - return new Color(red, green, blue); - }); - } + public org.bukkit.Color getBukkitColor() { + return org.bukkit.Color.fromRGB(getColor().getRGB()); + } - public org.bukkit.Color getBukkitColor() - { - return org.bukkit.Color.fromRGB(getColor().getRGB()); - } + public static Color blend(Color... c) { + if (c == null || c.length <= 0) { + return null; + } + float ratio = 1f / ((float) c.length); - 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; - int a = 0; - int r = 0; - int g = 0; - int b = 0; + for (int i = 0; i < c.length; i++) { + int rgb = c[i].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); + } - for (int i = 0; i < c.length; i++) { - int rgb = c[i].getRGB(); - int a1 = (rgb >> 24 & 0xff); - int r1 = ((rgb & 0xff0000) >> 16); - int g1 = ((rgb & 0xff00) >> 8); - int b1 = (rgb & 0xff); - a += ((int) a1 * ratio); - r += ((int) r1 * ratio); - g += ((int) g1 * ratio); - b += ((int) b1 * ratio); - } - - return new Color(a << 24 | r << 16 | g << 8 | b); - } + return new Color(a << 24 | r << 16 | g << 8 | b); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisCompat.java b/src/main/java/com/volmit/iris/object/IrisCompat.java index ee1e2ef24..a1f3b6384 100644 --- a/src/main/java/com/volmit/iris/object/IrisCompat.java +++ b/src/main/java/com/volmit/iris/object/IrisCompat.java @@ -11,358 +11,327 @@ import java.io.File; import java.io.IOException; @Data -public class IrisCompat -{ - private KList blockFilters; - private KList itemFilters; +public class IrisCompat { + private KList blockFilters; + private KList itemFilters; - public IrisCompat() - { - blockFilters = getDefaultBlockCompatabilityFilters(); - itemFilters = getDefaultItemCompatabilityFilters(); - } + public IrisCompat() { + blockFilters = getDefaultBlockCompatabilityFilters(); + itemFilters = getDefaultItemCompatabilityFilters(); + } - public BlockData getBlock(String n) - { - String buf = n; - int err = 16; + public BlockData getBlock(String n) { + String buf = n; + int err = 16; - BlockData tx = B.getOrNull(buf); + BlockData tx = B.getOrNull(buf); - if(tx != null) - { - return tx; - } + if (tx != null) { + return tx; + } - searching: while(true) - { - if(err-- <= 0) - { - return B.get("STONE"); - } + searching: + while (true) { + if (err-- <= 0) { + return B.get("STONE"); + } - for(IrisCompatabilityBlockFilter i : blockFilters) - { - if(i.getWhen().equalsIgnoreCase(buf)) - { - BlockData b = i.getReplace(); + for (IrisCompatabilityBlockFilter i : blockFilters) { + if (i.getWhen().equalsIgnoreCase(buf)) { + BlockData b = i.getReplace(); - if(b != null) - { - return b; - } + if (b != null) { + return b; + } - buf = i.getSupplement(); - continue searching; - } - } + buf = i.getSupplement(); + continue searching; + } + } - return B.get("STONE"); - } - } + return B.get("STONE"); + } + } - public Material getItem(String n) - { - String buf = n; - int err = 16; - Material txf = B.getMaterialOrNull(buf); + public Material getItem(String n) { + String buf = n; + int err = 16; + Material txf = B.getMaterialOrNull(buf); - if(txf != null) - { - return txf; - } + if (txf != null) { + return txf; + } - int nomore = 64; + int nomore = 64; - searching: while(true) - { - if(nomore < 0) - { - return B.getMaterial("STONE"); - } + searching: + while (true) { + if (nomore < 0) { + return B.getMaterial("STONE"); + } - nomore--; - if(err-- <= 0) - { - break; - } + nomore--; + if (err-- <= 0) { + break; + } - for(IrisCompatabilityItemFilter i : itemFilters) - { - if(i.getWhen().equalsIgnoreCase(buf)) - { - Material b = i.getReplace(); + for (IrisCompatabilityItemFilter i : itemFilters) { + if (i.getWhen().equalsIgnoreCase(buf)) { + Material b = i.getReplace(); - if(b != null) - { - return b; - } + if (b != null) { + return b; + } - buf = i.getSupplement(); - continue searching; - } - } + buf = i.getSupplement(); + continue searching; + } + } - break; - } + break; + } - buf = n; - BlockData tx = B.getOrNull(buf); + buf = n; + BlockData tx = B.getOrNull(buf); - if(tx != null) - { - return tx.getMaterial(); - } - nomore = 64; + if (tx != null) { + return tx.getMaterial(); + } + nomore = 64; - searching: while(true) - { - if(nomore < 0) - { - return B.getMaterial("STONE"); - } + searching: + while (true) { + if (nomore < 0) { + return B.getMaterial("STONE"); + } - nomore--; + nomore--; - if(err-- <= 0) - { - return B.getMaterial("STONE"); - } + if (err-- <= 0) { + return B.getMaterial("STONE"); + } - for(IrisCompatabilityBlockFilter i : blockFilters) - { - if(i.getWhen().equalsIgnoreCase(buf)) - { - BlockData b = i.getReplace(); + for (IrisCompatabilityBlockFilter i : blockFilters) { + if (i.getWhen().equalsIgnoreCase(buf)) { + BlockData b = i.getReplace(); - if(b != null) - { - return b.getMaterial(); - } + if (b != null) { + return b.getMaterial(); + } - buf = i.getSupplement(); - continue searching; - } - } + buf = i.getSupplement(); + continue searching; + } + } - return B.getMaterial("STONE"); - } - } + return B.getMaterial("STONE"); + } + } - public static IrisCompat configured(File f) throws IOException - { - 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)); + public static IrisCompat configured(File f) throws IOException { + 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.attemptAsync(() -> IO.writeAll(f, defa)); - } + if (!f.exists()) { + J.attemptAsync(() -> IO.writeAll(f, defa)); + } - try - { - IrisCompat rea = new Gson().fromJson(IO.readAll(f), IrisCompat.class); + try { + IrisCompat rea = new Gson().fromJson(IO.readAll(f), IrisCompat.class); - for(IrisCompatabilityBlockFilter i : rea.getBlockFilters()) - { - def.getBlockFilters().add(i); - } + for (IrisCompatabilityBlockFilter i : rea.getBlockFilters()) { + def.getBlockFilters().add(i); + } - for(IrisCompatabilityItemFilter i : rea.getItemFilters()) - { - def.getItemFilters().add(i); - } - } - catch(JsonSyntaxException e) - { - e.printStackTrace(); - } - catch(IOException e){ - throw e; - } + for (IrisCompatabilityItemFilter i : rea.getItemFilters()) { + def.getItemFilters().add(i); + } + } catch (JsonSyntaxException e) { + e.printStackTrace(); + } catch (IOException e) { + throw e; + } - return def; - } + return def; + } - private static KList getDefaultItemCompatabilityFilters() - { - KList filters = new KList<>(); + 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.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.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")); + // 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; - } + return filters; + } - private static KList getDefaultBlockCompatabilityFilters() - { - KList filters = new KList<>(); + private static KList getDefaultBlockCompatabilityFilters() { + KList filters = new KList<>(); - // 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("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.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("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.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")); + // 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; - } + return filters; + } } diff --git a/src/main/java/com/volmit/iris/object/IrisCompatabilityBlockFilter.java b/src/main/java/com/volmit/iris/object/IrisCompatabilityBlockFilter.java index 54331f4e5..ad0b5f691 100644 --- a/src/main/java/com/volmit/iris/object/IrisCompatabilityBlockFilter.java +++ b/src/main/java/com/volmit/iris/object/IrisCompatabilityBlockFilter.java @@ -6,7 +6,6 @@ import com.volmit.iris.util.B; import com.volmit.iris.util.Desc; import com.volmit.iris.util.DontObfuscate; import com.volmit.iris.util.Required; - import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -18,49 +17,44 @@ import org.bukkit.block.data.BlockData; @AllArgsConstructor @Desc("Find and replace object materials for compatability") @Data -public class IrisCompatabilityBlockFilter -{ - @Required - @DontObfuscate - @Desc("When iris sees this block, and it's not reconized") - private String when = ""; +public class IrisCompatabilityBlockFilter { + @Required + @DontObfuscate + @Desc("When iris sees this block, and it's not reconized") + private String when = ""; - @Required - @DontObfuscate - @Desc("Replace it with this block. Dont worry if this block is also not reconized, iris repeat this compat check.") - private String supplement = ""; + @Required + @DontObfuscate + @Desc("Replace it with this block. Dont worry if this block is also not reconized, iris repeat this compat check.") + private String supplement = ""; - @DontObfuscate - @Desc("If exact is true, it compares block data for example minecraft:some_log[axis=x]") - private boolean exact = false; + @DontObfuscate + @Desc("If exact is true, it compares block data for example minecraft:some_log[axis=x]") + private boolean exact = false; - private final transient AtomicCache findData = new AtomicCache<>(true); - private final transient AtomicCache replaceData = new AtomicCache<>(true); + private final transient AtomicCache findData = new AtomicCache<>(true); + private final transient AtomicCache replaceData = new AtomicCache<>(true); - public IrisCompatabilityBlockFilter(String when, String supplement) - { - this(when, supplement, false); - } + public IrisCompatabilityBlockFilter(String when, String supplement) { + this(when, supplement, false); + } - public BlockData getFind() - { - return findData.aquire(() -> B.get(when)); - } + public BlockData getFind() { + return findData.aquire(() -> B.get(when)); + } - public BlockData getReplace() - { - return replaceData.aquire(() -> - { - BlockData b = B.getOrNull(supplement); + public BlockData getReplace() { + return replaceData.aquire(() -> + { + BlockData b = B.getOrNull(supplement); - if(b == null) - { - return null; - } + if (b == null) { + return null; + } - Iris.warn("Compat: Using " + supplement + " in place of " + when + " since this server doesnt support '" + supplement + "'"); + Iris.warn("Compat: Using " + supplement + " in place of " + when + " since this server doesnt support '" + supplement + "'"); - return b; - }); - } + return b; + }); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisCompatabilityItemFilter.java b/src/main/java/com/volmit/iris/object/IrisCompatabilityItemFilter.java index 498f0b8dc..6d4a012fa 100644 --- a/src/main/java/com/volmit/iris/object/IrisCompatabilityItemFilter.java +++ b/src/main/java/com/volmit/iris/object/IrisCompatabilityItemFilter.java @@ -1,62 +1,55 @@ package com.volmit.iris.object; -import org.bukkit.Material; - import com.volmit.iris.Iris; import com.volmit.iris.scaffold.cache.AtomicCache; import com.volmit.iris.util.B; import com.volmit.iris.util.Desc; import com.volmit.iris.util.DontObfuscate; import com.volmit.iris.util.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 -{ - @Required - @DontObfuscate - @Desc("When iris sees this block, and it's not reconized") - private String when = ""; +public class IrisCompatabilityItemFilter { + @Required + @DontObfuscate + @Desc("When iris sees this block, and it's not reconized") + private String when = ""; - @Required - @DontObfuscate - @Desc("Replace it with this block. Dont worry if this block is also not reconized, iris repeat this compat check.") - private String supplement = ""; + @Required + @DontObfuscate + @Desc("Replace it with this block. Dont worry if this block is also not reconized, iris repeat this compat check.") + private String supplement = ""; - private final transient AtomicCache findData = new AtomicCache<>(true); - private final transient AtomicCache replaceData = new AtomicCache<>(true); + private final transient AtomicCache findData = new AtomicCache<>(true); + private final transient AtomicCache replaceData = new AtomicCache<>(true); - public IrisCompatabilityItemFilter(String when, String supplement) - { - this.when = when; - this.supplement = supplement; - } + public IrisCompatabilityItemFilter(String when, String supplement) { + this.when = when; + this.supplement = supplement; + } - public Material getFind() - { - return findData.aquire(() -> B.getMaterial(when)); - } + public Material getFind() { + return findData.aquire(() -> B.getMaterial(when)); + } - public Material getReplace() - { - return replaceData.aquire(() -> - { - Material b = B.getMaterialOrNull(supplement); + public Material getReplace() { + return replaceData.aquire(() -> + { + Material b = B.getMaterialOrNull(supplement); - if(b == null) - { - return null; - } - - Iris.verbose("Compat: Using " + supplement + " in place of " + when + " since this server doesnt support '" + supplement + "'"); + if (b == null) { + return null; + } - return b; - }); - } + Iris.verbose("Compat: Using " + supplement + " in place of " + when + " since this server doesnt support '" + supplement + "'"); + + return b; + }); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisDecorator.java b/src/main/java/com/volmit/iris/object/IrisDecorator.java index 00cc6e8ac..2f197c8b2 100644 --- a/src/main/java/com/volmit/iris/object/IrisDecorator.java +++ b/src/main/java/com/volmit/iris/object/IrisDecorator.java @@ -1,11 +1,10 @@ package com.volmit.iris.object; import com.volmit.iris.Iris; -import com.volmit.iris.scaffold.cache.AtomicCache; -import com.volmit.iris.manager.IrisDataManager; import com.volmit.iris.generator.noise.CNG; +import com.volmit.iris.manager.IrisDataManager; +import com.volmit.iris.scaffold.cache.AtomicCache; import com.volmit.iris.util.*; - import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -17,226 +16,201 @@ import org.bukkit.block.data.BlockData; @AllArgsConstructor @Desc("A biome decorator is used for placing flowers, grass, cacti and so on") @Data -public class IrisDecorator -{ - @DontObfuscate - @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(); +public class IrisDecorator { + @DontObfuscate + @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(); - @DontObfuscate - @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; + @DontObfuscate + @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; - @DontObfuscate - @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(); + @DontObfuscate + @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"}) - @DontObfuscate - @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(); + @DependsOn({"stackMin", "stackMax"}) + @DontObfuscate + @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(); - @DontObfuscate - @Desc("Tells iris where this decoration is a part of. I.e. SHORE_LINE or SEA_SURFACE") - private DecorationPart partOf = DecorationPart.NONE; + @DontObfuscate + @Desc("Tells iris where this decoration is a part of. I.e. SHORE_LINE or SEA_SURFACE") + private DecorationPart partOf = DecorationPart.NONE; - @DependsOn({"stackMin", "stackMax"}) - @MinNumber(1) - @MaxNumber(256) // TODO: WARNING HEIGHT - @DontObfuscate - @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(256) // TODO: WARNING HEIGHT + @DontObfuscate + @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(256) // TODO: WARNING HEIGHT - @DontObfuscate - @Desc("The maximum repeat stack height") - private int stackMax = 1; + @DependsOn({"stackMin", "stackMax"}) + @MinNumber(1) + @MaxNumber(256) // TODO: WARNING HEIGHT + @DontObfuscate + @Desc("The maximum repeat stack height") + private int stackMax = 1; - @Required - @MinNumber(0) - @MaxNumber(1) - @DontObfuscate - @Desc("The chance for this decorator to decorate at a given X,Y coordinate. This is hit 256 times per chunk (per surface block)") // TODO: WARNING HEIGHT - private double chance = 0.1; + @Required + @MinNumber(0) + @MaxNumber(1) + @DontObfuscate + @Desc("The chance for this decorator to decorate at a given X,Y coordinate. This is hit 256 times per chunk (per surface block)") + // TODO: WARNING HEIGHT + private double chance = 0.1; - @Required - @ArrayType(min = 1, type = IrisBlockData.class) - @DontObfuscate - @Desc("The palette of blocks to pick from when this decorator needs to place.") - private KList palette = new KList().qadd(new IrisBlockData("grass")); + @Required + @ArrayType(min = 1, type = IrisBlockData.class) + @DontObfuscate + @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) - @DontObfuscate - @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(); + @ArrayType(min = 1, type = IrisBlockData.class) + @DontObfuscate + @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) - @DontObfuscate - @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; + @DependsOn("topPalette") + @MinNumber(0.01) + @MaxNumber(1.0) + @DontObfuscate + @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; - 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 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<>(); - public int getHeight(RNG rng, double x, double z, IrisDataManager data) - { - if(stackMin == stackMax) - { - return stackMin; - } + public int getHeight(RNG rng, double x, double z, IrisDataManager data) { + if (stackMin == stackMax) { + return stackMin; + } - return getHeightGenerator(rng, data).fit(stackMin, stackMax, x / heightVariance.getZoom(), z / heightVariance.getZoom()) + 1; - } + return getHeightGenerator(rng, data).fit(stackMin, stackMax, x / heightVariance.getZoom(), z / heightVariance.getZoom()) + 1; + } - public CNG getHeightGenerator(RNG rng, IrisDataManager data) - { - return heightGenerator.aquire(() -> - { - return heightVariance.create(rng.nextParallelRNG(getBlockData(data).size() + stackMax + stackMin)); - }); - } + public CNG getHeightGenerator(RNG rng, IrisDataManager data) { + return heightGenerator.aquire(() -> + { + return heightVariance.create(rng.nextParallelRNG(getBlockData(data).size() + stackMax + stackMin)); + }); + } - public CNG getGenerator(RNG rng, IrisDataManager data) - { - return layerGenerator.aquire(() -> style.create(rng.nextParallelRNG((int) (getBlockData(data).size())))); - } + public CNG getGenerator(RNG rng, IrisDataManager data) { + return layerGenerator.aquire(() -> style.create(rng.nextParallelRNG(getBlockData(data).size()))); + } - public CNG getVarianceGenerator(RNG rng, IrisDataManager data) - { - return varianceGenerator.aquire(() -> - variance.create( - rng.nextParallelRNG((int) (getBlockData(data).size()))) + public CNG getVarianceGenerator(RNG rng, IrisDataManager data) { + return varianceGenerator.aquire(() -> + variance.create( + rng.nextParallelRNG(getBlockData(data).size())) - .scale(1D / variance.getZoom())); - } + .scale(1D / variance.getZoom())); + } - public KList add(String b) - { - palette.add(new IrisBlockData(b)); - return palette; - } + public KList add(String b) { + palette.add(new IrisBlockData(b)); + return palette; + } - public BlockData getBlockData(IrisBiome b, RNG rng, double x, double z, IrisDataManager data) - { - if(getBlockData(data).isEmpty()) - { - Iris.warn("Empty Block Data for " + b.getName()); - return null; - } + public BlockData getBlockData(IrisBiome b, RNG rng, double x, double z, IrisDataManager data) { + if (getBlockData(data).isEmpty()) { + Iris.warn("Empty Block Data for " + b.getName()); + return null; + } - double xx = x / style.getZoom(); - double zz = z / style.getZoom(); + double xx = x / style.getZoom(); + double zz = z / style.getZoom(); - if(getGenerator(rng, data).fitDouble(0D, 1D, xx, zz) <= chance) - { - if(getBlockData(data).size() == 1) - { - return getBlockData(data).get(0); - } + if (getGenerator(rng, data).fitDouble(0D, 1D, xx, zz) <= chance) { + if (getBlockData(data).size() == 1) { + return getBlockData(data).get(0); + } - return getVarianceGenerator(rng, data).fit(getBlockData(data), z, x); //X and Z must be switched - } + return getVarianceGenerator(rng, data).fit(getBlockData(data), z, x); //X and Z must be switched + } - return null; - } + return null; + } - public BlockData getBlockData100(IrisBiome b, RNG rng, double x, double z, IrisDataManager data) - { - if(getBlockData(data).isEmpty()) - { - Iris.warn("Empty Block Data for " + b.getName()); - return null; - } + public BlockData getBlockData100(IrisBiome b, RNG rng, double x, double z, IrisDataManager data) { + if (getBlockData(data).isEmpty()) { + Iris.warn("Empty Block Data for " + b.getName()); + return null; + } - double xx = x; - double zz = z; + double xx = x; + double zz = z; - if(!getVarianceGenerator(rng, data).isStatic()) - { - xx = x / style.getZoom(); - zz = z / style.getZoom(); - } + if (!getVarianceGenerator(rng, data).isStatic()) { + xx = x / style.getZoom(); + zz = z / style.getZoom(); + } - if(getBlockData(data).size() == 1) - { - return getBlockData(data).get(0); - } + if (getBlockData(data).size() == 1) { + return getBlockData(data).get(0); + } - return getVarianceGenerator(rng, data).fit(getBlockData(data), z, x).clone(); //X and Z must be switched - } + return getVarianceGenerator(rng, data).fit(getBlockData(data), z, x).clone(); //X and Z must be switched + } - public BlockData getBlockDataForTop(IrisBiome b, RNG rng, double x, double z, IrisDataManager data) - { - if(getBlockDataTops(data).isEmpty()) - { - return null; - } + public BlockData getBlockDataForTop(IrisBiome b, RNG rng, double x, double z, IrisDataManager data) { + if (getBlockDataTops(data).isEmpty()) { + return null; + } - double xx = x / style.getZoom(); - double zz = z / style.getZoom(); + double xx = x / style.getZoom(); + double zz = z / style.getZoom(); - if(getGenerator(rng, data).fitDouble(0D, 1D, xx, zz) <= chance) - { - if(getBlockData(data).size() == 1) - { - return getBlockDataTops(data).get(0); - } + if (getGenerator(rng, data).fitDouble(0D, 1D, xx, zz) <= chance) { + if (getBlockData(data).size() == 1) { + return getBlockDataTops(data).get(0); + } - return getVarianceGenerator(rng, data).fit(getBlockDataTops(data), z, x); //X and Z must be switched - } + return getVarianceGenerator(rng, data).fit(getBlockDataTops(data), z, x); //X and Z must be switched + } - return null; - } + return null; + } - public KList getBlockData(IrisDataManager data) - { - return blockData.aquire(() -> - { - KList blockData = new KList<>(); - for(IrisBlockData i : palette) - { - BlockData bx = i.getBlockData(data); - if(bx != null) - { - for (int n = 0; n < i.getWeight(); n++) { - blockData.add(bx); - } - } - } + public KList getBlockData(IrisDataManager data) { + return blockData.aquire(() -> + { + KList blockData = new KList<>(); + for (IrisBlockData i : palette) { + BlockData bx = i.getBlockData(data); + if (bx != null) { + for (int n = 0; n < i.getWeight(); n++) { + blockData.add(bx); + } + } + } - return blockData; - }); - } + return blockData; + }); + } - public KList getBlockDataTops(IrisDataManager data) - { - return blockDataTops.aquire(() -> - { - KList blockDataTops = new KList<>(); - for(IrisBlockData i : topPalette) - { - BlockData bx = i.getBlockData(data); - if(bx != null) - { - for (int n = 0; n < i.getWeight(); n++) { - blockDataTops.add(bx); - } - } - } + public KList getBlockDataTops(IrisDataManager data) { + return blockDataTops.aquire(() -> + { + KList blockDataTops = new KList<>(); + for (IrisBlockData i : topPalette) { + BlockData bx = i.getBlockData(data); + if (bx != null) { + for (int n = 0; n < i.getWeight(); n++) { + blockDataTops.add(bx); + } + } + } - return blockDataTops; - }); - } + return blockDataTops; + }); + } - public boolean isStacking() - { - return getStackMax() > 1; - } + public boolean isStacking() { + return getStackMax() > 1; + } } diff --git a/src/main/java/com/volmit/iris/object/IrisDepositGenerator.java b/src/main/java/com/volmit/iris/object/IrisDepositGenerator.java index 28a692dd9..67b26fe88 100644 --- a/src/main/java/com/volmit/iris/object/IrisDepositGenerator.java +++ b/src/main/java/com/volmit/iris/object/IrisDepositGenerator.java @@ -1,7 +1,7 @@ package com.volmit.iris.object; -import com.volmit.iris.scaffold.cache.AtomicCache; import com.volmit.iris.manager.IrisDataManager; +import com.volmit.iris.scaffold.cache.AtomicCache; import com.volmit.iris.util.*; import lombok.AllArgsConstructor; import lombok.Data; @@ -15,135 +15,121 @@ import org.bukkit.util.BlockVector; @AllArgsConstructor @Desc("Creates ore & other block deposits underground") @Data -public class IrisDepositGenerator -{ - @Required - @MinNumber(0) - @MaxNumber(256) // TODO: WARNING HEIGHT - @DontObfuscate - @Desc("The minimum height this deposit can generate at") - private int minHeight = 7; +public class IrisDepositGenerator { + @Required + @MinNumber(0) + @MaxNumber(256) // TODO: WARNING HEIGHT + @DontObfuscate + @Desc("The minimum height this deposit can generate at") + private int minHeight = 7; - @Required - @MinNumber(0) - @MaxNumber(256) // TODO: WARNING HEIGHT - @DontObfuscate - @Desc("The maximum height this deposit can generate at") - private int maxHeight = 55; + @Required + @MinNumber(0) + @MaxNumber(256) // TODO: WARNING HEIGHT + @DontObfuscate + @Desc("The maximum height this deposit can generate at") + private int maxHeight = 55; - @Required - @MinNumber(1) - @MaxNumber(32) - @DontObfuscate - @Desc("The minimum amount of deposit blocks per clump") - private int minSize = 3; + @Required + @MinNumber(1) + @MaxNumber(32) + @DontObfuscate + @Desc("The minimum amount of deposit blocks per clump") + private int minSize = 3; - @Required - @MinNumber(1) - @MaxNumber(32) - @DontObfuscate - @Desc("The maximum amount of deposit blocks per clump") - private int maxSize = 5; + @Required + @MinNumber(1) + @MaxNumber(32) + @DontObfuscate + @Desc("The maximum amount of deposit blocks per clump") + private int maxSize = 5; - @Required - @MinNumber(1) - @MaxNumber(128) - @DontObfuscate - @Desc("The maximum amount of clumps per chunk") - private int maxPerChunk = 3; + @Required + @MinNumber(1) + @MaxNumber(128) + @DontObfuscate + @Desc("The maximum amount of clumps per chunk") + private int maxPerChunk = 3; - @Required - @MinNumber(0) - @MaxNumber(128) - @DontObfuscate - @Desc("The minimum amount of clumps per chunk") - private int minPerChunk = 1; + @Required + @MinNumber(0) + @MaxNumber(128) + @DontObfuscate + @Desc("The minimum amount of clumps per chunk") + private int minPerChunk = 1; - @Required - @ArrayType(min = 1, type = IrisBlockData.class) - @DontObfuscate - @Desc("The palette of blocks to be used in this deposit generator") - private KList palette = new KList(); + @Required + @ArrayType(min = 1, type = IrisBlockData.class) + @DontObfuscate + @Desc("The palette of blocks to be used in this deposit generator") + private KList palette = new KList(); - @MinNumber(1) - @MaxNumber(64) - @DontObfuscate - @Desc("Ore varience is how many different objects clumps iris will create") - private int varience = 3; + @MinNumber(1) + @MaxNumber(64) + @DontObfuscate + @Desc("Ore varience is how many different objects clumps iris will create") + private int varience = 3; - private final transient AtomicCache> objects = new AtomicCache<>(); - private final transient AtomicCache> blockData = new AtomicCache<>(); + private final transient AtomicCache> objects = new AtomicCache<>(); + private final transient AtomicCache> blockData = new AtomicCache<>(); - public IrisObject getClump(RNG rng, IrisDataManager rdata) - { - KList objects = this.objects.aquire(() -> - { - RNG rngv = rng.nextParallelRNG(3957778); - KList objectsf = new KList<>(); + public IrisObject getClump(RNG rng, IrisDataManager rdata) { + KList objects = this.objects.aquire(() -> + { + RNG rngv = rng.nextParallelRNG(3957778); + KList objectsf = new KList<>(); - for(int i = 0; i < varience; i++) - { - objectsf.add(generateClumpObject(rngv.nextParallelRNG(2349 * i + 3598), rdata)); - } + for (int i = 0; i < varience; i++) { + objectsf.add(generateClumpObject(rngv.nextParallelRNG(2349 * i + 3598), rdata)); + } - return objectsf; - }); - return objects.get(rng.i(0, objects.size() - 1)); - } + return objectsf; + }); + return objects.get(rng.i(0, objects.size() - 1)); + } - public int getMaxDimension() - { - return Math.min(11, (int) Math.round(Math.pow(maxSize, 1D / 3D))); - } + public int getMaxDimension() { + return Math.min(11, (int) Math.round(Math.pow(maxSize, 1D / 3D))); + } - private IrisObject generateClumpObject(RNG rngv, IrisDataManager rdata) - { - int s = rngv.i(minSize, maxSize); - int dim = Math.min(11, (int) Math.round(Math.pow(maxSize, 1D / 3D))); - int w = dim / 2; - IrisObject o = new IrisObject(dim, dim, dim); + private IrisObject generateClumpObject(RNG rngv, IrisDataManager rdata) { + int s = rngv.i(minSize, maxSize); + int dim = Math.min(11, (int) Math.round(Math.pow(maxSize, 1D / 3D))); + int w = dim / 2; + IrisObject o = new IrisObject(dim, dim, dim); - if(s == 1) - { - o.getBlocks().put(o.getCenter(), nextBlock(rngv, rdata)); - } + if (s == 1) { + o.getBlocks().put(o.getCenter(), nextBlock(rngv, rdata)); + } else { + while (s > 0) { + s--; + BlockVector ang = new BlockVector(rngv.i(-w, w), rngv.i(-w, w), rngv.i(-w, w)); + BlockVector pos = o.getCenter().clone().add(ang).toBlockVector(); + o.getBlocks().put(pos, nextBlock(rngv, rdata)); + } + } - else - { - while(s > 0) - { - s--; - BlockVector ang = new BlockVector(rngv.i(-w, w), rngv.i(-w, w), rngv.i(-w, w)); - BlockVector pos = o.getCenter().clone().add(ang).toBlockVector(); - o.getBlocks().put(pos, nextBlock(rngv, rdata)); - } - } + return o; + } - return o; - } + private BlockData nextBlock(RNG rngv, IrisDataManager rdata) { + return getBlockData(rdata).get(rngv.i(0, getBlockData(rdata).size() - 1)); + } - private BlockData nextBlock(RNG rngv, IrisDataManager rdata) - { - return getBlockData(rdata).get(rngv.i(0, getBlockData(rdata).size() - 1)); - } + public KList getBlockData(IrisDataManager rdata) { + return blockData.aquire(() -> + { + KList blockData = new KList<>(); - public KList getBlockData(IrisDataManager rdata) - { - return blockData.aquire(() -> - { - KList blockData = new KList<>(); + for (IrisBlockData ix : palette) { + BlockData bx = ix.getBlockData(rdata); - for(IrisBlockData ix : palette) - { - BlockData bx = ix.getBlockData(rdata); + if (bx != null) { + blockData.add(bx); + } + } - if(bx != null) - { - blockData.add(bx); - } - } - - return blockData; - }); - } + return blockData; + }); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisDimension.java b/src/main/java/com/volmit/iris/object/IrisDimension.java index 3dd81807d..4aadaf5bb 100644 --- a/src/main/java/com/volmit/iris/object/IrisDimension.java +++ b/src/main/java/com/volmit/iris/object/IrisDimension.java @@ -20,458 +20,436 @@ import org.bukkit.block.data.BlockData; @Desc("Represents a dimension") @Data @EqualsAndHashCode(callSuper = false) -public class IrisDimension extends IrisRegistrant -{ - public static final BlockData STONE = Material.STONE.createBlockData(); - public static final BlockData WATER = Material.WATER.createBlockData(); - - @MinNumber(2) - @Required - @DontObfuscate - @Desc("The human readable name of this dimension") - private String name = "A Dimension"; - - @Desc("You can create mutliple dimensions on top of each other taking up less height of the same world. Such as the nether with a floor + ceiling.") - @ArrayType(min = 1,type = IrisDimensionIndex.class) - private KList dimensionalComposite = new KList<>(); - - @DontObfuscate - @Desc("Create an inverted dimension in the sky (like the nether)") - private IrisDimension sky = null; - - @RegistryListJigsaw - @DontObfuscate - @Desc("If defined, Iris will place the given jigsaw structure where minecraft should place the overworld stronghold.") - private String stronghold; - - @DontObfuscate - @Desc("Improves the biome grid variation by shuffling the cell grid more depending on the seed. This makes biomes across multiple seeds look far different than before.") - private boolean aggressiveBiomeReshuffle = false; - - @DontObfuscate - @Desc("Instead of a flat bottom, applies a clamp (using this noise style) to the bottom instead of a flat bottom. Useful for carving out center-dimensions in a dimension composite world.") - private IrisShapedGeneratorStyle undercarriage = null; - - @DontObfuscate - @Desc("Upon joining this world, Iris will send a resource pack request to the client. If they have previously selected yes, it will auto-switch depending on which dimension they go to.") - private String resourcePack = ""; - - @DontObfuscate - @Desc("Entity spawns to override or add to this dimension") - @ArrayType(min = 1, type = IrisEntitySpawnOverride.class) - private KList entitySpawnOverrides = new KList<>(); - - @DontObfuscate - @Desc("Add specific features in exact positions") - @ArrayType(min = 1, type = IrisFeaturePositional.class) - private KList specificFeatures = new KList<>(); - - @DontObfuscate - @Desc("Entity spawns during generation") - @ArrayType(min = 1, type = IrisEntityInitialSpawn.class) - private KList entityInitialSpawns = new KList<>(); - - @DontObfuscate - @Desc("Add random chances for terrain features") - @ArrayType(min = 1, type = IrisFeaturePotential.class) - private KList features = new KList<>(); - - @DontObfuscate - @Desc("Reference loot tables in this area") - private IrisLootReference loot = new IrisLootReference(); - - @MinNumber(0) - @DontObfuscate - @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) - @DontObfuscate - @Desc("Define custom block drops for this dimension") - private KList blockDrops = new KList<>(); - - @DontObfuscate - @Desc("Should bedrock be generated or not.") - private boolean bedrock = true; - - @MinNumber(0) - @MaxNumber(1) - @DontObfuscate - @Desc("The land chance. Up to 1.0 for total land or 0.0 for total sea") - private double landChance = 0.625; - - @DontObfuscate - @Desc("The placement style of regions") - private IrisGeneratorStyle regionStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - - @DontObfuscate - @Desc("The placement style of land/sea") - private IrisGeneratorStyle continentalStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - - @DontObfuscate - @Desc("The placement style of biomes") - private IrisGeneratorStyle landBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - - @DontObfuscate - @Desc("The placement style of biomes") - private IrisGeneratorStyle shoreBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - - @DontObfuscate - @Desc("The placement style of biomes") - private IrisGeneratorStyle seaBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - - @DontObfuscate - @Desc("The placement style of biomes") - private IrisGeneratorStyle caveBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - - @DontObfuscate - @Desc("The placement style of biomes") - private IrisGeneratorStyle riverBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - - @DontObfuscate - @Desc("The placement style of biomes") - private IrisGeneratorStyle lakeBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - - @DontObfuscate - @Desc("The placement style of biomes") - private IrisGeneratorStyle islandBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - - @DontObfuscate - @Desc("The placement style of biomes") - private IrisGeneratorStyle islandBiomeChanceStyle = NoiseStyle.CELLULAR_HEIGHT_IRIS_DOUBLE.style(); - - @DontObfuscate - @Desc("The placement style of biomes") - private IrisGeneratorStyle skylandBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); - - @DontObfuscate - @Desc("Generate caves or not.") - private boolean caves = true; - - @DontObfuscate - @Desc("Instead of filling objects with air, fills them with cobweb so you can see them") - private boolean debugSmartBore = false; - - @DontObfuscate - @Desc("Carve terrain or not") - private boolean carving = true; - - @DontObfuscate - @Desc("If defined, If air is defined below the area, this fluid will always place") - private IrisCaveFluid forceFluid = new IrisCaveFluid(); - - @DontObfuscate - @Desc("Generate decorations or not") - private boolean decorate = true; - - @DontObfuscate - @Desc("Generate ravines or not") - private boolean ravines = false; - - @MinNumber(1) - @DontObfuscate - @Desc("The rarity of a ravine layer having a lib (or rib) that sticks in or out by one block. Minecraft's default is 3.") - private int ravineRibRarity = 2; - - @MinNumber(1) - @DontObfuscate - @Desc("The rarity of ravines. Each chunk has a 1 in X chance") - private int ravineRarity = 50; - - @DontObfuscate - @Desc("Use post processing or not") - private boolean postProcessing = true; - - @DontObfuscate - @Desc("Add slabs in post processing") - private boolean postProcessingSlabs = true; - - @DontObfuscate - @Desc("Add painted walls in post processing") - private boolean postProcessingWalls = true; - - @DontObfuscate - @Desc("Use post processing for caves or not") - private boolean postProcessCaves = true; - - @DontObfuscate - @Desc("The world environment") - private Environment environment = Environment.NORMAL; - - @RegistryListRegion - @Required - @ArrayType(min = 1, type = String.class) - @DontObfuscate - @Desc("Define all of the regions to include in this dimension. Dimensions -> Regions -> Biomes -> Objects etc") - private KList regions = new KList<>(); - - @ArrayType(min = 1, type = IrisJigsawStructurePlacement.class) - @DontObfuscate - @Desc("Jigsaw structures") - private KList jigsawStructures = new KList<>(); - - @Required - @MinNumber(0) - @MaxNumber(255) - @DontObfuscate - @Desc("The fluid height for this dimension") - private int fluidHeight = 63; - - @RegistryListBiome - @DontObfuscate - @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 = ""; - - @RegistryListBiome - @DontObfuscate - @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) - @DontObfuscate - @Desc("Zoom in or out the biome size. Higher = bigger biomes") - private double biomeZoom = 5D; - - @MinNumber(0.0001) - @MaxNumber(512) - @DontObfuscate - @Desc("Zoom in or out the terrain. This stretches the terrain. Due to performance improvements, Higher than 2.0 may cause weird rounding artifacts. Lower = more terrain changes per block. Its a true zoom-out.") - private double terrainZoom = 1D; - - @MinNumber(0) - @MaxNumber(360) - @DontObfuscate - @Desc("You can rotate the input coordinates by an angle. This can make terrain appear more natural (less sharp corners and lines). This literally rotates the entire dimension by an angle. Hint: Try 12 degrees or something not on a 90 or 45 degree angle.") - private double dimensionAngleDeg = 0; - - @MinNumber(0) - @MaxNumber(8192) - @DontObfuscate - @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) - @DontObfuscate - @Desc("Coordinate fracturing zoom. Higher = less frequent warping, Lower = more frequent and rapid warping / swirls.") - private double coordFractureZoom = 8; - - @MinNumber(0.0001) - @MaxNumber(512) - @DontObfuscate - @Desc("This zooms in the land space") - private double landZoom = 1; - - @MinNumber(0.0001) - @MaxNumber(512) - @DontObfuscate - @Desc("This zooms oceanic biomes") - private double seaZoom = 1; - - @MinNumber(0.0001) - @MaxNumber(512) - @DontObfuscate - @Desc("Zoom in continents") - private double continentZoom = 1; - - @MinNumber(0.0001) - @MaxNumber(512) - @DontObfuscate - @Desc("Change the size of regions") - private double regionZoom = 1; - - @DontObfuscate - @Desc("Disable this to stop placing schematics in biomes") - private boolean placeObjects = true; - - @DontObfuscate - @Desc("Prevent Leaf decay as if placed in creative mode") - private boolean preventLeafDecay = false; - - @ArrayType(min = 1, type = IrisDepositGenerator.class) - @DontObfuscate - @Desc("Define global deposit generators") - private KList deposits = new KList<>(); - - @ArrayType(min = 1, type = IrisShapedGeneratorStyle.class) - @DontObfuscate - @Desc("Overlay additional noise on top of the interoplated terrain.") - private KList overlayNoise = new KList<>(); - - @ArrayType(min = 1, type = IrisCaveLayer.class) - @DontObfuscate - @Desc("Define cave layers") - private KList caveLayers = new KList<>(); - - @ArrayType(min = 1, type = IrisCarveLayer.class) - @DontObfuscate - @Desc("Define carve layers") - private KList carveLayers = new KList<>(); - - @MinNumber(0.0001) - @MaxNumber(512) - @DontObfuscate - @Desc("The rock zoom mostly for zooming in on a wispy palette") - private double rockZoom = 5; - - @DontObfuscate - @Desc("The palette of blocks for 'stone'") - private IrisMaterialPalette rockPalette = new IrisMaterialPalette().qclear().qadd("stone"); - - @DontObfuscate - @Desc("The palette of blocks for 'water'") - private IrisMaterialPalette fluidPalette = new IrisMaterialPalette().qclear().qadd("water"); - - @ArrayType(min = 1, type = IrisBiomeMutation.class) - @DontObfuscate - @Desc("Define biome mutations for this dimension") - private KList mutations = new KList<>(); - - 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<>(); - - public boolean hasSky() - { - return getSky() != null; - } - - 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 isCarved(int x, int y, int z, RNG rng, int terrainHeight) - { - if(isCarving() && terrainHeight > getFluidHeight() || y < terrainHeight) - { - for(IrisCarveLayer j : getCarveLayers()) - { - if(j.isCarved(rng, x, y, z)) - { - return true; - } - } - } - - return false; - } - - public Environment getEnvironment(){ - return environment; - } - - 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) - { - KList r = new KList<>(); - - for(String i : getRegions()) - { - r.add(g.getData().getRegionLoader().load(i)); - } - - return r; - } - - public KList getAllAnyRegions() - { - KList r = new KList<>(); - - for(String i : getRegions()) - { - r.add(IrisDataManager.loadAnyRegion(i)); - } - - return r; - } - - public KList getAllBiomes(DataProvider g) - { - KList r = new KList<>(); - - for(IrisRegion i : getAllRegions(g)) - { - if(i == null) - { - continue; - } - - r.addAll(i.getAllBiomes(g)); - } - - return r; - } - - 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 LAKE: - return lakeBiomeStyle; - case RIVER: - return riverBiomeStyle; - case LAND: - return landBiomeStyle; - case SEA: - return seaBiomeStyle; - case SHORE: - return shoreBiomeStyle; - default: - break; - } - - return landBiomeStyle; - } +public class IrisDimension extends IrisRegistrant { + public static final BlockData STONE = Material.STONE.createBlockData(); + public static final BlockData WATER = Material.WATER.createBlockData(); + + @MinNumber(2) + @Required + @DontObfuscate + @Desc("The human readable name of this dimension") + private String name = "A Dimension"; + + @Desc("You can create mutliple dimensions on top of each other taking up less height of the same world. Such as the nether with a floor + ceiling.") + @ArrayType(min = 1, type = IrisDimensionIndex.class) + private KList dimensionalComposite = new KList<>(); + + @DontObfuscate + @Desc("Create an inverted dimension in the sky (like the nether)") + private IrisDimension sky = null; + + @RegistryListJigsaw + @DontObfuscate + @Desc("If defined, Iris will place the given jigsaw structure where minecraft should place the overworld stronghold.") + private String stronghold; + + @DontObfuscate + @Desc("Improves the biome grid variation by shuffling the cell grid more depending on the seed. This makes biomes across multiple seeds look far different than before.") + private boolean aggressiveBiomeReshuffle = false; + + @DontObfuscate + @Desc("Instead of a flat bottom, applies a clamp (using this noise style) to the bottom instead of a flat bottom. Useful for carving out center-dimensions in a dimension composite world.") + private IrisShapedGeneratorStyle undercarriage = null; + + @DontObfuscate + @Desc("Upon joining this world, Iris will send a resource pack request to the client. If they have previously selected yes, it will auto-switch depending on which dimension they go to.") + private String resourcePack = ""; + + @DontObfuscate + @Desc("Entity spawns to override or add to this dimension") + @ArrayType(min = 1, type = IrisEntitySpawnOverride.class) + private KList entitySpawnOverrides = new KList<>(); + + @DontObfuscate + @Desc("Add specific features in exact positions") + @ArrayType(min = 1, type = IrisFeaturePositional.class) + private KList specificFeatures = new KList<>(); + + @DontObfuscate + @Desc("Entity spawns during generation") + @ArrayType(min = 1, type = IrisEntityInitialSpawn.class) + private KList entityInitialSpawns = new KList<>(); + + @DontObfuscate + @Desc("Add random chances for terrain features") + @ArrayType(min = 1, type = IrisFeaturePotential.class) + private KList features = new KList<>(); + + @DontObfuscate + @Desc("Reference loot tables in this area") + private IrisLootReference loot = new IrisLootReference(); + + @MinNumber(0) + @DontObfuscate + @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) + @DontObfuscate + @Desc("Define custom block drops for this dimension") + private KList blockDrops = new KList<>(); + + @DontObfuscate + @Desc("Should bedrock be generated or not.") + private boolean bedrock = true; + + @MinNumber(0) + @MaxNumber(1) + @DontObfuscate + @Desc("The land chance. Up to 1.0 for total land or 0.0 for total sea") + private double landChance = 0.625; + + @DontObfuscate + @Desc("The placement style of regions") + private IrisGeneratorStyle regionStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); + + @DontObfuscate + @Desc("The placement style of land/sea") + private IrisGeneratorStyle continentalStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); + + @DontObfuscate + @Desc("The placement style of biomes") + private IrisGeneratorStyle landBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); + + @DontObfuscate + @Desc("The placement style of biomes") + private IrisGeneratorStyle shoreBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); + + @DontObfuscate + @Desc("The placement style of biomes") + private IrisGeneratorStyle seaBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); + + @DontObfuscate + @Desc("The placement style of biomes") + private IrisGeneratorStyle caveBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); + + @DontObfuscate + @Desc("The placement style of biomes") + private IrisGeneratorStyle riverBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); + + @DontObfuscate + @Desc("The placement style of biomes") + private IrisGeneratorStyle lakeBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); + + @DontObfuscate + @Desc("The placement style of biomes") + private IrisGeneratorStyle islandBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); + + @DontObfuscate + @Desc("The placement style of biomes") + private IrisGeneratorStyle islandBiomeChanceStyle = NoiseStyle.CELLULAR_HEIGHT_IRIS_DOUBLE.style(); + + @DontObfuscate + @Desc("The placement style of biomes") + private IrisGeneratorStyle skylandBiomeStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style(); + + @DontObfuscate + @Desc("Generate caves or not.") + private boolean caves = true; + + @DontObfuscate + @Desc("Instead of filling objects with air, fills them with cobweb so you can see them") + private boolean debugSmartBore = false; + + @DontObfuscate + @Desc("Carve terrain or not") + private boolean carving = true; + + @DontObfuscate + @Desc("If defined, If air is defined below the area, this fluid will always place") + private IrisCaveFluid forceFluid = new IrisCaveFluid(); + + @DontObfuscate + @Desc("Generate decorations or not") + private boolean decorate = true; + + @DontObfuscate + @Desc("Generate ravines or not") + private boolean ravines = false; + + @MinNumber(1) + @DontObfuscate + @Desc("The rarity of a ravine layer having a lib (or rib) that sticks in or out by one block. Minecraft's default is 3.") + private int ravineRibRarity = 2; + + @MinNumber(1) + @DontObfuscate + @Desc("The rarity of ravines. Each chunk has a 1 in X chance") + private int ravineRarity = 50; + + @DontObfuscate + @Desc("Use post processing or not") + private boolean postProcessing = true; + + @DontObfuscate + @Desc("Add slabs in post processing") + private boolean postProcessingSlabs = true; + + @DontObfuscate + @Desc("Add painted walls in post processing") + private boolean postProcessingWalls = true; + + @DontObfuscate + @Desc("Use post processing for caves or not") + private boolean postProcessCaves = true; + + @DontObfuscate + @Desc("The world environment") + private Environment environment = Environment.NORMAL; + + @RegistryListRegion + @Required + @ArrayType(min = 1, type = String.class) + @DontObfuscate + @Desc("Define all of the regions to include in this dimension. Dimensions -> Regions -> Biomes -> Objects etc") + private KList regions = new KList<>(); + + @ArrayType(min = 1, type = IrisJigsawStructurePlacement.class) + @DontObfuscate + @Desc("Jigsaw structures") + private KList jigsawStructures = new KList<>(); + + @Required + @MinNumber(0) + @MaxNumber(255) + @DontObfuscate + @Desc("The fluid height for this dimension") + private int fluidHeight = 63; + + @RegistryListBiome + @DontObfuscate + @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 = ""; + + @RegistryListBiome + @DontObfuscate + @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) + @DontObfuscate + @Desc("Zoom in or out the biome size. Higher = bigger biomes") + private double biomeZoom = 5D; + + @MinNumber(0.0001) + @MaxNumber(512) + @DontObfuscate + @Desc("Zoom in or out the terrain. This stretches the terrain. Due to performance improvements, Higher than 2.0 may cause weird rounding artifacts. Lower = more terrain changes per block. Its a true zoom-out.") + private double terrainZoom = 1D; + + @MinNumber(0) + @MaxNumber(360) + @DontObfuscate + @Desc("You can rotate the input coordinates by an angle. This can make terrain appear more natural (less sharp corners and lines). This literally rotates the entire dimension by an angle. Hint: Try 12 degrees or something not on a 90 or 45 degree angle.") + private double dimensionAngleDeg = 0; + + @MinNumber(0) + @MaxNumber(8192) + @DontObfuscate + @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) + @DontObfuscate + @Desc("Coordinate fracturing zoom. Higher = less frequent warping, Lower = more frequent and rapid warping / swirls.") + private double coordFractureZoom = 8; + + @MinNumber(0.0001) + @MaxNumber(512) + @DontObfuscate + @Desc("This zooms in the land space") + private double landZoom = 1; + + @MinNumber(0.0001) + @MaxNumber(512) + @DontObfuscate + @Desc("This zooms oceanic biomes") + private double seaZoom = 1; + + @MinNumber(0.0001) + @MaxNumber(512) + @DontObfuscate + @Desc("Zoom in continents") + private double continentZoom = 1; + + @MinNumber(0.0001) + @MaxNumber(512) + @DontObfuscate + @Desc("Change the size of regions") + private double regionZoom = 1; + + @DontObfuscate + @Desc("Disable this to stop placing schematics in biomes") + private boolean placeObjects = true; + + @DontObfuscate + @Desc("Prevent Leaf decay as if placed in creative mode") + private boolean preventLeafDecay = false; + + @ArrayType(min = 1, type = IrisDepositGenerator.class) + @DontObfuscate + @Desc("Define global deposit generators") + private KList deposits = new KList<>(); + + @ArrayType(min = 1, type = IrisShapedGeneratorStyle.class) + @DontObfuscate + @Desc("Overlay additional noise on top of the interoplated terrain.") + private KList overlayNoise = new KList<>(); + + @ArrayType(min = 1, type = IrisCaveLayer.class) + @DontObfuscate + @Desc("Define cave layers") + private KList caveLayers = new KList<>(); + + @ArrayType(min = 1, type = IrisCarveLayer.class) + @DontObfuscate + @Desc("Define carve layers") + private KList carveLayers = new KList<>(); + + @MinNumber(0.0001) + @MaxNumber(512) + @DontObfuscate + @Desc("The rock zoom mostly for zooming in on a wispy palette") + private double rockZoom = 5; + + @DontObfuscate + @Desc("The palette of blocks for 'stone'") + private IrisMaterialPalette rockPalette = new IrisMaterialPalette().qclear().qadd("stone"); + + @DontObfuscate + @Desc("The palette of blocks for 'water'") + private IrisMaterialPalette fluidPalette = new IrisMaterialPalette().qclear().qadd("water"); + + @ArrayType(min = 1, type = IrisBiomeMutation.class) + @DontObfuscate + @Desc("Define biome mutations for this dimension") + private KList mutations = new KList<>(); + + 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<>(); + + public boolean hasSky() { + return getSky() != null; + } + + 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 isCarved(int x, int y, int z, RNG rng, int terrainHeight) { + if (isCarving() && terrainHeight > getFluidHeight() || y < terrainHeight) { + for (IrisCarveLayer j : getCarveLayers()) { + if (j.isCarved(rng, x, y, z)) { + return true; + } + } + } + + return false; + } + + public Environment getEnvironment() { + return environment; + } + + 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) { + KList r = new KList<>(); + + for (String i : getRegions()) { + r.add(g.getData().getRegionLoader().load(i)); + } + + return r; + } + + public KList getAllAnyRegions() { + KList r = new KList<>(); + + for (String i : getRegions()) { + r.add(IrisDataManager.loadAnyRegion(i)); + } + + return r; + } + + public KList getAllBiomes(DataProvider g) { + KList r = new KList<>(); + + for (IrisRegion i : getAllRegions(g)) { + if (i == null) { + continue; + } + + r.addAll(i.getAllBiomes(g)); + } + + return r; + } + + 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 LAKE: + return lakeBiomeStyle; + case RIVER: + return riverBiomeStyle; + case LAND: + return landBiomeStyle; + case SEA: + return seaBiomeStyle; + case SHORE: + return shoreBiomeStyle; + default: + break; + } + + return landBiomeStyle; + } } diff --git a/src/main/java/com/volmit/iris/object/IrisDimensionIndex.java b/src/main/java/com/volmit/iris/object/IrisDimensionIndex.java index 18d443728..f50fd2a61 100644 --- a/src/main/java/com/volmit/iris/object/IrisDimensionIndex.java +++ b/src/main/java/com/volmit/iris/object/IrisDimensionIndex.java @@ -1,11 +1,6 @@ package com.volmit.iris.object; -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.MinNumber; -import com.volmit.iris.util.RegistryListDimension; -import com.volmit.iris.util.Required; - +import com.volmit.iris.util.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; @@ -18,25 +13,24 @@ import lombok.experimental.Accessors; @Desc("Represents an index for dimensions to take up vertical slots in the same world") @Data @EqualsAndHashCode(callSuper = false) -public class IrisDimensionIndex -{ - @Required - @DontObfuscate - @Desc("The weight of this dimension. If there are 2 dimensions, if the weight is the same on both, both dimensions will take up 128 blocks of height.") - private double weight = 1D; +public class IrisDimensionIndex { + @Required + @DontObfuscate + @Desc("The weight of this dimension. If there are 2 dimensions, if the weight is the same on both, both dimensions will take up 128 blocks of height.") + private double weight = 1D; - @DontObfuscate - @Desc("If inverted is set to true, the dimension will be updide down in the world") - private boolean inverted = false; + @DontObfuscate + @Desc("If inverted is set to true, the dimension will be updide down in the world") + private boolean inverted = false; - @DontObfuscate - @Desc("Only one dimension layer should be set to primary. The primary dimension layer is where players spawn, and the biomes that the vanilla structure system uses to figure out what structures to place.") - private boolean primary = false; + @DontObfuscate + @Desc("Only one dimension layer should be set to primary. The primary dimension layer is where players spawn, and the biomes that the vanilla structure system uses to figure out what structures to place.") + private boolean primary = false; - @DontObfuscate - @Required - @RegistryListDimension - @MinNumber(1) - @Desc("Name of dimension") - private String dimension = ""; + @DontObfuscate + @Required + @RegistryListDimension + @MinNumber(1) + @Desc("Name of dimension") + private String dimension = ""; } diff --git a/src/main/java/com/volmit/iris/object/IrisDirection.java b/src/main/java/com/volmit/iris/object/IrisDirection.java index ad46dccb2..2d4abe649 100644 --- a/src/main/java/com/volmit/iris/object/IrisDirection.java +++ b/src/main/java/com/volmit/iris/object/IrisDirection.java @@ -13,538 +13,424 @@ import org.bukkit.util.Vector; * @author cyberpwn */ @Desc("A direction object") -public enum IrisDirection -{ - UP_POSITIVE_Y(0, 1, 0, CuboidDirection.Up), - DOWN_NEGATIVE_Y(0, -1, 0, CuboidDirection.Down), - NORTH_NEGATIVE_Z(0, 0, -1, CuboidDirection.North), - SOUTH_POSITIVE_Z(0, 0, 1, CuboidDirection.South), - EAST_POSITIVE_X(1, 0, 0, CuboidDirection.East), - WEST_NEGATIVE_X(-1, 0, 0, CuboidDirection.West); +public enum IrisDirection { + UP_POSITIVE_Y(0, 1, 0, CuboidDirection.Up), + DOWN_NEGATIVE_Y(0, -1, 0, CuboidDirection.Down), + NORTH_NEGATIVE_Z(0, 0, -1, CuboidDirection.North), + SOUTH_POSITIVE_Z(0, 0, 1, CuboidDirection.South), + EAST_POSITIVE_X(1, 0, 0, CuboidDirection.East), + WEST_NEGATIVE_X(-1, 0, 0, CuboidDirection.West); - private static KMap, DOP> permute = null; + private static KMap, DOP> permute = null; - private int x; - private int y; - private int z; - private CuboidDirection f; + private final int x; + private final int y; + private final int z; + private final CuboidDirection f; - public static IrisDirection getDirection(BlockFace f) - { - switch(f) - { - case DOWN: - return DOWN_NEGATIVE_Y; - case EAST: - case EAST_NORTH_EAST: - case EAST_SOUTH_EAST: - return EAST_POSITIVE_X; - case NORTH: - case NORTH_NORTH_WEST: - case NORTH_EAST: - case NORTH_NORTH_EAST: - case NORTH_WEST: - return NORTH_NEGATIVE_Z; - case SELF: - case UP: - return UP_POSITIVE_Y; - case SOUTH: - case SOUTH_EAST: - case SOUTH_SOUTH_EAST: - case SOUTH_SOUTH_WEST: - case SOUTH_WEST: - return SOUTH_POSITIVE_Z; - case WEST: - case WEST_NORTH_WEST: - case WEST_SOUTH_WEST: - return WEST_NEGATIVE_X; - } + public static IrisDirection getDirection(BlockFace f) { + switch (f) { + case DOWN: + return DOWN_NEGATIVE_Y; + case EAST: + case EAST_NORTH_EAST: + case EAST_SOUTH_EAST: + return EAST_POSITIVE_X; + case NORTH: + case NORTH_NORTH_WEST: + case NORTH_EAST: + case NORTH_NORTH_EAST: + case NORTH_WEST: + return NORTH_NEGATIVE_Z; + case SELF: + case UP: + return UP_POSITIVE_Y; + case SOUTH: + case SOUTH_EAST: + case SOUTH_SOUTH_EAST: + case SOUTH_SOUTH_WEST: + case SOUTH_WEST: + return SOUTH_POSITIVE_Z; + case WEST: + case WEST_NORTH_WEST: + case WEST_SOUTH_WEST: + return WEST_NEGATIVE_X; + } - return DOWN_NEGATIVE_Y; - } - - public static IrisDirection fromJigsawBlock(String direction) { - for(IrisDirection i : IrisDirection.values()) - { - if(i.name().toLowerCase().split("\\Q_\\E")[0] - .equals(direction.split("\\Q_\\E")[0])) - { - return i; - } - } - - return null; + return DOWN_NEGATIVE_Y; } - public static IrisDirection getDirection(Jigsaw.Orientation orientation) { - switch(orientation) - { - case DOWN_EAST: - case UP_EAST: - case EAST_UP: - return EAST_POSITIVE_X; - case DOWN_NORTH: - case UP_NORTH: - case NORTH_UP: - return NORTH_NEGATIVE_Z; - case DOWN_SOUTH: - case UP_SOUTH: - case SOUTH_UP: - return SOUTH_POSITIVE_Z; - case DOWN_WEST: - case UP_WEST: - case WEST_UP: - return WEST_NEGATIVE_X; - } + public static IrisDirection fromJigsawBlock(String direction) { + for (IrisDirection i : IrisDirection.values()) { + if (i.name().toLowerCase().split("\\Q_\\E")[0] + .equals(direction.split("\\Q_\\E")[0])) { + return i; + } + } - return null; - } + return null; + } - @Override - public String toString() - { - switch(this) - { - case DOWN_NEGATIVE_Y: - return "Down"; - case EAST_POSITIVE_X: - return "East"; - case NORTH_NEGATIVE_Z: - return "North"; - case SOUTH_POSITIVE_Z: - return "South"; - case UP_POSITIVE_Y: - return "Up"; - case WEST_NEGATIVE_X: - return "West"; - } + public static IrisDirection getDirection(Jigsaw.Orientation orientation) { + switch (orientation) { + case DOWN_EAST: + case UP_EAST: + case EAST_UP: + return EAST_POSITIVE_X; + case DOWN_NORTH: + case UP_NORTH: + case NORTH_UP: + return NORTH_NEGATIVE_Z; + case DOWN_SOUTH: + case UP_SOUTH: + case SOUTH_UP: + return SOUTH_POSITIVE_Z; + case DOWN_WEST: + case UP_WEST: + case WEST_UP: + return WEST_NEGATIVE_X; + } - return "?"; - } + return null; + } - public boolean isVertical() - { - return equals(DOWN_NEGATIVE_Y) || equals(UP_POSITIVE_Y); - } + @Override + public String toString() { + switch (this) { + case DOWN_NEGATIVE_Y: + return "Down"; + case EAST_POSITIVE_X: + return "East"; + case NORTH_NEGATIVE_Z: + return "North"; + case SOUTH_POSITIVE_Z: + return "South"; + case UP_POSITIVE_Y: + return "Up"; + case WEST_NEGATIVE_X: + return "West"; + } - public static IrisDirection closest(Vector v) - { - double m = Double.MAX_VALUE; - IrisDirection s = null; + return "?"; + } - for(IrisDirection i : values()) - { - Vector x = i.toVector(); - double g = x.distance(v); + public boolean isVertical() { + return equals(DOWN_NEGATIVE_Y) || equals(UP_POSITIVE_Y); + } - if(g < m) - { - m = g; - s = i; - } - } + public static IrisDirection closest(Vector v) { + double m = Double.MAX_VALUE; + IrisDirection s = null; - return s; - } + for (IrisDirection i : values()) { + Vector x = i.toVector(); + double g = x.distance(v); - public static IrisDirection closest(Vector v, IrisDirection... d) - { - double m = Double.MAX_VALUE; - IrisDirection s = null; + if (g < m) { + m = g; + s = i; + } + } - for(IrisDirection i : d) - { - Vector x = i.toVector(); - double g = x.distance(v); + return s; + } - if(g < m) - { - m = g; - s = i; - } - } + public static IrisDirection closest(Vector v, IrisDirection... d) { + double m = Double.MAX_VALUE; + IrisDirection s = null; - return s; - } + for (IrisDirection i : d) { + Vector x = i.toVector(); + double g = x.distance(v); - public static IrisDirection closest(Vector v, KList d) - { - double m = Double.MAX_VALUE; - IrisDirection s = null; + if (g < m) { + m = g; + s = i; + } + } - for(IrisDirection i : d) - { - Vector x = i.toVector(); - double g = x.distance(v); + return s; + } - if(g < m) - { - m = g; - s = i; - } - } + public static IrisDirection closest(Vector v, KList d) { + double m = Double.MAX_VALUE; + IrisDirection s = null; - return s; - } + for (IrisDirection i : d) { + Vector x = i.toVector(); + double g = x.distance(v); - public Vector toVector() - { - return new Vector(x, y, z); - } + if (g < m) { + m = g; + s = i; + } + } - public boolean isCrooked(IrisDirection to) - { - if(equals(to.reverse())) - { - return false; - } + return s; + } - return !equals(to); - } + public Vector toVector() { + return new Vector(x, y, z); + } - private IrisDirection(int x, int y, int z, CuboidDirection f) - { - this.x = x; - this.y = y; - this.z = z; - this.f = f; - } + public boolean isCrooked(IrisDirection to) { + if (equals(to.reverse())) { + return false; + } - public Vector angle(Vector initial, IrisDirection d) - { - calculatePermutations(); + return !equals(to); + } - for(GBiset i : permute.keySet()) - { - if(i.getA().equals(this) && i.getB().equals(d)) - { - return permute.get(i).op(initial); - } - } + IrisDirection(int x, int y, int z, CuboidDirection f) { + this.x = x; + this.y = y; + this.z = z; + this.f = f; + } - return initial; - } + public Vector angle(Vector initial, IrisDirection d) { + calculatePermutations(); - 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; - } + for (GBiset i : permute.keySet()) { + if (i.getA().equals(this) && i.getB().equals(d)) { + return permute.get(i).op(initial); + } + } - return EAST_POSITIVE_X; - } + return initial; + } - public int x() - { - return x; - } + 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; + } - public int y() - { - return y; - } + return EAST_POSITIVE_X; + } - public int z() - { - return z; - } + public int x() { + return x; + } - public CuboidDirection f() - { - return f; - } + public int y() { + return y; + } - public static KList news() - { - return new KList().add(NORTH_NEGATIVE_Z, EAST_POSITIVE_X, WEST_NEGATIVE_X, SOUTH_POSITIVE_Z); - } + public int z() { + return z; + } - public static IrisDirection getDirection(Vector v) - { - Vector k = VectorMath.triNormalize(v.clone().normalize()); + public CuboidDirection f() { + return f; + } - for(IrisDirection i : udnews()) - { - if(i.x == k.getBlockX() && i.y == k.getBlockY() && i.z == k.getBlockZ()) - { - return i; - } - } + public static KList news() { + return new KList().add(NORTH_NEGATIVE_Z, EAST_POSITIVE_X, WEST_NEGATIVE_X, SOUTH_POSITIVE_Z); + } - return IrisDirection.NORTH_NEGATIVE_Z; - } + public static IrisDirection getDirection(Vector v) { + Vector k = VectorMath.triNormalize(v.clone().normalize()); - 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); - } + for (IrisDirection i : udnews()) { + if (i.x == k.getBlockX() && i.y == k.getBlockY() && i.z == k.getBlockZ()) { + return i; + } + } - /** - * 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; - } + return IrisDirection.NORTH_NEGATIVE_Z; + } - if(b == 0) - { - return DOWN_NEGATIVE_Y; - } + 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); + } - else if(b == 1) - { - return UP_POSITIVE_Y; - } + /** + * 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; + } - else if(b == 2) - { - return NORTH_NEGATIVE_Z; - } + 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; + } + } - else if(b == 3) - { - return SOUTH_POSITIVE_Z; - } + /** + * 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; + } - else if(b == 4) - { - return WEST_NEGATIVE_X; - } + return -1; + } - else - { - return EAST_POSITIVE_X; - } - } + public static void calculatePermutations() { + if (permute != null) { + return; + } - /** - * 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; - } + permute = new KMap, DOP>(); - return -1; - } + for (IrisDirection i : udnews()) { + for (IrisDirection j : udnews()) { + GBiset b = new GBiset(i, j); - public static void calculatePermutations() - { - if(permute != null) - { - return; - } + 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; + } + }); + } + } + } + } - permute = new KMap, DOP>(); + public BlockFace getFace() { + switch (this) { + case DOWN_NEGATIVE_Y: + return BlockFace.DOWN; + case EAST_POSITIVE_X: + return BlockFace.EAST; + case NORTH_NEGATIVE_Z: + return BlockFace.NORTH; + case SOUTH_POSITIVE_Z: + return BlockFace.SOUTH; + case UP_POSITIVE_Y: + return BlockFace.UP; + case WEST_NEGATIVE_X: + return BlockFace.WEST; + } - for(IrisDirection i : udnews()) - { - for(IrisDirection j : udnews()) - { - GBiset b = new GBiset(i, j); + return null; + } - if(i.equals(j)) - { - permute.put(b, new DOP("DIRECT") - { - @Override - public Vector op(Vector v) - { - return v; - } - }); - } + public Axis getAxis() { + switch (this) { + case DOWN_NEGATIVE_Y: + case UP_POSITIVE_Y: + return Axis.Y; + case EAST_POSITIVE_X: + case WEST_NEGATIVE_X: + return Axis.X; + case NORTH_NEGATIVE_Z: + case SOUTH_POSITIVE_Z: + return Axis.Z; + } - 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; - } - }); - } - } - } - } - - public BlockFace getFace() - { - switch(this) - { - case DOWN_NEGATIVE_Y: - return BlockFace.DOWN; - case EAST_POSITIVE_X: - return BlockFace.EAST; - case NORTH_NEGATIVE_Z: - return BlockFace.NORTH; - case SOUTH_POSITIVE_Z: - return BlockFace.SOUTH; - case UP_POSITIVE_Y: - return BlockFace.UP; - case WEST_NEGATIVE_X: - return BlockFace.WEST; - } - - return null; - } - - public Axis getAxis() - { - switch(this) - { - case DOWN_NEGATIVE_Y: - case UP_POSITIVE_Y: - return Axis.Y; - case EAST_POSITIVE_X: - case WEST_NEGATIVE_X: - return Axis.X; - case NORTH_NEGATIVE_Z: - case SOUTH_POSITIVE_Z: - return Axis.Z; - } - - return null; - } + return null; + } } diff --git a/src/main/java/com/volmit/iris/object/IrisEffect.java b/src/main/java/com/volmit/iris/object/IrisEffect.java index 88f925f77..479b67daa 100644 --- a/src/main/java/com/volmit/iris/object/IrisEffect.java +++ b/src/main/java/com/volmit/iris/object/IrisEffect.java @@ -20,273 +20,251 @@ import org.bukkit.potion.PotionEffectType; @AllArgsConstructor @Desc("An iris effect") @Data -public class IrisEffect -{ +public class IrisEffect { - @DontObfuscate - @Desc("The potion effect to apply in this area") - private String potionEffect = ""; + @DontObfuscate + @Desc("The potion effect to apply in this area") + private String potionEffect = ""; - @DontObfuscate - @Desc("The particle effect to apply in the area") - private Particle particleEffect = null; + @DontObfuscate + @Desc("The particle effect to apply in the area") + private Particle particleEffect = null; - @DependsOn({"particleEffect"}) - @MinNumber(-32) - @MaxNumber(32) - @DontObfuscate - @Desc("Randomly offset from the surface to this surface+value") - private int particleOffset = 0; + @DependsOn({"particleEffect"}) + @MinNumber(-32) + @MaxNumber(32) + @DontObfuscate + @Desc("Randomly offset from the surface to this surface+value") + private int particleOffset = 0; - @DependsOn({"particleEffect"}) - @MinNumber(-8) - @MaxNumber(8) - @DontObfuscate - @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) + @DontObfuscate + @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) - @DontObfuscate - @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) + @DontObfuscate + @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) - @DontObfuscate - @Desc("The alt z, usually represents motion if the particle count is zero. Otherwise an offset.") - private double particleAltZ = 0; + @DependsOn({"particleEffect"}) + @MinNumber(-8) + @MaxNumber(8) + @DontObfuscate + @Desc("The alt z, usually represents motion if the particle count is zero. Otherwise an offset.") + private double particleAltZ = 0; - @DependsOn({"particleEffect"}) - @DontObfuscate - @Desc("Randomize the altX by -altX to altX") - private boolean randomAltX = true; + @DependsOn({"particleEffect"}) + @DontObfuscate + @Desc("Randomize the altX by -altX to altX") + private boolean randomAltX = true; - @DependsOn({"particleEffect"}) - @DontObfuscate - @Desc("Randomize the altY by -altY to altY") - private boolean randomAltY = false; + @DependsOn({"particleEffect"}) + @DontObfuscate + @Desc("Randomize the altY by -altY to altY") + private boolean randomAltY = false; - @DependsOn({"particleEffect"}) - @DontObfuscate - @Desc("Randomize the altZ by -altZ to altZ") - private boolean randomAltZ = true; + @DependsOn({"particleEffect"}) + @DontObfuscate + @Desc("Randomize the altZ by -altZ to altZ") + private boolean randomAltZ = true; - @DontObfuscate - @Desc("The sound to play") - private Sound sound = null; + @DontObfuscate + @Desc("The sound to play") + private Sound sound = null; - @DependsOn({"sound"}) - @MinNumber(0) - @MaxNumber(512) - @DontObfuscate - @Desc("The max distance from the player the sound will play") - private int soundDistance = 12; + @DependsOn({"sound"}) + @MinNumber(0) + @MaxNumber(512) + @DontObfuscate + @Desc("The max distance from the player the sound will play") + private int soundDistance = 12; - @DependsOn({"sound", "maxPitch"}) - @MinNumber(0.01) - @MaxNumber(1.99) - @DontObfuscate - @Desc("The minimum sound pitch") - private double minPitch = 0.5D; + @DependsOn({"sound", "maxPitch"}) + @MinNumber(0.01) + @MaxNumber(1.99) + @DontObfuscate + @Desc("The minimum sound pitch") + private double minPitch = 0.5D; - @DependsOn({"sound", "minVolume"}) - @MinNumber(0.01) - @MaxNumber(1.99) - @DontObfuscate - @Desc("The max sound pitch") - private double maxPitch = 1.5D; + @DependsOn({"sound", "minVolume"}) + @MinNumber(0.01) + @MaxNumber(1.99) + @DontObfuscate + @Desc("The max sound pitch") + private double maxPitch = 1.5D; - @DependsOn({"sound"}) - @MinNumber(0.001) - @MaxNumber(512) - @DontObfuscate - @Desc("The sound volume.") - private double volume = 1.5D; + @DependsOn({"sound"}) + @MinNumber(0.001) + @MaxNumber(512) + @DontObfuscate + @Desc("The sound volume.") + private double volume = 1.5D; - @DependsOn({"particleEffect"}) - @MinNumber(0) - @MaxNumber(512) - @DontObfuscate - @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(512) + @DontObfuscate + @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) - @DontObfuscate - @Desc("How far away from the player particles can play") - private int particleDistance = 20; + @DependsOn({"particleEffect"}) + @MinNumber(0) + @MaxNumber(64) + @DontObfuscate + @Desc("How far away from the player particles can play") + private int particleDistance = 20; - @DependsOn({"particleEffect"}) - @MinNumber(0) - @MaxNumber(128) - @DontObfuscate - @Desc("How wide the particles can play (player's view left and right) RADIUS") - private int particleDistanceWidth = 24; + @DependsOn({"particleEffect"}) + @MinNumber(0) + @MaxNumber(128) + @DontObfuscate + @Desc("How wide the particles can play (player's view left and right) RADIUS") + private int particleDistanceWidth = 24; - @DependsOn({"particleEffect"}) - @DontObfuscate - @Desc("An extra value for some particles... Which bukkit doesn't even document.") - private double extra = 0; + @DependsOn({"particleEffect"}) + @DontObfuscate + @Desc("An extra value for some particles... Which bukkit doesn't even document.") + private double extra = 0; - @DependsOn({"potionEffect"}) - @MinNumber(-1) - @MaxNumber(1024) - @DontObfuscate - @Desc("The Potion Strength or -1 to disable") - private int potionStrength = -1; + @DependsOn({"potionEffect"}) + @MinNumber(-1) + @MaxNumber(1024) + @DontObfuscate + @Desc("The Potion Strength or -1 to disable") + private int potionStrength = -1; - @DependsOn({"potionEffect", "potionTicksMin"}) - @MinNumber(1) - @DontObfuscate - @Desc("The max time the potion will last for") - private int potionTicksMax = 155; + @DependsOn({"potionEffect", "potionTicksMin"}) + @MinNumber(1) + @DontObfuscate + @Desc("The max time the potion will last for") + private int potionTicksMax = 155; - @DependsOn({"potionEffect", "potionTicksMax"}) - @MinNumber(1) - @DontObfuscate - @Desc("The min time the potion will last for") - private int potionTicksMin = 75; + @DependsOn({"potionEffect", "potionTicksMax"}) + @MinNumber(1) + @DontObfuscate + @Desc("The min time the potion will last for") + private int potionTicksMin = 75; - @Required - @MinNumber(0) - @DontObfuscate - @Desc("The effect interval in milliseconds") - private int interval = 150; + @Required + @MinNumber(0) + @DontObfuscate + @Desc("The effect interval in milliseconds") + private int interval = 150; - @DependsOn({"particleEffect"}) - @MinNumber(0) - @MaxNumber(16) - @DontObfuscate - @Desc("The effect distance start away") - private int particleAway = 5; + @DependsOn({"particleEffect"}) + @MinNumber(0) + @MaxNumber(16) + @DontObfuscate + @Desc("The effect distance start away") + private int particleAway = 5; - @Required - @MinNumber(1) - @DontObfuscate - @Desc("The chance is 1 in CHANCE per interval") - private int chance = 50; + @Required + @MinNumber(1) + @DontObfuscate + @Desc("The chance is 1 in CHANCE per interval") + private int chance = 50; - private final transient AtomicCache pt = new AtomicCache<>(); - private final transient AtomicCache latch = new AtomicCache<>(); + private final transient AtomicCache pt = new AtomicCache<>(); + private final transient AtomicCache latch = new AtomicCache<>(); - public boolean canTick() - { - return latch.aquire(() -> new ChronoLatch(interval)).flip(); - } + public boolean canTick() { + return latch.aquire(() -> new ChronoLatch(interval)).flip(); + } - public PotionEffectType getRealType() - { - return pt.aquire(() -> - { - PotionEffectType t = PotionEffectType.LUCK; + public PotionEffectType getRealType() { + return pt.aquire(() -> + { + PotionEffectType t = PotionEffectType.LUCK; - if(getPotionEffect().isEmpty()) - { - return t; - } + if (getPotionEffect().isEmpty()) { + return t; + } - try - { - for(PotionEffectType i : PotionEffectType.values()) - { - if(i.getName().toUpperCase().replaceAll("\\Q \\E", "_").equals(getPotionEffect())) - { - t = i; + try { + for (PotionEffectType i : PotionEffectType.values()) { + if (i.getName().toUpperCase().replaceAll("\\Q \\E", "_").equals(getPotionEffect())) { + t = i; - return t; - } - } - } + return t; + } + } + } catch (Throwable e) { - catch(Throwable e) - { + } - } + Iris.warn("Unknown Potion Effect Type: " + getPotionEffect()); - Iris.warn("Unknown Potion Effect Type: " + getPotionEffect()); + return t; + }); + } - return t; - }); - } + public void apply(Player p, GeneratorAccess g) { + if (!canTick()) { + return; + } - public void apply(Player p, GeneratorAccess g) - { - if(!canTick()) - { - return; - } + if (RNG.r.nextInt(chance) != 0) { + return; + } - if(RNG.r.nextInt(chance) != 0) - { - return; - } + if (sound != null) { + Location part = p.getLocation().clone().add(RNG.r.i(-soundDistance, soundDistance), RNG.r.i(-soundDistance, soundDistance), RNG.r.i(-soundDistance, soundDistance)); - if(sound != null) - { - Location part = p.getLocation().clone().add(RNG.r.i(-soundDistance, soundDistance), RNG.r.i(-soundDistance, soundDistance), RNG.r.i(-soundDistance, soundDistance)); + J.s(() -> { + p.playSound(part, getSound(), (float) volume, (float) RNG.r.d(minPitch, maxPitch)); + }); + } - J.s(() -> { - p.playSound(part, getSound(), (float) volume, (float) RNG.r.d(minPitch, maxPitch)); - }); - } + if (particleEffect != 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))); - if(particleEffect != 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()); + if (extra != 0) { + J.s(() -> { + p.spawnParticle(particleEffect, 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 { + J.s(() -> { + p.spawnParticle(particleEffect, 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); + }); + } + } - part.setY(Math.round(g.getHeight(part.getBlockX(), part.getBlockZ())) + 1); - part.add(RNG.r.d(), 0, RNG.r.d()); - if(extra != 0) - { - J.s(() -> { - p.spawnParticle(particleEffect, 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); - }); - } + if (potionStrength > -1) { + if (p.hasPotionEffect(getRealType())) { + PotionEffect e = p.getPotionEffect(getRealType()); + if (e.getAmplifier() > getPotionStrength()) { + return; + } - else - { - J.s(() -> { - p.spawnParticle(particleEffect, 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); - }); - } - } + J.s(() -> { + p.removePotionEffect(getRealType()); + }); + } - if(potionStrength > -1) - { - if(p.hasPotionEffect(getRealType())) - { - PotionEffect e = p.getPotionEffect(getRealType()); - if(e.getAmplifier() > getPotionStrength()) - { - return; - } - - J.s(() -> { - p.removePotionEffect(getRealType()); - }); - } - - J.s(() -> { - p.addPotionEffect(new PotionEffect(getRealType(), - RNG.r.i(Math.min(potionTicksMax, potionTicksMin), - Math.max(potionTicksMax, potionTicksMin)), - getPotionStrength(), - true, false, false)); - }); - } - } + J.s(() -> { + p.addPotionEffect(new PotionEffect(getRealType(), + RNG.r.i(Math.min(potionTicksMax, potionTicksMin), + Math.max(potionTicksMax, potionTicksMin)), + getPotionStrength(), + true, false, false)); + }); + } + } } diff --git a/src/main/java/com/volmit/iris/object/IrisEnchantment.java b/src/main/java/com/volmit/iris/object/IrisEnchantment.java index 6efb06c3f..cd0fee53a 100644 --- a/src/main/java/com/volmit/iris/object/IrisEnchantment.java +++ b/src/main/java/com/volmit/iris/object/IrisEnchantment.java @@ -1,95 +1,73 @@ package com.volmit.iris.object; -import java.lang.reflect.Field; - -import org.bukkit.enchantments.Enchantment; -import org.bukkit.inventory.meta.EnchantmentStorageMeta; -import org.bukkit.inventory.meta.ItemMeta; - -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.MaxNumber; -import com.volmit.iris.util.MinNumber; -import com.volmit.iris.util.RNG; -import com.volmit.iris.util.Required; - +import com.volmit.iris.util.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; +import org.bukkit.enchantments.Enchantment; +import org.bukkit.inventory.meta.EnchantmentStorageMeta; +import org.bukkit.inventory.meta.ItemMeta; + +import java.lang.reflect.Field; @Accessors(chain = true) @NoArgsConstructor @AllArgsConstructor @Desc("Represents an enchantment & level") @Data -public class IrisEnchantment -{ +public class IrisEnchantment { - @Required - @DontObfuscate - @Desc("The enchantment") - private String enchantment = ""; + @Required + @DontObfuscate + @Desc("The enchantment") + private String enchantment = ""; - @MinNumber(1) - @DontObfuscate - @Desc("Minimum amount of this loot") - private int minLevel = 1; + @MinNumber(1) + @DontObfuscate + @Desc("Minimum amount of this loot") + private int minLevel = 1; - @MinNumber(1) - @DontObfuscate - @Desc("Maximum amount of this loot") - private int maxLevel = 1; + @MinNumber(1) + @DontObfuscate + @Desc("Maximum amount of this loot") + private int maxLevel = 1; - @MinNumber(0) - @MaxNumber(1) - @DontObfuscate - @Desc("The chance that this enchantment is applied (0 to 1)") - private double chance = 1; + @MinNumber(0) + @MaxNumber(1) + @DontObfuscate + @Desc("The chance that this enchantment is applied (0 to 1)") + private double chance = 1; - public void apply(RNG rng, ItemMeta meta) - { - try - { - if(rng.nextDouble() < chance) - { - if (meta instanceof EnchantmentStorageMeta) { - ((EnchantmentStorageMeta) meta).addStoredEnchant(getEnchant(), getLevel(rng), true); - return; - } - meta.addEnchant(getEnchant(), getLevel(rng), true); - } - } + public void apply(RNG rng, ItemMeta meta) { + try { + if (rng.nextDouble() < chance) { + if (meta instanceof EnchantmentStorageMeta) { + ((EnchantmentStorageMeta) meta).addStoredEnchant(getEnchant(), getLevel(rng), true); + return; + } + meta.addEnchant(getEnchant(), getLevel(rng), true); + } + } catch (Throwable e) { - catch(Throwable e) - { + } + } - } - } + public Enchantment getEnchant() { + for (Field i : Enchantment.class.getDeclaredFields()) { + if (i.getType().equals(Enchantment.class) && i.getName().equals(getEnchantment())) { + try { + return (Enchantment) i.get(null); + } catch (IllegalArgumentException | IllegalAccessException e) { + e.printStackTrace(); + } + } + } - public Enchantment getEnchant() - { - for(Field i : Enchantment.class.getDeclaredFields()) - { - if(i.getType().equals(Enchantment.class) && i.getName().equals(getEnchantment())) - { - try - { - return (Enchantment) i.get(null); - } + return null; + } - catch(IllegalArgumentException | IllegalAccessException e) - { - e.printStackTrace(); - } - } - } - - return null; - } - - public int getLevel(RNG rng) - { - return rng.i(getMinLevel(), getMaxLevel()); - } + public int getLevel(RNG rng) { + return rng.i(getMinLevel(), getMaxLevel()); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisEntity.java b/src/main/java/com/volmit/iris/object/IrisEntity.java index 474038b39..a365241aa 100644 --- a/src/main/java/com/volmit/iris/object/IrisEntity.java +++ b/src/main/java/com/volmit/iris/object/IrisEntity.java @@ -31,295 +31,264 @@ import java.util.concurrent.atomic.AtomicReference; @Desc("Represents an iris entity.") @Data @EqualsAndHashCode(callSuper = false) -public class IrisEntity extends IrisRegistrant -{ - @Required - @DontObfuscate - @Desc("The type of entity to spawn. To spawn a mythic mob, set this type to unknown and define mythic type.") - private EntityType type = EntityType.UNKNOWN; +public class IrisEntity extends IrisRegistrant { + @Required + @DontObfuscate + @Desc("The type of entity to spawn. To spawn a mythic mob, set this type to unknown and define mythic type.") + private EntityType type = EntityType.UNKNOWN; - @RegistryListMythical - @Desc("The type of mythic mob (if mythic mobs is installed). If this is set, make sure to set 'type' to UNKNOWN") - @DontObfuscate - private String mythicalType = ""; + @RegistryListMythical + @Desc("The type of mythic mob (if mythic mobs is installed). If this is set, make sure to set 'type' to UNKNOWN") + @DontObfuscate + private String mythicalType = ""; - @DontObfuscate - @Desc("The custom name of this entity") - private String customName = ""; + @DontObfuscate + @Desc("The custom name of this entity") + private String customName = ""; - @DontObfuscate - @Desc("Should the name on this entity be visible even if you arent looking at it.") - private boolean customNameVisible = false; + @DontObfuscate + @Desc("Should the name on this entity be visible even if you arent looking at it.") + private boolean customNameVisible = false; - @DontObfuscate - @Desc("If this entity type is a mob, should it be aware of it's surroundings & interact with the world.") - private boolean aware = true; + @DontObfuscate + @Desc("If this entity type is a mob, should it be aware of it's surroundings & interact with the world.") + private boolean aware = true; - @DontObfuscate - @Desc("If this entity type is a creature, should it have ai goals.") - private boolean ai = true; + @DontObfuscate + @Desc("If this entity type is a creature, should it have ai goals.") + private boolean ai = true; - @DontObfuscate - @Desc("Should this entity be glowing") - private boolean glowing = false; + @DontObfuscate + @Desc("Should this entity be glowing") + private boolean glowing = false; - @DontObfuscate - @Desc("Should gravity apply to this entity") - private boolean gravity = true; + @DontObfuscate + @Desc("Should gravity apply to this entity") + private boolean gravity = true; - @DontObfuscate - @Desc("When an entity is invulnerable it can only be damaged by players increative mode.") - private boolean invulnerable = false; + @DontObfuscate + @Desc("When an entity is invulnerable it can only be damaged by players increative mode.") + private boolean invulnerable = false; - @DontObfuscate - @Desc("When an entity is silent it will not produce any sound.") - private boolean silent = false; + @DontObfuscate + @Desc("When an entity is silent it will not produce any sound.") + private boolean silent = false; - @DontObfuscate - @Desc("Should this entity be allowed to pickup items") - private boolean pickupItems = false; + @DontObfuscate + @Desc("Should this entity be allowed to pickup items") + private boolean pickupItems = false; - @DontObfuscate - @Desc("Should this entity be removed when far away") - private boolean removable = true; + @DontObfuscate + @Desc("Should this entity be removed when far away") + private boolean removable = true; - @DontObfuscate - @Desc("Entity helmet equipment") - private IrisLoot helmet = null; + @DontObfuscate + @Desc("Entity helmet equipment") + private IrisLoot helmet = null; - @DontObfuscate - @Desc("Entity chestplate equipment") - private IrisLoot chestplate = null; + @DontObfuscate + @Desc("Entity chestplate equipment") + private IrisLoot chestplate = null; - @DontObfuscate - @Desc("Entity boots equipment") - private IrisLoot boots = null; + @DontObfuscate + @Desc("Entity boots equipment") + private IrisLoot boots = null; - @DontObfuscate - @Desc("Entity leggings equipment") - private IrisLoot leggings = null; + @DontObfuscate + @Desc("Entity leggings equipment") + private IrisLoot leggings = null; - @DontObfuscate - @Desc("Entity main hand equipment") - private IrisLoot mainHand = null; + @DontObfuscate + @Desc("Entity main hand equipment") + private IrisLoot mainHand = null; - @DontObfuscate - @Desc("Entity off hand equipment") - private IrisLoot offHand = null; + @DontObfuscate + @Desc("Entity off hand equipment") + private IrisLoot offHand = null; - @DontObfuscate - @Desc("Make other entities ride this entity") - @ArrayType(min = 1, type = IrisEntity.class) - private KList passengers = new KList<>(); + @DontObfuscate + @Desc("Make other entities ride this entity") + @ArrayType(min = 1, type = IrisEntity.class) + private KList passengers = new KList<>(); - @DontObfuscate - @Desc("Attribute modifiers for this entity") - @ArrayType(min = 1, type = IrisAttributeModifier.class) - private KList attributes = new KList<>(); + @DontObfuscate + @Desc("Attribute modifiers for this entity") + @ArrayType(min = 1, type = IrisAttributeModifier.class) + private KList attributes = new KList<>(); - @DontObfuscate - @Desc("Loot tables for drops") - private IrisLootReference loot = new IrisLootReference(); + @DontObfuscate + @Desc("Loot tables for drops") + private IrisLootReference loot = new IrisLootReference(); - @DontObfuscate - @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; + @DontObfuscate + @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; - @DontObfuscate - @Desc("The main gene for a panda if the entity type is a panda") - private Gene pandaMainGene = Gene.NORMAL; + @DontObfuscate + @Desc("The main gene for a panda if the entity type is a panda") + private Gene pandaMainGene = Gene.NORMAL; - @DontObfuscate - @Desc("The hidden gene for a panda if the entity type is a panda") - private Gene pandaHiddenGene = Gene.NORMAL; + @DontObfuscate + @Desc("The hidden gene for a panda if the entity type is a panda") + private Gene pandaHiddenGene = Gene.NORMAL; - @DontObfuscate - @Desc("The this entity is ageable, set it's baby status") - private boolean baby = false; + @DontObfuscate + @Desc("The this entity is ageable, set it's baby status") + private boolean baby = false; - public Entity spawn(Engine gen, Location at) - { - return spawn(gen, at, new RNG(at.hashCode())); - } + public Entity spawn(Engine gen, Location at) { + return spawn(gen, at, new RNG(at.hashCode())); + } - public Entity spawn(Engine gen, Location at, RNG rng) - { - Entity e = doSpawn(at); - 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(true); + public Entity spawn(Engine gen, Location at, RNG rng) { + Entity e = doSpawn(at); + 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(true); - int gg = 0; - for(IrisEntity i : passengers) - { - e.addPassenger(i.spawn(gen, at, rng.nextParallelRNG(234858 + gg++))); - } + int gg = 0; + for (IrisEntity i : passengers) { + e.addPassenger(i.spawn(gen, at, rng.nextParallelRNG(234858 + gg++))); + } - if(e instanceof Attributable) - { - Attributable a = (Attributable) e; + if (e instanceof Attributable) { + Attributable a = (Attributable) e; - for(IrisAttributeModifier i : getAttributes()) - { - i.apply(rng, a); - } - } + for (IrisAttributeModifier i : getAttributes()) { + i.apply(rng, a); + } + } - if(e instanceof Lootable) - { - Lootable l = (Lootable) e; + if (e instanceof Lootable) { + Lootable l = (Lootable) e; - if(getLoot().getTables().isNotEmpty()) - { - l.setLootTable(new LootTable() - { - @Override - public NamespacedKey getKey() - { - return new NamespacedKey(Iris.instance, "loot-" + IrisEntity.this.hashCode()); - } + if (getLoot().getTables().isNotEmpty()) { + l.setLootTable(new LootTable() { + @Override + public NamespacedKey getKey() { + return new NamespacedKey(Iris.instance, "loot-" + IrisEntity.this.hashCode()); + } - @Override - public Collection populateLoot(Random random, LootContext context) - { - KList items = new KList<>(); + @Override + public Collection populateLoot(Random random, LootContext context) { + KList items = new KList<>(); - for(String fi : getLoot().getTables()) - { - IrisLootTable i = gen.getData().getLootLoader().load(fi); - items.addAll(i.getLoot(gen.isStudio(), false, rng.nextParallelRNG(345911), InventorySlotType.STORAGE, at.getBlockX(), at.getBlockY(), at.getBlockZ(), 8, 4)); - } + for (String fi : getLoot().getTables()) { + IrisLootTable i = gen.getData().getLootLoader().load(fi); + items.addAll(i.getLoot(gen.isStudio(), false, rng.nextParallelRNG(345911), InventorySlotType.STORAGE, at.getBlockX(), at.getBlockY(), at.getBlockZ(), 8, 4)); + } - return items; - } + return items; + } - @Override - public void fillInventory(Inventory inventory, Random random, LootContext context) - { - for(ItemStack i : populateLoot(random, context)) - { - inventory.addItem(i); - } + @Override + public void fillInventory(Inventory inventory, Random random, LootContext context) { + for (ItemStack i : populateLoot(random, context)) { + inventory.addItem(i); + } - gen.getCompound().getEngine(at.getBlockY()).scramble(inventory, rng); - } - }); - } - } + gen.getCompound().getEngine(at.getBlockY()).scramble(inventory, rng); + } + }); + } + } - if(e instanceof LivingEntity) - { - LivingEntity l = (LivingEntity) e; - l.setAI(isAi()); - l.setCanPickupItems(isPickupItems()); + 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))); - } + if (getLeashHolder() != null) { + l.setLeashHolder(getLeashHolder().spawn(gen, at, rng.nextParallelRNG(234548))); + } - l.setRemoveWhenFarAway(isRemovable()); + l.setRemoveWhenFarAway(isRemovable()); - if(getHelmet() != null && rng.i(1, getHelmet().getRarity()) == 1) - { - l.getEquipment().setHelmet(getHelmet().get(gen.isStudio(), rng)); - } + if (getHelmet() != null && rng.i(1, getHelmet().getRarity()) == 1) { + l.getEquipment().setHelmet(getHelmet().get(gen.isStudio(), rng)); + } - if(getChestplate() != null && rng.i(1, getChestplate().getRarity()) == 1) - { - l.getEquipment().setChestplate(getChestplate().get(gen.isStudio(), rng)); - } + if (getChestplate() != null && rng.i(1, getChestplate().getRarity()) == 1) { + l.getEquipment().setChestplate(getChestplate().get(gen.isStudio(), rng)); + } - if(getLeggings() != null && rng.i(1, getLeggings().getRarity()) == 1) - { - l.getEquipment().setLeggings(getLeggings().get(gen.isStudio(), rng)); - } + if (getLeggings() != null && rng.i(1, getLeggings().getRarity()) == 1) { + l.getEquipment().setLeggings(getLeggings().get(gen.isStudio(), rng)); + } - if(getBoots() != null && rng.i(1, getBoots().getRarity()) == 1) - { - l.getEquipment().setBoots(getBoots().get(gen.isStudio(), rng)); - } + if (getBoots() != null && rng.i(1, getBoots().getRarity()) == 1) { + l.getEquipment().setBoots(getBoots().get(gen.isStudio(), rng)); + } - if(getMainHand() != null && rng.i(1, getMainHand().getRarity()) == 1) - { - l.getEquipment().setItemInMainHand(getMainHand().get(gen.isStudio(), rng)); - } + if (getMainHand() != null && rng.i(1, getMainHand().getRarity()) == 1) { + l.getEquipment().setItemInMainHand(getMainHand().get(gen.isStudio(), rng)); + } - if(getOffHand() != null && rng.i(1, getOffHand().getRarity()) == 1) - { - l.getEquipment().setItemInOffHand(getOffHand().get(gen.isStudio(), rng)); - } - } + if (getOffHand() != null && rng.i(1, getOffHand().getRarity()) == 1) { + l.getEquipment().setItemInOffHand(getOffHand().get(gen.isStudio(), rng)); + } + } - if(e instanceof Ageable && isBaby()) - { - ((Ageable) e).setBaby(); - } + if (e instanceof Ageable && isBaby()) { + ((Ageable) e).setBaby(); + } - if(e instanceof Panda) - { - ((Panda) e).setMainGene(getPandaMainGene()); - ((Panda) e).setMainGene(getPandaHiddenGene()); - } + if (e instanceof Panda) { + ((Panda) e).setMainGene(getPandaMainGene()); + ((Panda) e).setMainGene(getPandaHiddenGene()); + } - if (e instanceof Villager) { - Villager villager = (Villager) e; - villager.setRemoveWhenFarAway(false); - Bukkit.getScheduler().scheduleSyncDelayedTask(Iris.instance, () -> { - villager.setPersistent(true); - villager.setCustomName(" "); - villager.setCustomNameVisible(false); - },1); - } + if (e instanceof Villager) { + Villager villager = (Villager) e; + villager.setRemoveWhenFarAway(false); + Bukkit.getScheduler().scheduleSyncDelayedTask(Iris.instance, () -> { + villager.setPersistent(true); + villager.setCustomName(" "); + villager.setCustomNameVisible(false); + }, 1); + } - if(Iris.awareEntities && e instanceof Mob) - { - Mob m = (Mob) e; - m.setAware(isAware()); - } + if (Iris.awareEntities && e instanceof Mob) { + Mob m = (Mob) e; + m.setAware(isAware()); + } - return e; - } + return e; + } - private Entity doSpawn(Location at) - { - 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<>(); - J.s(() -> ae.set(doSpawn(at))); - PrecisionStopwatch p = PrecisionStopwatch.start(); + private Entity doSpawn(Location at) { + 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<>(); + J.s(() -> ae.set(doSpawn(at))); + PrecisionStopwatch p = PrecisionStopwatch.start(); - while(ae == null) - { - J.sleep(3); - } + while (ae == null) { + J.sleep(3); + } - return ae.get(); - } + return ae.get(); + } - if(isMythical()) - { - return Iris.linkMythicMobs.spawn(getMythicalType(), at); - } + if (isMythical()) { + return Iris.linkMythicMobs.spawn(getMythicalType(), at); + } - return at.getWorld().spawnEntity(at, getType()); - } + return at.getWorld().spawnEntity(at, getType()); + } - public boolean isMythical() - { - return Iris.linkMythicMobs.supported() && !getMythicalType().trim().isEmpty(); - } + public boolean isMythical() { + return Iris.linkMythicMobs.supported() && !getMythicalType().trim().isEmpty(); + } - public boolean isCitizens() - { - return false; + public boolean isCitizens() { + return false; - // TODO: return Iris.linkCitizens.supported() && someType is not empty; - } + // TODO: return Iris.linkCitizens.supported() && someType is not empty; + } } diff --git a/src/main/java/com/volmit/iris/object/IrisEntityInitialSpawn.java b/src/main/java/com/volmit/iris/object/IrisEntityInitialSpawn.java index bc9a44d02..ab73b5725 100644 --- a/src/main/java/com/volmit/iris/object/IrisEntityInitialSpawn.java +++ b/src/main/java/com/volmit/iris/object/IrisEntityInitialSpawn.java @@ -16,70 +16,61 @@ import org.bukkit.entity.Entity; @AllArgsConstructor @Desc("Represents an entity spawn during initial chunk generation") @Data -public class IrisEntityInitialSpawn -{ - @RegistryListEntity - @Required - @DontObfuscate - @Desc("The entity") - private String entity = ""; +public class IrisEntityInitialSpawn { + @RegistryListEntity + @Required + @DontObfuscate + @Desc("The entity") + private String entity = ""; - @MinNumber(1) - @DontObfuscate - @Desc("The 1 in RARITY chance for this entity to spawn") - private int rarity = 1; + @MinNumber(1) + @DontObfuscate + @Desc("The 1 in RARITY chance for this entity to spawn") + private int rarity = 1; - @MinNumber(1) - @DontObfuscate - @Desc("The minumum of this entity to spawn") - private int minSpawns = 1; + @MinNumber(1) + @DontObfuscate + @Desc("The minumum of this entity to spawn") + private int minSpawns = 1; - @MinNumber(1) - @DontObfuscate - @Desc("The max of this entity to spawn") - private int maxSpawns = 1; + @MinNumber(1) + @DontObfuscate + @Desc("The max of this entity to spawn") + private int maxSpawns = 1; - private final transient AtomicCache rng = new AtomicCache<>(); - private final transient AtomicCache ent = new AtomicCache<>(); + private final transient AtomicCache rng = new AtomicCache<>(); + private final transient AtomicCache ent = new AtomicCache<>(); - public void spawn(Engine gen, Chunk c, RNG rng) - { - int spawns = rng.i(1, rarity) == 1 ? rng.i(minSpawns, maxSpawns) : 0; + public void spawn(Engine gen, Chunk c, RNG rng) { + int spawns = rng.i(1, rarity) == 1 ? rng.i(minSpawns, maxSpawns) : 0; - if(spawns > 0) - { - for(int i = 0; i < spawns; i++) - { - int x = (c.getX() * 16) + rng.i(15); - int z = (c.getZ() * 16) + rng.i(15); - int h = gen.getHeight(x, z) + gen.getMinHeight(); - spawn100(gen, new Location(c.getWorld(), x, h, z)); - } - } - } + if (spawns > 0) { + for (int i = 0; i < spawns; i++) { + int x = (c.getX() * 16) + rng.i(15); + int z = (c.getZ() * 16) + rng.i(15); + int h = gen.getHeight(x, z) + gen.getMinHeight(); + spawn100(gen, new Location(c.getWorld(), x, h, z)); + } + } + } - public IrisEntity getRealEntity(Engine g) - { - return ent.aquire(() -> g.getData().getEntityLoader().load(getEntity())); - } + 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; - } + public Entity spawn(Engine g, Location at) { + if (getRealEntity(g) == null) { + return null; + } - if(rng.aquire(() -> new RNG(g.getTarget().getWorld().getSeed() + 4)).i(1, getRarity()) == 1) - { - return spawn100(g, at); - } + if (rng.aquire(() -> new RNG(g.getTarget().getWorld().getSeed() + 4)).i(1, getRarity()) == 1) { + return spawn100(g, at); + } - return null; - } + return null; + } - private Entity spawn100(Engine g, Location at) - { - return getRealEntity(g).spawn(g, at.clone().add(0.5, 1, 0.5), rng.aquire(() -> new RNG(g.getTarget().getWorld().getSeed() + 4))); - } + private Entity spawn100(Engine g, Location at) { + return getRealEntity(g).spawn(g, at.clone().add(0.5, 1, 0.5), rng.aquire(() -> new RNG(g.getTarget().getWorld().getSeed() + 4))); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisEntitySpawnOverride.java b/src/main/java/com/volmit/iris/object/IrisEntitySpawnOverride.java index 3b2522bf2..66cb48f64 100644 --- a/src/main/java/com/volmit/iris/object/IrisEntitySpawnOverride.java +++ b/src/main/java/com/volmit/iris/object/IrisEntitySpawnOverride.java @@ -17,74 +17,65 @@ import org.bukkit.event.entity.EntitySpawnEvent; @AllArgsConstructor @Desc("Represents an entity spawn") @Data -public class IrisEntitySpawnOverride -{ - - @RegistryListEntity - @Required - @DontObfuscate - @Desc("The entity") - private String entity = ""; +public class IrisEntitySpawnOverride { - - @Required - @DontObfuscate - @Desc("If the following entity type spawns, spawn this entity. Set to unknown for any entity spawn") - private EntityType trigger = EntityType.UNKNOWN; - - - @DontObfuscate - @Desc("If the source is triggered, cancel spawning the original entity instead of ADDING a new entity.") - private boolean cancelSourceSpawn = false; - - - @MinNumber(1) - @DontObfuscate - @Desc("The 1 in RARITY chance for this entity to spawn") - private int rarity = 1; - - private final transient AtomicCache rng = new AtomicCache<>(); - private final transient AtomicCache ent = new AtomicCache<>(); + @RegistryListEntity + @Required + @DontObfuscate + @Desc("The entity") + private String entity = ""; - public Entity on(Engine g, Location at, EntityType t, EntitySpawnEvent ee) - { - if(!trigger.equals(EntityType.UNKNOWN)) - { - if(!trigger.equals(t)) - { - return null; - } - } + @Required + @DontObfuscate + @Desc("If the following entity type spawns, spawn this entity. Set to unknown for any entity spawn") + private EntityType trigger = EntityType.UNKNOWN; - Entity e = spawn(g, at); - if(e != null && isCancelSourceSpawn()) - { - ee.setCancelled(true); - ee.getEntity().remove(); - } + @DontObfuscate + @Desc("If the source is triggered, cancel spawning the original entity instead of ADDING a new entity.") + private boolean cancelSourceSpawn = false; - return e; - } - public Entity spawn(Engine g, Location at) - { - if(getRealEntity(g) == null) - { - return null; - } + @MinNumber(1) + @DontObfuscate + @Desc("The 1 in RARITY chance for this entity to spawn") + private int rarity = 1; - if(rng.aquire(() -> new RNG(g.getTarget().getWorld().getSeed() + 4)).i(1, getRarity()) == 1) - { - return getRealEntity(g).spawn(g, at, rng.aquire(() -> new RNG(g.getTarget().getWorld().getSeed() + 4))); - } + private final transient AtomicCache rng = new AtomicCache<>(); + private final transient AtomicCache ent = new AtomicCache<>(); - return null; - } - public IrisEntity getRealEntity(Engine g) - { - return ent.aquire(() -> g.getData().getEntityLoader().load(getEntity())); - } + public Entity on(Engine g, Location at, EntityType t, EntitySpawnEvent ee) { + if (!trigger.equals(EntityType.UNKNOWN)) { + if (!trigger.equals(t)) { + return null; + } + } + + Entity e = spawn(g, at); + + if (e != null && isCancelSourceSpawn()) { + ee.setCancelled(true); + ee.getEntity().remove(); + } + + return e; + } + + public Entity spawn(Engine g, Location at) { + if (getRealEntity(g) == null) { + return null; + } + + if (rng.aquire(() -> new RNG(g.getTarget().getWorld().getSeed() + 4)).i(1, getRarity()) == 1) { + return getRealEntity(g).spawn(g, at, rng.aquire(() -> new RNG(g.getTarget().getWorld().getSeed() + 4))); + } + + return null; + } + + public IrisEntity getRealEntity(Engine g) { + return ent.aquire(() -> g.getData().getEntityLoader().load(getEntity())); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisFeature.java b/src/main/java/com/volmit/iris/object/IrisFeature.java index 0e1937220..3c043d2b3 100644 --- a/src/main/java/com/volmit/iris/object/IrisFeature.java +++ b/src/main/java/com/volmit/iris/object/IrisFeature.java @@ -73,13 +73,12 @@ public class IrisFeature { private transient AtomicCache actualRadius = new AtomicCache<>(); - public double getActualRadius() - { - return actualRadius.aquire(() -> IrisInterpolation.getRealRadius(getInterpolator(),getInterpolationRadius())); + + public double getActualRadius() { + return actualRadius.aquire(() -> IrisInterpolation.getRealRadius(getInterpolator(), getInterpolationRadius())); } - public static IrisFeature read(DataInputStream s) throws IOException - { + public static IrisFeature read(DataInputStream s) throws IOException { return new Gson().fromJson(s.readUTF(), IrisFeature.class); } diff --git a/src/main/java/com/volmit/iris/object/IrisFeaturePositional.java b/src/main/java/com/volmit/iris/object/IrisFeaturePositional.java index f74767126..d8a71f336 100644 --- a/src/main/java/com/volmit/iris/object/IrisFeaturePositional.java +++ b/src/main/java/com/volmit/iris/object/IrisFeaturePositional.java @@ -15,8 +15,7 @@ import java.io.IOException; @NoArgsConstructor @Desc("Represents an Iris zone") public class IrisFeaturePositional { - public IrisFeaturePositional(int x, int z, IrisFeature feature) - { + public IrisFeaturePositional(int x, int z, IrisFeature feature) { this.x = x; this.z = z; this.feature = feature; @@ -40,8 +39,7 @@ public class IrisFeaturePositional { private transient AtomicCache provider = new AtomicCache<>(); private static double BLOCK = 1D / 256D; // TODO: WARNING HEIGHT - public static IrisFeaturePositional read(DataInputStream s) throws IOException - { + public static IrisFeaturePositional read(DataInputStream s) throws IOException { return new Gson().fromJson(s.readUTF(), IrisFeaturePositional.class); } @@ -49,60 +47,45 @@ public class IrisFeaturePositional { s.writeUTF(new Gson().toJson(this)); } - public boolean shouldFilter(double x, double z) - { + public boolean shouldFilter(double x, double z) { double actualRadius = getFeature().getActualRadius(); double dist2 = distance2(x, z); - if(getFeature().isInvertZone()) { + if (getFeature().isInvertZone()) { if (dist2 < Math.pow(getFeature().getBlockRadius() - actualRadius, 2)) { return false; } } - if(dist2 > Math.pow(getFeature().getBlockRadius() + actualRadius, 2)) - { - return false; - } - - return true; + return !(dist2 > Math.pow(getFeature().getBlockRadius() + actualRadius, 2)); } - public double getStrength(double x, double z) - { + public double getStrength(double x, double z) { double actualRadius = getFeature().getActualRadius(); double dist2 = distance2(x, z); - if(getFeature().isInvertZone()) - { - if (dist2 < Math.pow(getFeature().getBlockRadius() - actualRadius, 2)) - { + if (getFeature().isInvertZone()) { + if (dist2 < Math.pow(getFeature().getBlockRadius() - actualRadius, 2)) { return 0; } NoiseProvider d = provider.aquire(this::getNoiseProvider); - double s = IrisInterpolation.getNoise(getFeature().getInterpolator(), (int)x, (int)z, getFeature().getInterpolationRadius(), d); + double s = IrisInterpolation.getNoise(getFeature().getInterpolator(), (int) x, (int) z, getFeature().getInterpolationRadius(), d); - if(s <= 0) - { + if (s <= 0) { return 0; } return getFeature().getStrength() * s; - } - - else - { - if(dist2 > Math.pow(getFeature().getBlockRadius() + actualRadius, 2)) - { + } else { + if (dist2 > Math.pow(getFeature().getBlockRadius() + actualRadius, 2)) { return 0; } NoiseProvider d = provider.aquire(this::getNoiseProvider); - double s = IrisInterpolation.getNoise(getFeature().getInterpolator(), (int)x, (int)z, getFeature().getInterpolationRadius(), d); + double s = IrisInterpolation.getNoise(getFeature().getInterpolator(), (int) x, (int) z, getFeature().getInterpolationRadius(), d); - if(s <= 0) - { + if (s <= 0) { return 0; } @@ -110,10 +93,8 @@ public class IrisFeaturePositional { } } - public double getObjectChanceModifier(double x, double z) - { - if(getFeature().getObjectChance()>=1) - { + public double getObjectChanceModifier(double x, double z) { + if (getFeature().getObjectChance() >= 1) { return getFeature().getObjectChance(); } @@ -123,15 +104,13 @@ public class IrisFeaturePositional { public double filter(double x, double z, double noise) { double s = getStrength(x, z); - if(s <= 0) - { + if (s <= 0) { return noise; } double fx = noise; - if(getFeature().getConvergeToHeight() >= 0) - { + if (getFeature().getConvergeToHeight() >= 0) { fx = getFeature().getConvergeToHeight(); } @@ -150,13 +129,9 @@ public class IrisFeaturePositional { } private NoiseProvider getNoiseProvider() { - if(getFeature().isInvertZone()) - { + if (getFeature().isInvertZone()) { return (x, z) -> distance(x, z) > getFeature().getBlockRadius() ? 1D : 0D; - } - - else - { + } else { return (x, z) -> distance(x, z) < getFeature().getBlockRadius() ? 1D : 0D; } } diff --git a/src/main/java/com/volmit/iris/object/IrisFeaturePotential.java b/src/main/java/com/volmit/iris/object/IrisFeaturePotential.java index f31bb2b38..9e1f17d70 100644 --- a/src/main/java/com/volmit/iris/object/IrisFeaturePotential.java +++ b/src/main/java/com/volmit/iris/object/IrisFeaturePotential.java @@ -19,8 +19,7 @@ public class IrisFeaturePotential { @Desc("") private IrisFeature zone = new IrisFeature(); - public boolean hasZone(RNG rng, int cx, int cz) - { + public boolean hasZone(RNG rng, int cx, int cz) { return rng.nextInt(rarity) == 0; } } diff --git a/src/main/java/com/volmit/iris/object/IrisGenerator.java b/src/main/java/com/volmit/iris/object/IrisGenerator.java index 7b4871eed..d84c8826b 100644 --- a/src/main/java/com/volmit/iris/object/IrisGenerator.java +++ b/src/main/java/com/volmit/iris/object/IrisGenerator.java @@ -1,328 +1,274 @@ package com.volmit.iris.object; -import java.util.List; - import com.volmit.iris.Iris; -import com.volmit.iris.scaffold.cache.AtomicCache; import com.volmit.iris.generator.noise.CellGenerator; -import com.volmit.iris.util.ArrayType; -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.IRare; -import com.volmit.iris.util.IrisInterpolation; -import com.volmit.iris.util.KList; -import com.volmit.iris.util.MaxNumber; -import com.volmit.iris.util.MinNumber; -import com.volmit.iris.util.RNG; -import com.volmit.iris.util.Required; - +import com.volmit.iris.scaffold.cache.AtomicCache; +import com.volmit.iris.util.*; 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 -{ - @MinNumber(0.001) - @DontObfuscate - @Desc("The zoom or frequency.") - private double zoom = 1; +public class IrisGenerator extends IrisRegistrant { + @MinNumber(0.001) + @DontObfuscate + @Desc("The zoom or frequency.") + private double zoom = 1; - @MinNumber(0) - @DontObfuscate - @Desc("The opacity, essentially a multiplier on the output.") - private double opacity = 1; + @MinNumber(0) + @DontObfuscate + @Desc("The opacity, essentially a multiplier on the output.") + private double opacity = 1; - @DontObfuscate - @Desc("Multiply the compsites instead of adding them") - private boolean multiplicitive = false; + @DontObfuscate + @Desc("Multiply the compsites instead of adding them") + private boolean multiplicitive = false; - @MinNumber(0.001) - @DontObfuscate - @Desc("The size of the cell fractures") - private double cellFractureZoom = 1D; + @MinNumber(0.001) + @DontObfuscate + @Desc("The size of the cell fractures") + private double cellFractureZoom = 1D; - @MinNumber(0) - @DontObfuscate - @Desc("Cell Fracture Coordinate Shuffling") - private double cellFractureShuffle = 12D; + @MinNumber(0) + @DontObfuscate + @Desc("Cell Fracture Coordinate Shuffling") + private double cellFractureShuffle = 12D; - @DontObfuscate - @Desc("The height of fracture cells. Set to 0 to disable") - private double cellFractureHeight = 0D; + @DontObfuscate + @Desc("The height of fracture cells. Set to 0 to disable") + private double cellFractureHeight = 0D; - @MinNumber(0) - @MaxNumber(1) - @DontObfuscate - @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; + @MinNumber(0) + @MaxNumber(1) + @DontObfuscate + @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; - @DontObfuscate - @Desc("The offset to shift this noise x") - private double offsetX = 0; + @DontObfuscate + @Desc("The offset to shift this noise x") + private double offsetX = 0; - @DontObfuscate - @Desc("The offset to shift this noise z") - private double offsetZ = 0; + @DontObfuscate + @Desc("The offset to shift this noise z") + private double offsetZ = 0; - @Required - @DontObfuscate - @Desc("The seed for this generator") - private long seed = 1; + @Required + @DontObfuscate + @Desc("The seed for this generator") + private long seed = 1; - @Required - @DontObfuscate - @Desc("The interpolator to use when smoothing this generator into other regions & generators") - private IrisInterpolator interpolator = new IrisInterpolator(); + @Required + @DontObfuscate + @Desc("The interpolator to use when smoothing this generator into other regions & generators") + private IrisInterpolator interpolator = new IrisInterpolator(); - @MinNumber(0) - @MaxNumber(8192) - @DontObfuscate - @Desc("Cliff Height Max. Disable with 0 for min and max") - private double cliffHeightMax = 0; + @MinNumber(0) + @MaxNumber(8192) + @DontObfuscate + @Desc("Cliff Height Max. Disable with 0 for min and max") + private double cliffHeightMax = 0; - @MinNumber(0) - @MaxNumber(8192) - @DontObfuscate - @Desc("Cliff Height Min. Disable with 0 for min and max") - private double cliffHeightMin = 0; + @MinNumber(0) + @MaxNumber(8192) + @DontObfuscate + @Desc("Cliff Height Min. Disable with 0 for min and max") + private double cliffHeightMin = 0; - @ArrayType(min = 1, type = IrisNoiseGenerator.class) - @DontObfuscate - @Desc("The list of noise gens this gen contains.") - private KList composite = new KList(); + @ArrayType(min = 1, type = IrisNoiseGenerator.class) + @DontObfuscate + @Desc("The list of noise gens this gen contains.") + private KList composite = new KList(); - @DontObfuscate - @Desc("The noise gen for cliff height.") - private IrisNoiseGenerator cliffHeightGenerator = new IrisNoiseGenerator(); + @DontObfuscate + @Desc("The noise gen for cliff height.") + private IrisNoiseGenerator cliffHeightGenerator = new IrisNoiseGenerator(); - private final transient AtomicCache cellGen = new AtomicCache<>(); + private final transient AtomicCache cellGen = new AtomicCache<>(); - public double getMax() - { - return opacity; - } + public double getMax() { + return opacity; + } - public boolean hasCliffs() - { - return cliffHeightMax > 0; - } + public boolean hasCliffs() { + return cliffHeightMax > 0; + } - public CellGenerator getCellGenerator(long seed) - { - return cellGen.aquire(() -> new CellGenerator(new RNG(seed + 239466))); - } + public CellGenerator getCellGenerator(long seed) { + return cellGen.aquire(() -> new CellGenerator(new RNG(seed + 239466))); + } - public T fitRarity(KList b, long superSeed, double rx, double rz) - { - if(b.size() == 0) - { - return null; - } + public T fitRarity(KList b, long superSeed, double rx, double rz) { + if (b.size() == 0) { + return null; + } - if(b.size() == 1) - { - return b.get(0); - } + if (b.size() == 1) { + return b.get(0); + } - KList rarityMapped = new KList<>(); - boolean o = false; - int max = 1; - for(T i : b) - { - if(i.getRarity() > max) - { - max = i.getRarity(); - } - } + KList rarityMapped = new KList<>(); + boolean o = false; + int max = 1; + for (T i : b) { + if (i.getRarity() > max) { + max = i.getRarity(); + } + } - max++; + max++; - for(T i : b) - { - for(int j = 0; j < max - i.getRarity(); j++) - { - if(o = !o) - { - rarityMapped.add(i); - } + for (T i : b) { + for (int j = 0; j < max - i.getRarity(); j++) { + if (o = !o) { + rarityMapped.add(i); + } else { + rarityMapped.add(0, i); + } + } + } - else - { - rarityMapped.add(0, i); - } - } - } + if (rarityMapped.size() == 1) { + return rarityMapped.get(0); + } - if(rarityMapped.size() == 1) - { - return rarityMapped.get(0); - } + if (rarityMapped.isEmpty()) { + throw new RuntimeException("BAD RARITY MAP! RELATED TO: " + b.toString(", or possibly ")); + } - if(rarityMapped.isEmpty()) - { - throw new RuntimeException("BAD RARITY MAP! RELATED TO: " + b.toString(", or possibly ")); - } + return fit(rarityMapped, superSeed, rx, rz); + } - return fit(rarityMapped, superSeed, rx, rz); - } + public T fit(T[] v, long superSeed, double rx, double rz) { + if (v.length == 0) { + return null; + } - public T fit(T[] v, long superSeed, double rx, double rz) - { - if(v.length == 0) - { - return null; - } + if (v.length == 1) { + return v[0]; + } - if(v.length == 1) - { - return v[0]; - } + return v[fit(0, v.length - 1, superSeed, rx, rz)]; + } - 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; + } - 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); + } - if(v.size() == 1) - { - return v.get(0); - } + return v.get(fit(0, v.size() - 1, superSeed, rx, rz)); + } - 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; + } - public int fit(int min, int max, long superSeed, double rx, double rz) - { - if(min == max) - { - return min; - } + double noise = getHeight(rx, rz, superSeed); - double noise = getHeight(rx, rz, superSeed); + return (int) Math.round(IrisInterpolation.lerp(min, max, noise)); + } - 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); + } - 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); - double noise = getHeight(rx, rz, superSeed); + return (int) Math.round(IrisInterpolation.lerp(min, max, noise)); + } - 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; + } - public double fitDouble(double min, double max, long superSeed, double rx, double rz) - { - if(min == max) - { - return min; - } + double noise = getHeight(rx, rz, superSeed); - double noise = getHeight(rx, rz, superSeed); + return IrisInterpolation.lerp(min, max, noise); + } - return IrisInterpolation.lerp(min, max, noise); - } + public double getHeight(double rx, double rz, long superSeed) { + return getHeight(rx, 0, rz, superSeed); + } - public double getHeight(double rx, double rz, long superSeed) - { - return getHeight(rx, 0, rz, superSeed); - } + public double getHeight(double rx, double ry, double rz, long superSeed) { + if (composite.isEmpty()) { + Iris.warn("Useless Generator: Composite is empty in " + getLoadKey()); + return 0; + } - public double getHeight(double rx, double ry, double rz, long superSeed) - { - if(composite.isEmpty()) - { - Iris.warn("Useless Generator: Composite is empty in " + getLoadKey()); - return 0; - } + int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * seed + offsetX + offsetZ); + double h = 0; + double tp = multiplicitive ? 1 : 0; - int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * seed + offsetX + offsetZ); - double h = 0; - double tp = multiplicitive ? 1 : 0; + for (IrisNoiseGenerator i : composite) { + if (multiplicitive) { + tp *= i.getOpacity(); + h *= i.getNoise(seed + superSeed + hc, (rx + offsetX) / zoom, (rz + offsetZ) / zoom); + } else { + tp += i.getOpacity(); + h += i.getNoise(seed + superSeed + hc, (rx + offsetX) / zoom, (rz + offsetZ) / zoom); + } + } - for(IrisNoiseGenerator i : composite) - { - if(multiplicitive) - { - tp *= i.getOpacity(); - h *= i.getNoise(seed + superSeed + hc, (rx + offsetX) / zoom, (rz + offsetZ) / zoom); - } + double v = multiplicitive ? h * opacity : (h / tp) * opacity; - else - { - tp += i.getOpacity(); - h += i.getNoise(seed + superSeed + hc, (rx + offsetX) / zoom, (rz + offsetZ) / zoom); - } - } + if (Double.isNaN(v)) { + Iris.warn("Nan value on gen: " + getLoadKey() + ": H = " + h + " TP = " + tp + " OPACITY = " + opacity + " ZOOM = " + zoom); + } - double v = multiplicitive ? h * opacity : (h / tp) * opacity; + v = hasCliffs() ? cliff(rx, rz, v, superSeed + 294596 + hc) : v; + v = hasCellCracks() ? cell(rx, rz, v, superSeed + 48622 + hc) : v; - if(Double.isNaN(v)) - { - Iris.warn("Nan value on gen: " + getLoadKey() + ": H = " + h + " TP = " + tp + " OPACITY = " + opacity + " ZOOM = " + zoom); - } + return v; + } - v = hasCliffs() ? cliff(rx, rz, v, superSeed + 294596 + hc) : v; - v = hasCellCracks() ? cell(rx, rz, v, superSeed + 48622 + hc) : v; + public double cell(double rx, double rz, double v, double superSeed) { + getCellGenerator(seed + 46222).setShuffle(getCellFractureShuffle()); + return getCellGenerator(seed + 46222).getDistance(rx / getCellFractureZoom(), rz / getCellFractureZoom()) > getCellPercentSize() ? (v * getCellFractureHeight()) : v; + } - return v; - } + private boolean hasCellCracks() { + return getCellFractureHeight() != 0; + } - public double cell(double rx, double rz, double v, double superSeed) - { - getCellGenerator(seed + 46222).setShuffle(getCellFractureShuffle()); - return getCellGenerator(seed + 46222).getDistance(rx / getCellFractureZoom(), rz / getCellFractureZoom()) > getCellPercentSize() ? (v * getCellFractureHeight()) : v; - } + public double getCliffHeight(double rx, double rz, double superSeed) { + int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * seed + offsetX + offsetZ); + double h = cliffHeightGenerator.getNoise((long) (seed + superSeed + hc), (rx + offsetX) / zoom, (rz + offsetZ) / zoom); + return IrisInterpolation.lerp(cliffHeightMin, cliffHeightMax, h); + } - private boolean hasCellCracks() - { - return getCellFractureHeight() != 0; - } + 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 double getCliffHeight(double rx, double rz, double superSeed) - { - int hc = (int) ((cliffHeightMin * 10) + 10 + cliffHeightMax * seed + offsetX + offsetZ); - double h = cliffHeightGenerator.getNoise((long) (seed + superSeed + hc), (rx + offsetX) / zoom, (rz + offsetZ) / zoom); - return IrisInterpolation.lerp(cliffHeightMin, cliffHeightMax, h); - } + public IrisGenerator rescale(double scale) { + zoom /= scale; + return this; + } - 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 KList getAllComposites() { + KList g = new KList<>(); - public IrisGenerator rescale(double scale) - { - zoom /= scale; - return this; - } + for (IrisNoiseGenerator i : composite) { + g.addAll(i.getAllComposites()); + } - public KList getAllComposites() { - KList g = new KList<>(); - - for(IrisNoiseGenerator i : composite) - { - g.addAll(i.getAllComposites()); - } - - return g; - } + return g; + } } diff --git a/src/main/java/com/volmit/iris/object/IrisGeneratorStyle.java b/src/main/java/com/volmit/iris/object/IrisGeneratorStyle.java index cddf7d95e..b825a61c9 100644 --- a/src/main/java/com/volmit/iris/object/IrisGeneratorStyle.java +++ b/src/main/java/com/volmit/iris/object/IrisGeneratorStyle.java @@ -1,14 +1,8 @@ package com.volmit.iris.object; -import com.volmit.iris.scaffold.cache.AtomicCache; import com.volmit.iris.generator.noise.CNG; -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.MaxNumber; -import com.volmit.iris.util.MinNumber; -import com.volmit.iris.util.RNG; -import com.volmit.iris.util.Required; - +import com.volmit.iris.scaffold.cache.AtomicCache; +import com.volmit.iris.util.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -19,69 +13,63 @@ import lombok.experimental.Accessors; @AllArgsConstructor @Desc("A gen style") @Data -public class IrisGeneratorStyle -{ +public class IrisGeneratorStyle { - @Required - @DontObfuscate - @Desc("The chance is 1 in CHANCE per interval") - private NoiseStyle style = NoiseStyle.IRIS; + @Required + @DontObfuscate + @Desc("The chance is 1 in CHANCE per interval") + private NoiseStyle style = NoiseStyle.IRIS; - @DontObfuscate - @MinNumber(0.00001) - @Desc("The zoom of this style") - private double zoom = 1; + @DontObfuscate + @MinNumber(0.00001) + @Desc("The zoom of this style") + private double zoom = 1; - @DontObfuscate - @MinNumber(0.00001) - @Desc("The Output multiplier. Only used if parent is fracture.") - private double multiplier = 1; + @DontObfuscate + @MinNumber(0.00001) + @Desc("The Output multiplier. Only used if parent is fracture.") + private double multiplier = 1; - @DontObfuscate - @Desc("If set to true, each dimension will be fractured with a different order of input coordinates. This is usually 2 or 3 times slower than normal.") - private boolean maxFractureAccuracy = false; + @DontObfuscate + @Desc("If set to true, each dimension will be fractured with a different order of input coordinates. This is usually 2 or 3 times slower than normal.") + private boolean maxFractureAccuracy = false; - @DontObfuscate - @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; + @DontObfuscate + @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; - @DontObfuscate - @MinNumber(0.01562) - @MaxNumber(64) - @Desc("The exponent") - private double exponent = 1; + @DontObfuscate + @MinNumber(0.01562) + @MaxNumber(64) + @Desc("The exponent") + private double exponent = 1; - private final transient AtomicCache cng = new AtomicCache(); + private final transient AtomicCache cng = new AtomicCache(); - public IrisGeneratorStyle(NoiseStyle s) - { - this.style = s; - } + public IrisGeneratorStyle(NoiseStyle s) { + this.style = s; + } - public IrisGeneratorStyle zoomed(double z) - { - this.zoom = z; - return this; - } + public IrisGeneratorStyle zoomed(double z) { + this.zoom = z; + return this; + } - public CNG create(RNG rng) - { - return cng.aquire(() -> - { - CNG cng = style.create(rng).bake().scale(1D / zoom).pow(exponent).bake(); - cng.setTrueFracturing(maxFractureAccuracy); + public CNG create(RNG rng) { + return cng.aquire(() -> + { + CNG cng = style.create(rng).bake().scale(1D / zoom).pow(exponent).bake(); + cng.setTrueFracturing(maxFractureAccuracy); - if(fracture != null) - { - cng.fractureWith(fracture.create(rng.nextParallelRNG(2934)), fracture.getMultiplier()); - } + if (fracture != null) { + cng.fractureWith(fracture.create(rng.nextParallelRNG(2934)), fracture.getMultiplier()); + } - return cng; - }); - } + return cng; + }); + } - public boolean isFlat() - { - return style.equals(NoiseStyle.FLAT); - } + public boolean isFlat() { + return style.equals(NoiseStyle.FLAT); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisInterpolator.java b/src/main/java/com/volmit/iris/object/IrisInterpolator.java index 977e4c296..d173129da 100644 --- a/src/main/java/com/volmit/iris/object/IrisInterpolator.java +++ b/src/main/java/com/volmit/iris/object/IrisInterpolator.java @@ -1,13 +1,6 @@ package com.volmit.iris.object; -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.IrisInterpolation; -import com.volmit.iris.util.MaxNumber; -import com.volmit.iris.util.MinNumber; -import com.volmit.iris.util.NoiseProvider; -import com.volmit.iris.util.Required; - +import com.volmit.iris.util.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -18,28 +11,25 @@ import lombok.experimental.Accessors; @AllArgsConstructor @Desc("Configures rotation for iris") @Data -public class IrisInterpolator -{ +public class IrisInterpolator { - @Required - @DontObfuscate - @Desc("The interpolation method when two biomes use different heights but this same generator") - private InterpolationMethod function = InterpolationMethod.BICUBIC; + @Required + @DontObfuscate + @Desc("The interpolation method when two biomes use different heights but this same generator") + private InterpolationMethod function = InterpolationMethod.BICUBIC; - @Required - @MinNumber(1) - @MaxNumber(8192) - @DontObfuscate - @Desc("The range checked horizontally. Smaller ranges yeild more detail but are not as smooth.") - private double horizontalScale = 3; + @Required + @MinNumber(1) + @MaxNumber(8192) + @DontObfuscate + @Desc("The range checked horizontally. Smaller ranges yeild more detail but are not as smooth.") + private double horizontalScale = 3; - public double interpolate(double x, double z, NoiseProvider provider) - { - return interpolate((int) Math.round(x), (int) Math.round(z), provider); - } + 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 double interpolate(int x, int z, NoiseProvider provider) { + return IrisInterpolation.getNoise(getFunction(), x, z, getHorizontalScale(), provider); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisJigsawPiece.java b/src/main/java/com/volmit/iris/object/IrisJigsawPiece.java index 6bd52f0a9..375c09d93 100644 --- a/src/main/java/com/volmit/iris/object/IrisJigsawPiece.java +++ b/src/main/java/com/volmit/iris/object/IrisJigsawPiece.java @@ -18,89 +18,84 @@ import java.io.IOException; @Desc("Represents a structure tile") @Data @EqualsAndHashCode(callSuper = false) -public class IrisJigsawPiece extends IrisRegistrant -{ - @RegistryListObject - @Required - @DontObfuscate - @Desc("The object this piece represents") - private String object = ""; +public class IrisJigsawPiece extends IrisRegistrant { + @RegistryListObject + @Required + @DontObfuscate + @Desc("The object this piece represents") + private String object = ""; - @Required - @DontObfuscate - @ArrayType(type = IrisJigsawPieceConnector.class, min = 1) - @Desc("The connectors this object contains") - private KList connectors = new KList<>(); + @Required + @DontObfuscate + @ArrayType(type = IrisJigsawPieceConnector.class, min = 1) + @Desc("The connectors this object contains") + private KList connectors = new KList<>(); - @Desc("Configure everything about the object placement. Please don't define this unless you actually need it as using this option will slow down the jigsaw deign stage. Use this where you need it, just avoid using it everywhere to keep things fast.") - @DontObfuscate - private IrisObjectPlacement placementOptions = new IrisObjectPlacement().setMode(ObjectPlaceMode.FAST_MAX_HEIGHT); + @Desc("Configure everything about the object placement. Please don't define this unless you actually need it as using this option will slow down the jigsaw deign stage. Use this where you need it, just avoid using it everywhere to keep things fast.") + @DontObfuscate + private IrisObjectPlacement placementOptions = new IrisObjectPlacement().setMode(ObjectPlaceMode.FAST_MAX_HEIGHT); - private transient AtomicCache max2dDim = new AtomicCache<>(); - private transient AtomicCache max3dDim = new AtomicCache<>(); + private transient AtomicCache max2dDim = new AtomicCache<>(); + private transient AtomicCache max3dDim = new AtomicCache<>(); - public int getMax2dDimension() { - return max2dDim.aquire(() -> { - try { - BlockVector v = IrisObject.sampleSize(getLoader().getObjectLoader().findFile(getObject())); - return Math.max(v.getBlockX(), v.getBlockZ()); - } catch (IOException e) { - e.printStackTrace(); - } + public int getMax2dDimension() { + return max2dDim.aquire(() -> { + try { + BlockVector v = IrisObject.sampleSize(getLoader().getObjectLoader().findFile(getObject())); + return Math.max(v.getBlockX(), v.getBlockZ()); + } catch (IOException e) { + e.printStackTrace(); + } - return 0; - }); - } + return 0; + }); + } - public int getMax3dDimension() { - return max3dDim.aquire(() -> { - try { - BlockVector v = IrisObject.sampleSize(getLoader().getObjectLoader().findFile(getObject())); - return Math.max(Math.max(v.getBlockX(), v.getBlockZ()), v.getBlockY()); - } catch (IOException e) { - e.printStackTrace(); - } + public int getMax3dDimension() { + return max3dDim.aquire(() -> { + try { + BlockVector v = IrisObject.sampleSize(getLoader().getObjectLoader().findFile(getObject())); + return Math.max(Math.max(v.getBlockX(), v.getBlockZ()), v.getBlockY()); + } catch (IOException e) { + e.printStackTrace(); + } - return -1; - }); - } + return -1; + }); + } + public IrisJigsawPieceConnector getConnector(IrisPosition relativePosition) { + for (IrisJigsawPieceConnector i : connectors) { + if (i.getPosition().equals(relativePosition)) { + return i; + } + } - public IrisJigsawPieceConnector getConnector(IrisPosition relativePosition) { - for(IrisJigsawPieceConnector i : connectors) - { - if(i.getPosition().equals(relativePosition)) - { - return i; - } - } + return null; + } - return null; - } + public IrisJigsawPiece copy() { + IrisJigsawPiece p = new IrisJigsawPiece(); + p.setObject(getObject()); + p.setLoader(getLoader()); + p.setLoadKey(getLoadKey()); + p.setLoadFile(getLoadFile()); + p.setConnectors(new KList<>()); + p.setPlacementOptions(getPlacementOptions()); - public IrisJigsawPiece copy() { - IrisJigsawPiece p = new IrisJigsawPiece(); - p.setObject(getObject()); - p.setLoader(getLoader()); - p.setLoadKey(getLoadKey()); - p.setLoadFile(getLoadFile()); - p.setConnectors(new KList<>()); - p.setPlacementOptions(getPlacementOptions()); + for (IrisJigsawPieceConnector i : getConnectors()) { + p.getConnectors().add(i.copy()); + } - for(IrisJigsawPieceConnector i : getConnectors()) - { - p.getConnectors().add(i.copy()); - } + return p; + } - return p; - } + public boolean isTerminal() { + return connectors.size() == 1; + } - public boolean isTerminal() { - return connectors.size() == 1; - } - - public ObjectPlaceMode getPlaceMode() { - return getPlacementOptions().getMode(); - } + public ObjectPlaceMode getPlaceMode() { + return getPlacementOptions().getMode(); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisJigsawPieceConnector.java b/src/main/java/com/volmit/iris/object/IrisJigsawPieceConnector.java index 173579c4c..2f7c846c9 100644 --- a/src/main/java/com/volmit/iris/object/IrisJigsawPieceConnector.java +++ b/src/main/java/com/volmit/iris/object/IrisJigsawPieceConnector.java @@ -14,77 +14,75 @@ import lombok.experimental.Accessors; @Desc("Represents a structure tile") @Data @EqualsAndHashCode(callSuper = false) -public class IrisJigsawPieceConnector -{ - @Required - @DontObfuscate - @Desc("The name of this connector, such as entry, or table node. This is a name for organization. Other connectors can specifically use targetName to target a specific connector type. Multiple connectors can use the same name.") - private String name = ""; +public class IrisJigsawPieceConnector { + @Required + @DontObfuscate + @Desc("The name of this connector, such as entry, or table node. This is a name for organization. Other connectors can specifically use targetName to target a specific connector type. Multiple connectors can use the same name.") + private String name = ""; - @Required - @DontObfuscate - @Desc("Target a piece's connector with the specified name. For any piece's connector, define * or don't define it.") - private String targetName = "*"; + @Required + @DontObfuscate + @Desc("Target a piece's connector with the specified name. For any piece's connector, define * or don't define it.") + private String targetName = "*"; - @DontObfuscate - @Desc("Rotates the placed piece on this connector. If rotation is enabled, this connector will effectivley rotate, if this connector is facing the Z direction, then the connected piece would rotate in the X,Y direction in 90 degree segments.") - private boolean rotateConnector = false; + @DontObfuscate + @Desc("Rotates the placed piece on this connector. If rotation is enabled, this connector will effectivley rotate, if this connector is facing the Z direction, then the connected piece would rotate in the X,Y direction in 90 degree segments.") + private boolean rotateConnector = false; - @DontObfuscate - @Desc("If set to true, this connector is allowed to place pieces inside of it's own piece. For example if you are adding a light post, or house on top of a path piece, you would set this to true to allow the piece to collide with the path bounding box.") - private boolean innerConnector = false; + @DontObfuscate + @Desc("If set to true, this connector is allowed to place pieces inside of it's own piece. For example if you are adding a light post, or house on top of a path piece, you would set this to true to allow the piece to collide with the path bounding box.") + private boolean innerConnector = false; - @RegistryListJigsawPool - @Desc("Pick piece pools to place onto this connector") - @ArrayType(type = String.class, min = 1) - @Required - private KList pools = new KList<>(); + @RegistryListJigsawPool + @Desc("Pick piece pools to place onto this connector") + @ArrayType(type = String.class, min = 1) + @Required + private KList pools = new KList<>(); - @RegistryListEntity - @DontObfuscate - @Desc("Pick an entity to spawn on this connector") - private String spawnEntity; + @RegistryListEntity + @DontObfuscate + @Desc("Pick an entity to spawn on this connector") + private String spawnEntity; - @DontObfuscate - @Desc("Stop the entity from despawning") - private boolean keepEntity; + @DontObfuscate + @Desc("Stop the entity from despawning") + private boolean keepEntity; - @DontObfuscate - @MaxNumber(50) - @MinNumber(1) - @Desc("The amount of entities to spawn (must be a whole number)") - private int entityCount = 1; + @DontObfuscate + @MaxNumber(50) + @MinNumber(1) + @Desc("The amount of entities to spawn (must be a whole number)") + private int entityCount = 1; - @DontObfuscate - @Desc("The relative position this connector is located at for connecting to other pieces") - @Required - private IrisPosition position = new IrisPosition(0,0,0); + @DontObfuscate + @Desc("The relative position this connector is located at for connecting to other pieces") + @Required + private IrisPosition position = new IrisPosition(0, 0, 0); - @DontObfuscate - @Desc("The relative position to this connector to place entities at") - @DependsOn({"spawnEntity"}) - private IrisPosition entityPosition = null; + @DontObfuscate + @Desc("The relative position to this connector to place entities at") + @DependsOn({"spawnEntity"}) + private IrisPosition entityPosition = null; - @DontObfuscate - @Desc("The direction this connector is facing. If the direction is set to UP, then pieces will place ABOVE the connector.") - @Required - private IrisDirection direction = IrisDirection.UP_POSITIVE_Y; + @DontObfuscate + @Desc("The direction this connector is facing. If the direction is set to UP, then pieces will place ABOVE the connector.") + @Required + private IrisDirection direction = IrisDirection.UP_POSITIVE_Y; - public String toString() - { - return direction.getFace().name() + "@(" + position.getX() + "," + position.getY() + "," + position.getZ() + ")"; - } + public String toString() { + return direction.getFace().name() + "@(" + position.getX() + "," + position.getY() + "," + position.getZ() + ")"; + } - public IrisJigsawPieceConnector copy() { - IrisJigsawPieceConnector c = new IrisJigsawPieceConnector(); - c.setInnerConnector(isInnerConnector()); - c.setTargetName(getTargetName()); - c.setPosition(getPosition().copy()); - c.setDirection(getDirection()); - c.setRotateConnector(isRotateConnector()); - c.setName(getName()); - c.setSpawnEntity(getSpawnEntity()); - c.setPools(getPools().copy()); - return c; - } + public IrisJigsawPieceConnector copy() { + IrisJigsawPieceConnector c = new IrisJigsawPieceConnector(); + c.setInnerConnector(isInnerConnector()); + c.setTargetName(getTargetName()); + c.setPosition(getPosition().copy()); + c.setDirection(getDirection()); + c.setRotateConnector(isRotateConnector()); + c.setName(getName()); + c.setSpawnEntity(getSpawnEntity()); + c.setPools(getPools().copy()); + return c; + } } diff --git a/src/main/java/com/volmit/iris/object/IrisJigsawPlacement.java b/src/main/java/com/volmit/iris/object/IrisJigsawPlacement.java index 5736f0264..dee3c4cb7 100644 --- a/src/main/java/com/volmit/iris/object/IrisJigsawPlacement.java +++ b/src/main/java/com/volmit/iris/object/IrisJigsawPlacement.java @@ -11,17 +11,16 @@ import lombok.experimental.Accessors; @AllArgsConstructor @Desc("Represents a jigsaw placement") @Data -public class IrisJigsawPlacement -{ - @RegistryListJigsaw - @Required - @DontObfuscate - @Desc("The jigsaw structure to use") - private String structure = ""; +public class IrisJigsawPlacement { + @RegistryListJigsaw + @Required + @DontObfuscate + @Desc("The jigsaw structure to use") + private String structure = ""; - @Required - @MinNumber(1) - @DontObfuscate - @Desc("The rarity for this jigsaw structure to place on a per chunk basis") - private int rarity = 29; + @Required + @MinNumber(1) + @DontObfuscate + @Desc("The rarity for this jigsaw structure to place on a per chunk basis") + private int rarity = 29; } diff --git a/src/main/java/com/volmit/iris/object/IrisJigsawPool.java b/src/main/java/com/volmit/iris/object/IrisJigsawPool.java index 9a0c79cb4..682d18359 100644 --- a/src/main/java/com/volmit/iris/object/IrisJigsawPool.java +++ b/src/main/java/com/volmit/iris/object/IrisJigsawPool.java @@ -14,12 +14,11 @@ import lombok.experimental.Accessors; @Desc("Represents a structure piece pool") @Data @EqualsAndHashCode(callSuper = false) -public class IrisJigsawPool extends IrisRegistrant -{ - @RegistryListJigsawPiece - @Required - @DontObfuscate - @ArrayType(min = 1,type = String.class) - @Desc("A list of structure piece pools") - private KList pieces = new KList<>(); +public class IrisJigsawPool extends IrisRegistrant { + @RegistryListJigsawPiece + @Required + @DontObfuscate + @ArrayType(min = 1, type = String.class) + @Desc("A list of structure piece pools") + private KList pieces = new KList<>(); } diff --git a/src/main/java/com/volmit/iris/object/IrisJigsawStructure.java b/src/main/java/com/volmit/iris/object/IrisJigsawStructure.java index 5b44a1c5e..f99057e8f 100644 --- a/src/main/java/com/volmit/iris/object/IrisJigsawStructure.java +++ b/src/main/java/com/volmit/iris/object/IrisJigsawStructure.java @@ -16,122 +16,102 @@ import lombok.experimental.Accessors; @Desc("Represents a jigsaw structure") @Data @EqualsAndHashCode(callSuper = false) -public class IrisJigsawStructure extends IrisRegistrant -{ - @RegistryListJigsawPiece - @Required - @DontObfuscate - @ArrayType(min = 1,type = String.class) - @Desc("The starting pieces. Randomly chooses a starting piece, then connects pieces using the pools define in the starting piece.") - private KList pieces = new KList<>(); +public class IrisJigsawStructure extends IrisRegistrant { + @RegistryListJigsawPiece + @Required + @DontObfuscate + @ArrayType(min = 1, type = String.class) + @Desc("The starting pieces. Randomly chooses a starting piece, then connects pieces using the pools define in the starting piece.") + private KList pieces = new KList<>(); - @MaxNumber(32) - @MinNumber(1) - @DontObfuscate - @Desc("The maximum pieces that can step out from the center piece") - private int maxDepth = 9; + @MaxNumber(32) + @MinNumber(1) + @DontObfuscate + @Desc("The maximum pieces that can step out from the center piece") + private int maxDepth = 9; - @DontObfuscate - @Desc("Jigsaw grows the parallax layer which slows iris down a bit. Since there are so many pieces, Iris takes the avg piece size and calculates the parallax radius from that. Unless your structures are using only the biggest pieces, your structure should fit in the chosen size fine. If you are seeing cut-off parts of your structures or broken terrain, turn this option on. This option will pick the biggest piece dimensions and multiply it by your (maxDepth+1) * 2 as the size to grow the parallax layer by. But typically keep this off.") - private boolean useMaxPieceSizeForParallaxRadius = false; + @DontObfuscate + @Desc("Jigsaw grows the parallax layer which slows iris down a bit. Since there are so many pieces, Iris takes the avg piece size and calculates the parallax radius from that. Unless your structures are using only the biggest pieces, your structure should fit in the chosen size fine. If you are seeing cut-off parts of your structures or broken terrain, turn this option on. This option will pick the biggest piece dimensions and multiply it by your (maxDepth+1) * 2 as the size to grow the parallax layer by. But typically keep this off.") + private boolean useMaxPieceSizeForParallaxRadius = false; - @Desc("Add a noise feature to this village") - @DontObfuscate - private IrisFeature feature = null; + @Desc("Add a noise feature to this village") + @DontObfuscate + private IrisFeature feature = null; - @DontObfuscate - @Desc("If set to true, iris will look for any pieces with only one connector in valid pools for edge connectors and attach them to 'terminate' the paths/piece connectors. Essentially it caps off ends. For example in a village, Iris would add houses to the ends of roads where possible. For terminators to be selected, they can only have one connector or they wont be chosen.") - private boolean terminate = true; + @DontObfuscate + @Desc("If set to true, iris will look for any pieces with only one connector in valid pools for edge connectors and attach them to 'terminate' the paths/piece connectors. Essentially it caps off ends. For example in a village, Iris would add houses to the ends of roads where possible. For terminators to be selected, they can only have one connector or they wont be chosen.") + private boolean terminate = true; - private transient AtomicCache maxDimension = new AtomicCache<>(); + private transient AtomicCache maxDimension = new AtomicCache<>(); - private void loadPool(String p, KList pools, KList pieces) - { - if(p.isEmpty()) - { - return; - } + private void loadPool(String p, KList pools, KList pieces) { + if (p.isEmpty()) { + return; + } - IrisJigsawPool pool = getLoader().getJigsawPoolLoader().load(p); + IrisJigsawPool pool = getLoader().getJigsawPoolLoader().load(p); - if(pool == null) - { - Iris.warn("Can't find jigsaw pool: " + p); - return; - } + if (pool == null) { + Iris.warn("Can't find jigsaw pool: " + p); + return; + } - for(String i : pool.getPieces()) - { - if(pieces.addIfMissing(i)) - { - loadPiece(i, pools, pieces); - } - } - } + for (String i : pool.getPieces()) { + if (pieces.addIfMissing(i)) { + loadPiece(i, pools, pieces); + } + } + } - private void loadPiece(String p, KList pools, KList pieces) - { - IrisJigsawPiece piece = getLoader().getJigsawPieceLoader().load(p); + private void loadPiece(String p, KList pools, KList pieces) { + IrisJigsawPiece piece = getLoader().getJigsawPieceLoader().load(p); - if(piece == null) - { - Iris.warn("Can't find jigsaw piece: " + p); - return; - } + if (piece == null) { + Iris.warn("Can't find jigsaw piece: " + p); + return; + } - for(IrisJigsawPieceConnector i : piece.getConnectors()) - { - for(String j : i.getPools()) - { - if(pools.addIfMissing(j)) - { - loadPool(j, pools, pieces); - } - } - } - } + for (IrisJigsawPieceConnector i : piece.getConnectors()) { + for (String j : i.getPools()) { + if (pools.addIfMissing(j)) { + loadPool(j, pools, pieces); + } + } + } + } - public int getMaxDimension() - { - return maxDimension.aquire(() -> { - if(useMaxPieceSizeForParallaxRadius) - { - int max = 0; - KList pools = new KList<>(); - KList pieces = new KList<>(); + public int getMaxDimension() { + return maxDimension.aquire(() -> { + if (useMaxPieceSizeForParallaxRadius) { + int max = 0; + KList pools = new KList<>(); + KList pieces = new KList<>(); - for(String i : getPieces()) - { - loadPiece(i, pools, pieces); - } + for (String i : getPieces()) { + loadPiece(i, pools, pieces); + } - for(String i : pieces) - { - max = Math.max(max, getLoader().getJigsawPieceLoader().load(i).getMax3dDimension()); - } + for (String i : pieces) { + max = Math.max(max, getLoader().getJigsawPieceLoader().load(i).getMax3dDimension()); + } - return max * (((getMaxDepth() + 1) * 2) + 1); - } + return max * (((getMaxDepth() + 1) * 2) + 1); + } else { + KList pools = new KList<>(); + KList pieces = new KList<>(); - else - { - KList pools = new KList<>(); - KList pieces = new KList<>(); + for (String i : getPieces()) { + loadPiece(i, pools, pieces); + } - for(String i : getPieces()) - { - loadPiece(i, pools, pieces); - } + int avg = 0; - int avg = 0; + for (String i : pieces) { + avg += getLoader().getJigsawPieceLoader().load(i).getMax2dDimension(); + } - for(String i : pieces) - { - avg += getLoader().getJigsawPieceLoader().load(i).getMax2dDimension(); - } - - return (avg/(pieces.size() > 0 ? pieces.size() : 1)) * (((getMaxDepth() + 1) * 2) + 1); - } - }); - } + return (avg / (pieces.size() > 0 ? pieces.size() : 1)) * (((getMaxDepth() + 1) * 2) + 1); + } + }); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisJigsawStructurePlacement.java b/src/main/java/com/volmit/iris/object/IrisJigsawStructurePlacement.java index b4ddb4411..99594b411 100644 --- a/src/main/java/com/volmit/iris/object/IrisJigsawStructurePlacement.java +++ b/src/main/java/com/volmit/iris/object/IrisJigsawStructurePlacement.java @@ -17,16 +17,15 @@ import lombok.experimental.Accessors; @Desc("Represents a jigsaw structure placer") @Data @EqualsAndHashCode(callSuper = false) -public class IrisJigsawStructurePlacement extends IrisRegistrant -{ - @RegistryListJigsaw - @Required - @DontObfuscate - @Desc("The structure to place") - private String structure; +public class IrisJigsawStructurePlacement extends IrisRegistrant { + @RegistryListJigsaw + @Required + @DontObfuscate + @Desc("The structure to place") + private String structure; - @DontObfuscate - @Required - @Desc("The 1 in X chance rarity") - private int rarity = 100; + @DontObfuscate + @Required + @Desc("The 1 in X chance rarity") + private int rarity = 100; } diff --git a/src/main/java/com/volmit/iris/object/IrisLoot.java b/src/main/java/com/volmit/iris/object/IrisLoot.java index 559b7c18d..600c31301 100644 --- a/src/main/java/com/volmit/iris/object/IrisLoot.java +++ b/src/main/java/com/volmit/iris/object/IrisLoot.java @@ -1,7 +1,13 @@ package com.volmit.iris.object; -import java.awt.Color; - +import com.volmit.iris.Iris; +import com.volmit.iris.generator.noise.CNG; +import com.volmit.iris.scaffold.cache.AtomicCache; +import com.volmit.iris.util.*; +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; +import lombok.experimental.Accessors; import org.bukkit.DyeColor; import org.bukkit.Material; import org.bukkit.inventory.ItemFlag; @@ -11,305 +17,245 @@ import org.bukkit.inventory.meta.ItemMeta; import org.bukkit.inventory.meta.LeatherArmorMeta; import org.bukkit.material.Colorable; -import com.volmit.iris.Iris; -import com.volmit.iris.scaffold.cache.AtomicCache; -import com.volmit.iris.generator.noise.CNG; -import com.volmit.iris.util.ArrayType; -import com.volmit.iris.util.B; -import com.volmit.iris.util.C; -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.Form; -import com.volmit.iris.util.KList; -import com.volmit.iris.util.MaxNumber; -import com.volmit.iris.util.MinNumber; -import com.volmit.iris.util.RNG; -import com.volmit.iris.util.RegistryListItemType; -import com.volmit.iris.util.Required; - -import lombok.AllArgsConstructor; -import lombok.Data; -import lombok.NoArgsConstructor; -import lombok.experimental.Accessors; +import java.awt.*; @Accessors(chain = true) @NoArgsConstructor @AllArgsConstructor @Desc("Represents a loot entry") @Data -public class IrisLoot -{ - @DontObfuscate - @Desc("The target inventory slot types to fill this loot with") - private InventorySlotType slotTypes = InventorySlotType.STORAGE; +public class IrisLoot { + @DontObfuscate + @Desc("The target inventory slot types to fill this loot with") + private InventorySlotType slotTypes = InventorySlotType.STORAGE; - @MinNumber(1) - @DontObfuscate - @Desc("The sub rarity of this loot. Calculated after this loot table has been picked.") - private int rarity = 1; + @MinNumber(1) + @DontObfuscate + @Desc("The sub rarity of this loot. Calculated after this loot table has been picked.") + private int rarity = 1; - @MinNumber(1) - @DontObfuscate - @Desc("Minimum amount of this loot") - private int minAmount = 1; + @MinNumber(1) + @DontObfuscate + @Desc("Minimum amount of this loot") + private int minAmount = 1; - @MinNumber(1) - @DontObfuscate - @Desc("Maximum amount of this loot") - private int maxAmount = 1; + @MinNumber(1) + @DontObfuscate + @Desc("Maximum amount of this loot") + private int maxAmount = 1; - @MinNumber(1) - @DontObfuscate - @Desc("The display name of this item") - private String displayName = null; + @MinNumber(1) + @DontObfuscate + @Desc("The display name of this item") + private String displayName = null; - @MinNumber(0) - @MaxNumber(1) - @DontObfuscate - @Desc("Minimum durability percent") - private double minDurability = 0; + @MinNumber(0) + @MaxNumber(1) + @DontObfuscate + @Desc("Minimum durability percent") + private double minDurability = 0; - @MinNumber(0) - @MaxNumber(1) - @DontObfuscate - @Desc("Maximum durability percent") - private double maxDurability = 1; + @MinNumber(0) + @MaxNumber(1) + @DontObfuscate + @Desc("Maximum durability percent") + private double maxDurability = 1; - @DontObfuscate - @Desc("Define a custom model identifier 1.14+ only") - private Integer customModel = null; + @DontObfuscate + @Desc("Define a custom model identifier 1.14+ only") + private Integer customModel = null; - @DontObfuscate - @Desc("Set this to true to prevent it from being broken") - private boolean unbreakable = false; + @DontObfuscate + @Desc("Set this to true to prevent it from being broken") + private boolean unbreakable = false; - @ArrayType(min = 1, type = ItemFlag.class) - @DontObfuscate - @Desc("The item flags to add") - private KList itemFlags = new KList<>(); + @ArrayType(min = 1, type = ItemFlag.class) + @DontObfuscate + @Desc("The item flags to add") + private KList itemFlags = new KList<>(); - @DontObfuscate - @Desc("Apply enchantments to this item") - @ArrayType(min = 1, type = IrisEnchantment.class) - private KList enchantments = new KList<>(); + @DontObfuscate + @Desc("Apply enchantments to this item") + @ArrayType(min = 1, type = IrisEnchantment.class) + private KList enchantments = new KList<>(); - @DontObfuscate - @Desc("Apply attribute modifiers to this item") - @ArrayType(min = 1, type = IrisAttributeModifier.class) - private KList attributes = new KList<>(); + @DontObfuscate + @Desc("Apply attribute modifiers to this item") + @ArrayType(min = 1, type = IrisAttributeModifier.class) + private KList attributes = new KList<>(); - @ArrayType(min = 1, type = String.class) - @DontObfuscate - @Desc("Add lore to this item") - private KList lore = new KList<>(); + @ArrayType(min = 1, type = String.class) + @DontObfuscate + @Desc("Add lore to this item") + private KList lore = new KList<>(); - @RegistryListItemType - @Required - @DontObfuscate - @Desc("This is the item or block type. Does not accept minecraft:*. Only materials such as DIAMOND_SWORD or DIRT.") - private String type = ""; + @RegistryListItemType + @Required + @DontObfuscate + @Desc("This is the item or block type. Does not accept minecraft:*. Only materials such as DIAMOND_SWORD or DIRT.") + private String type = ""; - @DontObfuscate - @Desc("The dye color") - private DyeColor dyeColor = null; + @DontObfuscate + @Desc("The dye color") + private DyeColor dyeColor = null; - @DontObfuscate - @Desc("The leather armor color") - private String leatherColor = null; + @DontObfuscate + @Desc("The leather armor color") + private String leatherColor = null; - private final transient AtomicCache chance = new AtomicCache<>(); + private final transient AtomicCache chance = new AtomicCache<>(); - public Material getType() - { - return B.getMaterial(type); - } + public Material getType() { + return B.getMaterial(type); + } - public ItemStack get(boolean debug, RNG rng) - { - try - { - ItemStack is = new ItemStack(getType(), Math.max(1, rng.i(getMinAmount(), getMaxAmount()))); - ItemMeta m = is.getItemMeta(); + public ItemStack get(boolean debug, RNG rng) { + try { + ItemStack is = new ItemStack(getType(), Math.max(1, rng.i(getMinAmount(), getMaxAmount()))); + ItemMeta m = is.getItemMeta(); - if(getType().getMaxDurability() > 0 && m instanceof Damageable) - { - Damageable d = (Damageable) m; - int max = getType().getMaxDurability(); - d.setDamage((int) Math.round(Math.max(0, Math.min(max, (1D - rng.d(getMinDurability(), getMaxDurability())) * max)))); - } + if (getType().getMaxDurability() > 0 && m instanceof Damageable) { + Damageable d = (Damageable) m; + int max = getType().getMaxDurability(); + d.setDamage((int) Math.round(Math.max(0, Math.min(max, (1D - rng.d(getMinDurability(), getMaxDurability())) * max)))); + } - for(IrisEnchantment i : getEnchantments()) - { - i.apply(rng, m); - } + for (IrisEnchantment i : getEnchantments()) { + i.apply(rng, m); + } - for(IrisAttributeModifier i : getAttributes()) - { - i.apply(rng, m); - } + for (IrisAttributeModifier i : getAttributes()) { + i.apply(rng, m); + } - if(Iris.customModels) - { - m.setCustomModelData(getCustomModel()); - } + if (Iris.customModels) { + m.setCustomModelData(getCustomModel()); + } - m.setLocalizedName(C.translateAlternateColorCodes('&', displayName)); - m.setDisplayName(C.translateAlternateColorCodes('&', displayName)); - m.setUnbreakable(isUnbreakable()); + m.setLocalizedName(C.translateAlternateColorCodes('&', displayName)); + m.setDisplayName(C.translateAlternateColorCodes('&', displayName)); + m.setUnbreakable(isUnbreakable()); - for(ItemFlag i : getItemFlags()) - { - m.addItemFlags(i); - } + for (ItemFlag i : getItemFlags()) { + m.addItemFlags(i); + } - KList lore = new KList<>(); + KList lore = new KList<>(); - getLore().forEach((i) -> - { - String mf = C.translateAlternateColorCodes('&', i); + 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()); - } - } + if (mf.length() > 24) { + for (String g : Form.wrapWords(mf, 24).split("\\Q\n\\E")) { + lore.add(g.trim()); + } + } else { + lore.add(mf); + } + }); - else - { - lore.add(mf); - } - }); + if (debug) { + if (lore.isNotEmpty()) { + lore.add(C.GRAY + "--------------------"); + } - if(debug) - { - if(lore.isNotEmpty()) - { - lore.add(C.GRAY + "--------------------"); - } + lore.add(C.GRAY + "1 in " + (getRarity()) + " Chance (" + Form.pc(1D / (getRarity()), 5) + ")"); + } - lore.add(C.GRAY + "1 in " + (getRarity()) + " Chance (" + Form.pc(1D / (getRarity()), 5) + ")"); - } + m.setLore(lore); - m.setLore(lore); + if (getLeatherColor() != null && m instanceof LeatherArmorMeta) { + Color c = Color.decode(getLeatherColor()); + ((LeatherArmorMeta) m).setColor(org.bukkit.Color.fromRGB(c.getRed(), c.getGreen(), c.getBlue())); + } - if(getLeatherColor() != null && m instanceof LeatherArmorMeta) - { - Color c = Color.decode(getLeatherColor()); - ((LeatherArmorMeta) m).setColor(org.bukkit.Color.fromRGB(c.getRed(), c.getGreen(), c.getBlue())); - } + if (getDyeColor() != null && m instanceof Colorable) { + ((Colorable) m).setColor(getDyeColor()); + } - if(getDyeColor() != null && m instanceof Colorable) - { - ((Colorable) m).setColor(getDyeColor()); - } + is.setItemMeta(m); + return is; + } catch (Throwable e) { - is.setItemMeta(m); - return is; - } + } - catch(Throwable e) - { + return new ItemStack(Material.AIR); + } - } + public ItemStack get(boolean debug, boolean giveSomething, IrisLootTable table, RNG rng, int x, int y, int z) { + if (debug) { + chance.reset(); + } - return new ItemStack(Material.AIR); - } + if (giveSomething || chance.aquire(() -> NoiseStyle.STATIC.create(rng)).fit(1, rarity * table.getRarity(), x, y, z) == 1) { + if (getType() == null) { + Iris.warn("Cant find item type " + type); + return null; + } - public ItemStack get(boolean debug, boolean giveSomething, IrisLootTable table, RNG rng, int x, int y, int z) - { - if(debug) - { - chance.reset(); - } + try { + ItemStack is = new ItemStack(getType(), Math.max(1, rng.i(getMinAmount(), getMaxAmount()))); + ItemMeta m = is.getItemMeta(); - if(giveSomething || chance.aquire(() -> NoiseStyle.STATIC.create(rng)).fit(1, rarity * table.getRarity(), x, y, z) == 1) - { - if(getType() == null) - { - Iris.warn("Cant find item type " + type); - return null; - } + if (getType().getMaxDurability() > 0 && m instanceof Damageable) { + Damageable d = (Damageable) m; + int max = getType().getMaxDurability(); + d.setDamage((int) Math.round(Math.max(0, Math.min(max, (1D - rng.d(getMinDurability(), getMaxDurability())) * max)))); + } - try - { - ItemStack is = new ItemStack(getType(), Math.max(1, rng.i(getMinAmount(), getMaxAmount()))); - ItemMeta m = is.getItemMeta(); + for (IrisEnchantment i : getEnchantments()) { + i.apply(rng, m); + } - if(getType().getMaxDurability() > 0 && m instanceof Damageable) - { - Damageable d = (Damageable) m; - int max = getType().getMaxDurability(); - d.setDamage((int) Math.round(Math.max(0, Math.min(max, (1D - rng.d(getMinDurability(), getMaxDurability())) * max)))); - } + for (IrisAttributeModifier i : getAttributes()) { + i.apply(rng, m); + } - for(IrisEnchantment i : getEnchantments()) - { - i.apply(rng, m); - } + if (Iris.customModels) { + m.setCustomModelData(getCustomModel()); + } - for(IrisAttributeModifier i : getAttributes()) - { - i.apply(rng, m); - } + m.setLocalizedName(C.translateAlternateColorCodes('&', displayName)); + m.setDisplayName(C.translateAlternateColorCodes('&', displayName)); + m.setUnbreakable(isUnbreakable()); - if(Iris.customModels) - { - m.setCustomModelData(getCustomModel()); - } + for (ItemFlag i : getItemFlags()) { + m.addItemFlags(i); + } - m.setLocalizedName(C.translateAlternateColorCodes('&', displayName)); - m.setDisplayName(C.translateAlternateColorCodes('&', displayName)); - m.setUnbreakable(isUnbreakable()); + KList lore = new KList<>(); - for(ItemFlag i : getItemFlags()) - { - m.addItemFlags(i); - } + getLore().forEach((i) -> + { + String mf = C.translateAlternateColorCodes('&', i); - KList lore = new KList<>(); + if (mf.length() > 24) { + for (String g : Form.wrapWords(mf, 24).split("\\Q\n\\E")) { + lore.add(g.trim()); + } + } else { + lore.add(mf); + } + }); - getLore().forEach((i) -> - { - String mf = C.translateAlternateColorCodes('&', i); + if (debug) { + if (lore.isNotEmpty()) { + lore.add(C.GRAY + "--------------------"); + } - if(mf.length() > 24) - { - for(String g : Form.wrapWords(mf, 24).split("\\Q\n\\E")) - { - lore.add(g.trim()); - } - } + 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) + ")"); + } - else - { - lore.add(mf); - } - }); + m.setLore(lore); + is.setItemMeta(m); + return is; + } catch (Throwable e) { - if(debug) - { - 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); - is.setItemMeta(m); - return is; - } - - catch(Throwable e) - { - - } - } - - return null; - } + return null; + } } diff --git a/src/main/java/com/volmit/iris/object/IrisLootReference.java b/src/main/java/com/volmit/iris/object/IrisLootReference.java index 313a0097f..e7489daca 100644 --- a/src/main/java/com/volmit/iris/object/IrisLootReference.java +++ b/src/main/java/com/volmit/iris/object/IrisLootReference.java @@ -1,14 +1,8 @@ package com.volmit.iris.object; import com.volmit.iris.scaffold.cache.AtomicCache; -import com.volmit.iris.util.ArrayType; -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.KList; -import com.volmit.iris.util.MinNumber; -import com.volmit.iris.util.RegistryListLoot; - import com.volmit.iris.scaffold.data.DataProvider; +import com.volmit.iris.util.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -19,38 +13,35 @@ import lombok.experimental.Accessors; @AllArgsConstructor @Desc("Represents a loot entry") @Data -public class IrisLootReference -{ +public class IrisLootReference { - @DontObfuscate - @Desc("Add = add on top of parent tables, Replace = clear first then add these. Clear = Remove all and dont add loot from this or parent.") - private LootMode mode = LootMode.ADD; + @DontObfuscate + @Desc("Add = add on top of parent tables, Replace = clear first then add these. Clear = Remove all and dont add loot from this or parent.") + private LootMode mode = LootMode.ADD; - @DontObfuscate - @RegistryListLoot - @ArrayType(min = 1, type = String.class) - @Desc("Add loot table registries here") - private KList tables = new KList<>(); + @DontObfuscate + @RegistryListLoot + @ArrayType(min = 1, type = String.class) + @Desc("Add loot table registries here") + private KList tables = new KList<>(); - @MinNumber(0) - @DontObfuscate - @Desc("Increase the chance of loot in this area") - private double multiplier = 1D; + @MinNumber(0) + @DontObfuscate + @Desc("Increase the chance of loot in this area") + private double multiplier = 1D; - private final transient AtomicCache> tt = new AtomicCache<>(); + private final transient AtomicCache> tt = new AtomicCache<>(); - public KList getLootTables(DataProvider g) - { - return tt.aquire(() -> - { - KList t = new KList<>(); + public KList getLootTables(DataProvider g) { + return tt.aquire(() -> + { + KList t = new KList<>(); - for(String i : tables) - { - t.add(g.getData().getLootLoader().load(i)); - } + for (String i : tables) { + t.add(g.getData().getLootLoader().load(i)); + } - return t; - }); - } + return t; + }); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisLootTable.java b/src/main/java/com/volmit/iris/object/IrisLootTable.java index c44ce4f9b..7dcaa3c0b 100644 --- a/src/main/java/com/volmit/iris/object/IrisLootTable.java +++ b/src/main/java/com/volmit/iris/object/IrisLootTable.java @@ -1,21 +1,13 @@ package com.volmit.iris.object; -import org.bukkit.Material; -import org.bukkit.inventory.ItemStack; - -import com.volmit.iris.util.ArrayType; -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.KList; -import com.volmit.iris.util.MinNumber; -import com.volmit.iris.util.RNG; -import com.volmit.iris.util.Required; - +import com.volmit.iris.util.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; +import org.bukkit.Material; +import org.bukkit.inventory.ItemStack; @Accessors(chain = true) @NoArgsConstructor @@ -23,59 +15,55 @@ import lombok.experimental.Accessors; @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 -{ - @Required +public class IrisLootTable extends IrisRegistrant { + @Required - @Desc("The name of this loot table") - @DontObfuscate - @MinNumber(2) - private String name = ""; + @Desc("The name of this loot table") + @DontObfuscate + @MinNumber(2) + private String name = ""; - @MinNumber(1) - @DontObfuscate - @Desc("The rarity as in 1 in X chance") - private int rarity = 1; + @MinNumber(1) + @DontObfuscate + @Desc("The rarity as in 1 in X chance") + private int rarity = 1; - @MinNumber(1) - @DontObfuscate - @Desc("The maximum amount of loot that can be picked in this table at a time.") - private int maxPicked = 5; + @MinNumber(1) + @DontObfuscate + @Desc("The maximum amount of loot that can be picked in this table at a time.") + private int maxPicked = 5; - @MinNumber(0) - @DontObfuscate - @Desc("The minimum amount of loot that can be picked in this table at a time.") - private int minPicked = 1; + @MinNumber(0) + @DontObfuscate + @Desc("The minimum amount of loot that can be picked in this table at a time.") + private int minPicked = 1; - @DontObfuscate - @Desc("The loot in this table") - @ArrayType(min = 1, type = IrisLoot.class) - private KList loot = new KList<>(); + @DontObfuscate + @Desc("The loot in this table") + @ArrayType(min = 1, type = IrisLoot.class) + private KList loot = new KList<>(); - public KList getLoot(boolean debug, boolean doSomething, RNG rng, InventorySlotType slot, int x, int y, int z, int gg, int ffs) - { - KList lootf = new KList<>(); + public KList getLoot(boolean debug, boolean doSomething, RNG rng, InventorySlotType slot, int x, int y, int z, int gg, int ffs) { + KList lootf = new KList<>(); - int m = 0; - int mx = rng.i(getMinPicked(), getMaxPicked()); + int m = 0; + int mx = rng.i(getMinPicked(), getMaxPicked()); - while (m < mx) { - int num = rng.i(loot.size()); + while (m < mx) { + int num = rng.i(loot.size()); - IrisLoot l = loot.get(num); + IrisLoot l = loot.get(num); - if(l.getSlotTypes() == slot) - { - ItemStack item = l.get(debug, false, this, rng, x, y, z); + if (l.getSlotTypes() == slot) { + ItemStack item = l.get(debug, false, this, rng, x, y, z); - if(item != null && item.getType() != Material.AIR) - { - lootf.add(item); - m++; - } - } - } + if (item != null && item.getType() != Material.AIR) { + lootf.add(item); + m++; + } + } + } - return lootf; - } + return lootf; + } } diff --git a/src/main/java/com/volmit/iris/object/IrisMaterialPalette.java b/src/main/java/com/volmit/iris/object/IrisMaterialPalette.java index f2365f597..8905bae0c 100644 --- a/src/main/java/com/volmit/iris/object/IrisMaterialPalette.java +++ b/src/main/java/com/volmit/iris/object/IrisMaterialPalette.java @@ -1,16 +1,9 @@ package com.volmit.iris.object; -import com.volmit.iris.scaffold.cache.AtomicCache; -import com.volmit.iris.manager.IrisDataManager; import com.volmit.iris.generator.noise.CNG; -import com.volmit.iris.util.ArrayType; -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.KList; -import com.volmit.iris.util.MinNumber; -import com.volmit.iris.util.RNG; -import com.volmit.iris.util.Required; - +import com.volmit.iris.manager.IrisDataManager; +import com.volmit.iris.scaffold.cache.AtomicCache; +import com.volmit.iris.util.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -22,95 +15,82 @@ import org.bukkit.block.data.BlockData; @AllArgsConstructor @Desc("A palette of materials") @Data -public class IrisMaterialPalette -{ - @DontObfuscate - @Desc("The style of noise") - private IrisGeneratorStyle style = NoiseStyle.STATIC.style(); +public class IrisMaterialPalette { + @DontObfuscate + @Desc("The style of noise") + private IrisGeneratorStyle style = NoiseStyle.STATIC.style(); - @MinNumber(0.0001) - @DontObfuscate - @Desc("The terrain zoom mostly for zooming in on a wispy palette") - private double zoom = 5; + @MinNumber(0.0001) + @DontObfuscate + @Desc("The terrain zoom mostly for zooming in on a wispy palette") + private double zoom = 5; - @Required - @ArrayType(min = 1, type = IrisBlockData.class) - @DontObfuscate - @Desc("The palette of blocks to be used in this layer") - private KList palette = new KList().qadd(new IrisBlockData("STONE")); + @Required + @ArrayType(min = 1, type = IrisBlockData.class) + @DontObfuscate + @Desc("The palette of blocks to be used in this layer") + private KList palette = new KList().qadd(new IrisBlockData("STONE")); - private final transient AtomicCache> blockData = new AtomicCache<>(); - private final transient AtomicCache layerGenerator = new AtomicCache<>(); - private final transient AtomicCache heightGenerator = new AtomicCache<>(); + private final transient AtomicCache> blockData = new AtomicCache<>(); + private final transient AtomicCache layerGenerator = new AtomicCache<>(); + private final transient AtomicCache heightGenerator = new AtomicCache<>(); - public BlockData get(RNG rng, double x, double y, double z, IrisDataManager rdata) - { - if(getBlockData(rdata).isEmpty()) - { - return null; - } + public BlockData get(RNG rng, double x, double y, double z, IrisDataManager rdata) { + if (getBlockData(rdata).isEmpty()) { + return null; + } - if(getBlockData(rdata).size() == 1) - { - return getBlockData(rdata).get(0); - } + if (getBlockData(rdata).size() == 1) { + return getBlockData(rdata).get(0); + } - return getLayerGenerator(rng, rdata).fit(getBlockData(rdata), x / zoom, y / zoom, z / zoom); - } + return getLayerGenerator(rng, rdata).fit(getBlockData(rdata), x / zoom, y / zoom, z / zoom); + } - public CNG getLayerGenerator(RNG rng, IrisDataManager rdata) - { - return layerGenerator.aquire(() -> - { - RNG rngx = rng.nextParallelRNG(-23498896 + getBlockData(rdata).size()); - return style.create(rngx); - }); - } + public CNG getLayerGenerator(RNG rng, IrisDataManager rdata) { + return layerGenerator.aquire(() -> + { + RNG rngx = rng.nextParallelRNG(-23498896 + getBlockData(rdata).size()); + return style.create(rngx); + }); + } - public IrisMaterialPalette qclear() - { - palette.clear(); - return this; - } + public IrisMaterialPalette qclear() { + palette.clear(); + return this; + } - public KList add(String b) - { - palette.add(new IrisBlockData(b)); + public KList add(String b) { + palette.add(new IrisBlockData(b)); - return palette; - } + return palette; + } - public IrisMaterialPalette qadd(String b) - { - palette.add(new IrisBlockData(b)); + public IrisMaterialPalette qadd(String b) { + palette.add(new IrisBlockData(b)); - return this; - } + return this; + } - public KList getBlockData(IrisDataManager rdata) - { - return blockData.aquire(() -> - { - KList blockData = new KList<>(); - for(IrisBlockData ix : palette) - { - BlockData bx = ix.getBlockData(rdata); - if(bx != null) - { - for(int i = 0; i < ix.getWeight(); i++) - { - blockData.add(bx); - } - } - } + public KList getBlockData(IrisDataManager rdata) { + return blockData.aquire(() -> + { + KList blockData = new KList<>(); + for (IrisBlockData ix : palette) { + BlockData bx = ix.getBlockData(rdata); + if (bx != null) { + for (int i = 0; i < ix.getWeight(); i++) { + blockData.add(bx); + } + } + } - return blockData; - }); - } + return blockData; + }); + } - public IrisMaterialPalette zero() - { - palette.clear(); - return this; - } + public IrisMaterialPalette zero() { + palette.clear(); + return this; + } } diff --git a/src/main/java/com/volmit/iris/object/IrisNoiseGenerator.java b/src/main/java/com/volmit/iris/object/IrisNoiseGenerator.java index 48e5c93fa..70a5b0b08 100644 --- a/src/main/java/com/volmit/iris/object/IrisNoiseGenerator.java +++ b/src/main/java/com/volmit/iris/object/IrisNoiseGenerator.java @@ -1,156 +1,137 @@ package com.volmit.iris.object; -import com.volmit.iris.scaffold.cache.AtomicCache; import com.volmit.iris.generator.noise.CNG; -import com.volmit.iris.util.ArrayType; -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.IrisInterpolation; -import com.volmit.iris.util.KList; -import com.volmit.iris.util.MinNumber; -import com.volmit.iris.util.RNG; -import com.volmit.iris.util.Required; - +import com.volmit.iris.scaffold.cache.AtomicCache; +import com.volmit.iris.util.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; -import java.util.Collection; - @Accessors(chain = true) @NoArgsConstructor @AllArgsConstructor @Desc("A noise generator") @Data -public class IrisNoiseGenerator -{ +public class IrisNoiseGenerator { - @MinNumber(0.0001) - @DontObfuscate - @Desc("The coordinate input zoom") - private double zoom = 1; + @MinNumber(0.0001) + @DontObfuscate + @Desc("The coordinate input zoom") + private double zoom = 1; - @DontObfuscate - @Desc("Reverse the output. So that noise = -noise + opacity") - private boolean negative = false; + @DontObfuscate + @Desc("Reverse the output. So that noise = -noise + opacity") + private boolean negative = false; - @MinNumber(0) - @DontObfuscate - @Desc("The output multiplier") - private double opacity = 1; + @MinNumber(0) + @DontObfuscate + @Desc("The output multiplier") + private double opacity = 1; - @DontObfuscate - @Desc("Coordinate offset x") - private double offsetX = 0; + @DontObfuscate + @Desc("Coordinate offset x") + private double offsetX = 0; - @DontObfuscate - @Desc("Height output offset y") - private double offsetY = 0; + @DontObfuscate + @Desc("Height output offset y") + private double offsetY = 0; - @DontObfuscate - @Desc("Coordinate offset z") - private double offsetZ = 0; + @DontObfuscate + @Desc("Coordinate offset z") + private double offsetZ = 0; - @Required - @DontObfuscate - @Desc("The seed") - private long seed = 0; + @Required + @DontObfuscate + @Desc("The seed") + private long seed = 0; - @DontObfuscate - @Desc("Apply a parametric curve on the output") - private boolean parametric = false; + @DontObfuscate + @Desc("Apply a parametric curve on the output") + private boolean parametric = false; - @DontObfuscate - @Desc("Apply a bezier curve on the output") - private boolean bezier = false; + @DontObfuscate + @Desc("Apply a bezier curve on the output") + private boolean bezier = false; - @DontObfuscate - @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; + @DontObfuscate + @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; - @DontObfuscate - @Desc("The exponent noise^EXPONENT") - private double exponent = 1; + @DontObfuscate + @Desc("The exponent noise^EXPONENT") + private double exponent = 1; - @DontObfuscate - @Desc("Enable / disable. Outputs offsetY if disabled") - private boolean enabled = true; + @DontObfuscate + @Desc("Enable / disable. Outputs offsetY if disabled") + private boolean enabled = true; - @Required - @DontObfuscate - @Desc("The Noise Style") - private IrisGeneratorStyle style = NoiseStyle.IRIS.style(); + @Required + @DontObfuscate + @Desc("The Noise Style") + private IrisGeneratorStyle style = NoiseStyle.IRIS.style(); - @MinNumber(1) - @DontObfuscate - @Desc("Multiple octaves for multple generators of changing zooms added together") - private int octaves = 1; + @MinNumber(1) + @DontObfuscate + @Desc("Multiple octaves for multple generators of changing zooms added together") + private int octaves = 1; - @ArrayType(min = 1, type = IrisNoiseGenerator.class) - @DontObfuscate - @Desc("Apply a child noise generator to fracture the input coordinates of this generator") - private KList fracture = new KList<>(); + @ArrayType(min = 1, type = IrisNoiseGenerator.class) + @DontObfuscate + @Desc("Apply a child noise generator to fracture the input coordinates of this generator") + private KList fracture = new KList<>(); - private final transient AtomicCache generator = new AtomicCache<>(); + private final transient AtomicCache generator = new AtomicCache<>(); - public IrisNoiseGenerator(boolean enabled) - { - this(); - this.enabled = enabled; - } + public IrisNoiseGenerator(boolean enabled) { + this(); + this.enabled = enabled; + } - protected CNG getGenerator(long superSeed) - { - return generator.aquire(() -> style.create(new RNG(superSeed + 33955677 - seed)).oct(octaves)); - } + protected CNG getGenerator(long superSeed) { + return generator.aquire(() -> style.create(new RNG(superSeed + 33955677 - seed)).oct(octaves)); + } - public double getMax() - { - return getOffsetY() + opacity; - } + public double getMax() { + return getOffsetY() + opacity; + } - public double getNoise(long superSeed, double xv, double zv) - { - if(!enabled) - { - return offsetY; - } + public double getNoise(long superSeed, double xv, double zv) { + if (!enabled) { + return offsetY; + } - double x = xv; - double z = zv; - int g = 33; + double x = xv; + double z = zv; + int g = 33; - for(IrisNoiseGenerator i : fracture) - { - if(i.isEnabled()) - { - x += i.getNoise(superSeed + seed + g, xv, zv) - (opacity / 2D); - z -= i.getNoise(superSeed + seed + g, zv, xv) - (opacity / 2D); - } - g += 819; - } + for (IrisNoiseGenerator i : fracture) { + if (i.isEnabled()) { + x += i.getNoise(superSeed + seed + g, xv, zv) - (opacity / 2D); + z -= i.getNoise(superSeed + seed + g, zv, xv) - (opacity / 2D); + } + g += 819; + } - double n = getGenerator(superSeed).fitDouble(0, opacity, (x / zoom) + offsetX, (z / zoom) + offsetZ); - 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; + double n = getGenerator(superSeed).fitDouble(0, opacity, (x / zoom) + offsetX, (z / zoom) + offsetZ); + 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; - } + return n; + } public KList getAllComposites() { - KList g = new KList(); + KList g = new KList(); - g.add(this); + g.add(this); - for(IrisNoiseGenerator i : getFracture()) - { - g.addAll(i.getAllComposites()); - } + for (IrisNoiseGenerator i : getFracture()) { + g.addAll(i.getAllComposites()); + } - return g; + return g; } } diff --git a/src/main/java/com/volmit/iris/object/IrisObject.java b/src/main/java/com/volmit/iris/object/IrisObject.java index 04a098882..f996c80a2 100644 --- a/src/main/java/com/volmit/iris/object/IrisObject.java +++ b/src/main/java/com/volmit/iris/object/IrisObject.java @@ -1,12 +1,5 @@ package com.volmit.iris.object; -import com.sk89q.worldedit.EditSession; -import com.sk89q.worldedit.WorldEditException; -import com.sk89q.worldedit.internal.annotation.Selection; -import com.sk89q.worldedit.math.BlockVector3; -import com.sk89q.worldedit.math.Vector3; -import com.sk89q.worldedit.regions.CuboidRegion; -import com.sk89q.worldedit.world.block.BlockTypes; import com.volmit.iris.Iris; import com.volmit.iris.manager.IrisDataManager; import com.volmit.iris.object.tile.TileData; @@ -15,7 +8,6 @@ import com.volmit.iris.util.*; import lombok.Data; import lombok.EqualsAndHashCode; import lombok.experimental.Accessors; -import org.bukkit.Bukkit; import org.bukkit.Location; import org.bukkit.Material; import org.bukkit.block.Block; @@ -37,1138 +29,932 @@ import java.util.function.Consumer; @Accessors(chain = true) @Data @EqualsAndHashCode(callSuper = false) -public class IrisObject extends IrisRegistrant -{ - private static final Vector HALF = new Vector(0.5, 0.5, 0.5); - private static final BlockData AIR = B.get("CAVE_AIR"); - private static final BlockData VAIR = B.get("VOID_AIR"); - private static final BlockData VAIR_DEBUG = B.get("COBWEB"); - private static final BlockData[] SNOW_LAYERS = new BlockData[] {B.get("minecraft:snow[layers=1]"), B.get("minecraft:snow[layers=2]"), B.get("minecraft:snow[layers=3]"), B.get("minecraft:snow[layers=4]"), B.get("minecraft:snow[layers=5]"), B.get("minecraft:snow[layers=6]"), B.get("minecraft:snow[layers=7]"), B.get("minecraft:snow[layers=8]")}; - public static boolean shitty = false; - private KMap blocks; - private KMap> states; - private int w; - private int d; - private int h; - private transient final IrisLock readLock = new IrisLock("read-conclock"); - private transient BlockVector center; - private transient volatile boolean smartBored = false; - private transient IrisLock lock = new IrisLock("Preloadcache"); - private transient AtomicCache aabb; - - public AxisAlignedBB getAABB() - { - return getAABBFor(new BlockVector(w,h,d)); - } - - public static BlockVector getCenterForSize(BlockVector size) - { - return new BlockVector(size.getX() / 2, size.getY() / 2, size.getZ() / 2); - } - - public static AxisAlignedBB getAABBFor(BlockVector size) - { - BlockVector center = new BlockVector(size.getX() / 2, size.getY() / 2, size.getZ() / 2); - return new AxisAlignedBB(new IrisPosition(new BlockVector(0,0,0).subtract(center).toBlockVector()), - new IrisPosition(new BlockVector(size.getX()-1,size.getY()-1,size.getZ()-1).subtract(center).toBlockVector())); - } - - public void ensureSmartBored(boolean debug) - { - if(smartBored) - { - return; - } - - lock.lock(); - int applied = 0; - if(getBlocks().isEmpty()) - { - lock.unlock(); - Iris.warn("Cannot Smart Bore " + getLoadKey() + " because it has 0 blocks in it."); - smartBored = true; - return; - } - - BlockVector max = new BlockVector(Double.MIN_VALUE, Double.MIN_VALUE, Double.MIN_VALUE); - BlockVector min = new BlockVector(Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE); - - for(BlockVector i : getBlocks().keySet()) - { - 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())); - } - - // Smash X - for(int rayY = min.getBlockY(); rayY <= max.getBlockY(); rayY++) - { - 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(getBlocks().containsKey(new BlockVector(ray, rayY, 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++) - { - BlockVector v = new BlockVector(i, rayY, rayZ); - - if(!getBlocks().containsKey(v) || B.isAir(getBlocks().get(v))) - { - getBlocks().put(v, debug ? VAIR_DEBUG : VAIR); - applied++; - } - } - } - } - } - - // Smash Y - for(int rayX = min.getBlockX(); rayX <= max.getBlockX(); rayX++) - { - 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(getBlocks().containsKey(new BlockVector(rayX, 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++) - { - BlockVector v = new BlockVector(rayX, i, rayZ); - - if(!getBlocks().containsKey(v) || B.isAir(getBlocks().get(v))) - { - getBlocks().put(v, debug ? VAIR_DEBUG : VAIR); - applied++; - } - } - } - } - } - - // Smash Z - for(int rayX = min.getBlockX(); rayX <= max.getBlockX(); rayX++) - { - 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(getBlocks().containsKey(new BlockVector(rayX, 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++) - { - BlockVector v = new BlockVector(rayX, rayY, i); - - if(!getBlocks().containsKey(v) || B.isAir(getBlocks().get(v))) - { - getBlocks().put(v, debug ? VAIR_DEBUG : VAIR); - applied++; - } - } - } - } - } - - Iris.verbose("- Applied Smart Bore to " + getLoadKey() + " Filled with " + applied + " VOID_AIR blocks."); - - smartBored = true; - lock.unlock(); - } - - public synchronized IrisObject copy() - { - IrisObject o = new IrisObject(w, h, d); - o.setLoadKey(o.getLoadKey()); - o.setCenter(getCenter().clone()); - - for(BlockVector i : getBlocks().keySet()) - { - o.getBlocks().put(i.clone(), Objects.requireNonNull(getBlocks().get(i)).clone()); - } - - for(BlockVector i : getStates().keySet()) - { - o.getStates().put(i.clone(), Objects.requireNonNull(getStates().get(i)).clone()); - } - - return o; - } - - public IrisObject(int w, int h, int d) - { - blocks = new KMap<>(); - states = new KMap<>(); - this.w = w; - this.h = h; - this.d = d; - center = new BlockVector(w / 2, h / 2, d / 2); - } - - @SuppressWarnings("resource") - public static BlockVector sampleSize(File file) throws IOException - { - FileInputStream in = new FileInputStream(file); - DataInputStream din = new DataInputStream(in); - BlockVector bv = new BlockVector(din.readInt(), din.readInt(), din.readInt()); - Iris.later(din::close); - return bv; - } - - public void readLegacy(InputStream in) throws IOException - { - DataInputStream din = new DataInputStream(in); - this.w = din.readInt(); - this.h = din.readInt(); - this.d = din.readInt(); - center = new BlockVector(w / 2, h / 2, d / 2); - int s = din.readInt(); - - for(int i = 0; i < s; i++) - { - getBlocks().put(new BlockVector(din.readShort(), din.readShort(), din.readShort()), B.get(din.readUTF())); - } - - try - { - int size = din.readInt(); - - for(int i = 0; i < size; i++) - { - getStates().put(new BlockVector(din.readShort(), din.readShort(), din.readShort()), TileData.read(din)); - } - } - - catch(Throwable ignored) - { - - } - } - - public void read(InputStream in) throws Throwable - { - DataInputStream din = new DataInputStream(in); - this.w = din.readInt(); - this.h = din.readInt(); - this.d = din.readInt(); - if(!din.readUTF().equals("Iris V2 IOB;")) - { - throw new IOException("Not V2 Format"); - } - center = new BlockVector(w / 2, h / 2, d / 2); - int s = din.readShort(); - int i; - KList palette = new KList<>(); - - for(i = 0; i < s; i++) - { - palette.add(din.readUTF()); - } - - s = din.readInt(); - - for(i = 0; i < s; i++) - { - getBlocks().put(new BlockVector(din.readShort(), din.readShort(), din.readShort()), B.get(palette.get(din.readShort()))); - } - - s = din.readInt(); - - for(i = 0; i < s; i++) - { - getStates().put(new BlockVector(din.readShort(), din.readShort(), din.readShort()), TileData.read(din)); - } - } - - public void write(OutputStream o) throws IOException - { - DataOutputStream dos = new DataOutputStream(o); - dos.writeInt(w); - dos.writeInt(h); - dos.writeInt(d); - dos.writeUTF("Iris V2 IOB;"); - KList palette = new KList<>(); - - for(BlockData i : getBlocks().values()) - { - palette.addIfMissing(i.getAsString()); - } - - dos.writeShort(palette.size()); - - for(String i : palette) - { - dos.writeUTF(i); - } - - dos.writeInt(getBlocks().size()); - - for(BlockVector i : getBlocks().keySet()) - { - dos.writeShort(i.getBlockX()); - dos.writeShort(i.getBlockY()); - dos.writeShort(i.getBlockZ()); - dos.writeShort(palette.indexOf(Objects.requireNonNull(getBlocks().get(i)).getAsString())); - } - - dos.writeInt(getStates().size()); - for(BlockVector i : getStates().keySet()) - { - dos.writeShort(i.getBlockX()); - dos.writeShort(i.getBlockY()); - dos.writeShort(i.getBlockZ()); - Objects.requireNonNull(getStates().get(i)).toBinary(dos); - } - } - - public void read(File file) throws IOException - { - if(shitty) - { - return; - } - - FileInputStream fin = new FileInputStream(file); - try - { - read(fin); - fin.close(); - } - - catch(Throwable e) - { - fin.close(); - fin = new FileInputStream(file); - readLegacy(fin); - fin.close(); - } - } - - public void write(File file) throws IOException - { - file.getParentFile().mkdirs(); - FileOutputStream out = new FileOutputStream(file); - write(out); - out.close(); - } - - public void clean() - { - KMap d = new KMap<>(); - - for(BlockVector i : getBlocks().keySet()) - { - d.put(new BlockVector(i.getBlockX(), i.getBlockY(), i.getBlockZ()), Objects.requireNonNull(getBlocks().get(i))); - } - - KMap> dx = new KMap<>(); - - for(BlockVector i : getBlocks().keySet()) - { - d.put(new BlockVector(i.getBlockX(), i.getBlockY(), i.getBlockZ()), Objects.requireNonNull(getBlocks().get(i))); - } - - for(BlockVector i : getStates().keySet()) - { - dx.put(new BlockVector(i.getBlockX(), i.getBlockY(), i.getBlockZ()), Objects.requireNonNull(getStates().get(i))); - } - - blocks = d; - states = dx; - } - - public BlockVector 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 BlockVector(x, y, z).subtract(center).toBlockVector(); - } - - public void setUnsigned(int x, int y, int z, BlockData block) - { - BlockVector v = getSigned(x,y,z); - - if(block == null) - { - getBlocks().remove(v); - getStates().remove(v); - } - - else - { - getBlocks().put(v, block); - } - } - - public void setUnsigned(int x, int y, int z, Block block) - { - BlockVector v = getSigned(x,y,z); - - if(block == null) - { - getBlocks().remove(v); - getStates().remove(v); - } - - else - { - BlockData data = block.getBlockData(); - getBlocks().put(v, data); - TileData state = TileData.getTileState(block); - if(state != null) - { - Iris.info("Saved State " + v); - getStates().put(v, state); - } - } - } - - public int place(int x, int z, IObjectPlacer placer, IrisObjectPlacement config, RNG rng, IrisDataManager 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, IrisDataManager 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, IrisDataManager rdata) - { - return place(x, yv, z, placer, config, rng, null, null, rdata); - } - - public int place(int x, int yv, int z, IObjectPlacer oplacer, IrisObjectPlacement config, RNG rng, Consumer listener, CarveResult c, IrisDataManager rdata) - { - IObjectPlacer placer = (config.getHeightmap() != null) ? new IObjectPlacer() { - final long s = rng.nextLong() + yv + z - x; - - public int getHighest(int param1Int1, int param1Int2) { - return (int)Math.round(config.getHeightmap().getNoise(this.s, param1Int1, param1Int2)); - } - - public int getHighest(int param1Int1, int param1Int2, boolean param1Boolean) { - return (int)Math.round(config.getHeightmap().getNoise(this.s, param1Int1, param1Int2)); - } - - public void set(int param1Int1, int param1Int2, int param1Int3, BlockData param1BlockData) { - oplacer.set(param1Int1, param1Int2, param1Int3, param1BlockData); - } - - public BlockData get(int param1Int1, int param1Int2, int param1Int3) { - return oplacer.get(param1Int1, param1Int2, param1Int3); - } - - public boolean isPreventingDecay() { - return oplacer.isPreventingDecay(); - } - - public boolean isSolid(int param1Int1, int param1Int2, int param1Int3) { - return oplacer.isSolid(param1Int1, param1Int2, param1Int3); - } - - public boolean isUnderwater(int param1Int1, int param1Int2) { - return oplacer.isUnderwater(param1Int1, param1Int2); - } - - public int getFluidHeight() { - return oplacer.getFluidHeight(); - } - - public boolean isDebugSmartBore() { - return oplacer.isDebugSmartBore(); - } - - public void setTile(int param1Int1, int param1Int2, int param1Int3, TileData param1TileData) { - oplacer.setTile(param1Int1, param1Int2, param1Int3, param1TileData); - } - } : oplacer; - - if(config.isSmartBore()) - { - ensureSmartBored(placer.isDebugSmartBore()); - } - - boolean warped = !config.getWarp().isFlat(); - boolean stilting = (config.getMode().equals(ObjectPlaceMode.STILT) || config.getMode().equals(ObjectPlaceMode.FAST_STILT)); - KMap heightmap = config.getSnow() > 0 ? new KMap<>() : null; - int spinx = rng.imax() / 1000; - int spiny = rng.imax() / 1000; - int spinz = rng.imax() / 1000; - int rty = config.getRotation().rotate(new BlockVector(0, getCenter().getBlockY(), 0), spinx, spiny, spinz).getBlockY(); - int ty = config.getTranslate().translate(new BlockVector(0, getCenter().getBlockY(), 0), config.getRotation(), spinx, spiny, spinz).getBlockY(); - int y = -1; - int xx, zz; - int yrand = config.getTranslate().getYRandom(); - yrand = yrand > 0 ? rng.i(0, yrand) : yrand < 0 ? rng.i(yrand, 0) : yrand; - - if(yv < 0) - { - if(config.getMode().equals(ObjectPlaceMode.CENTER_HEIGHT)) - { - y = (c != null ? c.getSurface() : placer.getHighest(x, z, config.isUnderwater())) + rty; - } - - else if(config.getMode().equals(ObjectPlaceMode.MAX_HEIGHT) || config.getMode().equals(ObjectPlaceMode.STILT)) - { - BlockVector offset = new BlockVector(config.getTranslate().getX(), config.getTranslate().getY(), config.getTranslate().getZ()); - BlockVector rotatedDimensions = config.getRotation().rotate(new BlockVector(getW(), getH(), getD()), spinx, spiny, spinz).clone(); - - for(int i = x - (rotatedDimensions.getBlockX() / 2) + offset.getBlockX(); i <= x + (rotatedDimensions.getBlockX() / 2) + offset.getBlockX(); i++) - { - for(int j = z - (rotatedDimensions.getBlockZ() / 2) + offset.getBlockZ(); j <= z + (rotatedDimensions.getBlockZ() / 2) + offset.getBlockZ(); j++) - { - int h = placer.getHighest(i, j, config.isUnderwater()) + rty; - - if(h > y) - { - y = h; - } - } - } - } - - else if(config.getMode().equals(ObjectPlaceMode.FAST_MAX_HEIGHT) ||config.getMode().equals(ObjectPlaceMode.VACUUM) || config.getMode().equals(ObjectPlaceMode.FAST_STILT)) - { - BlockVector offset = new BlockVector(config.getTranslate().getX(), config.getTranslate().getY(), config.getTranslate().getZ()); - BlockVector rotatedDimensions = config.getRotation().rotate(new BlockVector(getW(), getH(), getD()), spinx, spiny, spinz).clone(); - - for(int i = x - (rotatedDimensions.getBlockX() / 2) + offset.getBlockX(); i <= x + (rotatedDimensions.getBlockX() / 2) + offset.getBlockX(); i += (rotatedDimensions.getBlockX() / 2)+1) - { - for(int j = z - (rotatedDimensions.getBlockZ() / 2) + offset.getBlockZ(); j <= z + (rotatedDimensions.getBlockZ() / 2) + offset.getBlockZ(); j += (rotatedDimensions.getBlockZ() / 2)+1) - { - int h = placer.getHighest(i, j, config.isUnderwater()) + rty; - - if(h > y) - { - y = h; - } - } - } - } - - else if(config.getMode().equals(ObjectPlaceMode.MIN_HEIGHT)) - { - y = 257; - BlockVector offset = new BlockVector(config.getTranslate().getX(), config.getTranslate().getY(), config.getTranslate().getZ()); - BlockVector rotatedDimensions = config.getRotation().rotate(new BlockVector(getW(), getH(), getD()), spinx, spiny, spinz).clone(); - - for(int i = x - (rotatedDimensions.getBlockX() / 2) + offset.getBlockX(); i <= x + (rotatedDimensions.getBlockX() / 2) + offset.getBlockX(); i++) - { - for(int j = z - (rotatedDimensions.getBlockZ() / 2) + offset.getBlockZ(); j <= z + (rotatedDimensions.getBlockZ() / 2) + offset.getBlockZ(); j++) - { - int h = placer.getHighest(i, j, config.isUnderwater()) + rty; - - if(h < y) - { - y = h; - } - } - } - } - - else if(config.getMode().equals(ObjectPlaceMode.FAST_MIN_HEIGHT)) - { - y = 257; - BlockVector offset = new BlockVector(config.getTranslate().getX(), config.getTranslate().getY(), config.getTranslate().getZ()); - BlockVector rotatedDimensions = config.getRotation().rotate(new BlockVector(getW(), getH(), getD()), spinx, spiny, spinz).clone(); - - for(int i = x - (rotatedDimensions.getBlockX() / 2) + offset.getBlockX(); i <= x + (rotatedDimensions.getBlockX() / 2) + offset.getBlockX(); i += (rotatedDimensions.getBlockX() / 2)+1) - { - for(int j = z - (rotatedDimensions.getBlockZ() / 2) + offset.getBlockZ(); j <= z + (rotatedDimensions.getBlockZ() / 2) + offset.getBlockZ(); j += (rotatedDimensions.getBlockZ() / 2)+1) - { - int h = placer.getHighest(i, j, config.isUnderwater()) + rty; - - if(h < y) - { - y = h; - } - } - } - } - - else if(config.getMode().equals(ObjectPlaceMode.PAINT)) - { - y = placer.getHighest(x, z, config.isUnderwater()) + rty; - } - } - - else - { - y = yv; - } - - if(yv >= 0 && config.isBottom()) - { - y += Math.floorDiv(h, 2); - } - - if(yv < 0) - { - if(!config.isUnderwater() && !config.isOnwater() && placer.isUnderwater(x, z)) - { - return -1; - } - } - - if(c != null && Math.max(0, h + yrand + ty) + 1 >= c.getHeight()) - { - return -1; - } - - if(config.isUnderwater() && y + rty + ty >= placer.getFluidHeight()) - { - return -1; - } - - if(!config.getClamp().canPlace(y + rty + ty, y - rty + ty)) - { - return -1; - } - - if(config.isBore()) - { - BlockVector offset = new BlockVector(config.getTranslate().getX(), config.getTranslate().getY(), config.getTranslate().getZ()); - for(int i = x - Math.floorDiv(w, 2) + (int) offset.getX(); i <= x + Math.floorDiv(w, 2) - (w % 2 == 0 ? 1 : 0) + (int) offset.getX(); i++) - { - for(int j = y - Math.floorDiv(h, 2) - config.getBoreExtendMinY() + (int) offset.getY(); j <= y + Math.floorDiv(h, 2) + config.getBoreExtendMaxY() - (h % 2 == 0 ? 1 : 0) + (int) offset.getY(); j++) - { - for(int k = z - Math.floorDiv(d, 2) + (int) offset.getZ(); k <= z + Math.floorDiv(d, 2) - (d % 2 == 0 ? 1 : 0) + (int) offset.getX(); k++) - { - placer.set(i, j, k, AIR); - } - } - } - } - - int lowest = Integer.MAX_VALUE; - y += yrand; - readLock.lock(); - for(BlockVector g : getBlocks().keySet()) - { - BlockData d; - TileData tile = null; - - try - { - d = getBlocks().get(g); - tile = getStates().get(g); - } - - catch(Throwable e) - { - Iris.warn("Failed to read block node " + g.getBlockX() + "," + g.getBlockY() + "," + g.getBlockZ() + " in object " + getLoadKey() + " (cme)"); - d = AIR; - } - - if(d == null) - { - Iris.warn("Failed to read block node " + g.getBlockX() + "," + g.getBlockY() + "," + g.getBlockZ() + " in object " + getLoadKey() + " (null)"); - d = AIR; - } - - BlockVector i = g.clone(); - BlockData data = d.clone(); - i = config.getRotation().rotate(i.clone(), spinx, spiny, spinz).clone(); - i = config.getTranslate().translate(i.clone(), config.getRotation(), spinx, spiny, spinz).clone(); - - if(stilting && i.getBlockY() < lowest && !B.isAir(data)) - { - lowest = i.getBlockY(); - } - - if(placer.isPreventingDecay() && (data) instanceof Leaves && !((Leaves) (data)).isPersistent()) - { - ((Leaves) data).setPersistent(true); - } - - for(IrisObjectReplace j : config.getEdit()) - { - if (rng.chance(j.getChance())) { - for(BlockData k : j.getFind(rdata)) - { - if (j.isExact() ? k.matches(data) : k.getMaterial().equals(data.getMaterial())) { - BlockData newData = j.getReplace(rng, i.getX() + x, i.getY() + y, i.getZ() + z, rdata).clone(); - - if (newData.getMaterial() == data.getMaterial()) - data = data.merge(newData); - else - data = newData; - } - } - } - } - - data = config.getRotation().rotate(data, spinx, spiny, spinz); - xx = x + (int) Math.round(i.getX()); - int yy = y + (int) Math.round(i.getY()); - zz = z + (int) Math.round(i.getZ()); - - if(warped) - { - xx += config.warp(rng, i.getX() + x, i.getY() + y, i.getZ() + z); - zz += config.warp(rng, i.getZ() + z, i.getY() + y, i.getX() + x); - } - - if(yv < 0 && (config.getMode().equals(ObjectPlaceMode.PAINT))) - { - yy = (int) Math.round(i.getY()) + Math.floorDiv(h, 2) + placer.getHighest(xx, zz, config.isUnderwater()); - } - - if(heightmap != null) - { - ChunkPosition pos = new ChunkPosition(xx, zz); - - if(!heightmap.containsKey(pos)) - { - heightmap.put(pos, yy); - } - - if(heightmap.get(pos) < yy) - { - heightmap.put(pos, yy); - } - } - - if(config.isMeld() && !placer.isSolid(xx, yy, zz)) - { - continue; - } - - if(config.isWaterloggable() && yy <= placer.getFluidHeight() && data instanceof Waterlogged) - { - ((Waterlogged) data).setWaterlogged(true); - } - - if(listener != null) - { - listener.accept(new BlockPosition(xx, yy, zz)); - } - - if(!data.getMaterial().equals(Material.AIR) && !data.getMaterial().equals(Material.CAVE_AIR)) - { - placer.set(xx, yy, zz, data); - - if(tile != null) - { - placer.setTile(xx, yy, zz, tile); - } - } - } - readLock.unlock(); - - if(stilting) - { - readLock.lock(); - for(BlockVector g : getBlocks().keySet()) - { - BlockData d; - - try - { - d = getBlocks().get(g); - } - - catch(Throwable e) - { - Iris.warn("Failed to read block node " + g.getBlockX() + "," + g.getBlockY() + "," + g.getBlockZ() + " in object " + getLoadKey() + " (stilt cme)"); - d = AIR; - } - - if(d == null) - { - Iris.warn("Failed to read block node " + g.getBlockX() + "," + g.getBlockY() + "," + g.getBlockZ() + " in object " + getLoadKey() + " (stilt null)"); - d = AIR; - } - - BlockVector i = g.clone(); - i = config.getRotation().rotate(i.clone(), spinx, spiny, spinz).clone(); - i = config.getTranslate().translate(i.clone(), config.getRotation(), spinx, spiny, spinz).clone(); - - if(i.getBlockY() != lowest) - { - continue; - } - - - if(d == null || B.isAir(d)) - { - continue; - } - - xx = x + (int) Math.round(i.getX()); - zz = z + (int) Math.round(i.getZ()); - - if(warped) - { - xx += config.warp(rng, i.getX() + x, i.getY() + y, i.getZ() + z); - zz += config.warp(rng, i.getZ() + z, i.getY() + y, i.getX() + x); - } - - int yg = placer.getHighest(xx, zz, config.isUnderwater()); - - if(yv >= 0 && config.isBottom()) - { - y += Math.floorDiv(h, 2); - } - - for(int j = lowest + y; j > yg - config.getOverStilt() - 1; j--) - { - placer.set(xx, j, zz, d); - } - } - - readLock.unlock(); - } - - if(heightmap != null) - { - RNG rngx = rng.nextParallelRNG(3468854); - - for(ChunkPosition i : heightmap.k()) - { - int vx = i.getX(); - int vy = heightmap.get(i); - int vz = i.getZ(); - - if(config.getSnow() > 0) - { - int height = rngx.i(0, (int) (config.getSnow() * 7)); - placer.set(vx, vy + 1, vz, SNOW_LAYERS[Math.max(Math.min(height, 7), 0)]); - } - } - } - - return y; - } - - public IrisObject rotateCopy(IrisObjectRotation rt) { - IrisObject copy = copy(); - copy.rotate(rt, 0, 0, 0); - return copy; - } - - public void rotate(IrisObjectRotation r, int spinx, int spiny, int spinz) - { - KMap d = new KMap<>(); - - for(BlockVector i : getBlocks().keySet()) - { - d.put(r.rotate(i.clone(), spinx, spiny, spinz), r.rotate(Objects.requireNonNull(getBlocks().get(i)).clone(), spinx, spiny, spinz)); - } - - KMap> dx = new KMap<>(); - - for(BlockVector i : getStates().keySet()) - { - dx.put(r.rotate(i.clone(), spinx, spiny, spinz), Objects.requireNonNull(getStates().get(i))); - } - - blocks = d; - states = dx; - } - - public void place(Location at) - { - for(BlockVector i : getBlocks().keySet()) - { - Block b = at.clone().add(0, getCenter().getY(), 0).add(i).getBlock(); - b.setBlockData(Objects.requireNonNull(getBlocks().get(i)), false); - - if(getStates().containsKey(i)) - { - Iris.info(Objects.requireNonNull(states.get(i)).toString()); - BlockState st = b.getState(); - Objects.requireNonNull(getStates().get(i)).toBukkitTry(st); - st.update(); - } - } - } - - public void placeCenterY(Location at) - { - for(BlockVector i : getBlocks().keySet()) - { - Block b = at.clone().add(getCenter().getX(), getCenter().getY(), getCenter().getZ()).add(i).getBlock(); - b.setBlockData(Objects.requireNonNull(getBlocks().get(i)), false); - - if(getStates().containsKey(i)) - { - Objects.requireNonNull(getStates().get(i)).toBukkitTry(b.getState()); - } - } - } - - public synchronized KMap getBlocks() - { - return blocks; - } - - public synchronized KMap> getStates() - { - return states; - } - - public void unplaceCenterY(Location at) - { - for(BlockVector i : getBlocks().keySet()) - { - at.clone().add(getCenter().getX(), getCenter().getY(), getCenter().getZ()).add(i).getBlock().setBlockData(AIR, false); - } - } - - public IrisObject scaled(double scale) { - Vector sm1 = new Vector(scale-1, scale-1, scale-1); - scale = Math.max(0.001, Math.min(50, scale)); - if (scale<1){ - scale = scale-0.0001; - } - - IrisPosition l1 = getAABB().max(); - IrisPosition l2 = getAABB().min(); - Vector center = getCenter(); - if (getH()==2){ - center = center.setY(center.getBlockY() + 0.5); - } - if (getW()==2){ - center = center.setX(center.getBlockX()+0.5); - } - if (getD()==2){ - center = center.setZ(center.getBlockZ()+0.5); - } - HashMap placeBlock = new HashMap(); - - IrisObject oo = new IrisObject((int)Math.ceil((w * scale) + (scale*2)), (int)Math.ceil((h * scale) + (scale * 2)), (int)Math.ceil((d * scale) + (scale * 2))); - - for(BlockVector i : blocks.keySet()) - { - BlockData bd = blocks.get(i); - placeBlock.put(i.clone().add(HALF).subtract(center) - .multiply(scale).toBlockVector(), bd); - } - - for (BlockVector v : placeBlock.keySet()){ - if (scale>1) { - for (BlockVector vec : blocksBetweenTwoPoints(v.clone().add(center), v.clone().add(center).add(sm1))) { - oo.getBlocks().put(vec, placeBlock.get(v)); - } - } - - else { - oo.setUnsigned(v.getBlockX(), v.getBlockY(), v.getBlockZ(), placeBlock.get(v)); - } - } - - if(scale > 1) - { - // oo.trihermite((int) Math.round(scale)); - } - - return oo; - } - - public void trilinear(int rad) - { - KMap v = getBlocks().copy(); - KMap b = new KMap<>(); - BlockVector min = getAABB().minbv(); - BlockVector max = getAABB().maxbv(); - - for(int x = min.getBlockX(); x <= max.getBlockX(); x++) - { - for(int y = min.getBlockY(); y <= max.getBlockY(); y++) - { - for(int z = min.getBlockZ(); z <= max.getBlockZ(); z++) - { - if(IrisInterpolation.getTrilinear(x,y,z,rad, (xx,yy,zz) -> { - BlockData data = v.get(new BlockVector((int)xx,(int)yy,(int)zz)); - - if(data == null || data.getMaterial().isAir()) - { - return 0; - } - - return 1; - }) >= 0.5) - { - b.put(new BlockVector(x,y,z), nearestBlockData(x,y,z)); - } - - else - { - b.put(new BlockVector(x,y,z), AIR); - } - } - } - } - - setBlocks(b); - } - - public void tricubic(int rad) - { - KMap v = getBlocks().copy(); - KMap b = new KMap<>(); - BlockVector min = getAABB().minbv(); - BlockVector max = getAABB().maxbv(); - - for(int x = min.getBlockX(); x <= max.getBlockX(); x++) - { - for(int y = min.getBlockY(); y <= max.getBlockY(); y++) - { - for(int z = min.getBlockZ(); z <= max.getBlockZ(); z++) - { - if(IrisInterpolation.getTricubic(x,y,z,rad, (xx,yy,zz) -> { - BlockData data = v.get(new BlockVector((int)xx,(int)yy,(int)zz)); - - if(data == null || data.getMaterial().isAir()) - { - return 0; - } - - return 1; - }) >= 0.5) - { - b.put(new BlockVector(x,y,z), nearestBlockData(x,y,z)); - } - - else - { - b.put(new BlockVector(x,y,z), AIR); - } - } - } - } - - setBlocks(b); - } - - public void trihermite(int rad) - { - trihermite(rad, 0D, 0D); - } - - public void trihermite(int rad, double tension, double bias) - { - KMap v = getBlocks().copy(); - KMap b = new KMap<>(); - BlockVector min = getAABB().minbv(); - BlockVector max = getAABB().maxbv(); - - for(int x = min.getBlockX(); x <= max.getBlockX(); x++) - { - for(int y = min.getBlockY(); y <= max.getBlockY(); y++) - { - for(int z = min.getBlockZ(); z <= max.getBlockZ(); z++) - { - if(IrisInterpolation.getTrihermite(x,y,z,rad, (xx,yy,zz) -> { - BlockData data = v.get(new BlockVector((int)xx,(int)yy,(int)zz)); - - if(data == null || data.getMaterial().isAir()) - { - return 0; - } - - return 1; - }, tension, bias) >= 0.5) - { - b.put(new BlockVector(x,y,z), nearestBlockData(x,y,z)); - } - - else - { - b.put(new BlockVector(x,y,z), AIR); - } - } - } - } - - setBlocks(b); - } - - private BlockData nearestBlockData(int x, int y, int z) { - BlockVector vv = new BlockVector(x,y,z); - BlockData r = getBlocks().get(vv); - - if(r != null && !r.getMaterial().isAir()) - { - return r; - } - - double d = Double.MAX_VALUE; - - for(BlockVector i : blocks.keySet()) - { - BlockData dat = blocks.get(i); - - if(dat.getMaterial().isAir()) - { - continue; - } - - double dx = i.distanceSquared(vv); - - if(dx < d) - { - d = dx; - r = dat; - } - } - - return r; - } - - private static List blocksBetweenTwoPoints(Vector loc1, Vector 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 BlockVector(x, y, z)); - } - } - } - return locations; - } +public class IrisObject extends IrisRegistrant { + private static final Vector HALF = new Vector(0.5, 0.5, 0.5); + private static final BlockData AIR = B.get("CAVE_AIR"); + private static final BlockData VAIR = B.get("VOID_AIR"); + private static final BlockData VAIR_DEBUG = B.get("COBWEB"); + private static final BlockData[] SNOW_LAYERS = new BlockData[]{B.get("minecraft:snow[layers=1]"), B.get("minecraft:snow[layers=2]"), B.get("minecraft:snow[layers=3]"), B.get("minecraft:snow[layers=4]"), B.get("minecraft:snow[layers=5]"), B.get("minecraft:snow[layers=6]"), B.get("minecraft:snow[layers=7]"), B.get("minecraft:snow[layers=8]")}; + public static boolean shitty = false; + private KMap blocks; + private KMap> states; + private int w; + private int d; + private int h; + private transient final IrisLock readLock = new IrisLock("read-conclock"); + private transient BlockVector center; + private transient volatile boolean smartBored = false; + private transient IrisLock lock = new IrisLock("Preloadcache"); + private transient AtomicCache aabb; + + public AxisAlignedBB getAABB() { + return getAABBFor(new BlockVector(w, h, d)); + } + + public static BlockVector getCenterForSize(BlockVector size) { + return new BlockVector(size.getX() / 2, size.getY() / 2, size.getZ() / 2); + } + + public static AxisAlignedBB getAABBFor(BlockVector size) { + BlockVector center = new BlockVector(size.getX() / 2, size.getY() / 2, size.getZ() / 2); + return new AxisAlignedBB(new IrisPosition(new BlockVector(0, 0, 0).subtract(center).toBlockVector()), + new IrisPosition(new BlockVector(size.getX() - 1, size.getY() - 1, size.getZ() - 1).subtract(center).toBlockVector())); + } + + public void ensureSmartBored(boolean debug) { + if (smartBored) { + return; + } + + lock.lock(); + int applied = 0; + if (getBlocks().isEmpty()) { + lock.unlock(); + Iris.warn("Cannot Smart Bore " + getLoadKey() + " because it has 0 blocks in it."); + smartBored = true; + return; + } + + BlockVector max = new BlockVector(Double.MIN_VALUE, Double.MIN_VALUE, Double.MIN_VALUE); + BlockVector min = new BlockVector(Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE); + + for (BlockVector i : getBlocks().keySet()) { + 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())); + } + + // Smash X + for (int rayY = min.getBlockY(); rayY <= max.getBlockY(); rayY++) { + 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 (getBlocks().containsKey(new BlockVector(ray, rayY, 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++) { + BlockVector v = new BlockVector(i, rayY, rayZ); + + if (!getBlocks().containsKey(v) || B.isAir(getBlocks().get(v))) { + getBlocks().put(v, debug ? VAIR_DEBUG : VAIR); + applied++; + } + } + } + } + } + + // Smash Y + for (int rayX = min.getBlockX(); rayX <= max.getBlockX(); rayX++) { + 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 (getBlocks().containsKey(new BlockVector(rayX, 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++) { + BlockVector v = new BlockVector(rayX, i, rayZ); + + if (!getBlocks().containsKey(v) || B.isAir(getBlocks().get(v))) { + getBlocks().put(v, debug ? VAIR_DEBUG : VAIR); + applied++; + } + } + } + } + } + + // Smash Z + for (int rayX = min.getBlockX(); rayX <= max.getBlockX(); rayX++) { + 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 (getBlocks().containsKey(new BlockVector(rayX, 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++) { + BlockVector v = new BlockVector(rayX, rayY, i); + + if (!getBlocks().containsKey(v) || B.isAir(getBlocks().get(v))) { + getBlocks().put(v, debug ? VAIR_DEBUG : VAIR); + applied++; + } + } + } + } + } + + Iris.verbose("- Applied Smart Bore to " + getLoadKey() + " Filled with " + applied + " VOID_AIR blocks."); + + smartBored = true; + lock.unlock(); + } + + public synchronized IrisObject copy() { + IrisObject o = new IrisObject(w, h, d); + o.setLoadKey(o.getLoadKey()); + o.setCenter(getCenter().clone()); + + for (BlockVector i : getBlocks().keySet()) { + o.getBlocks().put(i.clone(), Objects.requireNonNull(getBlocks().get(i)).clone()); + } + + for (BlockVector i : getStates().keySet()) { + o.getStates().put(i.clone(), Objects.requireNonNull(getStates().get(i)).clone()); + } + + return o; + } + + public IrisObject(int w, int h, int d) { + blocks = new KMap<>(); + states = new KMap<>(); + this.w = w; + this.h = h; + this.d = d; + center = new BlockVector(w / 2, h / 2, d / 2); + } + + @SuppressWarnings("resource") + public static BlockVector sampleSize(File file) throws IOException { + FileInputStream in = new FileInputStream(file); + DataInputStream din = new DataInputStream(in); + BlockVector bv = new BlockVector(din.readInt(), din.readInt(), din.readInt()); + Iris.later(din::close); + return bv; + } + + public void readLegacy(InputStream in) throws IOException { + DataInputStream din = new DataInputStream(in); + this.w = din.readInt(); + this.h = din.readInt(); + this.d = din.readInt(); + center = new BlockVector(w / 2, h / 2, d / 2); + int s = din.readInt(); + + for (int i = 0; i < s; i++) { + getBlocks().put(new BlockVector(din.readShort(), din.readShort(), din.readShort()), B.get(din.readUTF())); + } + + try { + int size = din.readInt(); + + for (int i = 0; i < size; i++) { + getStates().put(new BlockVector(din.readShort(), din.readShort(), din.readShort()), TileData.read(din)); + } + } catch (Throwable ignored) { + + } + } + + public void read(InputStream in) throws Throwable { + DataInputStream din = new DataInputStream(in); + this.w = din.readInt(); + this.h = din.readInt(); + this.d = din.readInt(); + if (!din.readUTF().equals("Iris V2 IOB;")) { + throw new IOException("Not V2 Format"); + } + center = new BlockVector(w / 2, h / 2, d / 2); + int s = din.readShort(); + int i; + KList palette = new KList<>(); + + for (i = 0; i < s; i++) { + palette.add(din.readUTF()); + } + + s = din.readInt(); + + for (i = 0; i < s; i++) { + getBlocks().put(new BlockVector(din.readShort(), din.readShort(), din.readShort()), B.get(palette.get(din.readShort()))); + } + + s = din.readInt(); + + for (i = 0; i < s; i++) { + getStates().put(new BlockVector(din.readShort(), din.readShort(), din.readShort()), TileData.read(din)); + } + } + + public void write(OutputStream o) throws IOException { + DataOutputStream dos = new DataOutputStream(o); + dos.writeInt(w); + dos.writeInt(h); + dos.writeInt(d); + dos.writeUTF("Iris V2 IOB;"); + KList palette = new KList<>(); + + for (BlockData i : getBlocks().values()) { + palette.addIfMissing(i.getAsString()); + } + + dos.writeShort(palette.size()); + + for (String i : palette) { + dos.writeUTF(i); + } + + dos.writeInt(getBlocks().size()); + + for (BlockVector i : getBlocks().keySet()) { + dos.writeShort(i.getBlockX()); + dos.writeShort(i.getBlockY()); + dos.writeShort(i.getBlockZ()); + dos.writeShort(palette.indexOf(Objects.requireNonNull(getBlocks().get(i)).getAsString())); + } + + dos.writeInt(getStates().size()); + for (BlockVector i : getStates().keySet()) { + dos.writeShort(i.getBlockX()); + dos.writeShort(i.getBlockY()); + dos.writeShort(i.getBlockZ()); + Objects.requireNonNull(getStates().get(i)).toBinary(dos); + } + } + + public void read(File file) throws IOException { + if (shitty) { + return; + } + + FileInputStream fin = new FileInputStream(file); + try { + read(fin); + fin.close(); + } catch (Throwable e) { + fin.close(); + fin = new FileInputStream(file); + readLegacy(fin); + fin.close(); + } + } + + public void write(File file) throws IOException { + file.getParentFile().mkdirs(); + FileOutputStream out = new FileOutputStream(file); + write(out); + out.close(); + } + + public void clean() { + KMap d = new KMap<>(); + + for (BlockVector i : getBlocks().keySet()) { + d.put(new BlockVector(i.getBlockX(), i.getBlockY(), i.getBlockZ()), Objects.requireNonNull(getBlocks().get(i))); + } + + KMap> dx = new KMap<>(); + + for (BlockVector i : getBlocks().keySet()) { + d.put(new BlockVector(i.getBlockX(), i.getBlockY(), i.getBlockZ()), Objects.requireNonNull(getBlocks().get(i))); + } + + for (BlockVector i : getStates().keySet()) { + dx.put(new BlockVector(i.getBlockX(), i.getBlockY(), i.getBlockZ()), Objects.requireNonNull(getStates().get(i))); + } + + blocks = d; + states = dx; + } + + public BlockVector 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 BlockVector(x, y, z).subtract(center).toBlockVector(); + } + + public void setUnsigned(int x, int y, int z, BlockData block) { + BlockVector v = getSigned(x, y, z); + + if (block == null) { + getBlocks().remove(v); + getStates().remove(v); + } else { + getBlocks().put(v, block); + } + } + + public void setUnsigned(int x, int y, int z, Block block) { + BlockVector v = getSigned(x, y, z); + + if (block == null) { + getBlocks().remove(v); + getStates().remove(v); + } else { + BlockData data = block.getBlockData(); + getBlocks().put(v, data); + TileData state = TileData.getTileState(block); + if (state != null) { + Iris.info("Saved State " + v); + getStates().put(v, state); + } + } + } + + public int place(int x, int z, IObjectPlacer placer, IrisObjectPlacement config, RNG rng, IrisDataManager 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, IrisDataManager 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, IrisDataManager rdata) { + return place(x, yv, z, placer, config, rng, null, null, rdata); + } + + public int place(int x, int yv, int z, IObjectPlacer oplacer, IrisObjectPlacement config, RNG rng, Consumer listener, CarveResult c, IrisDataManager rdata) { + IObjectPlacer placer = (config.getHeightmap() != null) ? new IObjectPlacer() { + final long s = rng.nextLong() + yv + z - x; + + public int getHighest(int param1Int1, int param1Int2) { + return (int) Math.round(config.getHeightmap().getNoise(this.s, param1Int1, param1Int2)); + } + + public int getHighest(int param1Int1, int param1Int2, boolean param1Boolean) { + return (int) Math.round(config.getHeightmap().getNoise(this.s, param1Int1, param1Int2)); + } + + public void set(int param1Int1, int param1Int2, int param1Int3, BlockData param1BlockData) { + oplacer.set(param1Int1, param1Int2, param1Int3, param1BlockData); + } + + public BlockData get(int param1Int1, int param1Int2, int param1Int3) { + return oplacer.get(param1Int1, param1Int2, param1Int3); + } + + public boolean isPreventingDecay() { + return oplacer.isPreventingDecay(); + } + + public boolean isSolid(int param1Int1, int param1Int2, int param1Int3) { + return oplacer.isSolid(param1Int1, param1Int2, param1Int3); + } + + public boolean isUnderwater(int param1Int1, int param1Int2) { + return oplacer.isUnderwater(param1Int1, param1Int2); + } + + public int getFluidHeight() { + return oplacer.getFluidHeight(); + } + + public boolean isDebugSmartBore() { + return oplacer.isDebugSmartBore(); + } + + public void setTile(int param1Int1, int param1Int2, int param1Int3, TileData param1TileData) { + oplacer.setTile(param1Int1, param1Int2, param1Int3, param1TileData); + } + } : oplacer; + + if (config.isSmartBore()) { + ensureSmartBored(placer.isDebugSmartBore()); + } + + boolean warped = !config.getWarp().isFlat(); + boolean stilting = (config.getMode().equals(ObjectPlaceMode.STILT) || config.getMode().equals(ObjectPlaceMode.FAST_STILT)); + KMap heightmap = config.getSnow() > 0 ? new KMap<>() : null; + int spinx = rng.imax() / 1000; + int spiny = rng.imax() / 1000; + int spinz = rng.imax() / 1000; + int rty = config.getRotation().rotate(new BlockVector(0, getCenter().getBlockY(), 0), spinx, spiny, spinz).getBlockY(); + int ty = config.getTranslate().translate(new BlockVector(0, getCenter().getBlockY(), 0), config.getRotation(), spinx, spiny, spinz).getBlockY(); + int y = -1; + int xx, zz; + int yrand = config.getTranslate().getYRandom(); + yrand = yrand > 0 ? rng.i(0, yrand) : yrand < 0 ? rng.i(yrand, 0) : yrand; + + if (yv < 0) { + if (config.getMode().equals(ObjectPlaceMode.CENTER_HEIGHT)) { + y = (c != null ? c.getSurface() : placer.getHighest(x, z, config.isUnderwater())) + rty; + } else if (config.getMode().equals(ObjectPlaceMode.MAX_HEIGHT) || config.getMode().equals(ObjectPlaceMode.STILT)) { + BlockVector offset = new BlockVector(config.getTranslate().getX(), config.getTranslate().getY(), config.getTranslate().getZ()); + BlockVector rotatedDimensions = config.getRotation().rotate(new BlockVector(getW(), getH(), getD()), spinx, spiny, spinz).clone(); + + for (int i = x - (rotatedDimensions.getBlockX() / 2) + offset.getBlockX(); i <= x + (rotatedDimensions.getBlockX() / 2) + offset.getBlockX(); i++) { + for (int j = z - (rotatedDimensions.getBlockZ() / 2) + offset.getBlockZ(); j <= z + (rotatedDimensions.getBlockZ() / 2) + offset.getBlockZ(); j++) { + int h = placer.getHighest(i, j, config.isUnderwater()) + rty; + + if (h > y) { + y = h; + } + } + } + } else if (config.getMode().equals(ObjectPlaceMode.FAST_MAX_HEIGHT) || config.getMode().equals(ObjectPlaceMode.VACUUM) || config.getMode().equals(ObjectPlaceMode.FAST_STILT)) { + BlockVector offset = new BlockVector(config.getTranslate().getX(), config.getTranslate().getY(), config.getTranslate().getZ()); + BlockVector rotatedDimensions = config.getRotation().rotate(new BlockVector(getW(), getH(), getD()), spinx, spiny, spinz).clone(); + + for (int i = x - (rotatedDimensions.getBlockX() / 2) + offset.getBlockX(); i <= x + (rotatedDimensions.getBlockX() / 2) + offset.getBlockX(); i += (rotatedDimensions.getBlockX() / 2) + 1) { + for (int j = z - (rotatedDimensions.getBlockZ() / 2) + offset.getBlockZ(); j <= z + (rotatedDimensions.getBlockZ() / 2) + offset.getBlockZ(); j += (rotatedDimensions.getBlockZ() / 2) + 1) { + int h = placer.getHighest(i, j, config.isUnderwater()) + rty; + + if (h > y) { + y = h; + } + } + } + } else if (config.getMode().equals(ObjectPlaceMode.MIN_HEIGHT)) { + y = 257; + BlockVector offset = new BlockVector(config.getTranslate().getX(), config.getTranslate().getY(), config.getTranslate().getZ()); + BlockVector rotatedDimensions = config.getRotation().rotate(new BlockVector(getW(), getH(), getD()), spinx, spiny, spinz).clone(); + + for (int i = x - (rotatedDimensions.getBlockX() / 2) + offset.getBlockX(); i <= x + (rotatedDimensions.getBlockX() / 2) + offset.getBlockX(); i++) { + for (int j = z - (rotatedDimensions.getBlockZ() / 2) + offset.getBlockZ(); j <= z + (rotatedDimensions.getBlockZ() / 2) + offset.getBlockZ(); j++) { + int h = placer.getHighest(i, j, config.isUnderwater()) + rty; + + if (h < y) { + y = h; + } + } + } + } else if (config.getMode().equals(ObjectPlaceMode.FAST_MIN_HEIGHT)) { + y = 257; + BlockVector offset = new BlockVector(config.getTranslate().getX(), config.getTranslate().getY(), config.getTranslate().getZ()); + BlockVector rotatedDimensions = config.getRotation().rotate(new BlockVector(getW(), getH(), getD()), spinx, spiny, spinz).clone(); + + for (int i = x - (rotatedDimensions.getBlockX() / 2) + offset.getBlockX(); i <= x + (rotatedDimensions.getBlockX() / 2) + offset.getBlockX(); i += (rotatedDimensions.getBlockX() / 2) + 1) { + for (int j = z - (rotatedDimensions.getBlockZ() / 2) + offset.getBlockZ(); j <= z + (rotatedDimensions.getBlockZ() / 2) + offset.getBlockZ(); j += (rotatedDimensions.getBlockZ() / 2) + 1) { + int h = placer.getHighest(i, j, config.isUnderwater()) + rty; + + if (h < y) { + y = h; + } + } + } + } else if (config.getMode().equals(ObjectPlaceMode.PAINT)) { + y = placer.getHighest(x, z, config.isUnderwater()) + rty; + } + } else { + y = yv; + } + + if (yv >= 0 && config.isBottom()) { + y += Math.floorDiv(h, 2); + } + + if (yv < 0) { + if (!config.isUnderwater() && !config.isOnwater() && placer.isUnderwater(x, z)) { + return -1; + } + } + + if (c != null && Math.max(0, h + yrand + ty) + 1 >= c.getHeight()) { + return -1; + } + + if (config.isUnderwater() && y + rty + ty >= placer.getFluidHeight()) { + return -1; + } + + if (!config.getClamp().canPlace(y + rty + ty, y - rty + ty)) { + return -1; + } + + if (config.isBore()) { + BlockVector offset = new BlockVector(config.getTranslate().getX(), config.getTranslate().getY(), config.getTranslate().getZ()); + for (int i = x - Math.floorDiv(w, 2) + (int) offset.getX(); i <= x + Math.floorDiv(w, 2) - (w % 2 == 0 ? 1 : 0) + (int) offset.getX(); i++) { + for (int j = y - Math.floorDiv(h, 2) - config.getBoreExtendMinY() + (int) offset.getY(); j <= y + Math.floorDiv(h, 2) + config.getBoreExtendMaxY() - (h % 2 == 0 ? 1 : 0) + (int) offset.getY(); j++) { + for (int k = z - Math.floorDiv(d, 2) + (int) offset.getZ(); k <= z + Math.floorDiv(d, 2) - (d % 2 == 0 ? 1 : 0) + (int) offset.getX(); k++) { + placer.set(i, j, k, AIR); + } + } + } + } + + int lowest = Integer.MAX_VALUE; + y += yrand; + readLock.lock(); + for (BlockVector g : getBlocks().keySet()) { + BlockData d; + TileData tile = null; + + try { + d = getBlocks().get(g); + tile = getStates().get(g); + } catch (Throwable e) { + Iris.warn("Failed to read block node " + g.getBlockX() + "," + g.getBlockY() + "," + g.getBlockZ() + " in object " + getLoadKey() + " (cme)"); + d = AIR; + } + + if (d == null) { + Iris.warn("Failed to read block node " + g.getBlockX() + "," + g.getBlockY() + "," + g.getBlockZ() + " in object " + getLoadKey() + " (null)"); + d = AIR; + } + + BlockVector i = g.clone(); + BlockData data = d.clone(); + i = config.getRotation().rotate(i.clone(), spinx, spiny, spinz).clone(); + i = config.getTranslate().translate(i.clone(), config.getRotation(), spinx, spiny, spinz).clone(); + + if (stilting && i.getBlockY() < lowest && !B.isAir(data)) { + lowest = i.getBlockY(); + } + + if (placer.isPreventingDecay() && (data) instanceof Leaves && !((Leaves) (data)).isPersistent()) { + ((Leaves) data).setPersistent(true); + } + + for (IrisObjectReplace j : config.getEdit()) { + if (rng.chance(j.getChance())) { + for (BlockData k : j.getFind(rdata)) { + if (j.isExact() ? k.matches(data) : k.getMaterial().equals(data.getMaterial())) { + BlockData newData = j.getReplace(rng, i.getX() + x, i.getY() + y, i.getZ() + z, rdata).clone(); + + if (newData.getMaterial() == data.getMaterial()) + data = data.merge(newData); + else + data = newData; + } + } + } + } + + data = config.getRotation().rotate(data, spinx, spiny, spinz); + xx = x + (int) Math.round(i.getX()); + int yy = y + (int) Math.round(i.getY()); + zz = z + (int) Math.round(i.getZ()); + + if (warped) { + xx += config.warp(rng, i.getX() + x, i.getY() + y, i.getZ() + z); + zz += config.warp(rng, i.getZ() + z, i.getY() + y, i.getX() + x); + } + + if (yv < 0 && (config.getMode().equals(ObjectPlaceMode.PAINT))) { + yy = (int) Math.round(i.getY()) + Math.floorDiv(h, 2) + placer.getHighest(xx, zz, config.isUnderwater()); + } + + if (heightmap != null) { + ChunkPosition pos = new ChunkPosition(xx, zz); + + if (!heightmap.containsKey(pos)) { + heightmap.put(pos, yy); + } + + if (heightmap.get(pos) < yy) { + heightmap.put(pos, yy); + } + } + + if (config.isMeld() && !placer.isSolid(xx, yy, zz)) { + continue; + } + + if (config.isWaterloggable() && yy <= placer.getFluidHeight() && data instanceof Waterlogged) { + ((Waterlogged) data).setWaterlogged(true); + } + + if (listener != null) { + listener.accept(new BlockPosition(xx, yy, zz)); + } + + if (!data.getMaterial().equals(Material.AIR) && !data.getMaterial().equals(Material.CAVE_AIR)) { + placer.set(xx, yy, zz, data); + + if (tile != null) { + placer.setTile(xx, yy, zz, tile); + } + } + } + readLock.unlock(); + + if (stilting) { + readLock.lock(); + for (BlockVector g : getBlocks().keySet()) { + BlockData d; + + try { + d = getBlocks().get(g); + } catch (Throwable e) { + Iris.warn("Failed to read block node " + g.getBlockX() + "," + g.getBlockY() + "," + g.getBlockZ() + " in object " + getLoadKey() + " (stilt cme)"); + d = AIR; + } + + if (d == null) { + Iris.warn("Failed to read block node " + g.getBlockX() + "," + g.getBlockY() + "," + g.getBlockZ() + " in object " + getLoadKey() + " (stilt null)"); + d = AIR; + } + + BlockVector i = g.clone(); + i = config.getRotation().rotate(i.clone(), spinx, spiny, spinz).clone(); + i = config.getTranslate().translate(i.clone(), config.getRotation(), spinx, spiny, spinz).clone(); + + if (i.getBlockY() != lowest) { + continue; + } + + + if (d == null || B.isAir(d)) { + continue; + } + + xx = x + (int) Math.round(i.getX()); + zz = z + (int) Math.round(i.getZ()); + + if (warped) { + xx += config.warp(rng, i.getX() + x, i.getY() + y, i.getZ() + z); + zz += config.warp(rng, i.getZ() + z, i.getY() + y, i.getX() + x); + } + + int yg = placer.getHighest(xx, zz, config.isUnderwater()); + + if (yv >= 0 && config.isBottom()) { + y += Math.floorDiv(h, 2); + } + + for (int j = lowest + y; j > yg - config.getOverStilt() - 1; j--) { + placer.set(xx, j, zz, d); + } + } + + readLock.unlock(); + } + + if (heightmap != null) { + RNG rngx = rng.nextParallelRNG(3468854); + + for (ChunkPosition i : heightmap.k()) { + int vx = i.getX(); + int vy = heightmap.get(i); + int vz = i.getZ(); + + if (config.getSnow() > 0) { + int height = rngx.i(0, (int) (config.getSnow() * 7)); + placer.set(vx, vy + 1, vz, SNOW_LAYERS[Math.max(Math.min(height, 7), 0)]); + } + } + } + + return y; + } + + public IrisObject rotateCopy(IrisObjectRotation rt) { + IrisObject copy = copy(); + copy.rotate(rt, 0, 0, 0); + return copy; + } + + public void rotate(IrisObjectRotation r, int spinx, int spiny, int spinz) { + KMap d = new KMap<>(); + + for (BlockVector i : getBlocks().keySet()) { + d.put(r.rotate(i.clone(), spinx, spiny, spinz), r.rotate(Objects.requireNonNull(getBlocks().get(i)).clone(), spinx, spiny, spinz)); + } + + KMap> dx = new KMap<>(); + + for (BlockVector i : getStates().keySet()) { + dx.put(r.rotate(i.clone(), spinx, spiny, spinz), Objects.requireNonNull(getStates().get(i))); + } + + blocks = d; + states = dx; + } + + public void place(Location at) { + for (BlockVector i : getBlocks().keySet()) { + Block b = at.clone().add(0, getCenter().getY(), 0).add(i).getBlock(); + b.setBlockData(Objects.requireNonNull(getBlocks().get(i)), false); + + if (getStates().containsKey(i)) { + Iris.info(Objects.requireNonNull(states.get(i)).toString()); + BlockState st = b.getState(); + Objects.requireNonNull(getStates().get(i)).toBukkitTry(st); + st.update(); + } + } + } + + public void placeCenterY(Location at) { + for (BlockVector i : getBlocks().keySet()) { + Block b = at.clone().add(getCenter().getX(), getCenter().getY(), getCenter().getZ()).add(i).getBlock(); + b.setBlockData(Objects.requireNonNull(getBlocks().get(i)), false); + + if (getStates().containsKey(i)) { + Objects.requireNonNull(getStates().get(i)).toBukkitTry(b.getState()); + } + } + } + + public synchronized KMap getBlocks() { + return blocks; + } + + public synchronized KMap> getStates() { + return states; + } + + public void unplaceCenterY(Location at) { + for (BlockVector i : getBlocks().keySet()) { + at.clone().add(getCenter().getX(), getCenter().getY(), getCenter().getZ()).add(i).getBlock().setBlockData(AIR, false); + } + } + + public IrisObject scaled(double scale) { + Vector sm1 = new Vector(scale - 1, scale - 1, scale - 1); + scale = Math.max(0.001, Math.min(50, scale)); + if (scale < 1) { + scale = scale - 0.0001; + } + + IrisPosition l1 = getAABB().max(); + IrisPosition l2 = getAABB().min(); + Vector center = getCenter(); + if (getH() == 2) { + center = center.setY(center.getBlockY() + 0.5); + } + if (getW() == 2) { + center = center.setX(center.getBlockX() + 0.5); + } + if (getD() == 2) { + center = center.setZ(center.getBlockZ() + 0.5); + } + HashMap placeBlock = new HashMap(); + + IrisObject oo = new IrisObject((int) Math.ceil((w * scale) + (scale * 2)), (int) Math.ceil((h * scale) + (scale * 2)), (int) Math.ceil((d * scale) + (scale * 2))); + + for (BlockVector i : blocks.keySet()) { + BlockData bd = blocks.get(i); + placeBlock.put(i.clone().add(HALF).subtract(center) + .multiply(scale).toBlockVector(), bd); + } + + for (BlockVector v : placeBlock.keySet()) { + if (scale > 1) { + for (BlockVector vec : blocksBetweenTwoPoints(v.clone().add(center), v.clone().add(center).add(sm1))) { + oo.getBlocks().put(vec, placeBlock.get(v)); + } + } else { + oo.setUnsigned(v.getBlockX(), v.getBlockY(), v.getBlockZ(), placeBlock.get(v)); + } + } + + if (scale > 1) { + // oo.trihermite((int) Math.round(scale)); + } + + return oo; + } + + public void trilinear(int rad) { + KMap v = getBlocks().copy(); + KMap b = new KMap<>(); + BlockVector min = getAABB().minbv(); + BlockVector max = getAABB().maxbv(); + + for (int x = min.getBlockX(); x <= max.getBlockX(); x++) { + for (int y = min.getBlockY(); y <= max.getBlockY(); y++) { + for (int z = min.getBlockZ(); z <= max.getBlockZ(); z++) { + if (IrisInterpolation.getTrilinear(x, y, z, rad, (xx, yy, zz) -> { + BlockData data = v.get(new BlockVector((int) xx, (int) yy, (int) zz)); + + if (data == null || data.getMaterial().isAir()) { + return 0; + } + + return 1; + }) >= 0.5) { + b.put(new BlockVector(x, y, z), nearestBlockData(x, y, z)); + } else { + b.put(new BlockVector(x, y, z), AIR); + } + } + } + } + + setBlocks(b); + } + + public void tricubic(int rad) { + KMap v = getBlocks().copy(); + KMap b = new KMap<>(); + BlockVector min = getAABB().minbv(); + BlockVector max = getAABB().maxbv(); + + for (int x = min.getBlockX(); x <= max.getBlockX(); x++) { + for (int y = min.getBlockY(); y <= max.getBlockY(); y++) { + for (int z = min.getBlockZ(); z <= max.getBlockZ(); z++) { + if (IrisInterpolation.getTricubic(x, y, z, rad, (xx, yy, zz) -> { + BlockData data = v.get(new BlockVector((int) xx, (int) yy, (int) zz)); + + if (data == null || data.getMaterial().isAir()) { + return 0; + } + + return 1; + }) >= 0.5) { + b.put(new BlockVector(x, y, z), nearestBlockData(x, y, z)); + } else { + b.put(new BlockVector(x, y, z), AIR); + } + } + } + } + + setBlocks(b); + } + + public void trihermite(int rad) { + trihermite(rad, 0D, 0D); + } + + public void trihermite(int rad, double tension, double bias) { + KMap v = getBlocks().copy(); + KMap b = new KMap<>(); + BlockVector min = getAABB().minbv(); + BlockVector max = getAABB().maxbv(); + + for (int x = min.getBlockX(); x <= max.getBlockX(); x++) { + for (int y = min.getBlockY(); y <= max.getBlockY(); y++) { + for (int z = min.getBlockZ(); z <= max.getBlockZ(); z++) { + if (IrisInterpolation.getTrihermite(x, y, z, rad, (xx, yy, zz) -> { + BlockData data = v.get(new BlockVector((int) xx, (int) yy, (int) zz)); + + if (data == null || data.getMaterial().isAir()) { + return 0; + } + + return 1; + }, tension, bias) >= 0.5) { + b.put(new BlockVector(x, y, z), nearestBlockData(x, y, z)); + } else { + b.put(new BlockVector(x, y, z), AIR); + } + } + } + } + + setBlocks(b); + } + + private BlockData nearestBlockData(int x, int y, int z) { + BlockVector vv = new BlockVector(x, y, z); + BlockData r = getBlocks().get(vv); + + if (r != null && !r.getMaterial().isAir()) { + return r; + } + + double d = Double.MAX_VALUE; + + for (BlockVector i : blocks.keySet()) { + BlockData dat = blocks.get(i); + + if (dat.getMaterial().isAir()) { + continue; + } + + double dx = i.distanceSquared(vv); + + if (dx < d) { + d = dx; + r = dat; + } + } + + return r; + } + + private static List blocksBetweenTwoPoints(Vector loc1, Vector 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 BlockVector(x, y, z)); + } + } + } + return locations; + } } diff --git a/src/main/java/com/volmit/iris/object/IrisObjectLimit.java b/src/main/java/com/volmit/iris/object/IrisObjectLimit.java index 9247ac00c..e60d331b4 100644 --- a/src/main/java/com/volmit/iris/object/IrisObjectLimit.java +++ b/src/main/java/com/volmit/iris/object/IrisObjectLimit.java @@ -4,7 +4,6 @@ import com.volmit.iris.util.Desc; import com.volmit.iris.util.DontObfuscate; import com.volmit.iris.util.MaxNumber; import com.volmit.iris.util.MinNumber; - import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -15,28 +14,21 @@ import lombok.experimental.Accessors; @AllArgsConstructor @Desc("Translate objects") @Data -public class IrisObjectLimit -{ +public class IrisObjectLimit { - @MinNumber(0) - @MaxNumber(255) - @DontObfuscate - @Desc("The minimum height for placement (bottom of object)") - private int minimumHeight = 0; + @MinNumber(0) + @MaxNumber(255) + @DontObfuscate + @Desc("The minimum height for placement (bottom of object)") + private int minimumHeight = 0; - @MinNumber(0) - @MaxNumber(255) - @DontObfuscate - @Desc("The maximum height for placement (top of object)") - private int maximumHeight = 255; + @MinNumber(0) + @MaxNumber(255) + @DontObfuscate + @Desc("The maximum height for placement (top of object)") + private int maximumHeight = 255; - public boolean canPlace(int h, int l) - { - if(h > maximumHeight || l < minimumHeight) - { - return false; - } - - return true; - } + public boolean canPlace(int h, int l) { + return h <= maximumHeight && l >= minimumHeight; + } } diff --git a/src/main/java/com/volmit/iris/object/IrisObjectLoot.java b/src/main/java/com/volmit/iris/object/IrisObjectLoot.java index 25c67c79e..ec2d540b1 100644 --- a/src/main/java/com/volmit/iris/object/IrisObjectLoot.java +++ b/src/main/java/com/volmit/iris/object/IrisObjectLoot.java @@ -1,14 +1,8 @@ package com.volmit.iris.object; -import com.volmit.iris.Iris; import com.volmit.iris.manager.IrisDataManager; import com.volmit.iris.scaffold.cache.AtomicCache; -import com.volmit.iris.util.ArrayType; -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.KList; -import com.volmit.iris.util.RegistryListLoot; -import com.volmit.iris.util.Required; +import com.volmit.iris.util.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -43,18 +37,15 @@ public class IrisObjectLoot { private final transient AtomicCache> filterCache = new AtomicCache<>(); - public KList getFilter(IrisDataManager rdata) - { + public KList getFilter(IrisDataManager rdata) { return filterCache.aquire(() -> { KList b = new KList<>(); - for(IrisBlockData i : filter) - { + for (IrisBlockData i : filter) { BlockData bx = i.getBlockData(rdata); - if(bx != null) - { + if (bx != null) { b.add(bx); } } diff --git a/src/main/java/com/volmit/iris/object/IrisObjectPlacement.java b/src/main/java/com/volmit/iris/object/IrisObjectPlacement.java index f2d515170..12cf41ae4 100644 --- a/src/main/java/com/volmit/iris/object/IrisObjectPlacement.java +++ b/src/main/java/com/volmit/iris/object/IrisObjectPlacement.java @@ -20,269 +20,260 @@ import org.bukkit.block.data.BlockData; @AllArgsConstructor @Desc("Represents an iris object placer. It places objects.") @Data -public class IrisObjectPlacement -{ - @RegistryListObject - @Required - @ArrayType(min = 1, type = String.class) - @DontObfuscate - @Desc("List of objects to place") - private KList place = new KList<>(); +public class IrisObjectPlacement { + @RegistryListObject + @Required + @ArrayType(min = 1, type = String.class) + @DontObfuscate + @Desc("List of objects to place") + private KList place = new KList<>(); - @Desc("Rotate this objects placement") - private IrisObjectRotation rotation = new IrisObjectRotation(); + @Desc("Rotate this objects placement") + private IrisObjectRotation rotation = new IrisObjectRotation(); - @DontObfuscate - @Desc("Limit the max height or min height of placement.") - private IrisObjectLimit clamp = new IrisObjectLimit(); + @DontObfuscate + @Desc("Limit the max height or min height of placement.") + private IrisObjectLimit clamp = new IrisObjectLimit(); - @MinNumber(0) - @MaxNumber(1) - @DontObfuscate - @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; + @MinNumber(0) + @MaxNumber(1) + @DontObfuscate + @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; - @Required - @MinNumber(0) - @MaxNumber(1) - @DontObfuscate - @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; + @Required + @MinNumber(0) + @MaxNumber(1) + @DontObfuscate + @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) - @DontObfuscate - @Desc("If the chance check passes, place this many in a single chunk") - private int density = 1; + @MinNumber(1) + @DontObfuscate + @Desc("If the chance check passes, place this many in a single chunk") + private int density = 1; - @MaxNumber(64) - @MinNumber(0) - @DontObfuscate - @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 = 0; + @MaxNumber(64) + @MinNumber(0) + @DontObfuscate + @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 = 0; - @MaxNumber(64) - @MinNumber(0) - @DontObfuscate - @Desc("When bore is enabled, expand max-y of the cuboid it removes") - private int boreExtendMaxY = 0; + @MaxNumber(64) + @MinNumber(0) + @DontObfuscate + @Desc("When bore is enabled, expand max-y of the cuboid it removes") + private int boreExtendMaxY = 0; - @MaxNumber(64) - @MinNumber(-1) - @DontObfuscate - @Desc("When bore is enabled, lower min-y of the cuboid it removes") - private int boreExtendMinY = 0; + @MaxNumber(64) + @MinNumber(-1) + @DontObfuscate + @Desc("When bore is enabled, lower min-y of the cuboid it removes") + private int boreExtendMinY = 0; - @DontObfuscate - @Desc("If set to true, objects will place on the terrain height, ignoring the water surface.") - private boolean underwater = false; + @DontObfuscate + @Desc("If set to true, objects will place on the terrain height, ignoring the water surface.") + private boolean underwater = false; - @DontObfuscate - @Desc("If set to true, objects will place in carvings (such as underground) or under an overhang.") - private CarvingMode carvingSupport = CarvingMode.SURFACE_ONLY; + @DontObfuscate + @Desc("If set to true, objects will place in carvings (such as underground) or under an overhang.") + private CarvingMode carvingSupport = CarvingMode.SURFACE_ONLY; - @DontObfuscate - @Desc("If this is defined, this object wont place on the terrain heightmap, but instead on this virtual heightmap") - private IrisNoiseGenerator heightmap; + @DontObfuscate + @Desc("If this is defined, this object wont place on the terrain heightmap, but instead on this virtual heightmap") + private IrisNoiseGenerator heightmap; - @DontObfuscate - @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; + @DontObfuscate + @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; - @DontObfuscate - @Desc("If set to true, Blocks placed underwater that could be waterlogged are waterlogged.") - private boolean waterloggable = false; + @DontObfuscate + @Desc("If set to true, Blocks placed underwater that could be waterlogged are waterlogged.") + private boolean waterloggable = false; - @DontObfuscate - @Desc("If set to true, objects will place on the fluid height level Such as boats.") - private boolean onwater = false; + @DontObfuscate + @Desc("If set to true, objects will place on the fluid height level Such as boats.") + private boolean onwater = false; - @DontObfuscate - @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; + @DontObfuscate + @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; - @DontObfuscate - @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; + @DontObfuscate + @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; - @DontObfuscate - @Desc("If set to true, air will be placed before the schematic places.") - private boolean bore = false; + @DontObfuscate + @Desc("If set to true, air will be placed before the schematic places.") + private boolean bore = false; - @DontObfuscate - @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); + @DontObfuscate + @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); - @DontObfuscate - @Desc("If the place mode is set to CENTER_HEIGHT_RIGID and you have an X/Z translation, Turning on translate center will also translate the center height check.") - private boolean translateCenter = false; + @DontObfuscate + @Desc("If the place mode is set to CENTER_HEIGHT_RIGID and you have an X/Z translation, Turning on translate center will also translate the center height check.") + private boolean translateCenter = false; - @DontObfuscate - @Desc("The placement mode") - private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT; + @DontObfuscate + @Desc("The placement mode") + private ObjectPlaceMode mode = ObjectPlaceMode.CENTER_HEIGHT; - @ArrayType(min = 1, type = IrisObjectReplace.class) - @DontObfuscate - @Desc("Find and replace blocks") - private KList edit = new KList<>(); + @ArrayType(min = 1, type = IrisObjectReplace.class) + @DontObfuscate + @Desc("Find and replace blocks") + private KList edit = new KList<>(); - @DontObfuscate - @Desc("Translate this object's placement") - private IrisObjectTranslate translate = new IrisObjectTranslate(); + @DontObfuscate + @Desc("Translate this object's placement") + private IrisObjectTranslate translate = new IrisObjectTranslate(); - @DontObfuscate - @Desc("Scale Objects") - private IrisObjectScale scale = new IrisObjectScale(); + @DontObfuscate + @Desc("Scale Objects") + private IrisObjectScale scale = new IrisObjectScale(); - @ArrayType(min = 1, type = IrisObjectLoot.class) - @DontObfuscate - @Desc("The loot tables to apply to these objects") - private KList loot = new KList<>(); + @ArrayType(min = 1, type = IrisObjectLoot.class) + @DontObfuscate + @Desc("The loot tables to apply to these objects") + private KList loot = new KList<>(); - public IrisObjectPlacement toPlacement(String... place) - { - IrisObjectPlacement p = new IrisObjectPlacement(); - p.setPlace(new KList<>(place)); - p.setTranslateCenter(translateCenter); - p.setMode(mode); - p.setEdit(edit); - p.setTranslate(translate); - p.setWarp(warp); - p.setBore(bore); - p.setMeld(meld); - p.setWaterloggable(waterloggable); - p.setOnwater(onwater); - p.setSmartBore(smartBore); - p.setCarvingSupport(carvingSupport); - p.setUnderwater(underwater); - p.setBoreExtendMaxY(boreExtendMaxY); - p.setBoreExtendMinY(boreExtendMinY); - p.setOverStilt(overStilt); - p.setDensity(density); - p.setChance(chance); - p.setSnow(snow); - p.setClamp(clamp); - p.setRotation(rotation); - p.setLoot(loot); - return p; - } + public IrisObjectPlacement toPlacement(String... place) { + IrisObjectPlacement p = new IrisObjectPlacement(); + p.setPlace(new KList<>(place)); + p.setTranslateCenter(translateCenter); + p.setMode(mode); + p.setEdit(edit); + p.setTranslate(translate); + p.setWarp(warp); + p.setBore(bore); + p.setMeld(meld); + p.setWaterloggable(waterloggable); + p.setOnwater(onwater); + p.setSmartBore(smartBore); + p.setCarvingSupport(carvingSupport); + p.setUnderwater(underwater); + p.setBoreExtendMaxY(boreExtendMaxY); + p.setBoreExtendMinY(boreExtendMinY); + p.setOverStilt(overStilt); + p.setDensity(density); + p.setChance(chance); + p.setSnow(snow); + p.setClamp(clamp); + p.setRotation(rotation); + p.setLoot(loot); + return p; + } - private final transient AtomicCache surfaceWarp = new AtomicCache<>(); + private final transient AtomicCache surfaceWarp = new AtomicCache<>(); - public CNG getSurfaceWarp(RNG rng) - { - return surfaceWarp.aquire(() -> - { - return getWarp().create(rng); - }); - } + public CNG getSurfaceWarp(RNG rng) { + return surfaceWarp.aquire(() -> + { + return getWarp().create(rng); + }); + } - public double warp(RNG rng, double x, double y, double z) - { - return getSurfaceWarp(rng).fitDouble(-(getWarp().getMultiplier() / 2D), (getWarp().getMultiplier() / 2D), x, y, z); - } + public double warp(RNG rng, double x, double y, double z) { + return getSurfaceWarp(rng).fitDouble(-(getWarp().getMultiplier() / 2D), (getWarp().getMultiplier() / 2D), x, y, z); + } - public int getTriesForChunk(RNG random) - { - if(chance <= 0) - { - return 0; - } + public int getTriesForChunk(RNG random) { + if (chance <= 0) { + return 0; + } - if(chance >= 1 || random.nextDouble() < chance) - { - return density; - } + if (chance >= 1 || random.nextDouble() < chance) { + return density; + } - return 0; - } + return 0; + } - public IrisObject getObject(DataProvider g, RNG random) - { - if(place.isEmpty()) - { - return null; - } + public IrisObject getObject(DataProvider g, RNG random) { + if (place.isEmpty()) { + return null; + } - return g.getData().getObjectLoader().load(place.get(random.nextInt(place.size()))); - } + return g.getData().getObjectLoader().load(place.get(random.nextInt(place.size()))); + } - public boolean isVacuum() { - return getMode().equals(ObjectPlaceMode.VACUUM); - } + public boolean isVacuum() { + return getMode().equals(ObjectPlaceMode.VACUUM); + } - private transient AtomicCache cache = new AtomicCache<>(); + private transient AtomicCache cache = new AtomicCache<>(); - private class TableCache { - transient WeightedRandom global = new WeightedRandom<>(); - transient KMap> basic = new KMap<>(); - transient KMap>> exact = new KMap<>(); - } + private class TableCache { + transient WeightedRandom global = new WeightedRandom<>(); + transient KMap> basic = new KMap<>(); + transient KMap>> exact = new KMap<>(); + } - private TableCache getCache(IrisDataManager manager) { - return cache.aquire(() -> { - TableCache tc = new TableCache(); + private TableCache getCache(IrisDataManager manager) { + return cache.aquire(() -> { + TableCache tc = new TableCache(); - for (IrisObjectLoot loot : getLoot()) { - IrisLootTable table = manager.getLootLoader().load(loot.getName()); - if (table == null) { - Iris.warn("Couldn't find loot table " + loot.getName()); - continue; - } + for (IrisObjectLoot loot : getLoot()) { + IrisLootTable table = manager.getLootLoader().load(loot.getName()); + if (table == null) { + Iris.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 (BlockData filterData : loot.getFilter(manager)) { - if (!tc.basic.containsKey(filterData.getMaterial())) { - tc.basic.put(filterData.getMaterial(), new WeightedRandom<>()); - } + 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 (BlockData filterData : loot.getFilter(manager)) { + if (!tc.basic.containsKey(filterData.getMaterial())) { + tc.basic.put(filterData.getMaterial(), new WeightedRandom<>()); + } - tc.basic.get(filterData.getMaterial()).put(table, loot.getWeight()); - } - } else //Filter is exact - { - for (BlockData filterData : loot.getFilter(manager)) { - if (!tc.exact.containsKey(filterData.getMaterial())) { - tc.exact.put(filterData.getMaterial(), new KMap<>()); - } + tc.basic.get(filterData.getMaterial()).put(table, loot.getWeight()); + } + } else //Filter is exact + { + for (BlockData filterData : loot.getFilter(manager)) { + 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 WeightedRandom<>()); - } + if (!tc.exact.get(filterData.getMaterial()).containsKey(filterData)) { + tc.exact.get(filterData.getMaterial()).put(filterData, new WeightedRandom<>()); + } - tc.exact.get(filterData.getMaterial()).get(filterData).put(table, loot.getWeight()); - } - } - } - return tc; - }); - } + tc.exact.get(filterData.getMaterial()).get(filterData).put(table, loot.getWeight()); + } + } + } + return tc; + }); + } - /** - * Gets the loot table that should be used for the block - * @param data The block data of the block - * @param dataManager Iris Data Manager - * @return The loot table it should use. - */ - public IrisLootTable getTable(BlockData data, IrisDataManager dataManager) { - TableCache cache = getCache(dataManager); + /** + * Gets the loot table that should be used for the block + * + * @param data The block data of the block + * @param dataManager Iris Data Manager + * @return The loot table it should use. + */ + public IrisLootTable getTable(BlockData data, IrisDataManager dataManager) { + TableCache cache = getCache(dataManager); - if(B.isStorageChest(data)) - { - IrisLootTable picked = null; - if (cache.exact.containsKey(data.getMaterial()) && cache.exact.containsKey(data)) { - picked = cache.exact.get(data.getMaterial()).get(data).pullRandom(); - } else if (cache.basic.containsKey(data.getMaterial())) { - picked = cache.basic.get(data.getMaterial()).pullRandom(); - } else if (cache.global.getSize() > 0){ - picked = cache.global.pullRandom(); - } + if (B.isStorageChest(data)) { + IrisLootTable picked = null; + if (cache.exact.containsKey(data.getMaterial()) && cache.exact.containsKey(data)) { + picked = cache.exact.get(data.getMaterial()).get(data).pullRandom(); + } else if (cache.basic.containsKey(data.getMaterial())) { + picked = cache.basic.get(data.getMaterial()).pullRandom(); + } else if (cache.global.getSize() > 0) { + picked = cache.global.pullRandom(); + } - return picked; - } + return picked; + } - return null; - } + return null; + } } diff --git a/src/main/java/com/volmit/iris/object/IrisObjectReplace.java b/src/main/java/com/volmit/iris/object/IrisObjectReplace.java index 259c97cb3..7450728d8 100644 --- a/src/main/java/com/volmit/iris/object/IrisObjectReplace.java +++ b/src/main/java/com/volmit/iris/object/IrisObjectReplace.java @@ -1,10 +1,9 @@ package com.volmit.iris.object; -import com.volmit.iris.scaffold.cache.AtomicCache; -import com.volmit.iris.manager.IrisDataManager; import com.volmit.iris.generator.noise.CNG; +import com.volmit.iris.manager.IrisDataManager; +import com.volmit.iris.scaffold.cache.AtomicCache; import com.volmit.iris.util.*; - import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -16,55 +15,50 @@ import org.bukkit.block.data.BlockData; @AllArgsConstructor @Desc("Find and replace object materials") @Data -public class IrisObjectReplace -{ - @ArrayType(min = 1, type = IrisBlockData.class) - @Required - @Desc("Find this block") - @DontObfuscate - private KList find = new KList<>(); +public class IrisObjectReplace { + @ArrayType(min = 1, type = IrisBlockData.class) + @Required + @Desc("Find this block") + @DontObfuscate + private KList find = new KList<>(); - @Required - @Desc("Replace it with this block palette") - @DontObfuscate - private IrisMaterialPalette replace = new IrisMaterialPalette(); + @Required + @Desc("Replace it with this block palette") + @DontObfuscate + private IrisMaterialPalette replace = new IrisMaterialPalette(); - @Desc("Exactly match the block data or not") - @DontObfuscate - private boolean exact = false; + @Desc("Exactly match the block data or not") + @DontObfuscate + private boolean exact = false; - @MinNumber(0) - @MaxNumber(1) - @Desc("Modifies the chance the block is replaced") - @DontObfuscate - private float chance = 1; + @MinNumber(0) + @MaxNumber(1) + @Desc("Modifies the chance the block is replaced") + @DontObfuscate + private float chance = 1; - private final transient AtomicCache replaceGen = new AtomicCache<>(); - private final transient AtomicCache> findData = new AtomicCache<>(); - private final transient AtomicCache> replaceData = new AtomicCache<>(); + private final transient AtomicCache replaceGen = new AtomicCache<>(); + private final transient AtomicCache> findData = new AtomicCache<>(); + private final transient AtomicCache> replaceData = new AtomicCache<>(); - public KList getFind(IrisDataManager rdata) - { - return findData.aquire(() -> - { - KList b = new KList<>(); + public KList getFind(IrisDataManager rdata) { + return findData.aquire(() -> + { + KList b = new KList<>(); - for(IrisBlockData i : find) - { - BlockData bx = i.getBlockData(rdata); + for (IrisBlockData i : find) { + BlockData bx = i.getBlockData(rdata); - if(bx != null) - { - b.add(bx); - } - } + if (bx != null) { + b.add(bx); + } + } - return b; - }); - } + return b; + }); + } - public BlockData getReplace(RNG seed, double x, double y, double z, IrisDataManager rdata) - { - return getReplace().get(seed, x, y, z, rdata); - } + public BlockData getReplace(RNG seed, double x, double y, double z, IrisDataManager rdata) { + return getReplace().get(seed, x, y, z, rdata); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisObjectRotation.java b/src/main/java/com/volmit/iris/object/IrisObjectRotation.java index 2690d2ac8..24c82cc8a 100644 --- a/src/main/java/com/volmit/iris/object/IrisObjectRotation.java +++ b/src/main/java/com/volmit/iris/object/IrisObjectRotation.java @@ -1,6 +1,5 @@ package com.volmit.iris.object; -import com.volmit.iris.Iris; import com.volmit.iris.util.Desc; import com.volmit.iris.util.DontObfuscate; import com.volmit.iris.util.KList; @@ -12,8 +11,6 @@ import org.bukkit.Axis; import org.bukkit.Material; import org.bukkit.block.BlockFace; import org.bukkit.block.data.*; -import org.bukkit.craftbukkit.v1_17_R1.block.data.CraftBlockData; -import org.bukkit.craftbukkit.v1_17_R1.block.impl.CraftRotatable; import org.bukkit.util.BlockVector; import java.util.List; @@ -23,511 +20,401 @@ import java.util.List; @AllArgsConstructor @Desc("Configures rotation for iris") @Data -public class IrisObjectRotation -{ - @DontObfuscate - @Desc("If this rotator is enabled or not") - private boolean enabled = true; - - @DontObfuscate - @Desc("The x axis rotation") - private IrisAxisRotationClamp xAxis = new IrisAxisRotationClamp(); - - @DontObfuscate - @Desc("The y axis rotation") - private IrisAxisRotationClamp yAxis = new IrisAxisRotationClamp(true, false, 0, 0, 90); - - @DontObfuscate - @Desc("The z axis rotation") - private IrisAxisRotationClamp zAxis = new IrisAxisRotationClamp(); - - 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) - { - return e.rotateCopy(this); - } - - public IrisJigsawPiece rotateCopy(IrisJigsawPiece v) { - IrisJigsawPiece piece = v.copy(); - for(IrisJigsawPieceConnector i : piece.getConnectors()) - { - i.setPosition(rotate(i.getPosition())); - i.setDirection(rotate(i.getDirection())); - } - - return piece; - } - - - public BlockVector rotate(BlockVector direction) { - return rotate(direction, 0,0,0); - } - - public IrisDirection rotate(IrisDirection direction) { - BlockVector v = rotate(direction.toVector().toBlockVector()); - return IrisDirection.closest(v); - } - - 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 getRotation(int spin, IrisAxisRotationClamp clamp) - { - if(!enabled) - { - return 0; - } - - if(!clamp.isEnabled()) - { - return 0; - } - - return clamp.getRadians(spin); - } - - public BlockFace getFace(BlockVector 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(BlockVector 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) - { - switch(axis) - { - case X: - return BlockFace.EAST; - case Y: - return BlockFace.UP; - case Z: - return BlockFace.NORTH; - } - - return BlockFace.NORTH; - } - - public Axis axisFor(BlockFace f) - { - switch(f) - { - case NORTH: - case SOUTH: - return Axis.Z; - case EAST: - case WEST: - return Axis.X; - case UP: - case DOWN: - return Axis.Y; - } - - return Axis.Y; - } - - public Axis axisFor2D(BlockFace f) - { - switch(f) - { - case NORTH: - case SOUTH: - return Axis.Z; - case EAST: - case WEST: - case UP: - case DOWN: - return Axis.X; - } - - return Axis.Z; - } - - 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) - { - Directional g = ((Directional) d); - BlockFace f = g.getFacing(); - BlockVector bv = new BlockVector(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) - { - Rotatable g = ((Rotatable) d); - BlockFace f = g.getRotation(); - - BlockVector bv = new BlockVector(f.getModX(), 0, f.getModZ()); - bv = rotate(bv.clone(), spinx, spiny, spinz); - BlockFace face = getHexFace(bv); - - g.setRotation(face); - - } - - else if(d instanceof Orientable) - { - BlockFace f = getFace(((Orientable) d).getAxis()); - BlockVector bv = new BlockVector(f.getModX(), f.getModY(), f.getModZ()); - bv = rotate(bv.clone(), spinx, spiny, spinz); - Axis a = getAxis(bv); - - if(!a.equals(((Orientable) d).getAxis()) && ((Orientable) d).getAxes().contains(a)) - { - ((Orientable) d).setAxis(a); - } - } - - else if(d instanceof MultipleFacing) - { - List faces = new KList<>(); - MultipleFacing g = (MultipleFacing) d; - - for(BlockFace i : g.getFaces()) - { - BlockVector bv = new BlockVector(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.getMaterial().equals(Material.NETHER_PORTAL) && d instanceof Orientable) - { - //TODO: Fucks up logs - Orientable g = ((Orientable) d); - BlockFace f = faceForAxis(g.getAxis()); - BlockVector bv = new BlockVector(f.getModX(), f.getModY(), f.getModZ()); - bv = rotate(bv.clone(), spinx, spiny, spinz); - BlockFace t = getFace(bv); - Axis a = !g.getAxes().contains(Axis.Y) ? axisFor(t) : axisFor2D(t); - ((Orientable) d).setAxis(a); - } - } - - catch(Throwable throwable) - { - - } - - return d; - } - - public Axis getAxis(BlockVector 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) - { - return new IrisPosition(rotate(new BlockVector(b.getX(), b.getY(), b.getZ()), spinx, spiny, spinz)); - } - - public BlockVector rotate(BlockVector b, int spinx, int spiny, int spinz) - { - if(!canRotate()) - { - return b; - } - - BlockVector 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.rotateAroundY(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(); - } - - public boolean canRotate() - { - return canRotateX() || canRotateY() || canRotateZ(); - } +public class IrisObjectRotation { + @DontObfuscate + @Desc("If this rotator is enabled or not") + private boolean enabled = true; + + @DontObfuscate + @Desc("The x axis rotation") + private IrisAxisRotationClamp xAxis = new IrisAxisRotationClamp(); + + @DontObfuscate + @Desc("The y axis rotation") + private IrisAxisRotationClamp yAxis = new IrisAxisRotationClamp(true, false, 0, 0, 90); + + @DontObfuscate + @Desc("The z axis rotation") + private IrisAxisRotationClamp zAxis = new IrisAxisRotationClamp(); + + 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) { + return e.rotateCopy(this); + } + + public IrisJigsawPiece rotateCopy(IrisJigsawPiece v) { + IrisJigsawPiece piece = v.copy(); + for (IrisJigsawPieceConnector i : piece.getConnectors()) { + i.setPosition(rotate(i.getPosition())); + i.setDirection(rotate(i.getDirection())); + } + + return piece; + } + + + public BlockVector rotate(BlockVector direction) { + return rotate(direction, 0, 0, 0); + } + + public IrisDirection rotate(IrisDirection direction) { + BlockVector v = rotate(direction.toVector().toBlockVector()); + return IrisDirection.closest(v); + } + + 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 getRotation(int spin, IrisAxisRotationClamp clamp) { + if (!enabled) { + return 0; + } + + if (!clamp.isEnabled()) { + return 0; + } + + return clamp.getRadians(spin); + } + + public BlockFace getFace(BlockVector 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(BlockVector 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) { + switch (axis) { + case X: + return BlockFace.EAST; + case Y: + return BlockFace.UP; + case Z: + return BlockFace.NORTH; + } + + return BlockFace.NORTH; + } + + public Axis axisFor(BlockFace f) { + switch (f) { + case NORTH: + case SOUTH: + return Axis.Z; + case EAST: + case WEST: + return Axis.X; + case UP: + case DOWN: + return Axis.Y; + } + + return Axis.Y; + } + + public Axis axisFor2D(BlockFace f) { + switch (f) { + case NORTH: + case SOUTH: + return Axis.Z; + case EAST: + case WEST: + case UP: + case DOWN: + return Axis.X; + } + + return Axis.Z; + } + + 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) { + Directional g = ((Directional) d); + BlockFace f = g.getFacing(); + BlockVector bv = new BlockVector(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) { + Rotatable g = ((Rotatable) d); + BlockFace f = g.getRotation(); + + BlockVector bv = new BlockVector(f.getModX(), 0, f.getModZ()); + bv = rotate(bv.clone(), spinx, spiny, spinz); + BlockFace face = getHexFace(bv); + + g.setRotation(face); + + } else if (d instanceof Orientable) { + BlockFace f = getFace(((Orientable) d).getAxis()); + BlockVector bv = new BlockVector(f.getModX(), f.getModY(), f.getModZ()); + bv = rotate(bv.clone(), spinx, spiny, spinz); + Axis a = getAxis(bv); + + if (!a.equals(((Orientable) d).getAxis()) && ((Orientable) d).getAxes().contains(a)) { + ((Orientable) d).setAxis(a); + } + } else if (d instanceof MultipleFacing) { + List faces = new KList<>(); + MultipleFacing g = (MultipleFacing) d; + + for (BlockFace i : g.getFaces()) { + BlockVector bv = new BlockVector(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.getMaterial().equals(Material.NETHER_PORTAL) && d instanceof Orientable) { + //TODO: Fucks up logs + Orientable g = ((Orientable) d); + BlockFace f = faceForAxis(g.getAxis()); + BlockVector bv = new BlockVector(f.getModX(), f.getModY(), f.getModZ()); + bv = rotate(bv.clone(), spinx, spiny, spinz); + BlockFace t = getFace(bv); + Axis a = !g.getAxes().contains(Axis.Y) ? axisFor(t) : axisFor2D(t); + ((Orientable) d).setAxis(a); + } + } catch (Throwable throwable) { + + } + + return d; + } + + public Axis getAxis(BlockVector 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) { + return new IrisPosition(rotate(new BlockVector(b.getX(), b.getY(), b.getZ()), spinx, spiny, spinz)); + } + + public BlockVector rotate(BlockVector b, int spinx, int spiny, int spinz) { + if (!canRotate()) { + return b; + } + + BlockVector 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.rotateAroundY(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(); + } + + public boolean canRotate() { + return canRotateX() || canRotateY() || canRotateZ(); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisObjectScale.java b/src/main/java/com/volmit/iris/object/IrisObjectScale.java index 60c7d6b54..a582b5e2c 100644 --- a/src/main/java/com/volmit/iris/object/IrisObjectScale.java +++ b/src/main/java/com/volmit/iris/object/IrisObjectScale.java @@ -12,79 +12,70 @@ import lombok.experimental.Accessors; @AllArgsConstructor @Desc("Scale objects") @Data -public class IrisObjectScale -{ - @MinNumber(1) - @MaxNumber(32) - @DontObfuscate - @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; +public class IrisObjectScale { + @MinNumber(1) + @MaxNumber(32) + @DontObfuscate + @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) - @DontObfuscate - @Desc("The minimum scale") - private double minimumScale = 1; + @MinNumber(0.01) + @MaxNumber(50) + @DontObfuscate + @Desc("The minimum scale") + private double minimumScale = 1; - @MinNumber(0.01) - @MaxNumber(50) - @DontObfuscate - @Desc("The maximum height for placement (top of object)") - private double maximumScale = 1; + @MinNumber(0.01) + @MaxNumber(50) + @DontObfuscate + @Desc("The maximum height for placement (top of object)") + private double maximumScale = 1; - private final transient ConcurrentLinkedHashMap> cache - = new ConcurrentLinkedHashMap.Builder>() - .initialCapacity(64) - .maximumWeightedCapacity(64) - .concurrencyLevel(32) - .build(); + private final transient ConcurrentLinkedHashMap> cache + = new ConcurrentLinkedHashMap.Builder>() + .initialCapacity(64) + .maximumWeightedCapacity(64) + .concurrencyLevel(32) + .build(); - public boolean shouldScale() - { - return ((minimumScale == maximumScale) && maximumScale == 1) || variations <= 0; - } + public boolean shouldScale() { + return ((minimumScale == maximumScale) && maximumScale == 1) || variations <= 0; + } - public int getMaxSizeFor(int indim) - { - return (int) (getMaxScale() * indim); - } + public int getMaxSizeFor(int indim) { + return (int) (getMaxScale() * indim); + } - public double getMaxScale() - { - double mx = 0; + public double getMaxScale() { + double mx = 0; - for(double i = minimumScale; i < maximumScale; i+= (maximumScale - minimumScale) / (double)(Math.min(variations, 32))) - { - mx = i; - } + for (double i = minimumScale; i < maximumScale; i += (maximumScale - minimumScale) / (double) (Math.min(variations, 32))) { + mx = i; + } - return mx; - } + return mx; + } - public IrisObject get(RNG rng, IrisObject origin) - { - if(shouldScale()) - { - return origin; - } + public IrisObject get(RNG rng, IrisObject origin) { + if (shouldScale()) { + return origin; + } - return cache.compute(origin, (k, v) -> { - if(v != null) - { - return v; - } + return cache.compute(origin, (k, v) -> { + if (v != null) { + return v; + } - KList c = new KList<>(); - for(double i = minimumScale; i < maximumScale; i+= (maximumScale - minimumScale) / (double)(Math.min(variations, 32))) - { - c.add(origin.scaled(i)); - } + KList c = new KList<>(); + for (double i = minimumScale; i < maximumScale; i += (maximumScale - minimumScale) / (double) (Math.min(variations, 32))) { + c.add(origin.scaled(i)); + } - return c; - }).getRandom(rng); - } + return c; + }).getRandom(rng); + } - public boolean canScaleBeyond() { - return shouldScale() && maximumScale > 1; - } + public boolean canScaleBeyond() { + return shouldScale() && maximumScale > 1; + } } diff --git a/src/main/java/com/volmit/iris/object/IrisObjectTranslate.java b/src/main/java/com/volmit/iris/object/IrisObjectTranslate.java index 240c673c0..b076183bf 100644 --- a/src/main/java/com/volmit/iris/object/IrisObjectTranslate.java +++ b/src/main/java/com/volmit/iris/object/IrisObjectTranslate.java @@ -1,73 +1,61 @@ package com.volmit.iris.object; -import org.bukkit.util.BlockVector; - -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.MaxNumber; -import com.volmit.iris.util.MinNumber; -import com.volmit.iris.util.Required; - +import com.volmit.iris.util.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; import lombok.experimental.Accessors; +import org.bukkit.util.BlockVector; @Accessors(chain = true) @NoArgsConstructor @AllArgsConstructor @Desc("Translate objects") @Data -public class IrisObjectTranslate -{ +public class IrisObjectTranslate { - @MinNumber(-128) // TODO: WARNING HEIGHT - @MaxNumber(128) // TODO: WARNING HEIGHT - @DontObfuscate - @Desc("The x shift in blocks") - private int x = 0; + @MinNumber(-128) // TODO: WARNING HEIGHT + @MaxNumber(128) // TODO: WARNING HEIGHT + @DontObfuscate + @Desc("The x shift in blocks") + private int x = 0; - @Required - @MinNumber(-256) // TODO: WARNING HEIGHT - @MaxNumber(256) // TODO: WARNING HEIGHT - @DontObfuscate - @Desc("The x shift in blocks") - private int y = 0; + @Required + @MinNumber(-256) // TODO: WARNING HEIGHT + @MaxNumber(256) // TODO: WARNING HEIGHT + @DontObfuscate + @Desc("The x shift in blocks") + private int y = 0; - @MinNumber(-128) // TODO: WARNING HEIGHT - @MaxNumber(128) // TODO: WARNING HEIGHT - @DontObfuscate - @Desc("Adds an additional amount of height randomly (translateY + rand(0 - yRandom))") - private int yRandom = 0; + @MinNumber(-128) // TODO: WARNING HEIGHT + @MaxNumber(128) // TODO: WARNING HEIGHT + @DontObfuscate + @Desc("Adds an additional amount of height randomly (translateY + rand(0 - yRandom))") + private int yRandom = 0; - @MinNumber(-128) // TODO: WARNING HEIGHT - @MaxNumber(128) // TODO: WARNING HEIGHT - @DontObfuscate - @Desc("The x shift in blocks") - private int z = 0; + @MinNumber(-128) // TODO: WARNING HEIGHT + @MaxNumber(128) // TODO: WARNING HEIGHT + @DontObfuscate + @Desc("The x shift in blocks") + private int z = 0; - public boolean canTranslate() - { - return x != 0 || y != 0 || z != 0; - } + public boolean canTranslate() { + return x != 0 || y != 0 || z != 0; + } - public BlockVector translate(BlockVector i) - { - if(canTranslate()) - { - return (BlockVector) i.clone().add(new BlockVector(x, y, z)); - } + public BlockVector translate(BlockVector i) { + if (canTranslate()) { + return (BlockVector) i.clone().add(new BlockVector(x, y, z)); + } - return i; - } + return i; + } - public BlockVector translate(BlockVector clone, IrisObjectRotation rotation, int sx, int sy, int sz) - { - if(canTranslate()) - { - return (BlockVector) clone.clone().add(rotation.rotate(new BlockVector(x, y, z), sx, sy, sz)); - } + public BlockVector translate(BlockVector clone, IrisObjectRotation rotation, int sx, int sy, int sz) { + if (canTranslate()) { + return (BlockVector) clone.clone().add(rotation.rotate(new BlockVector(x, y, z), sx, sy, sz)); + } - return clone; - } + return clone; + } } diff --git a/src/main/java/com/volmit/iris/object/IrisPosition.java b/src/main/java/com/volmit/iris/object/IrisPosition.java index 3c93c6ed1..3924e98d3 100644 --- a/src/main/java/com/volmit/iris/object/IrisPosition.java +++ b/src/main/java/com/volmit/iris/object/IrisPosition.java @@ -16,50 +16,49 @@ import org.bukkit.util.Vector; @AllArgsConstructor @Desc("Represents a position") @Data -public class IrisPosition -{ - @DontObfuscate - @Desc("The x position") - private int x = 0; +public class IrisPosition { + @DontObfuscate + @Desc("The x position") + private int x = 0; - @DontObfuscate - @Desc("The y position") - private int y = 0; + @DontObfuscate + @Desc("The y position") + private int y = 0; - @DontObfuscate - @Desc("The z position") - private int z = 0; + @DontObfuscate + @Desc("The z position") + private int z = 0; - public IrisPosition(BlockVector bv) { - this(bv.getBlockX(), bv.getBlockY(), bv.getBlockZ()); - } + public IrisPosition(BlockVector bv) { + this(bv.getBlockX(), bv.getBlockY(), bv.getBlockZ()); + } - public IrisPosition(Location l) { - this(l.getBlockX(), l.getBlockY(), l.getBlockZ()); - } + public IrisPosition(Location l) { + this(l.getBlockX(), l.getBlockY(), l.getBlockZ()); + } - public IrisPosition(Vector v) { - this(v.getBlockX(), v.getBlockY(), v.getBlockZ()); - } + public IrisPosition(Vector v) { + this(v.getBlockX(), v.getBlockY(), v.getBlockZ()); + } - public IrisPosition add(IrisPosition relativePosition) { - return new IrisPosition(relativePosition.x+x, relativePosition.y+y, relativePosition.z + 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 sub(IrisPosition relativePosition) { + return new IrisPosition(x - relativePosition.x, y - relativePosition.y, z - relativePosition.z); + } - public Location toLocation(World world) { - return new Location(world, x,y,z); - } + public Location toLocation(World world) { + return new Location(world, x, y, z); + } public IrisPosition copy() { - return new IrisPosition(x,y,z); + return new IrisPosition(x, y, z); } @Override public String toString() { - return "[" + getX() + "," + getY() + "," + getZ() + "]"; - } + return "[" + getX() + "," + getY() + "," + getZ() + "]"; + } } diff --git a/src/main/java/com/volmit/iris/object/IrisPosition2D.java b/src/main/java/com/volmit/iris/object/IrisPosition2D.java index 5011fada3..a4f918a7e 100644 --- a/src/main/java/com/volmit/iris/object/IrisPosition2D.java +++ b/src/main/java/com/volmit/iris/object/IrisPosition2D.java @@ -12,13 +12,12 @@ import lombok.experimental.Accessors; @AllArgsConstructor @Desc("Represents a position") @Data -public class IrisPosition2D -{ - @DontObfuscate - @Desc("The x position") - private int x = 0; +public class IrisPosition2D { + @DontObfuscate + @Desc("The x position") + private int x = 0; - @DontObfuscate - @Desc("The z position") - private int z = 0; + @DontObfuscate + @Desc("The z position") + private int z = 0; } diff --git a/src/main/java/com/volmit/iris/object/IrisPotionEffect.java b/src/main/java/com/volmit/iris/object/IrisPotionEffect.java index 4f55b1980..ba978f87a 100644 --- a/src/main/java/com/volmit/iris/object/IrisPotionEffect.java +++ b/src/main/java/com/volmit/iris/object/IrisPotionEffect.java @@ -1,21 +1,15 @@ package com.volmit.iris.object; -import org.bukkit.entity.LivingEntity; -import org.bukkit.potion.PotionEffect; -import org.bukkit.potion.PotionEffectType; - import com.volmit.iris.Iris; import com.volmit.iris.scaffold.cache.AtomicCache; -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.MaxNumber; -import com.volmit.iris.util.MinNumber; -import com.volmit.iris.util.Required; - +import com.volmit.iris.util.*; 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 @@ -23,88 +17,75 @@ import lombok.experimental.Accessors; @DontObfuscate @Desc("An iris potion effect") @Data -public class IrisPotionEffect -{ +public class IrisPotionEffect { - @Required - @DontObfuscate - @Desc("The potion effect to apply in this area") - private String potionEffect = ""; + @Required + @DontObfuscate + @Desc("The potion effect to apply in this area") + private String potionEffect = ""; - @Required - @MinNumber(-1) - @MaxNumber(1024) - @DontObfuscate - @Desc("The Potion Strength or -1 to disable") - private int strength = -1; + @Required + @MinNumber(-1) + @MaxNumber(1024) + @DontObfuscate + @Desc("The Potion Strength or -1 to disable") + private int strength = -1; - @Required - @MinNumber(1) - @DontObfuscate - @Desc("The time the potion will last for") - private int ticks = 200; + @Required + @MinNumber(1) + @DontObfuscate + @Desc("The time the potion will last for") + private int ticks = 200; - @DontObfuscate - @Desc("Is the effect ambient") - private boolean ambient = false; + @DontObfuscate + @Desc("Is the effect ambient") + private boolean ambient = false; - @DontObfuscate - @Desc("Is the effect showing particles") - private boolean particles = true; + @DontObfuscate + @Desc("Is the effect showing particles") + private boolean particles = true; - private final transient AtomicCache pt = new AtomicCache<>(); + private final transient AtomicCache pt = new AtomicCache<>(); - public PotionEffectType getRealType() - { - return pt.aquire(() -> - { - PotionEffectType t = PotionEffectType.LUCK; + public PotionEffectType getRealType() { + return pt.aquire(() -> + { + PotionEffectType t = PotionEffectType.LUCK; - if(getPotionEffect().isEmpty()) - { - return t; - } + if (getPotionEffect().isEmpty()) { + return t; + } - try - { - for(PotionEffectType i : PotionEffectType.values()) - { - if(i.getName().toUpperCase().replaceAll("\\Q \\E", "_").equals(getPotionEffect())) - { - t = i; + try { + for (PotionEffectType i : PotionEffectType.values()) { + if (i.getName().toUpperCase().replaceAll("\\Q \\E", "_").equals(getPotionEffect())) { + t = i; - return t; - } - } - } + return t; + } + } + } catch (Throwable e) { - catch(Throwable e) - { + } - } + Iris.warn("Unknown Potion Effect Type: " + getPotionEffect()); - Iris.warn("Unknown Potion Effect Type: " + getPotionEffect()); + return t; + }); + } - return t; - }); - } + public void apply(LivingEntity p) { + if (strength > -1) { + if (p.hasPotionEffect(getRealType())) { + PotionEffect e = p.getPotionEffect(getRealType()); + if (e.getAmplifier() > strength) { + return; + } - 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.removePotionEffect(getRealType()); - } - - p.addPotionEffect(new PotionEffect(getRealType(), ticks, strength, ambient, particles, false)); - } - } + p.addPotionEffect(new PotionEffect(getRealType(), ticks, strength, ambient, particles, false)); + } + } } diff --git a/src/main/java/com/volmit/iris/object/IrisRange.java b/src/main/java/com/volmit/iris/object/IrisRange.java index eb2668470..8b7f3623f 100644 --- a/src/main/java/com/volmit/iris/object/IrisRange.java +++ b/src/main/java/com/volmit/iris/object/IrisRange.java @@ -13,23 +13,20 @@ import lombok.experimental.Accessors; @AllArgsConstructor @Desc("Represents a range") @Data -public class IrisRange -{ - @DontObfuscate - @Desc("The minimum value") - private double min = 16; +public class IrisRange { + @DontObfuscate + @Desc("The minimum value") + private double min = 16; - @DontObfuscate - @Desc("The maximum value") - private double max = 32; + @DontObfuscate + @Desc("The maximum value") + private double max = 32; - public double get(RNG rng) - { - if(min == max) - { - return min; - } + public double get(RNG rng) { + if (min == max) { + return min; + } - return rng.d(min, max); - } + return rng.d(min, max); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisRareObject.java b/src/main/java/com/volmit/iris/object/IrisRareObject.java index 16c5ed518..d3d9a3ab2 100644 --- a/src/main/java/com/volmit/iris/object/IrisRareObject.java +++ b/src/main/java/com/volmit/iris/object/IrisRareObject.java @@ -1,11 +1,6 @@ package com.volmit.iris.object; -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.MinNumber; -import com.volmit.iris.util.RegistryListObject; -import com.volmit.iris.util.Required; - +import com.volmit.iris.util.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.EqualsAndHashCode; @@ -19,18 +14,17 @@ import lombok.experimental.Accessors; @Desc("Represents a structure tile") @Data @EqualsAndHashCode(callSuper = false) -public class IrisRareObject -{ +public class IrisRareObject { - @Required - @MinNumber(1) - @Desc("The rarity is 1 in X") - @DontObfuscate - private int rarity = 1; + @Required + @MinNumber(1) + @Desc("The rarity is 1 in X") + @DontObfuscate + private int rarity = 1; - @RegistryListObject - @Required - @Desc("The object to place if rarity check passed") - @DontObfuscate - private String object = ""; + @RegistryListObject + @Required + @Desc("The object to place if rarity check passed") + @DontObfuscate + private String object = ""; } diff --git a/src/main/java/com/volmit/iris/object/IrisRegion.java b/src/main/java/com/volmit/iris/object/IrisRegion.java index 3922ba30b..f7ebc8b81 100644 --- a/src/main/java/com/volmit/iris/object/IrisRegion.java +++ b/src/main/java/com/volmit/iris/object/IrisRegion.java @@ -17,574 +17,505 @@ import lombok.experimental.Accessors; @Desc("Represents an iris region") @Data @EqualsAndHashCode(callSuper = false) -public class IrisRegion extends IrisRegistrant implements IRare -{ - @MinNumber(2) - @Required - @DontObfuscate - @Desc("The name of the region") - private String name = "A Region"; - - @ArrayType(min = 1, type = IrisJigsawStructurePlacement.class) - @DontObfuscate - @Desc("Jigsaw structures") - private KList jigsawStructures = new KList<>(); - - @DontObfuscate - @Desc("Add random chances for terrain features") - @ArrayType(min = 1, type = IrisFeaturePotential.class) - private KList features = new KList<>(); - - @ArrayType(min = 1, type = IrisEffect.class) - @DontObfuscate - @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<>(); - - @DontObfuscate - @Desc("Entity spawns to override or add to this region") - @ArrayType(min = 1, type = IrisEntitySpawnOverride.class) - private KList entitySpawnOverrides = new KList<>(); - - @DontObfuscate - @Desc("Entity spawns during generation") - @ArrayType(min = 1, type = IrisEntityInitialSpawn.class) - private KList entityInitialSpawns = new KList<>(); - - @MinNumber(1) - @MaxNumber(128) - @DontObfuscate - @Desc("The rarity of the region") - private int rarity = 1; - - @ArrayType(min = 1, type = IrisBlockDrops.class) - @DontObfuscate - @Desc("Define custom block drops for this region") - private KList blockDrops = new KList<>(); - - @MinNumber(0.0001) - @MaxNumber(1) - @DontObfuscate - @Desc("The shore ration (How much percent of land should be a shore)") - private double shoreRatio = 0.13; - - @ArrayType(min = 1, type = IrisObjectPlacement.class) - @DontObfuscate - @Desc("Objects define what schematics (iob files) iris will place in this region") - private KList objects = new KList(); - - @MinNumber(0) - @DontObfuscate - @Desc("The min shore height") - private double shoreHeightMin = 1.2; - - @DontObfuscate - @Desc("Reference loot tables in this area") - private IrisLootReference loot = new IrisLootReference(); - - @MinNumber(0) - @DontObfuscate - @Desc("The the max shore height") - private double shoreHeightMax = 3.2; - - @MinNumber(0.0001) - @DontObfuscate - @Desc("The varience of the shore height") - private double shoreHeightZoom = 3.14; - - @MinNumber(0.0001) - @DontObfuscate - @Desc("How large land biomes are in this region") - private double landBiomeZoom = 1; - - @MinNumber(0.0001) - @DontObfuscate - @Desc("How large shore biomes are in this region") - private double shoreBiomeZoom = 1; - - @MinNumber(0.0001) - @DontObfuscate - @Desc("How large lake biomes are in this region") - private double lakeBiomeZoom = 1; - - @MinNumber(0.0001) - @DontObfuscate - @Desc("How large river biomes are in this region") - private double riverBiomeZoom = 1; - - @MinNumber(0.0001) - @DontObfuscate - @Desc("How large sea biomes are in this region") - private double seaBiomeZoom = 1; - - @MinNumber(0.0001) - @DontObfuscate - @Desc("How large cave biomes are in this region") - private double caveBiomeZoom = 1; - - @MinNumber(0.0001) - @MaxNumber(1) - @DontObfuscate - @Desc("The biome implosion ratio, how much to implode biomes into children (chance)") - private double biomeImplosionRatio = 0.4; - - @RegistryListBiome - @Required - @ArrayType(min = 1, type = String.class) - @DontObfuscate - @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<>(); - - @RegistryListBiome - @Required - @ArrayType(min = 1, type = String.class) - @DontObfuscate - @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 seaBiomes = new KList<>(); - - @RegistryListBiome - @Required - @ArrayType(min = 1, type = String.class) - @DontObfuscate - @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 shoreBiomes = new KList<>(); - - @RegistryListBiome - @ArrayType(min = 1, type = String.class) - @DontObfuscate - @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 riverBiomes = new KList<>(); - - @RegistryListBiome - @ArrayType(min = 1, type = String.class) - @DontObfuscate - @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 lakeBiomes = new KList<>(); - - @RegistryListBiome - @ArrayType(min = 1, type = String.class) - @DontObfuscate - @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 caveBiomes = new KList<>(); - - @ArrayType(min = 1, type = IrisRegionRidge.class) - @DontObfuscate - @Desc("Ridge biomes create a vein-like network like rivers through this region") - private KList ridgeBiomes = new KList<>(); - - @ArrayType(min = 1, type = IrisRegionSpot.class) - @DontObfuscate - @Desc("Spot biomes splotch themselves across this region like lakes") - private KList spotBiomes = 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<>(); - - @DontObfuscate - @Desc("The style of rivers") - private IrisGeneratorStyle riverStyle = NoiseStyle.VASCULAR_THIN.style().zoomed(7.77); - - @DontObfuscate - @Desc("The style of lakes") - private IrisGeneratorStyle lakeStyle = NoiseStyle.CELLULAR_IRIS_THICK.style(); - - @DontObfuscate - @Desc("The style of river chances") - private IrisGeneratorStyle riverChanceStyle = NoiseStyle.SIMPLEX.style().zoomed(4); - - @DontObfuscate - @Desc("Generate lakes in this region") - private boolean lakes = true; - - @DontObfuscate - @Desc("Generate rivers in this region") - private boolean rivers = true; - - @MinNumber(1) - @DontObfuscate - @Desc("Generate lakes in this region") - private int lakeRarity = 22; - - @MinNumber(1) - @DontObfuscate - @Desc("Generate rivers in this region") - private int riverRarity = 3; - - @MinNumber(0) - @MaxNumber(1) - @DontObfuscate - @Desc("Generate rivers in this region") - private double riverThickness = 0.1; - - @DontObfuscate - @Desc("A color for visualizing this region with a color. I.e. #F13AF5. This will show up on the map.") - private IrisColor color = null; - - 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> realLakeBiomes = new AtomicCache<>(); - private final transient AtomicCache> realRiverBiomes = 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 lakeGen = new AtomicCache<>(); - private final transient AtomicCache riverGen = new AtomicCache<>(); - private final transient AtomicCache riverChanceGen = new AtomicCache<>(); - - 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 boolean isRiver(RNG rng, double x, double z) - { - if(!isRivers()) - { - return false; - } - - if(getRiverBiomes().isEmpty()) - { - return false; - } - - if(getRiverChanceGen().aquire(() -> getRiverChanceStyle().create(rng)).fit(1, getRiverRarity(), x, z) != 1) - { - return false; - } - - if(getRiverGen().aquire(() -> getRiverStyle().create(rng)).fitDouble(0, 1, x, z) < getRiverThickness()) - { - return true; - } - - return false; - } - - public boolean isLake(RNG rng, double x, double z) - { - if(!isLakes()) - { - return false; - } - - if(getLakeBiomes().isEmpty()) - { - return false; - } - - if(getLakeGen().aquire(() -> getLakeStyle().create(rng)).fit(1, getLakeRarity(), x, z) == 1) - { - return true; - } - - return false; - } - - public double getBiomeZoom(InferredType t) - { - switch(t) - { - case CAVE: - return caveBiomeZoom; - case LAKE: - return lakeBiomeZoom; - case RIVER: - return riverBiomeZoom; - case LAND: - return landBiomeZoom; - case SEA: - return seaBiomeZoom; - case SHORE: - return shoreBiomeZoom; - default: - break; - } - - return 1; - } - - public KList getRidgeBiomeKeys() - { - return cacheRidge.aquire(() -> - { - KList cacheRidge = new KList(); - ridgeBiomes.forEach((i) -> cacheRidge.add(i.getBiome())); - - return cacheRidge; - }); - } - - public KList getSpotBiomeKeys() - { - return cacheSpot.aquire(() -> - { - KList cacheSpot = new KList(); - spotBiomes.forEach((i) -> cacheSpot.add(i.getBiome())); - return cacheSpot; - }); - } - - public CNG getShoreHeightGenerator() - { - return shoreHeightGenerator.aquire(() -> - { - return 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); - names.addAll(riverBiomes); - names.addAll(lakeBiomes); - spotBiomes.forEach((i) -> names.add(i.getBiome())); - ridgeBiomes.forEach((i) -> names.add(i.getBiome())); - - 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); - } - - else if(type.equals(InferredType.LAKE)) - { - return getRealLakeBiomes(g); - } - - else if(type.equals(InferredType.RIVER)) - { - return getRealRiverBiomes(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 getRealLakeBiomes(DataProvider g) - { - return realLakeBiomes.aquire(() -> - { - KList realLakeBiomes = new KList<>(); - - for(String i : getLakeBiomes()) - { - realLakeBiomes.add(g.getData().getBiomeLoader().load(i)); - } - - return realLakeBiomes; - }); - } - - public KList getRealRiverBiomes(DataProvider g) - { - return realRiverBiomes.aquire(() -> - { - KList realRiverBiomes = new KList<>(); - - for(String i : getRiverBiomes()) - { - realRiverBiomes.add(g.getData().getBiomeLoader().load(i)); - } - - return realRiverBiomes; - }); - } - - 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); - names.addAll(riverBiomes); - names.addAll(lakeBiomes); - spotBiomes.forEach((i) -> names.add(i.getBiome())); - ridgeBiomes.forEach((i) -> names.add(i.getBiome())); - - while(!names.isEmpty()) - { - for(String i : new KList<>(names)) - { - if(b.containsKey(i)) - { - names.remove(i); - continue; - } - - IrisBiome biome = IrisDataManager.loadAnyBiome(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 class IrisRegion extends IrisRegistrant implements IRare { + @MinNumber(2) + @Required + @DontObfuscate + @Desc("The name of the region") + private String name = "A Region"; + + @ArrayType(min = 1, type = IrisJigsawStructurePlacement.class) + @DontObfuscate + @Desc("Jigsaw structures") + private KList jigsawStructures = new KList<>(); + + @DontObfuscate + @Desc("Add random chances for terrain features") + @ArrayType(min = 1, type = IrisFeaturePotential.class) + private KList features = new KList<>(); + + @ArrayType(min = 1, type = IrisEffect.class) + @DontObfuscate + @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<>(); + + @DontObfuscate + @Desc("Entity spawns to override or add to this region") + @ArrayType(min = 1, type = IrisEntitySpawnOverride.class) + private KList entitySpawnOverrides = new KList<>(); + + @DontObfuscate + @Desc("Entity spawns during generation") + @ArrayType(min = 1, type = IrisEntityInitialSpawn.class) + private KList entityInitialSpawns = new KList<>(); + + @MinNumber(1) + @MaxNumber(128) + @DontObfuscate + @Desc("The rarity of the region") + private int rarity = 1; + + @ArrayType(min = 1, type = IrisBlockDrops.class) + @DontObfuscate + @Desc("Define custom block drops for this region") + private KList blockDrops = new KList<>(); + + @MinNumber(0.0001) + @MaxNumber(1) + @DontObfuscate + @Desc("The shore ration (How much percent of land should be a shore)") + private double shoreRatio = 0.13; + + @ArrayType(min = 1, type = IrisObjectPlacement.class) + @DontObfuscate + @Desc("Objects define what schematics (iob files) iris will place in this region") + private KList objects = new KList(); + + @MinNumber(0) + @DontObfuscate + @Desc("The min shore height") + private double shoreHeightMin = 1.2; + + @DontObfuscate + @Desc("Reference loot tables in this area") + private IrisLootReference loot = new IrisLootReference(); + + @MinNumber(0) + @DontObfuscate + @Desc("The the max shore height") + private double shoreHeightMax = 3.2; + + @MinNumber(0.0001) + @DontObfuscate + @Desc("The varience of the shore height") + private double shoreHeightZoom = 3.14; + + @MinNumber(0.0001) + @DontObfuscate + @Desc("How large land biomes are in this region") + private double landBiomeZoom = 1; + + @MinNumber(0.0001) + @DontObfuscate + @Desc("How large shore biomes are in this region") + private double shoreBiomeZoom = 1; + + @MinNumber(0.0001) + @DontObfuscate + @Desc("How large lake biomes are in this region") + private double lakeBiomeZoom = 1; + + @MinNumber(0.0001) + @DontObfuscate + @Desc("How large river biomes are in this region") + private double riverBiomeZoom = 1; + + @MinNumber(0.0001) + @DontObfuscate + @Desc("How large sea biomes are in this region") + private double seaBiomeZoom = 1; + + @MinNumber(0.0001) + @DontObfuscate + @Desc("How large cave biomes are in this region") + private double caveBiomeZoom = 1; + + @MinNumber(0.0001) + @MaxNumber(1) + @DontObfuscate + @Desc("The biome implosion ratio, how much to implode biomes into children (chance)") + private double biomeImplosionRatio = 0.4; + + @RegistryListBiome + @Required + @ArrayType(min = 1, type = String.class) + @DontObfuscate + @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<>(); + + @RegistryListBiome + @Required + @ArrayType(min = 1, type = String.class) + @DontObfuscate + @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 seaBiomes = new KList<>(); + + @RegistryListBiome + @Required + @ArrayType(min = 1, type = String.class) + @DontObfuscate + @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 shoreBiomes = new KList<>(); + + @RegistryListBiome + @ArrayType(min = 1, type = String.class) + @DontObfuscate + @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 riverBiomes = new KList<>(); + + @RegistryListBiome + @ArrayType(min = 1, type = String.class) + @DontObfuscate + @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 lakeBiomes = new KList<>(); + + @RegistryListBiome + @ArrayType(min = 1, type = String.class) + @DontObfuscate + @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 caveBiomes = new KList<>(); + + @ArrayType(min = 1, type = IrisRegionRidge.class) + @DontObfuscate + @Desc("Ridge biomes create a vein-like network like rivers through this region") + private KList ridgeBiomes = new KList<>(); + + @ArrayType(min = 1, type = IrisRegionSpot.class) + @DontObfuscate + @Desc("Spot biomes splotch themselves across this region like lakes") + private KList spotBiomes = 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<>(); + + @DontObfuscate + @Desc("The style of rivers") + private IrisGeneratorStyle riverStyle = NoiseStyle.VASCULAR_THIN.style().zoomed(7.77); + + @DontObfuscate + @Desc("The style of lakes") + private IrisGeneratorStyle lakeStyle = NoiseStyle.CELLULAR_IRIS_THICK.style(); + + @DontObfuscate + @Desc("The style of river chances") + private IrisGeneratorStyle riverChanceStyle = NoiseStyle.SIMPLEX.style().zoomed(4); + + @DontObfuscate + @Desc("Generate lakes in this region") + private boolean lakes = true; + + @DontObfuscate + @Desc("Generate rivers in this region") + private boolean rivers = true; + + @MinNumber(1) + @DontObfuscate + @Desc("Generate lakes in this region") + private int lakeRarity = 22; + + @MinNumber(1) + @DontObfuscate + @Desc("Generate rivers in this region") + private int riverRarity = 3; + + @MinNumber(0) + @MaxNumber(1) + @DontObfuscate + @Desc("Generate rivers in this region") + private double riverThickness = 0.1; + + @DontObfuscate + @Desc("A color for visualizing this region with a color. I.e. #F13AF5. This will show up on the map.") + private IrisColor color = null; + + 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> realLakeBiomes = new AtomicCache<>(); + private final transient AtomicCache> realRiverBiomes = 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 lakeGen = new AtomicCache<>(); + private final transient AtomicCache riverGen = new AtomicCache<>(); + private final transient AtomicCache riverChanceGen = new AtomicCache<>(); + + 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 boolean isRiver(RNG rng, double x, double z) { + if (!isRivers()) { + return false; + } + + if (getRiverBiomes().isEmpty()) { + return false; + } + + if (getRiverChanceGen().aquire(() -> getRiverChanceStyle().create(rng)).fit(1, getRiverRarity(), x, z) != 1) { + return false; + } + + return getRiverGen().aquire(() -> getRiverStyle().create(rng)).fitDouble(0, 1, x, z) < getRiverThickness(); + } + + public boolean isLake(RNG rng, double x, double z) { + if (!isLakes()) { + return false; + } + + if (getLakeBiomes().isEmpty()) { + return false; + } + + return getLakeGen().aquire(() -> getLakeStyle().create(rng)).fit(1, getLakeRarity(), x, z) == 1; + } + + public double getBiomeZoom(InferredType t) { + switch (t) { + case CAVE: + return caveBiomeZoom; + case LAKE: + return lakeBiomeZoom; + case RIVER: + return riverBiomeZoom; + case LAND: + return landBiomeZoom; + case SEA: + return seaBiomeZoom; + case SHORE: + return shoreBiomeZoom; + default: + break; + } + + return 1; + } + + public KList getRidgeBiomeKeys() { + return cacheRidge.aquire(() -> + { + KList cacheRidge = new KList(); + ridgeBiomes.forEach((i) -> cacheRidge.add(i.getBiome())); + + return cacheRidge; + }); + } + + public KList getSpotBiomeKeys() { + return cacheSpot.aquire(() -> + { + KList cacheSpot = new KList(); + spotBiomes.forEach((i) -> cacheSpot.add(i.getBiome())); + return cacheSpot; + }); + } + + public CNG getShoreHeightGenerator() { + return shoreHeightGenerator.aquire(() -> + { + return 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); + names.addAll(riverBiomes); + names.addAll(lakeBiomes); + spotBiomes.forEach((i) -> names.add(i.getBiome())); + ridgeBiomes.forEach((i) -> names.add(i.getBiome())); + + 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); + } else if (type.equals(InferredType.LAKE)) { + return getRealLakeBiomes(g); + } else if (type.equals(InferredType.RIVER)) { + return getRealRiverBiomes(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 getRealLakeBiomes(DataProvider g) { + return realLakeBiomes.aquire(() -> + { + KList realLakeBiomes = new KList<>(); + + for (String i : getLakeBiomes()) { + realLakeBiomes.add(g.getData().getBiomeLoader().load(i)); + } + + return realLakeBiomes; + }); + } + + public KList getRealRiverBiomes(DataProvider g) { + return realRiverBiomes.aquire(() -> + { + KList realRiverBiomes = new KList<>(); + + for (String i : getRiverBiomes()) { + realRiverBiomes.add(g.getData().getBiomeLoader().load(i)); + } + + return realRiverBiomes; + }); + } + + 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); + names.addAll(riverBiomes); + names.addAll(lakeBiomes); + spotBiomes.forEach((i) -> names.add(i.getBiome())); + ridgeBiomes.forEach((i) -> names.add(i.getBiome())); + + while (!names.isEmpty()) { + for (String i : new KList<>(names)) { + if (b.containsKey(i)) { + names.remove(i); + continue; + } + + IrisBiome biome = IrisDataManager.loadAnyBiome(i); + + names.remove(i); + if (biome == null) { + continue; + } + + names.add(biome.getCarvingBiome()); + b.put(biome.getLoadKey(), biome); + names.addAll(biome.getChildren()); + } + } + + return b.v(); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisRegionRidge.java b/src/main/java/com/volmit/iris/object/IrisRegionRidge.java index 398bb5680..faf463dda 100644 --- a/src/main/java/com/volmit/iris/object/IrisRegionRidge.java +++ b/src/main/java/com/volmit/iris/object/IrisRegionRidge.java @@ -1,15 +1,8 @@ package com.volmit.iris.object; -import com.volmit.iris.scaffold.cache.AtomicCache; import com.volmit.iris.generator.noise.CellGenerator; -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.MaxNumber; -import com.volmit.iris.util.MinNumber; -import com.volmit.iris.util.RNG; -import com.volmit.iris.util.RegistryListBiome; -import com.volmit.iris.util.Required; - +import com.volmit.iris.scaffold.cache.AtomicCache; +import com.volmit.iris.util.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -20,124 +13,111 @@ import lombok.experimental.Accessors; @AllArgsConstructor @Desc("A ridge config") @Data -public class IrisRegionRidge -{ - - @RegistryListBiome - @Required - @DontObfuscate - @Desc("The biome name") - private String biome = ""; +public class IrisRegionRidge { - - @Required - @DontObfuscate - @Desc("The type this biome should override (land sea or shore)") - private InferredType type = InferredType.LAND; - - - @DontObfuscate - @Desc("What type this spot is (i.e. target SEA but as LAND) like an island. Default matches the target type") - private InferredType as = InferredType.DEFER; - - - @DontObfuscate - @Desc("Use the distance from cell value to add or remove noise value. (Forces depth or height)") - private double noiseMultiplier = 0; - - - @Required - @MinNumber(0) - @MaxNumber(1) - @DontObfuscate - @Desc("The chance this biome will be placed in a given spot") - private double chance = 0.75; - - - @MinNumber(0) - @DontObfuscate - @Desc("The scale of the biome ridge. Higher values = wider veins & bigger connected cells") - private double scale = 5; - - - @DontObfuscate - @Desc("The chance scale (cell chances)") - private double chanceScale = 4; - - - @MinNumber(0) - @DontObfuscate - @Desc("The shuffle, how 'natural' this looks. Compared to pure polygons") - private double shuffle = 16; - - - @MinNumber(0) - @DontObfuscate - @Desc("The chance shuffle (polygon cell chances)") - private double chanceShuffle = 128; - - - @MinNumber(0) - @DontObfuscate - @Desc("The thickness of the vein") - private double thickness = 0.125; - - - @DontObfuscate - @Desc("If the noise multiplier is below zero, what should the air be filled with?") - private IrisBiomePaletteLayer air = new IrisBiomePaletteLayer().zero(); - - private final transient AtomicCache spot = new AtomicCache<>(); - private final transient AtomicCache ridge = new AtomicCache<>(); + @RegistryListBiome + @Required + @DontObfuscate + @Desc("The biome name") + private String biome = ""; - public CellGenerator getSpotGenerator(RNG rng) - { - return spot.aquire(() -> - { - CellGenerator spot = new CellGenerator(rng.nextParallelRNG((int) (198523 * getChance()))); - spot.setCellScale(chanceScale); - spot.setShuffle(shuffle); - return spot; - }); - } + @Required + @DontObfuscate + @Desc("The type this biome should override (land sea or shore)") + private InferredType type = InferredType.LAND; - public CellGenerator getRidgeGenerator(RNG rng) - { - return spot.aquire(() -> - { - CellGenerator ridge = new CellGenerator(rng.nextParallelRNG((int) (465583 * getChance()))); - ridge.setCellScale(scale); - ridge.setShuffle(shuffle); - return ridge; - }); - } - public double getRidgeHeight(RNG rng, double x, double z) - { - if(getNoiseMultiplier() == 0) - { - return 0; - } + @DontObfuscate + @Desc("What type this spot is (i.e. target SEA but as LAND) like an island. Default matches the target type") + private InferredType as = InferredType.DEFER; - return getSpotGenerator(rng).getDistance(x, z) * getRidgeGenerator(rng).getDistance(x, z) * getNoiseMultiplier(); - } - public boolean isRidge(RNG rng, double x, double z) - { - if(chance < 1) - { - if(getSpotGenerator(rng).getIndex(x, z, 1000) > chance * 1000) - { - return false; - } - } + @DontObfuscate + @Desc("Use the distance from cell value to add or remove noise value. (Forces depth or height)") + private double noiseMultiplier = 0; - if(getRidgeGenerator(rng).getDistance(x, z) <= thickness) - { - return true; - } - return false; - } + @Required + @MinNumber(0) + @MaxNumber(1) + @DontObfuscate + @Desc("The chance this biome will be placed in a given spot") + private double chance = 0.75; + + + @MinNumber(0) + @DontObfuscate + @Desc("The scale of the biome ridge. Higher values = wider veins & bigger connected cells") + private double scale = 5; + + + @DontObfuscate + @Desc("The chance scale (cell chances)") + private double chanceScale = 4; + + + @MinNumber(0) + @DontObfuscate + @Desc("The shuffle, how 'natural' this looks. Compared to pure polygons") + private double shuffle = 16; + + + @MinNumber(0) + @DontObfuscate + @Desc("The chance shuffle (polygon cell chances)") + private double chanceShuffle = 128; + + + @MinNumber(0) + @DontObfuscate + @Desc("The thickness of the vein") + private double thickness = 0.125; + + + @DontObfuscate + @Desc("If the noise multiplier is below zero, what should the air be filled with?") + private IrisBiomePaletteLayer air = new IrisBiomePaletteLayer().zero(); + + private final transient AtomicCache spot = new AtomicCache<>(); + private final transient AtomicCache ridge = new AtomicCache<>(); + + + public CellGenerator getSpotGenerator(RNG rng) { + return spot.aquire(() -> + { + CellGenerator spot = new CellGenerator(rng.nextParallelRNG((int) (198523 * getChance()))); + spot.setCellScale(chanceScale); + spot.setShuffle(shuffle); + return spot; + }); + } + + public CellGenerator getRidgeGenerator(RNG rng) { + return spot.aquire(() -> + { + CellGenerator ridge = new CellGenerator(rng.nextParallelRNG((int) (465583 * getChance()))); + ridge.setCellScale(scale); + ridge.setShuffle(shuffle); + return ridge; + }); + } + + public double getRidgeHeight(RNG rng, double x, double z) { + if (getNoiseMultiplier() == 0) { + return 0; + } + + return getSpotGenerator(rng).getDistance(x, z) * getRidgeGenerator(rng).getDistance(x, z) * getNoiseMultiplier(); + } + + public boolean isRidge(RNG rng, double x, double z) { + if (chance < 1) { + if (getSpotGenerator(rng).getIndex(x, z, 1000) > chance * 1000) { + return false; + } + } + + return getRidgeGenerator(rng).getDistance(x, z) <= thickness; + } } diff --git a/src/main/java/com/volmit/iris/object/IrisRegionSpot.java b/src/main/java/com/volmit/iris/object/IrisRegionSpot.java index 663534a99..ee836bb6c 100644 --- a/src/main/java/com/volmit/iris/object/IrisRegionSpot.java +++ b/src/main/java/com/volmit/iris/object/IrisRegionSpot.java @@ -1,14 +1,8 @@ package com.volmit.iris.object; -import com.volmit.iris.scaffold.cache.AtomicCache; import com.volmit.iris.generator.noise.CellGenerator; -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.MinNumber; -import com.volmit.iris.util.RNG; -import com.volmit.iris.util.RegistryListBiome; -import com.volmit.iris.util.Required; - +import com.volmit.iris.scaffold.cache.AtomicCache; +import com.volmit.iris.util.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -19,78 +13,68 @@ import lombok.experimental.Accessors; @AllArgsConstructor @Desc("A spot config") @Data -public class IrisRegionSpot -{ +public class IrisRegionSpot { - @RegistryListBiome - @Required - @DontObfuscate - @Desc("The biome to be placed") - private String biome = ""; + @RegistryListBiome + @Required + @DontObfuscate + @Desc("The biome to be placed") + private String biome = ""; - @Required - @DontObfuscate - @Desc("Where this spot overrides. Land sea or shore") - private InferredType type = InferredType.LAND; + @Required + @DontObfuscate + @Desc("Where this spot overrides. Land sea or shore") + private InferredType type = InferredType.LAND; - @DontObfuscate - @Desc("What type this spot is (i.e. target SEA but as LAND) like an island. Default matches the target type") - private InferredType as = InferredType.DEFER; + @DontObfuscate + @Desc("What type this spot is (i.e. target SEA but as LAND) like an island. Default matches the target type") + private InferredType as = InferredType.DEFER; - @DontObfuscate - @Desc("Use the distance from cell value to add or remove noise value. (Forces depth or height)") - private double noiseMultiplier = 0; + @DontObfuscate + @Desc("Use the distance from cell value to add or remove noise value. (Forces depth or height)") + private double noiseMultiplier = 0; - @MinNumber(0) - @DontObfuscate - @Desc("The scale of splotches") - private double scale = 1; + @MinNumber(0) + @DontObfuscate + @Desc("The scale of splotches") + private double scale = 1; - @Required - @MinNumber(1) - @DontObfuscate - @Desc("Rarity is how often this splotch appears. higher = less often") - private double rarity = 1; + @Required + @MinNumber(1) + @DontObfuscate + @Desc("Rarity is how often this splotch appears. higher = less often") + private double rarity = 1; - @MinNumber(0) - @DontObfuscate - @Desc("The shuffle or how natural the splotch looks like (anti-polygon)") - private double shuffle = 128; + @MinNumber(0) + @DontObfuscate + @Desc("The shuffle or how natural the splotch looks like (anti-polygon)") + private double shuffle = 128; - @DontObfuscate - @Desc("If the noise multiplier is below zero, what should the air be filled with?") - private IrisBiomePaletteLayer air = new IrisBiomePaletteLayer().zero(); + @DontObfuscate + @Desc("If the noise multiplier is below zero, what should the air be filled with?") + private IrisBiomePaletteLayer air = new IrisBiomePaletteLayer().zero(); - private final transient AtomicCache spot = new AtomicCache<>(); + private final transient AtomicCache spot = new AtomicCache<>(); - public CellGenerator getSpotGenerator(RNG rng) - { - return spot.aquire(() -> - { - CellGenerator spot = new CellGenerator(rng.nextParallelRNG((int) (168583 * (shuffle + 102) + rarity + (scale * 10465) + biome.length() + type.ordinal() + as.ordinal()))); - spot.setCellScale(scale); - spot.setShuffle(shuffle); - return spot; - }); - } + public CellGenerator getSpotGenerator(RNG rng) { + return spot.aquire(() -> + { + CellGenerator spot = new CellGenerator(rng.nextParallelRNG((int) (168583 * (shuffle + 102) + rarity + (scale * 10465) + biome.length() + type.ordinal() + as.ordinal()))); + spot.setCellScale(scale); + spot.setShuffle(shuffle); + return spot; + }); + } - public double getSpotHeight(RNG rng, double x, double z) - { - if(getNoiseMultiplier() == 0) - { - return 0; - } + public double getSpotHeight(RNG rng, double x, double z) { + if (getNoiseMultiplier() == 0) { + return 0; + } - return getSpotGenerator(rng).getDistance(x, z) * getNoiseMultiplier(); - } + return getSpotGenerator(rng).getDistance(x, z) * getNoiseMultiplier(); + } - public boolean isSpot(RNG rng, double x, double z) - { - if(getSpotGenerator(rng).getIndex(x, z, (int) (Math.round(rarity) + 8)) == (int) ((Math.round(rarity) + 8) / 2)) - { - return true; - } - - return false; - } + public boolean isSpot(RNG rng, double x, double z) { + return getSpotGenerator(rng).getIndex(x, z, (int) (Math.round(rarity) + 8)) == (int) ((Math.round(rarity) + 8) / 2); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisRegistrant.java b/src/main/java/com/volmit/iris/object/IrisRegistrant.java index b76580f4b..d59351cf0 100644 --- a/src/main/java/com/volmit/iris/object/IrisRegistrant.java +++ b/src/main/java/com/volmit/iris/object/IrisRegistrant.java @@ -6,11 +6,10 @@ import lombok.Data; import java.io.File; @Data -public class IrisRegistrant -{ - private transient IrisDataManager loader; +public class IrisRegistrant { + private transient IrisDataManager loader; - private transient String loadKey; + private transient String loadKey; - private transient File loadFile; + private transient File loadFile; } diff --git a/src/main/java/com/volmit/iris/object/IrisShapedGeneratorStyle.java b/src/main/java/com/volmit/iris/object/IrisShapedGeneratorStyle.java index 6dce49f63..43f17b97b 100644 --- a/src/main/java/com/volmit/iris/object/IrisShapedGeneratorStyle.java +++ b/src/main/java/com/volmit/iris/object/IrisShapedGeneratorStyle.java @@ -1,12 +1,6 @@ package com.volmit.iris.object; -import com.volmit.iris.util.Desc; -import com.volmit.iris.util.DontObfuscate; -import com.volmit.iris.util.MaxNumber; -import com.volmit.iris.util.MinNumber; -import com.volmit.iris.util.RNG; -import com.volmit.iris.util.Required; - +import com.volmit.iris.util.*; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -17,43 +11,39 @@ import lombok.experimental.Accessors; @AllArgsConstructor @Desc("This represents a generator with a min and max height") @Data -public class IrisShapedGeneratorStyle -{ - @Required - @DontObfuscate - @Desc("The generator id") +public class IrisShapedGeneratorStyle { + @Required + @DontObfuscate + @Desc("The generator id") - private IrisGeneratorStyle generator = new IrisGeneratorStyle(NoiseStyle.IRIS); + private IrisGeneratorStyle generator = new IrisGeneratorStyle(NoiseStyle.IRIS); - @Required - @MinNumber(-256) // TODO: WARNING HEIGHT - @MaxNumber(256) // TODO: WARNING HEIGHT + @Required + @MinNumber(-256) // TODO: WARNING HEIGHT + @MaxNumber(256) // TODO: WARNING HEIGHT - @DontObfuscate - @Desc("The min block value") - private int min = 0; + @DontObfuscate + @Desc("The min block value") + private int min = 0; - @Required - @MinNumber(-256) // TODO: WARNING HEIGHT - @MaxNumber(256) // TODO: WARNING HEIGHT - @DontObfuscate - @Desc("The max block value") - private int max = 0; + @Required + @MinNumber(-256) // TODO: WARNING HEIGHT + @MaxNumber(256) // TODO: WARNING HEIGHT + @DontObfuscate + @Desc("The max block value") + private int max = 0; - public double get(RNG rng, double... dim) - { - return generator.create(rng).fitDouble(min, max, dim); - } + public double get(RNG rng, double... dim) { + return generator.create(rng).fitDouble(min, max, dim); + } - public IrisShapedGeneratorStyle(NoiseStyle style, int min, int max) - { - this(style); - this.min = min; - this.max = max; - } + 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 IrisShapedGeneratorStyle(NoiseStyle style) { + this.generator = new IrisGeneratorStyle(style); + } } diff --git a/src/main/java/com/volmit/iris/object/IrisSlopeClip.java b/src/main/java/com/volmit/iris/object/IrisSlopeClip.java index 2a54d9d33..de974af4b 100644 --- a/src/main/java/com/volmit/iris/object/IrisSlopeClip.java +++ b/src/main/java/com/volmit/iris/object/IrisSlopeClip.java @@ -1,6 +1,9 @@ package com.volmit.iris.object; -import com.volmit.iris.util.*; +import com.volmit.iris.util.Desc; +import com.volmit.iris.util.DontObfuscate; +import com.volmit.iris.util.MaxNumber; +import com.volmit.iris.util.MinNumber; import lombok.AllArgsConstructor; import lombok.Data; import lombok.NoArgsConstructor; @@ -11,36 +14,28 @@ import lombok.experimental.Accessors; @AllArgsConstructor @Desc("Translate objects") @Data -public class IrisSlopeClip -{ - @MinNumber(0) - @MaxNumber(255) - @DontObfuscate - @Desc("The minimum slope for placement") - private double minimumSlope = 0; +public class IrisSlopeClip { + @MinNumber(0) + @MaxNumber(255) + @DontObfuscate + @Desc("The minimum slope for placement") + private double minimumSlope = 0; - @MinNumber(0) - @MaxNumber(255) - @DontObfuscate - @Desc("The maximum slope for placement") - private double maximumSlope = 10; + @MinNumber(0) + @MaxNumber(255) + @DontObfuscate + @Desc("The maximum slope for placement") + private double maximumSlope = 10; - public boolean isDefault() { - return minimumSlope <= 0 && maximumSlope >= 10; - } + public boolean isDefault() { + return minimumSlope <= 0 && maximumSlope >= 10; + } - public boolean isValid(double slope) - { - if(isDefault()) - { - return true; - } + public boolean isValid(double slope) { + if (isDefault()) { + return true; + } - if(minimumSlope > slope || maximumSlope < slope) - { - return false; - } - - return true; - } + return !(minimumSlope > slope) && !(maximumSlope < slope); + } } diff --git a/src/main/java/com/volmit/iris/object/LootMode.java b/src/main/java/com/volmit/iris/object/LootMode.java index 65747ca27..20b4a9bca 100644 --- a/src/main/java/com/volmit/iris/object/LootMode.java +++ b/src/main/java/com/volmit/iris/object/LootMode.java @@ -4,17 +4,16 @@ import com.volmit.iris.util.Desc; import com.volmit.iris.util.DontObfuscate; @Desc("A loot mode is used to descrive what to do with the existing loot layers before adding this loot. Using ADD will simply add this table to the building list of tables (i.e. add dimension tables, region tables then biome tables). By using clear or replace, you remove the parent tables before and add just your tables.") -public enum LootMode -{ - @Desc("Add to the existing parent loot tables") - @DontObfuscate - ADD, +public enum LootMode { + @Desc("Add to the existing parent loot tables") + @DontObfuscate + ADD, - @Desc("Clear all loot tables then add this table") - @DontObfuscate - CLEAR, + @Desc("Clear all loot tables then add this table") + @DontObfuscate + CLEAR, - @Desc("Replace all loot tables with this table (same as clear)") - @DontObfuscate - REPLACE; + @Desc("Replace all loot tables with this table (same as clear)") + @DontObfuscate + REPLACE } diff --git a/src/main/java/com/volmit/iris/object/NoiseStyle.java b/src/main/java/com/volmit/iris/object/NoiseStyle.java index f1a34c1fa..a9255d980 100644 --- a/src/main/java/com/volmit/iris/object/NoiseStyle.java +++ b/src/main/java/com/volmit/iris/object/NoiseStyle.java @@ -1,463 +1,457 @@ package com.volmit.iris.object; -import com.volmit.iris.scaffold.stream.ProceduralStream; import com.volmit.iris.generator.noise.CNG; import com.volmit.iris.generator.noise.CNGFactory; import com.volmit.iris.generator.noise.NoiseType; +import com.volmit.iris.scaffold.stream.ProceduralStream; import com.volmit.iris.util.Desc; import com.volmit.iris.util.DontObfuscate; import com.volmit.iris.util.RNG; @Desc("Styles of noise") @DontObfuscate -public enum NoiseStyle -{ - @Desc("White Noise is like static. Useful for block scattering but not terrain.") - @DontObfuscate - STATIC(rng -> new CNG(rng, NoiseType.WHITE, 1D, 1)), +public enum NoiseStyle { + @Desc("White Noise is like static. Useful for block scattering but not terrain.") + @DontObfuscate + STATIC(rng -> new CNG(rng, NoiseType.WHITE, 1D, 1)), - @Desc("Wispy Perlin-looking simplex noise. The 'iris' style noise.") - @DontObfuscate - IRIS(rng -> CNG.signature(rng).scale(1)), + @Desc("Wispy Perlin-looking simplex noise. The 'iris' style noise.") + @DontObfuscate + IRIS(rng -> CNG.signature(rng).scale(1)), - @Desc("Classic German Engineering") - @DontObfuscate - NOWHERE(rng -> CNG.signaturePerlin(rng).scale(0.776).bake()), + @Desc("Classic German Engineering") + @DontObfuscate + NOWHERE(rng -> CNG.signaturePerlin(rng).scale(0.776).bake()), - @Desc("Classic German Engineering") - @DontObfuscate - NOWHERE_CELLULAR(rng -> CNG.signaturePerlin(rng, NoiseType.CELLULAR).scale(1).bake()), + @Desc("Classic German Engineering") + @DontObfuscate + NOWHERE_CELLULAR(rng -> CNG.signaturePerlin(rng, NoiseType.CELLULAR).scale(1).bake()), - @Desc("Classic German Engineering") - @DontObfuscate - NOWHERE_SIMPLEX(rng -> CNG.signaturePerlin(rng, NoiseType.SIMPLEX).scale(1).bake()), + @Desc("Classic German Engineering") + @DontObfuscate + NOWHERE_SIMPLEX(rng -> CNG.signaturePerlin(rng, NoiseType.SIMPLEX).scale(1).bake()), - @Desc("Classic German Engineering") - @DontObfuscate - NOWHERE_GLOB(rng -> CNG.signaturePerlin(rng, NoiseType.GLOB).scale(1).bake()), + @Desc("Classic German Engineering") + @DontObfuscate + NOWHERE_GLOB(rng -> CNG.signaturePerlin(rng, NoiseType.GLOB).scale(1).bake()), - @Desc("Classic German Engineering") - @DontObfuscate - NOWHERE_VASCULAR(rng -> CNG.signaturePerlin(rng, NoiseType.VASCULAR).scale(1).bake()), + @Desc("Classic German Engineering") + @DontObfuscate + NOWHERE_VASCULAR(rng -> CNG.signaturePerlin(rng, NoiseType.VASCULAR).scale(1).bake()), - @Desc("Classic German Engineering") - @DontObfuscate - NOWHERE_CUBIC(rng -> CNG.signaturePerlin(rng, NoiseType.CUBIC).scale(1).bake()), + @Desc("Classic German Engineering") + @DontObfuscate + NOWHERE_CUBIC(rng -> CNG.signaturePerlin(rng, NoiseType.CUBIC).scale(1).bake()), - @Desc("Classic German Engineering") - @DontObfuscate - NOWHERE_SUPERFRACTAL(rng -> CNG.signaturePerlin(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX).scale(1).bake()), + @Desc("Classic German Engineering") + @DontObfuscate + NOWHERE_SUPERFRACTAL(rng -> CNG.signaturePerlin(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX).scale(1).bake()), - @Desc("Classic German Engineering") - @DontObfuscate - NOWHERE_FRACTAL(rng -> CNG.signaturePerlin(rng, NoiseType.FRACTAL_BILLOW_PERLIN).scale(1).bake()), + @Desc("Classic German Engineering") + @DontObfuscate + NOWHERE_FRACTAL(rng -> CNG.signaturePerlin(rng, NoiseType.FRACTAL_BILLOW_PERLIN).scale(1).bake()), - @Desc("Wispy Perlin-looking simplex noise. The 'iris' style noise.") - @DontObfuscate - IRIS_DOUBLE(rng -> CNG.signatureDouble(rng).scale(1)), + @Desc("Wispy Perlin-looking simplex noise. The 'iris' style noise.") + @DontObfuscate + IRIS_DOUBLE(rng -> CNG.signatureDouble(rng).scale(1)), - @Desc("Wispy Perlin-looking simplex noise. The 'iris' style noise.") - @DontObfuscate - IRIS_THICK(rng -> CNG.signatureThick(rng).scale(1)), + @Desc("Wispy Perlin-looking simplex noise. The 'iris' style noise.") + @DontObfuscate + IRIS_THICK(rng -> CNG.signatureThick(rng).scale(1)), - @Desc("Wispy Perlin-looking simplex noise. The 'iris' style noise.") - @DontObfuscate - IRIS_HALF(rng -> CNG.signatureHalf(rng).scale(1)), + @Desc("Wispy Perlin-looking simplex noise. The 'iris' style noise.") + @DontObfuscate + IRIS_HALF(rng -> CNG.signatureHalf(rng).scale(1)), - @Desc("Basic, Smooth & Fast Simplex noise.") - @DontObfuscate - SIMPLEX(rng -> new CNG(rng, 1D, 1).scale(1)), + @Desc("Basic, Smooth & Fast Simplex noise.") + @DontObfuscate + SIMPLEX(rng -> new CNG(rng, 1D, 1).scale(1)), - @Desc("Very Detailed smoke using simplex fractured with fractal billow simplex at high octaves.") - @DontObfuscate - 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("Very Detailed smoke using simplex fractured with fractal billow simplex at high octaves.") + @DontObfuscate + 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.") - @DontObfuscate - VASCULAR_THIN(rng -> new CNG(rng.nextParallelRNG(1), NoiseType.VASCULAR, 1D, 1).scale(1).pow(0.65)), + @Desc("Thinner Veins.") + @DontObfuscate + VASCULAR_THIN(rng -> new CNG(rng.nextParallelRNG(1), NoiseType.VASCULAR, 1D, 1).scale(1).pow(0.65)), - @Desc("Cells of simplex noise") - @DontObfuscate - 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("Cells of simplex noise") + @DontObfuscate + 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") - @DontObfuscate - 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("Veins of simplex noise") + @DontObfuscate + 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.") - @DontObfuscate - 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("Very Detailed fluid using simplex fractured with fractal billow simplex at high octaves.") + @DontObfuscate + 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") - @DontObfuscate - PERLIN(rng -> new CNG(rng, NoiseType.PERLIN, 1D, 1).scale(1.15)), + @Desc("Perlin. Like simplex but more natural") + @DontObfuscate + PERLIN(rng -> new CNG(rng, NoiseType.PERLIN, 1D, 1).scale(1.15)), - @Desc("Perlin. Like simplex but more natural") - @DontObfuscate - PERLIN_IRIS(rng -> CNG.signature(rng, NoiseType.PERLIN).scale(1.47)), + @Desc("Perlin. Like simplex but more natural") + @DontObfuscate + PERLIN_IRIS(rng -> CNG.signature(rng, NoiseType.PERLIN).scale(1.47)), - @Desc("Perlin. Like simplex but more natural") - @DontObfuscate - PERLIN_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.PERLIN).scale(1.47)), + @Desc("Perlin. Like simplex but more natural") + @DontObfuscate + PERLIN_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.PERLIN).scale(1.47)), - @Desc("Perlin. Like simplex but more natural") - @DontObfuscate - PERLIN_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.PERLIN).scale(1.47)), + @Desc("Perlin. Like simplex but more natural") + @DontObfuscate + PERLIN_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.PERLIN).scale(1.47)), - @Desc("Perlin. Like simplex but more natural") - @DontObfuscate - PERLIN_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.PERLIN).scale(1.47)), + @Desc("Perlin. Like simplex but more natural") + @DontObfuscate + PERLIN_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.PERLIN).scale(1.47)), - @Desc("Billow Fractal Perlin Noise.") - @DontObfuscate - FRACTAL_BILLOW_PERLIN(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_PERLIN, 1D, 1).scale(1.47)), + @Desc("Billow Fractal Perlin Noise.") + @DontObfuscate + FRACTAL_BILLOW_PERLIN(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_PERLIN, 1D, 1).scale(1.47)), - @Desc("Billow Fractal Perlin Noise. 2 Octaves") - @DontObfuscate - BIOCTAVE_FRACTAL_BILLOW_PERLIN(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_PERLIN, 1D, 2).scale(1.17)), + @Desc("Billow Fractal Perlin Noise. 2 Octaves") + @DontObfuscate + BIOCTAVE_FRACTAL_BILLOW_PERLIN(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_PERLIN, 1D, 2).scale(1.17)), - @Desc("Billow Fractal Simplex Noise. Single octave.") - @DontObfuscate - FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 1)), + @Desc("Billow Fractal Simplex Noise. Single octave.") + @DontObfuscate + FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 1)), - @Desc("FBM Fractal Simplex Noise. Single octave.") - @DontObfuscate - FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 1)), + @Desc("FBM Fractal Simplex Noise. Single octave.") + @DontObfuscate + FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 1)), - @Desc("Billow Fractal Iris Noise. Single octave.") - @DontObfuscate - FRACTAL_BILLOW_IRIS(rng -> CNG.signature(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX)), + @Desc("Billow Fractal Iris Noise. Single octave.") + @DontObfuscate + FRACTAL_BILLOW_IRIS(rng -> CNG.signature(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX)), - @Desc("FBM Fractal Iris Noise. Single octave.") - @DontObfuscate - FRACTAL_FBM_IRIS(rng -> CNG.signature(rng, NoiseType.FRACTAL_FBM_SIMPLEX)), + @Desc("FBM Fractal Iris Noise. Single octave.") + @DontObfuscate + FRACTAL_FBM_IRIS(rng -> CNG.signature(rng, NoiseType.FRACTAL_FBM_SIMPLEX)), - @Desc("Billow Fractal Iris Noise. Single octave.") - @DontObfuscate - FRACTAL_BILLOW_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX)), + @Desc("Billow Fractal Iris Noise. Single octave.") + @DontObfuscate + FRACTAL_BILLOW_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX)), - @Desc("FBM Fractal Iris Noise. Single octave.") - @DontObfuscate - FRACTAL_FBM_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.FRACTAL_FBM_SIMPLEX)), + @Desc("FBM Fractal Iris Noise. Single octave.") + @DontObfuscate + FRACTAL_FBM_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.FRACTAL_FBM_SIMPLEX)), - @Desc("Billow Fractal Iris Noise. Single octave.") - @DontObfuscate - FRACTAL_BILLOW_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX)), + @Desc("Billow Fractal Iris Noise. Single octave.") + @DontObfuscate + FRACTAL_BILLOW_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX)), - @Desc("FBM Fractal Iris Noise. Single octave.") - @DontObfuscate - FRACTAL_FBM_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.FRACTAL_FBM_SIMPLEX)), + @Desc("FBM Fractal Iris Noise. Single octave.") + @DontObfuscate + FRACTAL_FBM_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.FRACTAL_FBM_SIMPLEX)), - @Desc("Rigid Multi Fractal Simplex Noise. Single octave.") - @DontObfuscate - FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 1)), + @Desc("Rigid Multi Fractal Simplex Noise. Single octave.") + @DontObfuscate + FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 1)), - @Desc("Billow Fractal Simplex Noise. 2 octaves.") - @DontObfuscate - BIOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 2)), + @Desc("Billow Fractal Simplex Noise. 2 octaves.") + @DontObfuscate + BIOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 2)), - @Desc("FBM Fractal Simplex Noise. 2 octaves.") - @DontObfuscate - BIOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 2)), + @Desc("FBM Fractal Simplex Noise. 2 octaves.") + @DontObfuscate + BIOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 2)), - @Desc("Rigid Multi Fractal Simplex Noise. 2 octaves.") - @DontObfuscate - BIOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 2)), + @Desc("Rigid Multi Fractal Simplex Noise. 2 octaves.") + @DontObfuscate + BIOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 2)), - @Desc("Rigid Multi Fractal Simplex Noise. 3 octaves.") - @DontObfuscate - TRIOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 3)), + @Desc("Rigid Multi Fractal Simplex Noise. 3 octaves.") + @DontObfuscate + TRIOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 3)), - @Desc("Billow Fractal Simplex Noise. 3 octaves.") - @DontObfuscate - TRIOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 3)), + @Desc("Billow Fractal Simplex Noise. 3 octaves.") + @DontObfuscate + TRIOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 3)), - @Desc("FBM Fractal Simplex Noise. 3 octaves.") - @DontObfuscate - TRIOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 3)), + @Desc("FBM Fractal Simplex Noise. 3 octaves.") + @DontObfuscate + TRIOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 3)), - @Desc("Rigid Multi Fractal Simplex Noise. 4 octaves.") - @DontObfuscate - QUADOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 4)), + @Desc("Rigid Multi Fractal Simplex Noise. 4 octaves.") + @DontObfuscate + QUADOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 4)), - @Desc("Billow Fractal Simplex Noise. 4 octaves.") - @DontObfuscate - QUADOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 4)), + @Desc("Billow Fractal Simplex Noise. 4 octaves.") + @DontObfuscate + QUADOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 4)), - @Desc("FBM Fractal Simplex Noise. 4 octaves.") - @DontObfuscate - QUADOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 4)), + @Desc("FBM Fractal Simplex Noise. 4 octaves.") + @DontObfuscate + QUADOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 4)), - @Desc("Rigid Multi Fractal Simplex Noise. 5 octaves.") - @DontObfuscate - QUINTOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 5)), + @Desc("Rigid Multi Fractal Simplex Noise. 5 octaves.") + @DontObfuscate + QUINTOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 5)), - @Desc("Billow Fractal Simplex Noise. 5 octaves.") - @DontObfuscate - QUINTOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 5)), + @Desc("Billow Fractal Simplex Noise. 5 octaves.") + @DontObfuscate + QUINTOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 5)), - @Desc("FBM Fractal Simplex Noise. 5 octaves.") - @DontObfuscate - QUINTOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 5)), + @Desc("FBM Fractal Simplex Noise. 5 octaves.") + @DontObfuscate + QUINTOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 5)), - @Desc("Rigid Multi Fractal Simplex Noise. 6 octaves.") - @DontObfuscate - SEXOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 6)), + @Desc("Rigid Multi Fractal Simplex Noise. 6 octaves.") + @DontObfuscate + SEXOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 6)), - @Desc("Billow Fractal Simplex Noise. 6 octaves.") - @DontObfuscate - SEXOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 6)), + @Desc("Billow Fractal Simplex Noise. 6 octaves.") + @DontObfuscate + SEXOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 6)), - @Desc("FBM Fractal Simplex Noise. 6 octaves.") - @DontObfuscate - SEXOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 6)), + @Desc("FBM Fractal Simplex Noise. 6 octaves.") + @DontObfuscate + SEXOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 6)), - @Desc("Rigid Multi Fractal Simplex Noise. 7 octaves.") - @DontObfuscate - SEPTOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 7)), + @Desc("Rigid Multi Fractal Simplex Noise. 7 octaves.") + @DontObfuscate + SEPTOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 7)), - @Desc("Billow Fractal Simplex Noise. 7 octaves.") - @DontObfuscate - SEPTOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 7)), + @Desc("Billow Fractal Simplex Noise. 7 octaves.") + @DontObfuscate + SEPTOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 7)), - @Desc("FBM Fractal Simplex Noise. 7 octaves.") - @DontObfuscate - SEPTOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 7)), + @Desc("FBM Fractal Simplex Noise. 7 octaves.") + @DontObfuscate + SEPTOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 7)), - @Desc("Rigid Multi Fractal Simplex Noise. 8 octaves.") - @DontObfuscate - OCTOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 8)), + @Desc("Rigid Multi Fractal Simplex Noise. 8 octaves.") + @DontObfuscate + OCTOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 8)), - @Desc("Billow Fractal Simplex Noise. 8 octaves.") - @DontObfuscate - OCTOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 8)), + @Desc("Billow Fractal Simplex Noise. 8 octaves.") + @DontObfuscate + OCTOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 8)), - @Desc("FBM Fractal Simplex Noise. 8 octaves.") - @DontObfuscate - OCTOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 8)), + @Desc("FBM Fractal Simplex Noise. 8 octaves.") + @DontObfuscate + OCTOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 8)), - @Desc("Rigid Multi Fractal Simplex Noise. 9 octaves.") - @DontObfuscate - NONOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 9)), + @Desc("Rigid Multi Fractal Simplex Noise. 9 octaves.") + @DontObfuscate + NONOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 9)), - @Desc("Billow Fractal Simplex Noise. 9 octaves.") - @DontObfuscate - NONOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 9)), + @Desc("Billow Fractal Simplex Noise. 9 octaves.") + @DontObfuscate + NONOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 9)), - @Desc("FBM Fractal Simplex Noise. 9 octaves.") - @DontObfuscate - NONOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 9)), + @Desc("FBM Fractal Simplex Noise. 9 octaves.") + @DontObfuscate + NONOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 9)), - @Desc("Rigid Multi Fractal Simplex Noise. 10 octaves.") - @DontObfuscate - VIGOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 10)), + @Desc("Rigid Multi Fractal Simplex Noise. 10 octaves.") + @DontObfuscate + VIGOCTAVE_FRACTAL_RM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_RIGID_MULTI_SIMPLEX, 1D, 10)), - @Desc("Billow Fractal Simplex Noise. 10 octaves.") - @DontObfuscate - VIGOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 10)), + @Desc("Billow Fractal Simplex Noise. 10 octaves.") + @DontObfuscate + VIGOCTAVE_FRACTAL_BILLOW_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_BILLOW_SIMPLEX, 1D, 10)), - @Desc("FBM Fractal Simplex Noise. 10 octaves.") - @DontObfuscate - VIGOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 10)), + @Desc("FBM Fractal Simplex Noise. 10 octaves.") + @DontObfuscate + VIGOCTAVE_FRACTAL_FBM_SIMPLEX(rng -> new CNG(rng, NoiseType.FRACTAL_FBM_SIMPLEX, 1D, 10)), - @Desc("Basic, Smooth & Fast Simplex noise. Uses 2 octaves") - @DontObfuscate - BIOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 2).scale(1D / 2D)), + @Desc("Basic, Smooth & Fast Simplex noise. Uses 2 octaves") + @DontObfuscate + BIOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 2).scale(1D / 2D)), - @Desc("Basic, Smooth & Fast Simplex noise. Uses 3 octaves") - @DontObfuscate - TRIOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 3).scale(1D / 3D)), + @Desc("Basic, Smooth & Fast Simplex noise. Uses 3 octaves") + @DontObfuscate + TRIOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 3).scale(1D / 3D)), - @Desc("Basic, Smooth & Fast Simplex noise. Uses 4 octaves") - @DontObfuscate - QUADOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 4).scale(1D / 4D)), + @Desc("Basic, Smooth & Fast Simplex noise. Uses 4 octaves") + @DontObfuscate + QUADOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 4).scale(1D / 4D)), - @Desc("Basic, Smooth & Fast Simplex noise. Uses 5 octaves") - @DontObfuscate - QUINTOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 5).scale(1D / 5D)), + @Desc("Basic, Smooth & Fast Simplex noise. Uses 5 octaves") + @DontObfuscate + QUINTOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 5).scale(1D / 5D)), - @Desc("Basic, Smooth & Fast Simplex noise. Uses 6 octaves") - @DontObfuscate - SEXOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 6).scale(1D / 6D)), + @Desc("Basic, Smooth & Fast Simplex noise. Uses 6 octaves") + @DontObfuscate + SEXOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 6).scale(1D / 6D)), - @Desc("Basic, Smooth & Fast Simplex noise. Uses 7 octaves") - @DontObfuscate - SEPTOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 7).scale(1D / 12D)), + @Desc("Basic, Smooth & Fast Simplex noise. Uses 7 octaves") + @DontObfuscate + SEPTOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 7).scale(1D / 12D)), - @Desc("Basic, Smooth & Fast Simplex noise. Uses 8 octaves") - @DontObfuscate - OCTOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 8).scale(1D / 25D)), + @Desc("Basic, Smooth & Fast Simplex noise. Uses 8 octaves") + @DontObfuscate + OCTOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 8).scale(1D / 25D)), - @Desc("Basic, Smooth & Fast Simplex noise. Uses 9 octaves") - @DontObfuscate - NONOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 9).scale(1D / 50D)), + @Desc("Basic, Smooth & Fast Simplex noise. Uses 9 octaves") + @DontObfuscate + NONOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 9).scale(1D / 50D)), - @Desc("Basic, Smooth & Fast Simplex noise. Uses 10 octaves") - @DontObfuscate - VIGOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 10).scale(1D / 100D)), + @Desc("Basic, Smooth & Fast Simplex noise. Uses 10 octaves") + @DontObfuscate + VIGOCTAVE_SIMPLEX(rng -> new CNG(rng, 1D, 10).scale(1D / 100D)), - @Desc("Glob noise is like cellular, but with globs...") - @DontObfuscate - GLOB(rng -> new CNG(rng, NoiseType.GLOB, 1D, 1)), + @Desc("Glob noise is like cellular, but with globs...") + @DontObfuscate + GLOB(rng -> new CNG(rng, NoiseType.GLOB, 1D, 1)), - @Desc("Glob noise is like cellular, but with globs...") - @DontObfuscate - GLOB_IRIS(rng -> CNG.signature(rng, NoiseType.GLOB)), + @Desc("Glob noise is like cellular, but with globs...") + @DontObfuscate + GLOB_IRIS(rng -> CNG.signature(rng, NoiseType.GLOB)), - @Desc("Glob noise is like cellular, but with globs...") - @DontObfuscate - GLOB_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.GLOB)), + @Desc("Glob noise is like cellular, but with globs...") + @DontObfuscate + GLOB_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.GLOB)), - @Desc("Glob noise is like cellular, but with globs...") - @DontObfuscate - GLOB_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.GLOB)), + @Desc("Glob noise is like cellular, but with globs...") + @DontObfuscate + GLOB_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.GLOB)), - @Desc("Glob noise is like cellular, but with globs...") - @DontObfuscate - GLOB_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.GLOB)), + @Desc("Glob noise is like cellular, but with globs...") + @DontObfuscate + GLOB_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.GLOB)), - @Desc("Cubic Noise") - @DontObfuscate - CUBIC(rng -> new CNG(rng, NoiseType.CUBIC, 1D, 1).scale(256)), + @Desc("Cubic Noise") + @DontObfuscate + CUBIC(rng -> new CNG(rng, NoiseType.CUBIC, 1D, 1).scale(256)), - @Desc("Fractal Cubic Noise") - @DontObfuscate - FRACTAL_CUBIC(rng -> new CNG(rng, NoiseType.FRACTAL_CUBIC, 1D, 1).scale(2)), + @Desc("Fractal Cubic Noise") + @DontObfuscate + FRACTAL_CUBIC(rng -> new CNG(rng, NoiseType.FRACTAL_CUBIC, 1D, 1).scale(2)), - @Desc("Fractal Cubic Noise With Iris Swirls") - @DontObfuscate - FRACTAL_CUBIC_IRIS(rng -> CNG.signature(rng, NoiseType.FRACTAL_CUBIC).scale(2)), + @Desc("Fractal Cubic Noise With Iris Swirls") + @DontObfuscate + FRACTAL_CUBIC_IRIS(rng -> CNG.signature(rng, NoiseType.FRACTAL_CUBIC).scale(2)), - @Desc("Fractal Cubic Noise With Iris Swirls") - @DontObfuscate - FRACTAL_CUBIC_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.FRACTAL_CUBIC).scale(2)), + @Desc("Fractal Cubic Noise With Iris Swirls") + @DontObfuscate + FRACTAL_CUBIC_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.FRACTAL_CUBIC).scale(2)), - @Desc("Fractal Cubic Noise With Iris Swirls") - @DontObfuscate - FRACTAL_CUBIC_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.FRACTAL_CUBIC).scale(2)), + @Desc("Fractal Cubic Noise With Iris Swirls") + @DontObfuscate + FRACTAL_CUBIC_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.FRACTAL_CUBIC).scale(2)), - @Desc("Fractal Cubic Noise With Iris Swirls") - @DontObfuscate - FRACTAL_CUBIC_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.FRACTAL_CUBIC).scale(2)), + @Desc("Fractal Cubic Noise With Iris Swirls") + @DontObfuscate + FRACTAL_CUBIC_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.FRACTAL_CUBIC).scale(2)), - @Desc("Fractal Cubic Noise, 2 Octaves") - @DontObfuscate - BIOCTAVE_FRACTAL_CUBIC(rng -> new CNG(rng, NoiseType.FRACTAL_CUBIC, 1D, 2).scale(2)), + @Desc("Fractal Cubic Noise, 2 Octaves") + @DontObfuscate + BIOCTAVE_FRACTAL_CUBIC(rng -> new CNG(rng, NoiseType.FRACTAL_CUBIC, 1D, 2).scale(2)), - @Desc("Fractal Cubic Noise, 3 Octaves") - @DontObfuscate - TRIOCTAVE_FRACTAL_CUBIC(rng -> new CNG(rng, NoiseType.FRACTAL_CUBIC, 1D, 3).scale(1.5)), + @Desc("Fractal Cubic Noise, 3 Octaves") + @DontObfuscate + TRIOCTAVE_FRACTAL_CUBIC(rng -> new CNG(rng, NoiseType.FRACTAL_CUBIC, 1D, 3).scale(1.5)), - @Desc("Fractal Cubic Noise, 4 Octaves") - @DontObfuscate - QUADOCTAVE_FRACTAL_CUBIC(rng -> new CNG(rng, NoiseType.FRACTAL_CUBIC, 1D, 4).scale(1)), + @Desc("Fractal Cubic Noise, 4 Octaves") + @DontObfuscate + QUADOCTAVE_FRACTAL_CUBIC(rng -> new CNG(rng, NoiseType.FRACTAL_CUBIC, 1D, 4).scale(1)), - @Desc("Cubic Noise") - @DontObfuscate - CUBIC_IRIS(rng -> CNG.signature(rng, NoiseType.CUBIC).scale(256)), + @Desc("Cubic Noise") + @DontObfuscate + CUBIC_IRIS(rng -> CNG.signature(rng, NoiseType.CUBIC).scale(256)), - @Desc("Cubic Noise") - @DontObfuscate - CUBIC_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.CUBIC).scale(256)), + @Desc("Cubic Noise") + @DontObfuscate + CUBIC_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.CUBIC).scale(256)), - @Desc("Cubic Noise") - @DontObfuscate - CUBIC_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.CUBIC).scale(256)), + @Desc("Cubic Noise") + @DontObfuscate + CUBIC_IRIS_DOUBLE(rng -> CNG.signatureDouble(rng, NoiseType.CUBIC).scale(256)), - @Desc("Cubic Noise") - @DontObfuscate - CUBIC_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.CUBIC).scale(256)), + @Desc("Cubic Noise") + @DontObfuscate + CUBIC_IRIS_THICK(rng -> CNG.signatureThick(rng, NoiseType.CUBIC).scale(256)), - @Desc("Cellular noise creates the same noise level for cells, changes noise level on cell borders.") - @DontObfuscate - 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.") + @DontObfuscate + 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. Cells are distorted using Iris styled wispy noise.") - @DontObfuscate - 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.") + @DontObfuscate + 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.") - @DontObfuscate - 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.") + @DontObfuscate + 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.") - @DontObfuscate - 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.") + @DontObfuscate + 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.") - @DontObfuscate - CELLULAR_IRIS_HALF(rng -> CNG.signatureHalf(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.") + @DontObfuscate + 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") - @DontObfuscate - 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") + @DontObfuscate + 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.") - @DontObfuscate - 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.") + @DontObfuscate + 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.") - @DontObfuscate - 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.") + @DontObfuscate + 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.") - @DontObfuscate - 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.") + @DontObfuscate + 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.") - @DontObfuscate - CELLULAR_HEIGHT_IRIS_HALF(rng -> CNG.signatureHalf(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.") + @DontObfuscate + CELLULAR_HEIGHT_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.CELLULAR_HEIGHT)), - @Desc("Vascular noise gets higher as the position nears a cell border.") - @DontObfuscate - VASCULAR(rng -> new CNG(rng, NoiseType.VASCULAR, 1D, 1)), + @Desc("Vascular noise gets higher as the position nears a cell border.") + @DontObfuscate + VASCULAR(rng -> new CNG(rng, NoiseType.VASCULAR, 1D, 1)), - @Desc("It always returns 0.5") - @DontObfuscate - FLAT(rng -> new CNG(rng, NoiseType.FLAT, 1D, 1)), + @Desc("It always returns 0.5") + @DontObfuscate + FLAT(rng -> new CNG(rng, NoiseType.FLAT, 1D, 1)), - @Desc("Vascular noise gets higher as the position nears a cell border. Cells are distorted using Iris styled wispy noise.") - @DontObfuscate - 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.") + @DontObfuscate + 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.") - @DontObfuscate - 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.") + @DontObfuscate + 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.") - @DontObfuscate - 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.") + @DontObfuscate + 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.") - @DontObfuscate - VASCULAR_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.VASCULAR)), + @Desc("Vascular noise gets higher as the position nears a cell border. Cells are distorted using Iris styled wispy noise.") + @DontObfuscate + VASCULAR_IRIS_HALF(rng -> CNG.signatureHalf(rng, NoiseType.VASCULAR)), - ; + ; - private CNGFactory f; + private final CNGFactory f; - private NoiseStyle(CNGFactory f) - { - this.f = f; - } - - public ProceduralStream stream(RNG seed) - { - return create(seed).stream(); - } + NoiseStyle(CNGFactory f) { + this.f = f; + } - public ProceduralStream stream(long seed) - { - return create(new RNG(seed)).stream(); - } + public ProceduralStream stream(RNG seed) { + return create(seed).stream(); + } - public CNG create(RNG seed) - { - return f.create(seed).bake(); - } + public ProceduralStream stream(long seed) { + return create(new RNG(seed)).stream(); + } - public IrisGeneratorStyle style() - { - return new IrisGeneratorStyle(this); - } + public CNG create(RNG seed) { + return f.create(seed).bake(); + } + + public IrisGeneratorStyle style() { + return new IrisGeneratorStyle(this); + } } diff --git a/src/main/java/com/volmit/iris/object/ObjectPlaceMode.java b/src/main/java/com/volmit/iris/object/ObjectPlaceMode.java index 44fbfb589..fa5d513b8 100644 --- a/src/main/java/com/volmit/iris/object/ObjectPlaceMode.java +++ b/src/main/java/com/volmit/iris/object/ObjectPlaceMode.java @@ -4,41 +4,40 @@ import com.volmit.iris.util.Desc; import com.volmit.iris.util.DontObfuscate; @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.") - @DontObfuscate - 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.") + @DontObfuscate + CENTER_HEIGHT, - @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.") - @DontObfuscate - MAX_HEIGHT, + @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.") + @DontObfuscate + MAX_HEIGHT, - @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.\"") - @DontObfuscate - FAST_MAX_HEIGHT, + @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.\"") + @DontObfuscate + FAST_MAX_HEIGHT, - @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") - @DontObfuscate - MIN_HEIGHT, + @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") + @DontObfuscate + MIN_HEIGHT, - @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") - @DontObfuscate - FAST_MIN_HEIGHT, + @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") + @DontObfuscate + FAST_MIN_HEIGHT, - @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.") - @DontObfuscate - STILT, + @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.") + @DontObfuscate + STILT, - @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)") - @DontObfuscate - FAST_STILT, + @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)") + @DontObfuscate + FAST_STILT, - @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.") - @DontObfuscate - PAINT, + @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.") + @DontObfuscate + PAINT, - @Desc("Applies multiple terrain features into the parallax layer before this object places to distort the height, essentially vacuuming the terrain's heightmap closer to the bottom of this object. Uses MAX_HEIGHT to place") - @DontObfuscate - VACUUM + @Desc("Applies multiple terrain features into the parallax layer before this object places to distort the height, essentially vacuuming the terrain's heightmap closer to the bottom of this object. Uses MAX_HEIGHT to place") + @DontObfuscate + VACUUM } diff --git a/src/main/java/com/volmit/iris/object/tile/TileBanner.java b/src/main/java/com/volmit/iris/object/tile/TileBanner.java index 20e833532..206b126cf 100644 --- a/src/main/java/com/volmit/iris/object/tile/TileBanner.java +++ b/src/main/java/com/volmit/iris/object/tile/TileBanner.java @@ -1,8 +1,8 @@ package com.volmit.iris.object.tile; -import lombok.Data; import com.volmit.iris.scaffold.data.nbt.tag.CompoundTag; import com.volmit.iris.scaffold.data.nbt.tag.ListTag; +import lombok.Data; import org.bukkit.DyeColor; import org.bukkit.Material; import org.bukkit.block.Banner; @@ -92,22 +92,38 @@ public class TileBanner implements TileData { public boolean isBanner(Material material) { switch (material) { - case RED_BANNER: case RED_WALL_BANNER: - case ORANGE_BANNER: case ORANGE_WALL_BANNER: - case YELLOW_BANNER: case YELLOW_WALL_BANNER: - case LIME_BANNER: case LIME_WALL_BANNER: - case GREEN_BANNER: case GREEN_WALL_BANNER: - case CYAN_BANNER: case CYAN_WALL_BANNER: - case LIGHT_BLUE_BANNER: case LIGHT_BLUE_WALL_BANNER: - case BLUE_BANNER: case BLUE_WALL_BANNER: - case PURPLE_BANNER: case PURPLE_WALL_BANNER: - case MAGENTA_BANNER: case MAGENTA_WALL_BANNER: - case PINK_BANNER: case PINK_WALL_BANNER: - case WHITE_BANNER: case WHITE_WALL_BANNER: - case LIGHT_GRAY_BANNER: case LIGHT_GRAY_WALL_BANNER: - case GRAY_BANNER: case GRAY_WALL_BANNER: - case BLACK_BANNER: case BLACK_WALL_BANNER: - case BROWN_BANNER: case BROWN_WALL_BANNER: + case RED_BANNER: + case RED_WALL_BANNER: + case ORANGE_BANNER: + case ORANGE_WALL_BANNER: + case YELLOW_BANNER: + case YELLOW_WALL_BANNER: + case LIME_BANNER: + case LIME_WALL_BANNER: + case GREEN_BANNER: + case GREEN_WALL_BANNER: + case CYAN_BANNER: + case CYAN_WALL_BANNER: + case LIGHT_BLUE_BANNER: + case LIGHT_BLUE_WALL_BANNER: + case BLUE_BANNER: + case BLUE_WALL_BANNER: + case PURPLE_BANNER: + case PURPLE_WALL_BANNER: + case MAGENTA_BANNER: + case MAGENTA_WALL_BANNER: + case PINK_BANNER: + case PINK_WALL_BANNER: + case WHITE_BANNER: + case WHITE_WALL_BANNER: + case LIGHT_GRAY_BANNER: + case LIGHT_GRAY_WALL_BANNER: + case GRAY_BANNER: + case GRAY_WALL_BANNER: + case BLACK_BANNER: + case BLACK_WALL_BANNER: + case BROWN_BANNER: + case BROWN_WALL_BANNER: return true; default: return false; diff --git a/src/main/java/com/volmit/iris/object/tile/TileData.java b/src/main/java/com/volmit/iris/object/tile/TileData.java index 3ac98f56c..8b73aac3f 100644 --- a/src/main/java/com/volmit/iris/object/tile/TileData.java +++ b/src/main/java/com/volmit/iris/object/tile/TileData.java @@ -1,7 +1,7 @@ package com.volmit.iris.object.tile; -import com.volmit.iris.util.KList; import com.volmit.iris.scaffold.data.nbt.tag.CompoundTag; +import com.volmit.iris.util.KList; import org.bukkit.block.Block; import org.bukkit.block.BlockState; import org.bukkit.block.TileState; @@ -13,7 +13,7 @@ import java.io.IOException; public interface TileData extends Cloneable { - public static final KList> registry = setup(); + KList> registry = setup(); static KList> setup() { KList> registry = new KList<>(); @@ -25,29 +25,24 @@ public interface TileData extends Cloneable { return registry; } - public static TileData read(DataInputStream s) throws Throwable { + static TileData read(DataInputStream s) throws Throwable { int id = s.readShort(); TileData d = registry.get(id).getClass().getConstructor().newInstance(); d.fromBinary(s); return d; } - public static void setTileState(Block block, TileData data) - { - if(data.isApplicable(block.getBlockData())) - { + static void setTileState(Block block, TileData data) { + if (data.isApplicable(block.getBlockData())) { data.toBukkitTry(block.getState()); } } - public static TileData getTileState(Block block) - { - for(TileData i : registry) - { + static TileData getTileState(Block block) { + for (TileData i : registry) { BlockData data = block.getBlockData(); - if(i.isApplicable(data)) - { + if (i.isApplicable(data)) { try { TileData s = i.getClass().getConstructor().newInstance(); s.fromBukkitTry(block.getState()); @@ -61,49 +56,41 @@ public interface TileData extends Cloneable { return null; } - public String getTileId(); + String getTileId(); - public boolean isApplicable(BlockData data); + boolean isApplicable(BlockData data); - public void toBukkit(T t); + void toBukkit(T t); - public void fromBukkit(T t); + void fromBukkit(T t); - public default boolean toBukkitTry(BlockState t) - { + default boolean toBukkitTry(BlockState t) { try { toBukkit((T) t); return true; - } - - catch(Throwable e) - { + } catch (Throwable e) { } return false; } - public default boolean fromBukkitTry(BlockState t) - { + default boolean fromBukkitTry(BlockState t) { try { fromBukkit((T) t); return true; - } - - catch(Throwable e) - { + } catch (Throwable e) { } return false; } - public TileData clone(); + TileData clone(); - public void toBinary(DataOutputStream out) throws IOException; + void toBinary(DataOutputStream out) throws IOException; - public void toNBT(CompoundTag tag); + void toNBT(CompoundTag tag); - public void fromBinary(DataInputStream in) throws IOException; + void fromBinary(DataInputStream in) throws IOException; } diff --git a/src/main/java/com/volmit/iris/object/tile/TileSign.java b/src/main/java/com/volmit/iris/object/tile/TileSign.java index 3c873ede4..52b19cc2b 100644 --- a/src/main/java/com/volmit/iris/object/tile/TileSign.java +++ b/src/main/java/com/volmit/iris/object/tile/TileSign.java @@ -1,7 +1,7 @@ package com.volmit.iris.object.tile; -import lombok.Data; import com.volmit.iris.scaffold.data.nbt.tag.CompoundTag; +import lombok.Data; import org.bukkit.DyeColor; import org.bukkit.block.Sign; import org.bukkit.block.data.BlockData; diff --git a/src/main/java/com/volmit/iris/object/tile/TileSpawner.java b/src/main/java/com/volmit/iris/object/tile/TileSpawner.java index f95c1a50a..0849b18d2 100644 --- a/src/main/java/com/volmit/iris/object/tile/TileSpawner.java +++ b/src/main/java/com/volmit/iris/object/tile/TileSpawner.java @@ -1,8 +1,8 @@ package com.volmit.iris.object.tile; -import lombok.Data; import com.volmit.iris.scaffold.data.nbt.tag.CompoundTag; import com.volmit.iris.scaffold.data.nbt.tag.ListTag; +import lombok.Data; import org.bukkit.Material; import org.bukkit.block.CreatureSpawner; import org.bukkit.block.data.BlockData; diff --git a/src/main/java/com/volmit/iris/pregen/DirectWorldWriter.java b/src/main/java/com/volmit/iris/pregen/DirectWorldWriter.java index 48472c58a..42e08f839 100644 --- a/src/main/java/com/volmit/iris/pregen/DirectWorldWriter.java +++ b/src/main/java/com/volmit/iris/pregen/DirectWorldWriter.java @@ -2,17 +2,17 @@ package com.volmit.iris.pregen; import com.volmit.iris.nms.INMS; import com.volmit.iris.scaffold.cache.Cache; -import com.volmit.iris.scaffold.parallel.BurstExecutor; -import com.volmit.iris.scaffold.parallel.MultiBurst; -import com.volmit.iris.util.B; -import com.volmit.iris.util.KList; -import com.volmit.iris.util.KMap; import com.volmit.iris.scaffold.data.mca.Chunk; import com.volmit.iris.scaffold.data.mca.MCAFile; import com.volmit.iris.scaffold.data.mca.MCAUtil; import com.volmit.iris.scaffold.data.mca.Section; import com.volmit.iris.scaffold.data.nbt.tag.CompoundTag; import com.volmit.iris.scaffold.data.nbt.tag.StringTag; +import com.volmit.iris.scaffold.parallel.BurstExecutor; +import com.volmit.iris.scaffold.parallel.MultiBurst; +import com.volmit.iris.util.B; +import com.volmit.iris.util.KList; +import com.volmit.iris.util.KMap; import org.bukkit.NamespacedKey; import org.bukkit.block.Biome; import org.bukkit.block.data.BlockData; @@ -27,27 +27,23 @@ public class DirectWorldWriter { private static final Map blockDataCache = new KMap<>(); private static final Map biomeIds = computeBiomeIDs(); - public DirectWorldWriter(File worldFolder) - { + public DirectWorldWriter(File worldFolder) { this.worldFolder = worldFolder; writeBuffer = new KMap<>(); new File(worldFolder, "iris/mca-region").mkdirs(); } - public void flush() - { + public void flush() { BurstExecutor ex2 = MultiBurst.burst.burst(writeBuffer.size()); - for(Long i : new KList<>(writeBuffer.keySet())) - { + for (Long i : new KList<>(writeBuffer.keySet())) { ex2.queue(() -> { int x = Cache.keyX(i); int z = Cache.keyZ(i); try { File f = getMCAFile(x, z); - if(!f.exists()) - { + if (!f.exists()) { f.getParentFile().mkdirs(); f.createNewFile(); } @@ -63,32 +59,27 @@ public class DirectWorldWriter { ex2.complete(); } - public void optimizeChunk(int x, int z) - { + public void optimizeChunk(int x, int z) { getChunk(x, z).cleanupPalettesAndBlockStates(); } - public File getMCAFile(int x, int z) - { + public File getMCAFile(int x, int z) { return new File(worldFolder, "iris/mca-region/r." + x + "." + z + ".mca"); } public static BlockData getBlockData(CompoundTag tag) { - if (tag == null) - { + if (tag == null) { return B.getAir(); } String p = tag.getString("Name"); - if(tag.containsKey("Properties")) - { + if (tag.containsKey("Properties")) { CompoundTag props = tag.getCompoundTag("Properties"); p += "["; KList m = new KList<>(); - for(String i : props.keySet()) - { + for (String i : props.keySet()) { m.add(i + "=" + props.getString(i)); } @@ -97,20 +88,17 @@ public class DirectWorldWriter { BlockData b = B.getOrNull(p); - if(b == null) - { + if (b == null) { return B.getAir(); } return b; } - public static CompoundTag getCompound(BlockData blockData) - { + public static CompoundTag getCompound(BlockData blockData) { String data = blockData.getAsString(true); - if(blockDataCache.containsKey(data)) - { + if (blockDataCache.containsKey(data)) { return blockDataCache.get(data).clone(); } @@ -119,23 +107,17 @@ public class DirectWorldWriter { s.putString("Name", key.getNamespace() + ":" + key.getKey()); - if(data.contains("[")) - { + if (data.contains("[")) { String raw = data.split("\\Q[\\E")[1].replaceAll("\\Q]\\E", ""); CompoundTag props = new CompoundTag(); - if(raw.contains(",")) - { - for(String i : raw.split("\\Q,\\E")) - { + if (raw.contains(",")) { + for (String i : raw.split("\\Q,\\E")) { String[] m = i.split("\\Q=\\E"); String k = m[0]; String v = m[1]; props.put(k, new StringTag(v)); } - } - - else - { + } else { String[] m = raw.split("\\Q=\\E"); String k = m[0]; String v = m[1]; @@ -148,44 +130,34 @@ public class DirectWorldWriter { return s; } - public BlockData getBlockData(int x, int y, int z) - { - try - { + public BlockData getBlockData(int x, int y, int z) { + try { CompoundTag tag = getChunkSection(x >> 4, y >> 4, z >> 4).getBlockStateAt(x & 15, y & 15, z & 15); - if(tag == null) - { + if (tag == null) { return B.get("AIR"); } return getBlockData(tag); - } - - catch(Throwable e) - { + } catch (Throwable e) { } return B.get("AIR"); } - public void setBlockData(int x, int y, int z, BlockData data) - { + public void setBlockData(int x, int y, int z, BlockData data) { getChunkSection(x >> 4, y >> 4, z >> 4).setBlockStateAt(x & 15, y & 15, z & 15, getCompound(data), false); } - public void setBiome(int x, int y, int z, Biome biome) - { - getChunk(x>>4, z>>4).setBiomeAt(x&15, y, z &15, biomeIds.get(biome)); + public void setBiome(int x, int y, int z, Biome biome) { + getChunk(x >> 4, z >> 4).setBiomeAt(x & 15, y, z & 15, biomeIds.get(biome)); } - public Section getChunkSection(int x, int y, int z) - { + public Section getChunkSection(int x, int y, int z) { Chunk c = getChunk(x, z); Section s = c.getSection(y); - if(s == null) - { + if (s == null) { s = Section.newSection(); c.setSection(y, s); } @@ -197,33 +169,29 @@ public class DirectWorldWriter { } - public Chunk getChunk(int x, int z) - { + public Chunk getChunk(int x, int z) { MCAFile mca = getMCA(x >> 5, z >> 5); Chunk c = mca.getChunk(x & 31, z & 31); - if(c == null) - { + if (c == null) { c = Chunk.newChunk(); - mca.setChunk(x&31, z&31, c); + mca.setChunk(x & 31, z & 31, c); } return c; } - public MCAFile getMCA(int x, int z) - { + public MCAFile getMCA(int x, int z) { long key = Cache.key(x, z); MCAFile mca = writeBuffer.get(key); - if(mca != null) - { + if (mca != null) { return mca; } File f = getMCAFile(x, z); try { - mca = f.exists() ? MCAUtil.read(f) : new MCAFile(x, z); + mca = f.exists() ? MCAUtil.read(f) : new MCAFile(x, z); } catch (IOException e) { e.printStackTrace(); mca = new MCAFile(x, z); @@ -240,8 +208,7 @@ public class DirectWorldWriter { private static Map computeBiomeIDs() { Map biomeIds = new KMap<>(); - for(Biome biome : Biome.values()) - { + for (Biome biome : Biome.values()) { if (!biome.name().equals("CUSTOM")) { biomeIds.put(biome, INMS.get().getBiomeId(biome)); } diff --git a/src/main/java/com/volmit/iris/pregen/Pregenerator.java b/src/main/java/com/volmit/iris/pregen/Pregenerator.java index c5725e06c..00fb9c1c6 100644 --- a/src/main/java/com/volmit/iris/pregen/Pregenerator.java +++ b/src/main/java/com/volmit/iris/pregen/Pregenerator.java @@ -22,7 +22,6 @@ import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.image.BufferedImage; import java.awt.image.ImageObserver; -import java.awt.HeadlessException; import java.io.File; import java.io.IOException; import java.nio.file.Files; @@ -37,677 +36,588 @@ import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.locks.ReentrantLock; @Data -public class Pregenerator implements Listener -{ - private static Pregenerator instance; - private static final Color COLOR_ERROR = Color.decode("#E34113"); - private static final Color COLOR_MCA_PREPARE = Color.decode("#3CAAB5"); - private static final Color COLOR_MCA_RELOAD = Color.decode("#41FF61"); - private static final Color COLOR_MCA_GENERATE = Color.decode("#33FF8F"); - private static final Color COLOR_MCA_GENERATE_SLOW = Color.decode("#13BAE3"); - private static final Color COLOR_MCA_GENERATE_SLOW_ASYNC = Color.decode("#13BAE3"); - private static final Color COLOR_MCA_GENERATED = Color.decode("#33FF8F"); - private static final Color COLOR_MCA_GENERATED_MCA = Color.decode("#13E3C9"); - private static final Color COLOR_MCA_SEALED = Color.decode("#33FF8F"); - private static final Color COLOR_MCA_DEFERRED = Color.decode("#3CB57A"); - private final World world; - private int lowestBedrock; - private final DirectWorldWriter directWriter; - private final AtomicBoolean active; - private final AtomicBoolean running; - private final KList errors; - private final KList onComplete; - private final ChunkPosition max; - private final ChunkPosition min; - private final MCAPregenGui gui; - private final KList mcaDefer; - private final AtomicInteger generated; - private final AtomicInteger generatedLast; - private final RollingSequence perSecond; - private final AtomicInteger totalChunks; - private final AtomicLong memory; - private final AtomicReference memoryMetric; - private final AtomicReference method; - private final AtomicInteger vmcax; - private final AtomicInteger vmcaz; - private final AtomicInteger vcax; - private final AtomicInteger vcaz; - private final long elapsed; - private final ChronoLatch latch; - private IrisAccess access; - private final KList regionReload; - - public Pregenerator(World world, int blockSize, Runnable onComplete) - { - this(world, blockSize); - this.onComplete.add(onComplete); - } - - public Pregenerator(World world, int blockSize) throws HeadlessException - { - this(world, blockSize, true); - } - - public Pregenerator(World world, int blockSize, boolean dogui) throws HeadlessException - { - instance(); - regionReload = new KList<>(); - latch = new ChronoLatch(5000); - memoryMetric = new AtomicReference<>("..."); - method = new AtomicReference<>("STARTUP"); - memory = new AtomicLong(0); - this.world = world; - errors = new KList<>(); - vmcax = new AtomicInteger(); - vmcaz = new AtomicInteger(); - vcax = new AtomicInteger(); - vcaz = new AtomicInteger(); - perSecond = new RollingSequence(20); - generatedLast = new AtomicInteger(0); - totalChunks = new AtomicInteger(0); - generated = new AtomicInteger(0); - mcaDefer = new KList<>(); - access = IrisWorlds.access(world); - this.directWriter = new DirectWorldWriter(world.getWorldFolder()); - this.running = new AtomicBoolean(true); - this.active = new AtomicBoolean(true); - MultiBurst burst = new MultiBurst(Runtime.getRuntime().availableProcessors()); - int mcaSize = (((blockSize >> 4) + 2) >> 5) + 1; - onComplete = new KList<>(); - max = new ChunkPosition(0,0); - min = new ChunkPosition(0,0); - KList draw = new KList<>(); - new Spiraler(mcaSize, mcaSize, (xx,zz) -> { - min.setX(Math.min(xx << 5, min.getX())); - min.setZ(Math.min(zz << 5, min.getZ())); - max.setX(Math.max((xx << 5) + 31, max.getX())); - max.setZ(Math.max((zz << 5) + 31, max.getZ())); - totalChunks.getAndAdd(1024); - draw.add(() -> drawMCA(xx, zz, COLOR_MCA_PREPARE)); - }).drain(); - if(access != null) - { - lowestBedrock = access.getCompound().getLowestBedrock(); - } - gui = dogui ?(IrisSettings.get().getGui().isLocalPregenGui() && IrisSettings.get().getGui().isUseServerLaunchedGuis() ? MCAPregenGui.createAndShowGUI(this) : null) : null; - flushWorld(); - KList order = computeChunkOrder(); - Consumer3> mcaIteration = - (ox, oz, r) -> order.forEach((i) - -> r.accept(i.getX() + ox, i.getZ() + oz)); - draw.forEach(Runnable::run); - Spiraler spiraler = new Spiraler(mcaSize, mcaSize, (xx,zz) -> { - vmcax.set(xx); - vmcaz.set(zz); - flushWorld(); - drawMCA(xx, zz, COLOR_MCA_PREPARE); - if(access != null && generateMCARegion(xx, zz, burst, access, mcaIteration)) - { - flushWorld(); - } - - else - { - drawMCA(xx, zz, COLOR_MCA_DEFERRED); - } - }); - - elapsed = M.ms(); - - new Thread(() -> { - flushWorld(); - J.sleep(2000); - flushWorld(); - - while(running.get() && spiraler.hasNext()) - { - if(active.get()) - { - spiraler.next(); - } - } - - mcaDefer.removeDuplicates(); - - while(running.get() && mcaDefer.isNotEmpty()) - { - ChunkPosition p = mcaDefer.popLast(); - vmcax.set(p.getX()); - vmcaz.set(p.getZ()); - generateDeferedMCARegion(p.getX(), p.getZ(), burst, mcaIteration); - flushWorld(); - } - - burst.shutdownNow(); - directWriter.flush(); - flushWorld(); - onComplete.forEach(Runnable::run); - running.set(false); - active.set(false); - if(gui != null) - { - gui.close(); - } - }).start(); - new Thread(() -> { - PrecisionStopwatch p = PrecisionStopwatch.start(); - - while(running.get() && active.get()) { - int m = generated.get(); - int w = generatedLast.get(); - int up = m - w; - double dur = p.getMilliseconds(); - perSecond.put((int) (up / (dur / 1000D))); - p.reset(); - p.begin(); - updateProgress(); - generatedLast.set(m); - J.sleep(100); - long lmem = memory.get(); - memory.set(Runtime.getRuntime().freeMemory()); - - if(memory.get() > lmem) - { - long free = memory.get(); - long max = Runtime.getRuntime().maxMemory(); - long total = Runtime.getRuntime().totalMemory(); - long use = total - free; - memoryMetric.set(Form.memSize(use, 2) + " (" + Form.pc((double)use / (double)max, 0) + ")"); - } - } - }).start(); - } - - private boolean generateMCARegion(int x, int z, MultiBurst burst, IrisAccess access, Consumer3> mcaIteration) { - if(!Iris.instance.isMCA()) - { - return false; - } - - File mca = new File(world.getWorldFolder(), "region/r." + x + "." + z + ".mca"); - File mcg = directWriter.getMCAFile(x, z); - Path fileToMovePath = Paths.get(mcg.toURI()); - Path targetPath = Paths.get(mca.toURI()); - BurstExecutor e = burst.burst(1024); - int mcaox = x << 5; - int mcaoz = z << 5; - if(isMCAWritable(x,z) && !mca.exists()) - { - method.set("Direct (Fast)"); - mcaIteration.accept(mcaox, mcaoz, (ii, jj) -> e.queue(() -> { - draw(ii, jj, COLOR_MCA_GENERATE); - access.directWriteChunk(world, ii, jj, directWriter); - draw(ii, jj, COLOR_MCA_GENERATED_MCA); - generated.getAndIncrement(); - vcax.set(ii); - vcaz.set(jj); - })); - e.complete(); - directWriter.flush(); - if(!install(mcg, mca)) - { - drawMCA(x, z, COLOR_MCA_DEFERRED); - generated.set(generated.get() - 1024); - } - totalChunks.getAndAdd(1024); - mcaDefer.add(new ChunkPosition(x, z)); - } - - else - { - totalChunks.getAndAdd(1024); - mcaDefer.add(new ChunkPosition(x, z)); - e.complete(); - return false; - } - - return true; - } - - private boolean install(File from, File to) { - try - { - Files.move(from.toPath(), to.toPath()); - return true; - } - - catch(Throwable ignored) - { - - } - - try { - IO.copyFile(from, to); - from.delete(); - return true; - } catch (IOException ignored) { - - } - - return false; - } - - public void updateProgress() - { - if(!latch.flip()) - { - return; - } - - String[] v = getProgress(); - Iris.info("Pregeneration " + v[0] + " | " + v[1] + " | " + v[2] + " | " + v[3]); - } - - private void generateDeferedMCARegion(int x, int z, MultiBurst burst, Consumer3> mcaIteration) { - BurstExecutor e = burst.burst(1024); - int mcaox = x << 5; - int mcaoz = z << 5; - if(PaperLib.isPaper()) - { - method.set("PaperAsync (Slow)"); - mcaIteration.accept(mcaox, mcaoz, (ii, jj) -> { - e.queue(() -> { - try - { - CompletableFuture cc = PaperLib.getChunkAtAsync(world, ii, jj); - draw(ii, jj, COLOR_MCA_GENERATE_SLOW_ASYNC); - cc.join(); - draw(ii, jj, COLOR_MCA_GENERATED); - generated.getAndIncrement(); - vcax.set(ii); - vcaz.set(jj); - } - - catch(Throwable ex) - { - draw(ii, jj, COLOR_ERROR); - ChunkPosition pos = new ChunkPosition(ii, jj); - errors.add(pos); - totalChunks.addAndGet(1024); - mcaDefer.add(new ChunkPosition(pos.getX() >> 5, pos.getZ() >> 5)); - Iris.warn("Hole Detected in Chunk: " + pos.getX() + ", " + pos.getZ() + " (at block " + (pos.getX() << 4) + ", " + lowestBedrock + ", " + (pos.getZ() << 4) + ")"); - } - }); - }); - e.complete(); - } - - else - { - AtomicInteger m = new AtomicInteger(); - method.set("Spigot (Very Slow)"); - KList q = new KList<>(); - mcaIteration.accept(mcaox, mcaoz, (ii, jj) -> { - q.add(() -> { - draw(ii, jj, COLOR_MCA_GENERATE_SLOW); - world.getChunkAt(ii, jj).load(true); - Chunk c = world.getChunkAt(ii, jj); - draw(ii, jj, COLOR_MCA_GENERATED); - checkForError(c); - m.getAndIncrement(); - generated.getAndIncrement(); - vcax.set(ii); - vcaz.set(jj); - }); - }); - ChronoLatch tick = new ChronoLatch(1000); - new SR(0) { - @Override - public void run() { - if(tick.flip()) - { - return; - } - - if(q.isEmpty()) - { - cancel(); - return; - } - - try - { - q.pop().run(); - } - - catch(Throwable e) - { - - } - } - }; - - while(m.get() < 1024) - { - J.sleep(25); - } - } - } - - private void checkForError(Chunk c) { - if(lowestBedrock >= 0 && lowestBedrock < 256) - { - if(!c.getBlock(14, lowestBedrock, 14).getType().equals(Material.BEDROCK)) - { - ChunkPosition pos = new ChunkPosition(c.getX(), c.getZ()); - errors.add(pos); - totalChunks.addAndGet(1024); - mcaDefer.add(new ChunkPosition(pos.getX() >> 5, pos.getZ() >> 5)); - draw(pos.getX(), pos.getZ(), COLOR_ERROR); - Iris.warn("Hole Detected in Chunk: " + pos.getX() + ", " + pos.getZ() + " (at block " + (pos.getX() << 4) + ", " + lowestBedrock + ", " + (pos.getZ() << 4) + ")"); - } - } - } - - private KList computeChunkOrder() { - ChunkPosition center = new ChunkPosition(15, 15); - KList p = new KList<>(); - new Spiraler(33, 33, (x, z) -> { - int xx = x + 15; - int zz = z + 15; - if(xx < 0 || xx > 31 || zz < 0 || zz > 31) - { - return; - } - - p.add(new ChunkPosition(xx, zz)); - }).drain(); - p.sort(Comparator.comparing((i) -> i.distance(center))); - return p; - } - - public static Pregenerator getInstance() - { - return instance; - } - - public static boolean shutdownInstance(){ - if(instance != null) - { - instance.shutdown(); - instance = null; - return true; - } - - return false; - } - - public static void pauseResume() { - instance.active.set(!instance.active.get()); - } - - public static boolean isPaused() { - return instance.paused(); - } - - private void instance() { - if(instance != null) - { - instance.shutdown(); - } - - instance = this; - } - - public void shutdown() - { - running.set(false); - active.set(false); - } - - private void draw(int cx, int cz, Color color) - { - if(gui != null) - { - gui.func.accept(new ChunkPosition(cx, cz), color); - } - } - - private void drawMCA(int cx, int cz, Color color) - { - for(int i = 0; i < 32; i++) - { - for(int j = 0; j < 32; j++) - { - draw((cx << 5) + i, (cz << 5) + j, color); - } - } - } - - private void flushWorld() - { - if(Bukkit.isPrimaryThread()) - { - flushWorldSync(); - return; - } - - AtomicBoolean b = new AtomicBoolean(false); - J.s(() -> { - flushWorldSync(); - b.set(true); - }); - - while(!b.get()) - { - J.sleep(1); - } - } - - private void flushWorldSync() - { - for(Chunk i : world.getLoadedChunks()) - { - i.unload(true); - } - - world.save(); - } - - private boolean isMCAWritable(int x, int z) { - File mca = new File(world.getWorldFolder(), "region/r." + x + "." + z + ".mca"); - - if (mca.exists()) { - return false; - } - - for (Chunk i : world.getLoadedChunks()) - { - if(i.getX() >> 5 == x && i.getZ() >> 5 == z) - { - return false; - } - } - - return true; - } - - public String[] getProgress() { - long eta = (long) ((totalChunks.get() - generated.get()) * ((double)(M.ms() - elapsed) / (double) generated.get())); - - return new String[]{ - "Progress: " + Form.f(generated.get()) + " of " + Form.f(totalChunks.get()) + " (" + Form.pc((double)generated.get() / (double)totalChunks.get(), 0) + ")", - "ETA: " + Form.duration(eta, 0), - "Chunks/s: " + Form.f((int)perSecond.getAverage()), - "Memory: " + memoryMetric.get(), - "Cursor: " + "MCA(" + vmcax.get() + ", " + vmcaz.get() + ") @ (" + vcax.get() + ", " + vcaz.get() + ")", - "Gen Mode: " + method.get(), - }; - } - - public boolean paused() { - return !active.get(); - } - - public static class MCAPregenGui extends JPanel implements KeyListener - { - private Pregenerator job; - private static final long serialVersionUID = 2094606939770332040L; - private KList order = new KList<>(); - private int res = 512; - Graphics2D bg; - private ReentrantLock l; - private BufferedImage image = new BufferedImage(res, res, BufferedImage.TYPE_INT_RGB); - private Consumer2 func; - private JFrame frame; - - public MCAPregenGui() - { - - } - - public void paint(int x, int z, Color c) - { - func.accept(new ChunkPosition(x, z), c); - } - - @Override - public void paint(Graphics gx) - { - Graphics2D g = (Graphics2D) gx; - bg = (Graphics2D) image.getGraphics(); - - l.lock(); - while(order.isNotEmpty()) - { - try - { - order.pop().run(); - } - - catch(Throwable e) - { - - } - } - l.unlock(); - - g.drawImage(image, 0, 0, getParent().getWidth(), getParent().getHeight(), new ImageObserver() - { - @Override - public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) - { - return true; - } - }); - - g.setColor(Color.WHITE); - g.setFont(new Font("Hevetica", Font.BOLD, 28)); - String[] prog = job.getProgress(); - int h = g.getFontMetrics().getHeight() + 5; - int hh = 20; - - if(job.paused()) - { - g.drawString("PAUSED", 20, hh += h); - - g.drawString("Press P to Resume", 20, hh += h); - } - - else - { - for(String i : prog) - { - g.drawString(i, 20, hh += h); - } - - g.drawString("Press P to Pause", 20, hh += h); - } - - J.sleep((long) (IrisSettings.get().getGui().isMaximumPregenGuiFPS() ? 4 : 250)); - repaint(); - } - - private void draw(ChunkPosition p, Color c, Graphics2D bg) - { - double pw = M.lerpInverse(job.getMin().getX(), job.getMax().getX(), p.getX()); - double ph = M.lerpInverse(job.getMin().getZ(), job.getMax().getZ(), p.getZ()); - double pwa = M.lerpInverse(job.getMin().getX(), job.getMax().getX(), p.getX() + 1); - double pha = M.lerpInverse(job.getMin().getZ(), job.getMax().getZ(), p.getZ() + 1); - int x = (int) M.lerp(0, res, pw); - int z = (int) M.lerp(0, res, ph); - int xa = (int) M.lerp(0, res, pwa); - int za = (int) M.lerp(0, res, pha); - bg.setColor(c); - bg.fillRect(x, z, xa - x, za - z); - } - - @SuppressWarnings("deprecation") - private static MCAPregenGui createAndShowGUI(Pregenerator j) throws HeadlessException - { - JFrame frame; - try { - frame = new JFrame("Pregen View"); - } catch (HeadlessException e) { - throw e; - } - MCAPregenGui nv = new MCAPregenGui(); - frame.addKeyListener(nv); - nv.l = new ReentrantLock(); - nv.frame = frame; - nv.job = j; - nv.func = (c, b) -> - { - if(b.equals(Color.pink) && c.equals(new ChunkPosition(Integer.MAX_VALUE, Integer.MAX_VALUE))) - { - frame.hide(); - } - nv.l.lock(); - nv.order.add(() -> nv.draw(c, b, nv.bg)); - nv.l.unlock(); - }; - frame.add(nv); - frame.setSize(1000, 1000); - frame.setVisible(true); - File file = Iris.getCached("Iris Icon", "https://raw.githubusercontent.com/VolmitSoftware/Iris/master/icon.png"); - - if(file != null) - { - try - { - frame.setIconImage(ImageIO.read(file)); - } - - catch(IOException e) - { - - } - } - - return nv; - } - - public static void launch(Pregenerator g) - { - J.a(() -> - { - createAndShowGUI(g); - }); - } - - @Override - public void keyTyped(KeyEvent e) - { - - } - - @Override - public void keyPressed(KeyEvent e) - { - - } - - @Override - public void keyReleased(KeyEvent e) - { - if(e.getKeyCode() == KeyEvent.VK_P) - { - Pregenerator.pauseResume(); - } - } - - public void close() { - frame.setVisible(false); - } - } +public class Pregenerator implements Listener { + private static Pregenerator instance; + private static final Color COLOR_ERROR = Color.decode("#E34113"); + private static final Color COLOR_MCA_PREPARE = Color.decode("#3CAAB5"); + private static final Color COLOR_MCA_RELOAD = Color.decode("#41FF61"); + private static final Color COLOR_MCA_GENERATE = Color.decode("#33FF8F"); + private static final Color COLOR_MCA_GENERATE_SLOW = Color.decode("#13BAE3"); + private static final Color COLOR_MCA_GENERATE_SLOW_ASYNC = Color.decode("#13BAE3"); + private static final Color COLOR_MCA_GENERATED = Color.decode("#33FF8F"); + private static final Color COLOR_MCA_GENERATED_MCA = Color.decode("#13E3C9"); + private static final Color COLOR_MCA_SEALED = Color.decode("#33FF8F"); + private static final Color COLOR_MCA_DEFERRED = Color.decode("#3CB57A"); + private final World world; + private int lowestBedrock; + private final DirectWorldWriter directWriter; + private final AtomicBoolean active; + private final AtomicBoolean running; + private final KList errors; + private final KList onComplete; + private final ChunkPosition max; + private final ChunkPosition min; + private final MCAPregenGui gui; + private final KList mcaDefer; + private final AtomicInteger generated; + private final AtomicInteger generatedLast; + private final RollingSequence perSecond; + private final AtomicInteger totalChunks; + private final AtomicLong memory; + private final AtomicReference memoryMetric; + private final AtomicReference method; + private final AtomicInteger vmcax; + private final AtomicInteger vmcaz; + private final AtomicInteger vcax; + private final AtomicInteger vcaz; + private final long elapsed; + private final ChronoLatch latch; + private IrisAccess access; + private final KList regionReload; + + public Pregenerator(World world, int blockSize, Runnable onComplete) { + this(world, blockSize); + this.onComplete.add(onComplete); + } + + public Pregenerator(World world, int blockSize) throws HeadlessException { + this(world, blockSize, true); + } + + public Pregenerator(World world, int blockSize, boolean dogui) throws HeadlessException { + instance(); + regionReload = new KList<>(); + latch = new ChronoLatch(5000); + memoryMetric = new AtomicReference<>("..."); + method = new AtomicReference<>("STARTUP"); + memory = new AtomicLong(0); + this.world = world; + errors = new KList<>(); + vmcax = new AtomicInteger(); + vmcaz = new AtomicInteger(); + vcax = new AtomicInteger(); + vcaz = new AtomicInteger(); + perSecond = new RollingSequence(20); + generatedLast = new AtomicInteger(0); + totalChunks = new AtomicInteger(0); + generated = new AtomicInteger(0); + mcaDefer = new KList<>(); + access = IrisWorlds.access(world); + this.directWriter = new DirectWorldWriter(world.getWorldFolder()); + this.running = new AtomicBoolean(true); + this.active = new AtomicBoolean(true); + MultiBurst burst = new MultiBurst(Runtime.getRuntime().availableProcessors()); + int mcaSize = (((blockSize >> 4) + 2) >> 5) + 1; + onComplete = new KList<>(); + max = new ChunkPosition(0, 0); + min = new ChunkPosition(0, 0); + KList draw = new KList<>(); + new Spiraler(mcaSize, mcaSize, (xx, zz) -> { + min.setX(Math.min(xx << 5, min.getX())); + min.setZ(Math.min(zz << 5, min.getZ())); + max.setX(Math.max((xx << 5) + 31, max.getX())); + max.setZ(Math.max((zz << 5) + 31, max.getZ())); + totalChunks.getAndAdd(1024); + draw.add(() -> drawMCA(xx, zz, COLOR_MCA_PREPARE)); + }).drain(); + if (access != null) { + lowestBedrock = access.getCompound().getLowestBedrock(); + } + gui = dogui ? (IrisSettings.get().getGui().isLocalPregenGui() && IrisSettings.get().getGui().isUseServerLaunchedGuis() ? MCAPregenGui.createAndShowGUI(this) : null) : null; + flushWorld(); + KList order = computeChunkOrder(); + Consumer3> mcaIteration = + (ox, oz, r) -> order.forEach((i) + -> r.accept(i.getX() + ox, i.getZ() + oz)); + draw.forEach(Runnable::run); + Spiraler spiraler = new Spiraler(mcaSize, mcaSize, (xx, zz) -> { + vmcax.set(xx); + vmcaz.set(zz); + flushWorld(); + drawMCA(xx, zz, COLOR_MCA_PREPARE); + if (access != null && generateMCARegion(xx, zz, burst, access, mcaIteration)) { + flushWorld(); + } else { + drawMCA(xx, zz, COLOR_MCA_DEFERRED); + } + }); + + elapsed = M.ms(); + + new Thread(() -> { + flushWorld(); + J.sleep(2000); + flushWorld(); + + while (running.get() && spiraler.hasNext()) { + if (active.get()) { + spiraler.next(); + } + } + + mcaDefer.removeDuplicates(); + + while (running.get() && mcaDefer.isNotEmpty()) { + ChunkPosition p = mcaDefer.popLast(); + vmcax.set(p.getX()); + vmcaz.set(p.getZ()); + generateDeferedMCARegion(p.getX(), p.getZ(), burst, mcaIteration); + flushWorld(); + } + + burst.shutdownNow(); + directWriter.flush(); + flushWorld(); + onComplete.forEach(Runnable::run); + running.set(false); + active.set(false); + if (gui != null) { + gui.close(); + } + }).start(); + new Thread(() -> { + PrecisionStopwatch p = PrecisionStopwatch.start(); + + while (running.get() && active.get()) { + int m = generated.get(); + int w = generatedLast.get(); + int up = m - w; + double dur = p.getMilliseconds(); + perSecond.put((int) (up / (dur / 1000D))); + p.reset(); + p.begin(); + updateProgress(); + generatedLast.set(m); + J.sleep(100); + long lmem = memory.get(); + memory.set(Runtime.getRuntime().freeMemory()); + + if (memory.get() > lmem) { + long free = memory.get(); + long max = Runtime.getRuntime().maxMemory(); + long total = Runtime.getRuntime().totalMemory(); + long use = total - free; + memoryMetric.set(Form.memSize(use, 2) + " (" + Form.pc((double) use / (double) max, 0) + ")"); + } + } + }).start(); + } + + private boolean generateMCARegion(int x, int z, MultiBurst burst, IrisAccess access, Consumer3> mcaIteration) { + if (!Iris.instance.isMCA()) { + return false; + } + + File mca = new File(world.getWorldFolder(), "region/r." + x + "." + z + ".mca"); + File mcg = directWriter.getMCAFile(x, z); + Path fileToMovePath = Paths.get(mcg.toURI()); + Path targetPath = Paths.get(mca.toURI()); + BurstExecutor e = burst.burst(1024); + int mcaox = x << 5; + int mcaoz = z << 5; + if (isMCAWritable(x, z) && !mca.exists()) { + method.set("Direct (Fast)"); + mcaIteration.accept(mcaox, mcaoz, (ii, jj) -> e.queue(() -> { + draw(ii, jj, COLOR_MCA_GENERATE); + access.directWriteChunk(world, ii, jj, directWriter); + draw(ii, jj, COLOR_MCA_GENERATED_MCA); + generated.getAndIncrement(); + vcax.set(ii); + vcaz.set(jj); + })); + e.complete(); + directWriter.flush(); + if (!install(mcg, mca)) { + drawMCA(x, z, COLOR_MCA_DEFERRED); + generated.set(generated.get() - 1024); + } + totalChunks.getAndAdd(1024); + mcaDefer.add(new ChunkPosition(x, z)); + } else { + totalChunks.getAndAdd(1024); + mcaDefer.add(new ChunkPosition(x, z)); + e.complete(); + return false; + } + + return true; + } + + private boolean install(File from, File to) { + try { + Files.move(from.toPath(), to.toPath()); + return true; + } catch (Throwable ignored) { + + } + + try { + IO.copyFile(from, to); + from.delete(); + return true; + } catch (IOException ignored) { + + } + + return false; + } + + public void updateProgress() { + if (!latch.flip()) { + return; + } + + String[] v = getProgress(); + Iris.info("Pregeneration " + v[0] + " | " + v[1] + " | " + v[2] + " | " + v[3]); + } + + private void generateDeferedMCARegion(int x, int z, MultiBurst burst, Consumer3> mcaIteration) { + BurstExecutor e = burst.burst(1024); + int mcaox = x << 5; + int mcaoz = z << 5; + if (PaperLib.isPaper()) { + method.set("PaperAsync (Slow)"); + mcaIteration.accept(mcaox, mcaoz, (ii, jj) -> { + e.queue(() -> { + try { + CompletableFuture cc = PaperLib.getChunkAtAsync(world, ii, jj); + draw(ii, jj, COLOR_MCA_GENERATE_SLOW_ASYNC); + cc.join(); + draw(ii, jj, COLOR_MCA_GENERATED); + generated.getAndIncrement(); + vcax.set(ii); + vcaz.set(jj); + } catch (Throwable ex) { + draw(ii, jj, COLOR_ERROR); + ChunkPosition pos = new ChunkPosition(ii, jj); + errors.add(pos); + totalChunks.addAndGet(1024); + mcaDefer.add(new ChunkPosition(pos.getX() >> 5, pos.getZ() >> 5)); + Iris.warn("Hole Detected in Chunk: " + pos.getX() + ", " + pos.getZ() + " (at block " + (pos.getX() << 4) + ", " + lowestBedrock + ", " + (pos.getZ() << 4) + ")"); + } + }); + }); + e.complete(); + } else { + AtomicInteger m = new AtomicInteger(); + method.set("Spigot (Very Slow)"); + KList q = new KList<>(); + mcaIteration.accept(mcaox, mcaoz, (ii, jj) -> { + q.add(() -> { + draw(ii, jj, COLOR_MCA_GENERATE_SLOW); + world.getChunkAt(ii, jj).load(true); + Chunk c = world.getChunkAt(ii, jj); + draw(ii, jj, COLOR_MCA_GENERATED); + checkForError(c); + m.getAndIncrement(); + generated.getAndIncrement(); + vcax.set(ii); + vcaz.set(jj); + }); + }); + ChronoLatch tick = new ChronoLatch(1000); + new SR(0) { + @Override + public void run() { + if (tick.flip()) { + return; + } + + if (q.isEmpty()) { + cancel(); + return; + } + + try { + q.pop().run(); + } catch (Throwable e) { + + } + } + }; + + while (m.get() < 1024) { + J.sleep(25); + } + } + } + + private void checkForError(Chunk c) { + if (lowestBedrock >= 0 && lowestBedrock < 256) { + if (!c.getBlock(14, lowestBedrock, 14).getType().equals(Material.BEDROCK)) { + ChunkPosition pos = new ChunkPosition(c.getX(), c.getZ()); + errors.add(pos); + totalChunks.addAndGet(1024); + mcaDefer.add(new ChunkPosition(pos.getX() >> 5, pos.getZ() >> 5)); + draw(pos.getX(), pos.getZ(), COLOR_ERROR); + Iris.warn("Hole Detected in Chunk: " + pos.getX() + ", " + pos.getZ() + " (at block " + (pos.getX() << 4) + ", " + lowestBedrock + ", " + (pos.getZ() << 4) + ")"); + } + } + } + + private KList computeChunkOrder() { + ChunkPosition center = new ChunkPosition(15, 15); + KList p = new KList<>(); + new Spiraler(33, 33, (x, z) -> { + int xx = x + 15; + int zz = z + 15; + if (xx < 0 || xx > 31 || zz < 0 || zz > 31) { + return; + } + + p.add(new ChunkPosition(xx, zz)); + }).drain(); + p.sort(Comparator.comparing((i) -> i.distance(center))); + return p; + } + + public static Pregenerator getInstance() { + return instance; + } + + public static boolean shutdownInstance() { + if (instance != null) { + instance.shutdown(); + instance = null; + return true; + } + + return false; + } + + public static void pauseResume() { + instance.active.set(!instance.active.get()); + } + + public static boolean isPaused() { + return instance.paused(); + } + + private void instance() { + if (instance != null) { + instance.shutdown(); + } + + instance = this; + } + + public void shutdown() { + running.set(false); + active.set(false); + } + + private void draw(int cx, int cz, Color color) { + if (gui != null) { + gui.func.accept(new ChunkPosition(cx, cz), color); + } + } + + private void drawMCA(int cx, int cz, Color color) { + for (int i = 0; i < 32; i++) { + for (int j = 0; j < 32; j++) { + draw((cx << 5) + i, (cz << 5) + j, color); + } + } + } + + private void flushWorld() { + if (Bukkit.isPrimaryThread()) { + flushWorldSync(); + return; + } + + AtomicBoolean b = new AtomicBoolean(false); + J.s(() -> { + flushWorldSync(); + b.set(true); + }); + + while (!b.get()) { + J.sleep(1); + } + } + + private void flushWorldSync() { + for (Chunk i : world.getLoadedChunks()) { + i.unload(true); + } + + world.save(); + } + + private boolean isMCAWritable(int x, int z) { + File mca = new File(world.getWorldFolder(), "region/r." + x + "." + z + ".mca"); + + if (mca.exists()) { + return false; + } + + for (Chunk i : world.getLoadedChunks()) { + if (i.getX() >> 5 == x && i.getZ() >> 5 == z) { + return false; + } + } + + return true; + } + + public String[] getProgress() { + long eta = (long) ((totalChunks.get() - generated.get()) * ((double) (M.ms() - elapsed) / (double) generated.get())); + + return new String[]{ + "Progress: " + Form.f(generated.get()) + " of " + Form.f(totalChunks.get()) + " (" + Form.pc((double) generated.get() / (double) totalChunks.get(), 0) + ")", + "ETA: " + Form.duration(eta, 0), + "Chunks/s: " + Form.f((int) perSecond.getAverage()), + "Memory: " + memoryMetric.get(), + "Cursor: " + "MCA(" + vmcax.get() + ", " + vmcaz.get() + ") @ (" + vcax.get() + ", " + vcaz.get() + ")", + "Gen Mode: " + method.get(), + }; + } + + public boolean paused() { + return !active.get(); + } + + public static class MCAPregenGui extends JPanel implements KeyListener { + private Pregenerator job; + private static final long serialVersionUID = 2094606939770332040L; + private final KList order = new KList<>(); + private final int res = 512; + Graphics2D bg; + private ReentrantLock l; + private final BufferedImage image = new BufferedImage(res, res, BufferedImage.TYPE_INT_RGB); + private Consumer2 func; + private JFrame frame; + + public MCAPregenGui() { + + } + + public void paint(int x, int z, Color c) { + func.accept(new ChunkPosition(x, z), c); + } + + @Override + public void paint(Graphics gx) { + Graphics2D g = (Graphics2D) gx; + bg = (Graphics2D) image.getGraphics(); + + l.lock(); + while (order.isNotEmpty()) { + try { + order.pop().run(); + } catch (Throwable e) { + + } + } + l.unlock(); + + g.drawImage(image, 0, 0, getParent().getWidth(), getParent().getHeight(), new ImageObserver() { + @Override + public boolean imageUpdate(Image img, int infoflags, int x, int y, int width, int height) { + return true; + } + }); + + g.setColor(Color.WHITE); + g.setFont(new Font("Hevetica", Font.BOLD, 28)); + String[] prog = job.getProgress(); + int h = g.getFontMetrics().getHeight() + 5; + int hh = 20; + + if (job.paused()) { + g.drawString("PAUSED", 20, hh += h); + + g.drawString("Press P to Resume", 20, hh += h); + } else { + for (String i : prog) { + g.drawString(i, 20, hh += h); + } + + g.drawString("Press P to Pause", 20, hh += h); + } + + J.sleep(IrisSettings.get().getGui().isMaximumPregenGuiFPS() ? 4 : 250); + repaint(); + } + + private void draw(ChunkPosition p, Color c, Graphics2D bg) { + double pw = M.lerpInverse(job.getMin().getX(), job.getMax().getX(), p.getX()); + double ph = M.lerpInverse(job.getMin().getZ(), job.getMax().getZ(), p.getZ()); + double pwa = M.lerpInverse(job.getMin().getX(), job.getMax().getX(), p.getX() + 1); + double pha = M.lerpInverse(job.getMin().getZ(), job.getMax().getZ(), p.getZ() + 1); + int x = (int) M.lerp(0, res, pw); + int z = (int) M.lerp(0, res, ph); + int xa = (int) M.lerp(0, res, pwa); + int za = (int) M.lerp(0, res, pha); + bg.setColor(c); + bg.fillRect(x, z, xa - x, za - z); + } + + @SuppressWarnings("deprecation") + private static MCAPregenGui createAndShowGUI(Pregenerator j) throws HeadlessException { + JFrame frame; + try { + frame = new JFrame("Pregen View"); + } catch (HeadlessException e) { + throw e; + } + MCAPregenGui nv = new MCAPregenGui(); + frame.addKeyListener(nv); + nv.l = new ReentrantLock(); + nv.frame = frame; + nv.job = j; + nv.func = (c, b) -> + { + if (b.equals(Color.pink) && c.equals(new ChunkPosition(Integer.MAX_VALUE, Integer.MAX_VALUE))) { + frame.hide(); + } + nv.l.lock(); + nv.order.add(() -> nv.draw(c, b, nv.bg)); + nv.l.unlock(); + }; + frame.add(nv); + frame.setSize(1000, 1000); + frame.setVisible(true); + File file = Iris.getCached("Iris Icon", "https://raw.githubusercontent.com/VolmitSoftware/Iris/master/icon.png"); + + if (file != null) { + try { + frame.setIconImage(ImageIO.read(file)); + } catch (IOException e) { + + } + } + + return nv; + } + + public static void launch(Pregenerator g) { + J.a(() -> + { + createAndShowGUI(g); + }); + } + + @Override + public void keyTyped(KeyEvent e) { + + } + + @Override + public void keyPressed(KeyEvent e) { + + } + + @Override + public void keyReleased(KeyEvent e) { + if (e.getKeyCode() == KeyEvent.VK_P) { + Pregenerator.pauseResume(); + } + } + + public void close() { + frame.setVisible(false); + } + } } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/scaffold/IrisWorldCreator.java b/src/main/java/com/volmit/iris/scaffold/IrisWorldCreator.java index b177517ba..263b3ffb8 100644 --- a/src/main/java/com/volmit/iris/scaffold/IrisWorldCreator.java +++ b/src/main/java/com/volmit/iris/scaffold/IrisWorldCreator.java @@ -1,6 +1,5 @@ package com.volmit.iris.scaffold; -import com.volmit.iris.Iris; import com.volmit.iris.manager.IrisDataManager; import com.volmit.iris.object.IrisDimension; import com.volmit.iris.scaffold.engine.EngineCompositeGenerator; @@ -10,8 +9,7 @@ import org.bukkit.WorldCreator; import java.io.File; -public class IrisWorldCreator -{ +public class IrisWorldCreator { private String name; private boolean studio = false; private String dimensionName = null; @@ -19,57 +17,48 @@ public class IrisWorldCreator private int maxHeight = 256; private int minHeight = 0; - public IrisWorldCreator() - { + public IrisWorldCreator() { } - public IrisWorldCreator dimension(String loadKey) - { + public IrisWorldCreator dimension(String loadKey) { this.dimensionName = loadKey; return this; } - public IrisWorldCreator height(int maxHeight) - { + public IrisWorldCreator height(int maxHeight) { this.maxHeight = maxHeight; this.minHeight = 0; return this; } - public IrisWorldCreator height(int minHeight, int maxHeight) - { + public IrisWorldCreator height(int minHeight, int maxHeight) { this.maxHeight = maxHeight; this.minHeight = minHeight; return this; } - public IrisWorldCreator name(String name) - { + public IrisWorldCreator name(String name) { this.name = name; return this; } - public IrisWorldCreator seed(long seed) - { + public IrisWorldCreator seed(long seed) { this.seed = seed; return this; } - public IrisWorldCreator studioMode() - { + public IrisWorldCreator studioMode() { this.studio = true; return this; } - public IrisWorldCreator productionMode() - { + public IrisWorldCreator productionMode() { this.studio = false; return this; } - public WorldCreator create() - { + public WorldCreator create() { EngineCompositeGenerator g = new EngineCompositeGenerator(dimensionName, !studio); g.initialize(new FakeWorld(name, minHeight, maxHeight, seed, new File(name), findEnvironment())); @@ -81,13 +70,9 @@ public class IrisWorldCreator private World.Environment findEnvironment() { IrisDimension dim = IrisDataManager.loadAnyDimension(dimensionName); - if(dim == null || dim.getEnvironment() == null) - { + if (dim == null || dim.getEnvironment() == null) { return World.Environment.NORMAL; - } - - else - { + } else { return dim.getEnvironment(); } } diff --git a/src/main/java/com/volmit/iris/scaffold/IrisWorlds.java b/src/main/java/com/volmit/iris/scaffold/IrisWorlds.java index ecb719545..e19925557 100644 --- a/src/main/java/com/volmit/iris/scaffold/IrisWorlds.java +++ b/src/main/java/com/volmit/iris/scaffold/IrisWorlds.java @@ -9,60 +9,49 @@ import org.bukkit.Bukkit; import org.bukkit.World; import org.bukkit.entity.Player; -public class IrisWorlds -{ - private static final KMap provisioned = new KMap<>(); +public class IrisWorlds { + private static final KMap provisioned = new KMap<>(); - public static void register(World w, IrisAccess p) - { - provisioned.put(w.getUID().toString(), p); - } + public static void register(World w, IrisAccess p) { + provisioned.put(w.getUID().toString(), p); + } - public static boolean isIrisWorld(World world) - { - if(world == null) - { - return false; - } + public static boolean isIrisWorld(World world) { + if (world == null) { + return false; + } - if(provisioned.containsKey(world.getUID().toString())) - { - return true; - } + if (provisioned.containsKey(world.getUID().toString())) { + return true; + } - return world.getGenerator() instanceof IrisAccess || world.getGenerator() instanceof IrisAccessProvider; - } + return world.getGenerator() instanceof IrisAccess || world.getGenerator() instanceof IrisAccessProvider; + } - public static IrisAccess access(World world) - { - if(isIrisWorld(world)) - { - if(provisioned.containsKey(world.getUID().toString())) - { - return provisioned.get(world.getUID().toString()); - } + public static IrisAccess access(World world) { + if (isIrisWorld(world)) { + if (provisioned.containsKey(world.getUID().toString())) { + return provisioned.get(world.getUID().toString()); + } - return world.getGenerator() instanceof IrisAccessProvider ? (((IrisAccessProvider)world.getGenerator()).getAccess()) : ((IrisAccess) world.getGenerator()); - } + return world.getGenerator() instanceof IrisAccessProvider ? (((IrisAccessProvider) world.getGenerator()).getAccess()) : ((IrisAccess) world.getGenerator()); + } - return null; - } + return null; + } public static boolean evacuate(World world) { - for(World i : Bukkit.getWorlds()) - { - if(!i.getName().equals(world.getName())) - { - for(Player j : world.getPlayers()) - { - new MortarSender(j, Iris.instance.getTag()).sendMessage("You have been evacuated from this world."); - j.teleport(i.getSpawnLocation()); - } + for (World i : Bukkit.getWorlds()) { + if (!i.getName().equals(world.getName())) { + for (Player j : world.getPlayers()) { + new MortarSender(j, Iris.instance.getTag()).sendMessage("You have been evacuated from this world."); + j.teleport(i.getSpawnLocation()); + } - return true; - } - } + return true; + } + } - return false; + return false; } } diff --git a/src/main/java/com/volmit/iris/scaffold/cache/AtomicCache.java b/src/main/java/com/volmit/iris/scaffold/cache/AtomicCache.java index 63d93ca0f..24c5eab28 100644 --- a/src/main/java/com/volmit/iris/scaffold/cache/AtomicCache.java +++ b/src/main/java/com/volmit/iris/scaffold/cache/AtomicCache.java @@ -5,115 +5,100 @@ import com.volmit.iris.util.M; import java.util.function.Supplier; -public class AtomicCache -{ - private transient volatile T t; - private transient volatile long a; - private transient volatile int validations; - private final IrisLock check; - private final IrisLock time; - private final IrisLock write; - private final boolean nullSupport; +public class AtomicCache { + private transient volatile T t; + private transient volatile long a; + private transient volatile int validations; + private final IrisLock check; + private final IrisLock time; + private final IrisLock write; + private final boolean nullSupport; - public AtomicCache() - { - this(false); - } + public AtomicCache() { + this(false); + } - public AtomicCache(boolean nullSupport) - { - this.nullSupport = nullSupport; - check = new IrisLock("Check"); - write = new IrisLock("Write"); - time = new IrisLock("Time"); - validations = 0; - a = -1; - t = null; - } + public AtomicCache(boolean nullSupport) { + this.nullSupport = nullSupport; + check = new IrisLock("Check"); + write = new IrisLock("Write"); + time = new IrisLock("Time"); + validations = 0; + a = -1; + t = null; + } - public void reset() - { - check.lock(); - write.lock(); - time.lock(); - a = -1; - t = null; - time.unlock(); - write.unlock(); - check.unlock(); - } + public void reset() { + check.lock(); + write.lock(); + time.lock(); + a = -1; + t = null; + time.unlock(); + write.unlock(); + check.unlock(); + } - public T aquire(Supplier t) - { - if(nullSupport) - { - return aquireNull(t); - } + public T aquire(Supplier t) { + if (nullSupport) { + return aquireNull(t); + } - if(this.t != null && validations > 1000) - { - return this.t; - } + if (this.t != null && validations > 1000) { + return this.t; + } - if(this.t != null && M.ms() - a > 1000) - { - if(this.t != null) - { - validations++; - } + if (this.t != null && M.ms() - a > 1000) { + if (this.t != null) { + validations++; + } - return this.t; - } + return this.t; + } - check.lock(); + check.lock(); - if(this.t == null) - { - write.lock(); - this.t = t.get(); + if (this.t == null) { + write.lock(); + this.t = t.get(); - time.lock(); + time.lock(); - if(a == -1) - { - a = M.ms(); - } + if (a == -1) { + a = M.ms(); + } - time.unlock(); - write.unlock(); - } + time.unlock(); + write.unlock(); + } - check.unlock(); - return this.t; - } + check.unlock(); + return this.t; + } - public T aquireNull(Supplier t) - { - if(validations > 1000) - { - return this.t; - } + public T aquireNull(Supplier t) { + if (validations > 1000) { + return this.t; + } - if(M.ms() - a > 1000) - { - validations++; - return this.t; - } + if (M.ms() - a > 1000) { + validations++; + return this.t; + } - check.lock(); - write.lock(); - this.t = t.get(); + check.lock(); + write.lock(); + this.t = t.get(); - time.lock(); + time.lock(); - if(a == -1) - { - a = M.ms(); - } + if (a == -1) { + a = M.ms(); + } - time.unlock(); - write.unlock(); - check.unlock(); - return this.t; - } + time.unlock(); + write.unlock(); + check.unlock(); + return this.t; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/cache/Cache.java b/src/main/java/com/volmit/iris/scaffold/cache/Cache.java index fcdf5150d..583cce6cd 100644 --- a/src/main/java/com/volmit/iris/scaffold/cache/Cache.java +++ b/src/main/java/com/volmit/iris/scaffold/cache/Cache.java @@ -2,28 +2,24 @@ package com.volmit.iris.scaffold.cache; import org.bukkit.Chunk; -public interface Cache -{ +public interface Cache { static long key(Chunk chunk) { return key(chunk.getX(), chunk.getZ()); } - public int getId(); + int getId(); - public V get(int x, int z); + V get(int x, int z); - public static long key(int x, int z) - { - return (((long)x) << 32) | (z & 0xffffffffL); + static long key(int x, int z) { + return (((long) x) << 32) | (z & 0xffffffffL); } - public static int keyX(long key) - { - return (int)(key >> 32); + static int keyX(long key) { + return (int) (key >> 32); } - public static int keyZ(long key) - { - return (int)key; + static int keyZ(long key) { + return (int) key; } } diff --git a/src/main/java/com/volmit/iris/scaffold/cache/Multicache.java b/src/main/java/com/volmit/iris/scaffold/cache/Multicache.java index 84a023f70..bf0cad559 100644 --- a/src/main/java/com/volmit/iris/scaffold/cache/Multicache.java +++ b/src/main/java/com/volmit/iris/scaffold/cache/Multicache.java @@ -1,11 +1,10 @@ package com.volmit.iris.scaffold.cache; -public interface Multicache -{ +public interface Multicache { @SuppressWarnings("hiding") - public Cache getCache(int id); + Cache getCache(int id); @SuppressWarnings("hiding") - public Cache createCache(); + Cache createCache(); } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/scaffold/data/DataPalette.java b/src/main/java/com/volmit/iris/scaffold/data/DataPalette.java index 29c4cff02..7c36b2211 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/DataPalette.java +++ b/src/main/java/com/volmit/iris/scaffold/data/DataPalette.java @@ -9,59 +9,48 @@ import java.io.IOException; public class DataPalette { private final KList palette; - public DataPalette() - { + public DataPalette() { this(new KList<>(16)); } - public DataPalette(KList palette) - { + public DataPalette(KList palette) { this.palette = palette; } - public KList getPalette() - { + public KList getPalette() { return palette; } - public int getIndex(T t) - { + public int getIndex(T t) { int v = 0; - synchronized (palette) - { - v = palette.indexOf(t); + synchronized (palette) { + v = palette.indexOf(t); - if(v == -1) - { - v = palette.size(); - palette.add(t); - } - } + if (v == -1) { + v = palette.size(); + palette.add(t); + } + } return v; } - public void write(IOAdapter adapter, DataOutputStream dos) throws IOException - { - synchronized (palette) - { + public void write(IOAdapter adapter, DataOutputStream dos) throws IOException { + synchronized (palette) { dos.writeShort(getPalette().size() + Short.MIN_VALUE); - for(int i = 0; i < palette.size(); i++) - { + for (int i = 0; i < palette.size(); i++) { adapter.write(palette.get(i), dos); } } } - public static DataPalette getPalette(IOAdapter adapter, DataInputStream din) throws IOException - { + public static DataPalette getPalette(IOAdapter adapter, DataInputStream din) throws IOException { KList palette = new KList<>(); int s = din.readShort() - Short.MIN_VALUE; - for(int i = 0; i < s; i++) - { + for (int i = 0; i < s; i++) { palette.add(adapter.read(din)); } diff --git a/src/main/java/com/volmit/iris/scaffold/data/DataProvider.java b/src/main/java/com/volmit/iris/scaffold/data/DataProvider.java index 2254ec831..c986a3c54 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/DataProvider.java +++ b/src/main/java/com/volmit/iris/scaffold/data/DataProvider.java @@ -2,7 +2,6 @@ package com.volmit.iris.scaffold.data; import com.volmit.iris.manager.IrisDataManager; -public interface DataProvider -{ - public IrisDataManager getData(); +public interface DataProvider { + IrisDataManager getData(); } diff --git a/src/main/java/com/volmit/iris/scaffold/data/IOAdapter.java b/src/main/java/com/volmit/iris/scaffold/data/IOAdapter.java index 64c136d90..f2fd79347 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/IOAdapter.java +++ b/src/main/java/com/volmit/iris/scaffold/data/IOAdapter.java @@ -1,10 +1,11 @@ package com.volmit.iris.scaffold.data; -import java.io.*; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; -public interface IOAdapter -{ - public void write(T t, DataOutputStream dos) throws IOException; +public interface IOAdapter { + void write(T t, DataOutputStream dos) throws IOException; - public T read(DataInputStream din) throws IOException; + T read(DataInputStream din) throws IOException; } diff --git a/src/main/java/com/volmit/iris/scaffold/data/io/Deserializer.java b/src/main/java/com/volmit/iris/scaffold/data/io/Deserializer.java index a8f627a54..6b30a3207 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/io/Deserializer.java +++ b/src/main/java/com/volmit/iris/scaffold/data/io/Deserializer.java @@ -1,42 +1,37 @@ package com.volmit.iris.scaffold.data.io; -import java.io.BufferedInputStream; -import java.io.ByteArrayInputStream; -import java.io.File; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.InputStream; +import java.io.*; import java.net.URL; public interface Deserializer { - T fromStream(InputStream stream) throws IOException; + T fromStream(InputStream stream) throws IOException; - default T fromFile(File file) throws IOException { - try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) { - return fromStream(bis); - } - } + default T fromFile(File file) throws IOException { + try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file))) { + return fromStream(bis); + } + } - default T fromBytes(byte[] data) throws IOException { - ByteArrayInputStream stream = new ByteArrayInputStream(data); - return fromStream(stream); - } + default T fromBytes(byte[] data) throws IOException { + ByteArrayInputStream stream = new ByteArrayInputStream(data); + return fromStream(stream); + } - default T fromResource(Class clazz, String path) throws IOException { - try (InputStream stream = clazz.getClassLoader().getResourceAsStream(path)) { - if (stream == null) { - throw new IOException("resource \"" + path + "\" not found"); - } - return fromStream(stream); - } - } + default T fromResource(Class clazz, String path) throws IOException { + try (InputStream stream = clazz.getClassLoader().getResourceAsStream(path)) { + if (stream == null) { + throw new IOException("resource \"" + path + "\" not found"); + } + return fromStream(stream); + } + } - default T fromURL(URL url) throws IOException { - try (InputStream stream = url.openStream()) { - return fromStream(stream); - } - } + default T fromURL(URL url) throws IOException { + try (InputStream stream = url.openStream()) { + return fromStream(stream); + } + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/io/ExceptionBiFunction.java b/src/main/java/com/volmit/iris/scaffold/data/io/ExceptionBiFunction.java index b7e2a0365..a252ac428 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/io/ExceptionBiFunction.java +++ b/src/main/java/com/volmit/iris/scaffold/data/io/ExceptionBiFunction.java @@ -1,7 +1,7 @@ package com.volmit.iris.scaffold.data.io; @FunctionalInterface -public interface ExceptionBiFunction { +public interface ExceptionBiFunction { - R accept(T t, U u) throws E; + R accept(T t, U u) throws E; } diff --git a/src/main/java/com/volmit/iris/scaffold/data/io/ExceptionTriConsumer.java b/src/main/java/com/volmit/iris/scaffold/data/io/ExceptionTriConsumer.java index 56643ff75..91a7c9314 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/io/ExceptionTriConsumer.java +++ b/src/main/java/com/volmit/iris/scaffold/data/io/ExceptionTriConsumer.java @@ -3,5 +3,5 @@ package com.volmit.iris.scaffold.data.io; @FunctionalInterface public interface ExceptionTriConsumer { - void accept(T t, U u, V v) throws E; + void accept(T t, U u, V v) throws E; } diff --git a/src/main/java/com/volmit/iris/scaffold/data/io/MaxDepthIO.java b/src/main/java/com/volmit/iris/scaffold/data/io/MaxDepthIO.java index f042ff717..31ab52d5c 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/io/MaxDepthIO.java +++ b/src/main/java/com/volmit/iris/scaffold/data/io/MaxDepthIO.java @@ -2,12 +2,12 @@ package com.volmit.iris.scaffold.data.io; public interface MaxDepthIO { - default int decrementMaxDepth(int maxDepth) { - if (maxDepth < 0) { - throw new IllegalArgumentException("negative maximum depth is not allowed"); - } else if (maxDepth == 0) { - throw new MaxDepthReachedException("reached maximum depth of NBT structure"); - } - return --maxDepth; - } + default int decrementMaxDepth(int maxDepth) { + if (maxDepth < 0) { + throw new IllegalArgumentException("negative maximum depth is not allowed"); + } else if (maxDepth == 0) { + throw new MaxDepthReachedException("reached maximum depth of NBT structure"); + } + return --maxDepth; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/io/MaxDepthReachedException.java b/src/main/java/com/volmit/iris/scaffold/data/io/MaxDepthReachedException.java index dc85f7216..e74f4388b 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/io/MaxDepthReachedException.java +++ b/src/main/java/com/volmit/iris/scaffold/data/io/MaxDepthReachedException.java @@ -6,7 +6,7 @@ package com.volmit.iris.scaffold.data.io; @SuppressWarnings("serial") public class MaxDepthReachedException extends RuntimeException { - public MaxDepthReachedException(String msg) { - super(msg); - } + public MaxDepthReachedException(String msg) { + super(msg); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/io/Serializer.java b/src/main/java/com/volmit/iris/scaffold/data/io/Serializer.java index d6cfe2e2b..bfe2f83e2 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/io/Serializer.java +++ b/src/main/java/com/volmit/iris/scaffold/data/io/Serializer.java @@ -1,26 +1,21 @@ package com.volmit.iris.scaffold.data.io; -import java.io.BufferedOutputStream; -import java.io.ByteArrayOutputStream; -import java.io.File; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.OutputStream; +import java.io.*; public interface Serializer { - void toStream(T object, OutputStream out) throws IOException; + void toStream(T object, OutputStream out) throws IOException; - default void toFile(T object, File file) throws IOException { - try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) { - toStream(object, bos); - } - } + default void toFile(T object, File file) throws IOException { + try (BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) { + toStream(object, bos); + } + } - default byte[] toBytes(T object) throws IOException { - ByteArrayOutputStream bos = new ByteArrayOutputStream(); - toStream(object, bos); - bos.close(); - return bos.toByteArray(); - } + default byte[] toBytes(T object) throws IOException { + ByteArrayOutputStream bos = new ByteArrayOutputStream(); + toStream(object, bos); + bos.close(); + return bos.toByteArray(); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/io/StringDeserializer.java b/src/main/java/com/volmit/iris/scaffold/data/io/StringDeserializer.java index 32c05b569..655c27470 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/io/StringDeserializer.java +++ b/src/main/java/com/volmit/iris/scaffold/data/io/StringDeserializer.java @@ -1,37 +1,31 @@ package com.volmit.iris.scaffold.data.io; -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; +import java.io.*; public interface StringDeserializer extends Deserializer { - T fromReader(Reader reader) throws IOException; + T fromReader(Reader reader) throws IOException; - default T fromString(String s) throws IOException { - return fromReader(new StringReader(s)); - } + default T fromString(String s) throws IOException { + return fromReader(new StringReader(s)); + } - @Override - default T fromStream(InputStream stream) throws IOException { - try (Reader reader = new InputStreamReader(stream)) { - return fromReader(reader); - } - } + @Override + default T fromStream(InputStream stream) throws IOException { + try (Reader reader = new InputStreamReader(stream)) { + return fromReader(reader); + } + } - @Override - default T fromFile(File file) throws IOException { - try (Reader reader = new FileReader(file)) { - return fromReader(reader); - } - } + @Override + default T fromFile(File file) throws IOException { + try (Reader reader = new FileReader(file)) { + return fromReader(reader); + } + } - @Override - default T fromBytes(byte[] data) throws IOException { - return fromReader(new StringReader(new String(data))); - } + @Override + default T fromBytes(byte[] data) throws IOException { + return fromReader(new StringReader(new String(data))); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/io/StringSerializer.java b/src/main/java/com/volmit/iris/scaffold/data/io/StringSerializer.java index c289f1e91..49ba63655 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/io/StringSerializer.java +++ b/src/main/java/com/volmit/iris/scaffold/data/io/StringSerializer.java @@ -1,35 +1,29 @@ package com.volmit.iris.scaffold.data.io; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.StringWriter; -import java.io.Writer; +import java.io.*; public interface StringSerializer extends Serializer { - void toWriter(T object, Writer writer) throws IOException; + void toWriter(T object, Writer writer) throws IOException; - default String toString(T object) throws IOException { - Writer writer = new StringWriter(); - toWriter(object, writer); - writer.flush(); - return writer.toString(); - } + default String toString(T object) throws IOException { + Writer writer = new StringWriter(); + toWriter(object, writer); + writer.flush(); + return writer.toString(); + } - @Override - default void toStream(T object, OutputStream stream) throws IOException { - Writer writer = new OutputStreamWriter(stream); - toWriter(object, writer); - writer.flush(); - } + @Override + default void toStream(T object, OutputStream stream) throws IOException { + Writer writer = new OutputStreamWriter(stream); + toWriter(object, writer); + writer.flush(); + } - @Override - default void toFile(T object, File file) throws IOException { - try (Writer writer = new FileWriter(file)) { - toWriter(object, writer); - } - } + @Override + default void toFile(T object, File file) throws IOException { + try (Writer writer = new FileWriter(file)) { + toWriter(object, writer); + } + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/mca/Chunk.java b/src/main/java/com/volmit/iris/scaffold/data/mca/Chunk.java index b09ed9825..4c8de7d1c 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/mca/Chunk.java +++ b/src/main/java/com/volmit/iris/scaffold/data/mca/Chunk.java @@ -6,639 +6,661 @@ import com.volmit.iris.scaffold.data.nbt.io.NamedTag; import com.volmit.iris.scaffold.data.nbt.tag.CompoundTag; import com.volmit.iris.scaffold.data.nbt.tag.ListTag; -import java.io.BufferedInputStream; -import java.io.BufferedOutputStream; -import java.io.ByteArrayOutputStream; -import java.io.FileInputStream; -import java.io.IOException; -import java.io.RandomAccessFile; +import java.io.*; import java.util.Arrays; + import static com.volmit.iris.scaffold.data.mca.LoadFlags.*; public class Chunk { - public static final int DEFAULT_DATA_VERSION = 1628; + public static final int DEFAULT_DATA_VERSION = 1628; - private boolean partial; + private boolean partial; - private int lastMCAUpdate; + private int lastMCAUpdate; - private CompoundTag data; + private CompoundTag data; - private int dataVersion; - private long lastUpdate; - private long inhabitedTime; - private int[] biomes; - private CompoundTag heightMaps; - private CompoundTag carvingMasks; - private final Section[] sections = new Section[16]; - private ListTag entities; - private ListTag tileEntities; - private ListTag tileTicks; - private ListTag liquidTicks; - private ListTag> lights; - private ListTag> liquidsToBeTicked; - private ListTag> toBeTicked; - private ListTag> postProcessing; - private String status; - private CompoundTag structures; + private int dataVersion; + private long lastUpdate; + private long inhabitedTime; + private int[] biomes; + private CompoundTag heightMaps; + private CompoundTag carvingMasks; + private final Section[] sections = new Section[16]; + private ListTag entities; + private ListTag tileEntities; + private ListTag tileTicks; + private ListTag liquidTicks; + private ListTag> lights; + private ListTag> liquidsToBeTicked; + private ListTag> toBeTicked; + private ListTag> postProcessing; + private String status; + private CompoundTag structures; - Chunk(int lastMCAUpdate) { - this.lastMCAUpdate = lastMCAUpdate; - } + Chunk(int lastMCAUpdate) { + this.lastMCAUpdate = lastMCAUpdate; + } - /** - * Create a new chunk based on raw base data from a region file. - * @param data The raw base data to be used. - */ - public Chunk(CompoundTag data) { - this.data = data; - initReferences(ALL_DATA); - } + /** + * Create a new chunk based on raw base data from a region file. + * + * @param data The raw base data to be used. + */ + public Chunk(CompoundTag data) { + this.data = data; + initReferences(ALL_DATA); + } - private void initReferences(long loadFlags) { - if (data == null) { - throw new NullPointerException("data cannot be null"); - } - CompoundTag level; - if ((level = data.getCompoundTag("Level")) == null) { - throw new IllegalArgumentException("data does not contain \"Level\" tag"); - } - dataVersion = data.getInt("DataVersion"); - inhabitedTime = level.getLong("InhabitedTime"); - lastUpdate = level.getLong("LastUpdate"); - if ((loadFlags & BIOMES) != 0) { - biomes = level.getIntArray("Biomes"); - } - if ((loadFlags & HEIGHTMAPS) != 0) { - heightMaps = level.getCompoundTag("Heightmaps"); - } - if ((loadFlags & CARVING_MASKS) != 0) { - carvingMasks = level.getCompoundTag("CarvingMasks"); - } - if ((loadFlags & ENTITIES) != 0) { - entities = level.containsKey("Entities") ? level.getListTag("Entities").asCompoundTagList() : null; - } - if ((loadFlags & TILE_ENTITIES) != 0) { - tileEntities = level.containsKey("TileEntities") ? level.getListTag("TileEntities").asCompoundTagList() : null; - } - if ((loadFlags & TILE_TICKS) != 0) { - tileTicks = level.containsKey("TileTicks") ? level.getListTag("TileTicks").asCompoundTagList() : null; - } - if ((loadFlags & LIQUID_TICKS) != 0) { - liquidTicks = level.containsKey("LiquidTicks") ? level.getListTag("LiquidTicks").asCompoundTagList() : null; - } - if ((loadFlags & LIGHTS) != 0) { - lights = level.containsKey("Lights") ? level.getListTag("Lights").asListTagList() : null; - } - if ((loadFlags & LIQUIDS_TO_BE_TICKED) != 0) { - liquidsToBeTicked = level.containsKey("LiquidsToBeTicked") ? level.getListTag("LiquidsToBeTicked").asListTagList() : null; - } - if ((loadFlags & TO_BE_TICKED) != 0) { - toBeTicked = level.containsKey("ToBeTicked") ? level.getListTag("ToBeTicked").asListTagList() : null; - } - if ((loadFlags & POST_PROCESSING) != 0) { - postProcessing = level.containsKey("PostProcessing") ? level.getListTag("PostProcessing").asListTagList() : null; - } - status = level.getString("Status"); - if ((loadFlags & STRUCTURES) != 0) { - structures = level.getCompoundTag("Structures"); - } - if ((loadFlags & (BLOCK_LIGHTS|BLOCK_STATES|SKY_LIGHT)) != 0 && level.containsKey("Sections")) { - for (CompoundTag section : level.getListTag("Sections").asCompoundTagList()) { - int sectionIndex = section.getByte("Y"); - if (sectionIndex > 15 || sectionIndex < 0) { - continue; - } - Section newSection = new Section(section, dataVersion, loadFlags); - if (newSection.isEmpty()) { - continue; - } - sections[sectionIndex] = newSection; - } - } + private void initReferences(long loadFlags) { + if (data == null) { + throw new NullPointerException("data cannot be null"); + } + CompoundTag level; + if ((level = data.getCompoundTag("Level")) == null) { + throw new IllegalArgumentException("data does not contain \"Level\" tag"); + } + dataVersion = data.getInt("DataVersion"); + inhabitedTime = level.getLong("InhabitedTime"); + lastUpdate = level.getLong("LastUpdate"); + if ((loadFlags & BIOMES) != 0) { + biomes = level.getIntArray("Biomes"); + } + if ((loadFlags & HEIGHTMAPS) != 0) { + heightMaps = level.getCompoundTag("Heightmaps"); + } + if ((loadFlags & CARVING_MASKS) != 0) { + carvingMasks = level.getCompoundTag("CarvingMasks"); + } + if ((loadFlags & ENTITIES) != 0) { + entities = level.containsKey("Entities") ? level.getListTag("Entities").asCompoundTagList() : null; + } + if ((loadFlags & TILE_ENTITIES) != 0) { + tileEntities = level.containsKey("TileEntities") ? level.getListTag("TileEntities").asCompoundTagList() : null; + } + if ((loadFlags & TILE_TICKS) != 0) { + tileTicks = level.containsKey("TileTicks") ? level.getListTag("TileTicks").asCompoundTagList() : null; + } + if ((loadFlags & LIQUID_TICKS) != 0) { + liquidTicks = level.containsKey("LiquidTicks") ? level.getListTag("LiquidTicks").asCompoundTagList() : null; + } + if ((loadFlags & LIGHTS) != 0) { + lights = level.containsKey("Lights") ? level.getListTag("Lights").asListTagList() : null; + } + if ((loadFlags & LIQUIDS_TO_BE_TICKED) != 0) { + liquidsToBeTicked = level.containsKey("LiquidsToBeTicked") ? level.getListTag("LiquidsToBeTicked").asListTagList() : null; + } + if ((loadFlags & TO_BE_TICKED) != 0) { + toBeTicked = level.containsKey("ToBeTicked") ? level.getListTag("ToBeTicked").asListTagList() : null; + } + if ((loadFlags & POST_PROCESSING) != 0) { + postProcessing = level.containsKey("PostProcessing") ? level.getListTag("PostProcessing").asListTagList() : null; + } + status = level.getString("Status"); + if ((loadFlags & STRUCTURES) != 0) { + structures = level.getCompoundTag("Structures"); + } + if ((loadFlags & (BLOCK_LIGHTS | BLOCK_STATES | SKY_LIGHT)) != 0 && level.containsKey("Sections")) { + for (CompoundTag section : level.getListTag("Sections").asCompoundTagList()) { + int sectionIndex = section.getByte("Y"); + if (sectionIndex > 15 || sectionIndex < 0) { + continue; + } + Section newSection = new Section(section, dataVersion, loadFlags); + if (newSection.isEmpty()) { + continue; + } + sections[sectionIndex] = newSection; + } + } - // If we haven't requested the full set of data we can drop the underlying raw data to let the GC handle it. - if (loadFlags != ALL_DATA) { - data = null; - partial = true; - } else { - partial = false; - } - } + // If we haven't requested the full set of data we can drop the underlying raw data to let the GC handle it. + if (loadFlags != ALL_DATA) { + data = null; + partial = true; + } else { + partial = false; + } + } - /** - * Serializes this chunk to a RandomAccessFile. - * @param raf The RandomAccessFile to be written to. - * @param xPos The x-coordinate of the chunk. - * @param zPos The z-coodrinate of the chunk. - * @return The amount of bytes written to the RandomAccessFile. - * @throws UnsupportedOperationException When something went wrong during writing. - * @throws IOException When something went wrong during writing. - */ - public int serialize(RandomAccessFile raf, int xPos, int zPos) throws IOException { - if (partial) { - throw new UnsupportedOperationException("Partially loaded chunks cannot be serialized"); - } - ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); - try (BufferedOutputStream nbtOut = new BufferedOutputStream(CompressionType.ZLIB.compress(baos))) { - new NBTSerializer(false).toStream(new NamedTag(null, updateHandle(xPos, zPos)), nbtOut); - } - byte[] rawData = baos.toByteArray(); - raf.writeInt(rawData.length + 1); // including the byte to store the compression type - raf.writeByte(CompressionType.ZLIB.getID()); - raf.write(rawData); - return rawData.length + 5; - } + /** + * Serializes this chunk to a RandomAccessFile. + * + * @param raf The RandomAccessFile to be written to. + * @param xPos The x-coordinate of the chunk. + * @param zPos The z-coodrinate of the chunk. + * @return The amount of bytes written to the RandomAccessFile. + * @throws UnsupportedOperationException When something went wrong during writing. + * @throws IOException When something went wrong during writing. + */ + public int serialize(RandomAccessFile raf, int xPos, int zPos) throws IOException { + if (partial) { + throw new UnsupportedOperationException("Partially loaded chunks cannot be serialized"); + } + ByteArrayOutputStream baos = new ByteArrayOutputStream(4096); + try (BufferedOutputStream nbtOut = new BufferedOutputStream(CompressionType.ZLIB.compress(baos))) { + new NBTSerializer(false).toStream(new NamedTag(null, updateHandle(xPos, zPos)), nbtOut); + } + byte[] rawData = baos.toByteArray(); + raf.writeInt(rawData.length + 1); // including the byte to store the compression type + raf.writeByte(CompressionType.ZLIB.getID()); + raf.write(rawData); + return rawData.length + 5; + } - /** - * Reads chunk data from a RandomAccessFile. The RandomAccessFile must already be at the correct position. - * @param raf The RandomAccessFile to read the chunk data from. - * @throws IOException When something went wrong during reading. - */ - public void deserialize(RandomAccessFile raf) throws IOException { - deserialize(raf, ALL_DATA); - } + /** + * Reads chunk data from a RandomAccessFile. The RandomAccessFile must already be at the correct position. + * + * @param raf The RandomAccessFile to read the chunk data from. + * @throws IOException When something went wrong during reading. + */ + public void deserialize(RandomAccessFile raf) throws IOException { + deserialize(raf, ALL_DATA); + } - /** - * Reads chunk data from a RandomAccessFile. The RandomAccessFile must already be at the correct position. - * @param raf The RandomAccessFile to read the chunk data from. - * @param loadFlags A logical or of {@link LoadFlags} constants indicating what data should be loaded - * @throws IOException When something went wrong during reading. - */ - public void deserialize(RandomAccessFile raf, long loadFlags) throws IOException { - byte compressionTypeByte = raf.readByte(); - CompressionType compressionType = CompressionType.getFromID(compressionTypeByte); - if (compressionType == null) { - throw new IOException("invalid compression type " + compressionTypeByte); - } - BufferedInputStream dis = new BufferedInputStream(compressionType.decompress(new FileInputStream(raf.getFD()))); - NamedTag tag = new NBTDeserializer(false).fromStream(dis); - if (tag != null && tag.getTag() instanceof CompoundTag) { - data = (CompoundTag) tag.getTag(); - initReferences(loadFlags); - } else { - throw new IOException("invalid data tag: " + (tag == null ? "null" : tag.getClass().getName())); - } - } + /** + * Reads chunk data from a RandomAccessFile. The RandomAccessFile must already be at the correct position. + * + * @param raf The RandomAccessFile to read the chunk data from. + * @param loadFlags A logical or of {@link LoadFlags} constants indicating what data should be loaded + * @throws IOException When something went wrong during reading. + */ + public void deserialize(RandomAccessFile raf, long loadFlags) throws IOException { + byte compressionTypeByte = raf.readByte(); + CompressionType compressionType = CompressionType.getFromID(compressionTypeByte); + if (compressionType == null) { + throw new IOException("invalid compression type " + compressionTypeByte); + } + BufferedInputStream dis = new BufferedInputStream(compressionType.decompress(new FileInputStream(raf.getFD()))); + NamedTag tag = new NBTDeserializer(false).fromStream(dis); + if (tag != null && tag.getTag() instanceof CompoundTag) { + data = (CompoundTag) tag.getTag(); + initReferences(loadFlags); + } else { + throw new IOException("invalid data tag: " + (tag == null ? "null" : tag.getClass().getName())); + } + } - /** - * @deprecated Use {@link #getBiomeAt(int, int, int)} instead - */ - @Deprecated - public int getBiomeAt(int blockX, int blockZ) { - if (dataVersion < 2202) { - if (biomes == null || biomes.length != 256) { - return -1; - } - return biomes[getBlockIndex(blockX, blockZ)]; - } else { - throw new IllegalStateException("cannot get biome using Chunk#getBiomeAt(int,int) from biome data with DataVersion of 2202 or higher, use Chunk#getBiomeAt(int,int,int) instead"); - } - } + /** + * @deprecated Use {@link #getBiomeAt(int, int, int)} instead + */ + @Deprecated + public int getBiomeAt(int blockX, int blockZ) { + if (dataVersion < 2202) { + if (biomes == null || biomes.length != 256) { + return -1; + } + return biomes[getBlockIndex(blockX, blockZ)]; + } else { + throw new IllegalStateException("cannot get biome using Chunk#getBiomeAt(int,int) from biome data with DataVersion of 2202 or higher, use Chunk#getBiomeAt(int,int,int) instead"); + } + } - /** - * Fetches a biome id at a specific block in this chunk. - * The coordinates can be absolute coordinates or relative to the region or chunk. - * @param blockX The x-coordinate of the block. - * @param blockY The y-coordinate of the block. - * @param blockZ The z-coordinate of the block. - * @return The biome id or -1 if the biomes are not correctly initialized. - */ - public int getBiomeAt(int blockX, int blockY, int blockZ) { - if (dataVersion < 2202) { - if (biomes == null || biomes.length != 256) { - return -1; - } - return biomes[getBlockIndex(blockX, blockZ)]; - } else { - if (biomes == null || biomes.length != 1024) { - return -1; - } - int biomeX = (blockX & 0xF) >> 2; - int biomeY = (blockY & 0xF) >> 2; - int biomeZ = (blockZ & 0xF) >> 2; + /** + * Fetches a biome id at a specific block in this chunk. + * The coordinates can be absolute coordinates or relative to the region or chunk. + * + * @param blockX The x-coordinate of the block. + * @param blockY The y-coordinate of the block. + * @param blockZ The z-coordinate of the block. + * @return The biome id or -1 if the biomes are not correctly initialized. + */ + public int getBiomeAt(int blockX, int blockY, int blockZ) { + if (dataVersion < 2202) { + if (biomes == null || biomes.length != 256) { + return -1; + } + return biomes[getBlockIndex(blockX, blockZ)]; + } else { + if (biomes == null || biomes.length != 1024) { + return -1; + } + int biomeX = (blockX & 0xF) >> 2; + int biomeY = (blockY & 0xF) >> 2; + int biomeZ = (blockZ & 0xF) >> 2; - return biomes[getBiomeIndex(biomeX, biomeY, biomeZ)]; - } - } + return biomes[getBiomeIndex(biomeX, biomeY, biomeZ)]; + } + } - @Deprecated - public void setBiomeAt(int blockX, int blockZ, int biomeID) { - if (dataVersion < 2202) { - if (biomes == null || biomes.length != 256) { - biomes = new int[256]; - Arrays.fill(biomes, -1); - } - biomes[getBlockIndex(blockX, blockZ)] = biomeID; - } else { - if (biomes == null || biomes.length != 1024) { - biomes = new int[1024]; - Arrays.fill(biomes, -1); - } + @Deprecated + public void setBiomeAt(int blockX, int blockZ, int biomeID) { + if (dataVersion < 2202) { + if (biomes == null || biomes.length != 256) { + biomes = new int[256]; + Arrays.fill(biomes, -1); + } + biomes[getBlockIndex(blockX, blockZ)] = biomeID; + } else { + if (biomes == null || biomes.length != 1024) { + biomes = new int[1024]; + Arrays.fill(biomes, -1); + } - int biomeX = (blockX & 0xF) >> 2; - int biomeZ = (blockZ & 0xF) >> 2; + int biomeX = (blockX & 0xF) >> 2; + int biomeZ = (blockZ & 0xF) >> 2; - for (int y = 0; y < 64; y++) { - biomes[getBiomeIndex(biomeX, y, biomeZ)] = biomeID; - } - } - } + for (int y = 0; y < 64; y++) { + biomes[getBiomeIndex(biomeX, y, biomeZ)] = biomeID; + } + } + } - /** - * Sets a biome id at a specific block column. - * The coordinates can be absolute coordinates or relative to the region or chunk. - * @param blockX The x-coordinate of the block column. - * @param blockZ The z-coordinate of the block column. - * @param biomeID The biome id to be set. - * When set to a negative number, Minecraft will replace it with the block column's default biome. - */ - public void setBiomeAt(int blockX, int blockY, int blockZ, int biomeID) { - if (dataVersion < 2202) { - if (biomes == null || biomes.length != 256) { - biomes = new int[256]; - Arrays.fill(biomes, -1); - } - biomes[getBlockIndex(blockX, blockZ)] = biomeID; - } else { - if (biomes == null || biomes.length != 1024) { - biomes = new int[1024]; - Arrays.fill(biomes, -1); - } + /** + * Sets a biome id at a specific block column. + * The coordinates can be absolute coordinates or relative to the region or chunk. + * + * @param blockX The x-coordinate of the block column. + * @param blockZ The z-coordinate of the block column. + * @param biomeID The biome id to be set. + * When set to a negative number, Minecraft will replace it with the block column's default biome. + */ + public void setBiomeAt(int blockX, int blockY, int blockZ, int biomeID) { + if (dataVersion < 2202) { + if (biomes == null || biomes.length != 256) { + biomes = new int[256]; + Arrays.fill(biomes, -1); + } + biomes[getBlockIndex(blockX, blockZ)] = biomeID; + } else { + if (biomes == null || biomes.length != 1024) { + biomes = new int[1024]; + Arrays.fill(biomes, -1); + } - int biomeX = (blockX & 0xF) >> 2; - int biomeZ = (blockZ & 0xF) >> 2; + int biomeX = (blockX & 0xF) >> 2; + int biomeZ = (blockZ & 0xF) >> 2; - biomes[getBiomeIndex(biomeX, blockY, biomeZ)] = biomeID; - } - } + biomes[getBiomeIndex(biomeX, blockY, biomeZ)] = biomeID; + } + } - int getBiomeIndex(int biomeX, int biomeY, int biomeZ) { - return biomeY * 64 + biomeZ * 4 + biomeX; - } + int getBiomeIndex(int biomeX, int biomeY, int biomeZ) { + return biomeY * 64 + biomeZ * 4 + biomeX; + } - public CompoundTag getBlockStateAt(int blockX, int blockY, int blockZ) { - Section section = sections[MCAUtil.blockToChunk(blockY)]; - if (section == null) { - return null; - } - return section.getBlockStateAt(blockX, blockY, blockZ); - } + public CompoundTag getBlockStateAt(int blockX, int blockY, int blockZ) { + Section section = sections[MCAUtil.blockToChunk(blockY)]; + if (section == null) { + return null; + } + return section.getBlockStateAt(blockX, blockY, blockZ); + } - /** - * Sets a block state at a specific location. - * The block coordinates can be absolute or relative to the region or chunk. - * @param blockX The x-coordinate of the block. - * @param blockY The y-coordinate of the block. - * @param blockZ The z-coordinate of the block. - * @param state The block state to be set. - * @param cleanup When true, it will cleanup all palettes of this chunk. - * This option should only be used moderately to avoid unnecessary recalculation of the palette indices. - * Recalculating the Palette should only be executed once right before saving the Chunk to file. - */ - public void setBlockStateAt(int blockX, int blockY, int blockZ, CompoundTag state, boolean cleanup) { - int sectionIndex = MCAUtil.blockToChunk(blockY); - Section section = sections[sectionIndex]; - if (section == null) { - section = sections[sectionIndex] = Section.newSection(); - } - section.setBlockStateAt(blockX, blockY, blockZ, state, cleanup); - } + /** + * Sets a block state at a specific location. + * The block coordinates can be absolute or relative to the region or chunk. + * + * @param blockX The x-coordinate of the block. + * @param blockY The y-coordinate of the block. + * @param blockZ The z-coordinate of the block. + * @param state The block state to be set. + * @param cleanup When true, it will cleanup all palettes of this chunk. + * This option should only be used moderately to avoid unnecessary recalculation of the palette indices. + * Recalculating the Palette should only be executed once right before saving the Chunk to file. + */ + public void setBlockStateAt(int blockX, int blockY, int blockZ, CompoundTag state, boolean cleanup) { + int sectionIndex = MCAUtil.blockToChunk(blockY); + Section section = sections[sectionIndex]; + if (section == null) { + section = sections[sectionIndex] = Section.newSection(); + } + section.setBlockStateAt(blockX, blockY, blockZ, state, cleanup); + } - /** - * @return The DataVersion of this chunk. - */ - public int getDataVersion() { - return dataVersion; - } + /** + * @return The DataVersion of this chunk. + */ + public int getDataVersion() { + return dataVersion; + } - /** - * Sets the DataVersion of this chunk. This does not check if the data of this chunk conforms - * to that DataVersion, that is the responsibility of the developer. - * @param dataVersion The DataVersion to be set. - */ - public void setDataVersion(int dataVersion) { - this.dataVersion = dataVersion; - } + /** + * Sets the DataVersion of this chunk. This does not check if the data of this chunk conforms + * to that DataVersion, that is the responsibility of the developer. + * + * @param dataVersion The DataVersion to be set. + */ + public void setDataVersion(int dataVersion) { + this.dataVersion = dataVersion; + } - /** - * @return The timestamp when this region file was last updated in seconds since 1970-01-01. - */ - public int getLastMCAUpdate() { - return lastMCAUpdate; - } + /** + * @return The timestamp when this region file was last updated in seconds since 1970-01-01. + */ + public int getLastMCAUpdate() { + return lastMCAUpdate; + } - /** - * Sets the timestamp when this region file was last updated in seconds since 1970-01-01. - * @param lastMCAUpdate The time in seconds since 1970-01-01. - */ - public void setLastMCAUpdate(int lastMCAUpdate) { - this.lastMCAUpdate = lastMCAUpdate; - } + /** + * Sets the timestamp when this region file was last updated in seconds since 1970-01-01. + * + * @param lastMCAUpdate The time in seconds since 1970-01-01. + */ + public void setLastMCAUpdate(int lastMCAUpdate) { + this.lastMCAUpdate = lastMCAUpdate; + } - /** - * @return The generation station of this chunk. - */ - public String getStatus() { - return status; - } + /** + * @return The generation station of this chunk. + */ + public String getStatus() { + return status; + } - /** - * Sets the generation status of this chunk. - * @param status The generation status of this chunk. - */ - public void setStatus(String status) { - this.status = status; - } + /** + * Sets the generation status of this chunk. + * + * @param status The generation status of this chunk. + */ + public void setStatus(String status) { + this.status = status; + } - /** - * Fetches the section at the given y-coordinate. - * @param sectionY The y-coordinate of the section in this chunk ranging from 0 to 15. - * @return The Section. - */ - public Section getSection(int sectionY) { - return sections[sectionY]; - } + /** + * Fetches the section at the given y-coordinate. + * + * @param sectionY The y-coordinate of the section in this chunk ranging from 0 to 15. + * @return The Section. + */ + public Section getSection(int sectionY) { + return sections[sectionY]; + } - /** - * Sets a section at a givesn y-coordinate - * @param sectionY The y-coordinate of the section in this chunk ranging from 0 to 15. - * @param section The section to be set. - */ - public void setSection(int sectionY, Section section) { - sections[sectionY] = section; - } + /** + * Sets a section at a givesn y-coordinate + * + * @param sectionY The y-coordinate of the section in this chunk ranging from 0 to 15. + * @param section The section to be set. + */ + public void setSection(int sectionY, Section section) { + sections[sectionY] = section; + } - /** - * @return The timestamp when this chunk was last updated as a UNIX timestamp. - */ - public long getLastUpdate() { - return lastUpdate; - } + /** + * @return The timestamp when this chunk was last updated as a UNIX timestamp. + */ + public long getLastUpdate() { + return lastUpdate; + } - /** - * Sets the time when this chunk was last updated as a UNIX timestamp. - * @param lastUpdate The UNIX timestamp. - */ - public void setLastUpdate(long lastUpdate) { - this.lastUpdate = lastUpdate; - } + /** + * Sets the time when this chunk was last updated as a UNIX timestamp. + * + * @param lastUpdate The UNIX timestamp. + */ + public void setLastUpdate(long lastUpdate) { + this.lastUpdate = lastUpdate; + } - /** - * @return The cumulative amount of time players have spent in this chunk in ticks. - */ - public long getInhabitedTime() { - return inhabitedTime; - } + /** + * @return The cumulative amount of time players have spent in this chunk in ticks. + */ + public long getInhabitedTime() { + return inhabitedTime; + } - /** - * Sets the cumulative amount of time players have spent in this chunk in ticks. - * @param inhabitedTime The time in ticks. - */ - public void setInhabitedTime(long inhabitedTime) { - this.inhabitedTime = inhabitedTime; - } + /** + * Sets the cumulative amount of time players have spent in this chunk in ticks. + * + * @param inhabitedTime The time in ticks. + */ + public void setInhabitedTime(long inhabitedTime) { + this.inhabitedTime = inhabitedTime; + } - /** - * @return A matrix of biome IDs for all block columns in this chunk. - */ - public int[] getBiomes() { - return biomes; - } + /** + * @return A matrix of biome IDs for all block columns in this chunk. + */ + public int[] getBiomes() { + return biomes; + } - /** - * Sets the biome IDs for this chunk. - * @param biomes The biome ID matrix of this chunk. Must have a length of 256. - * @throws IllegalArgumentException When the biome matrix does not have a length of 256 - * or is null - */ - public void setBiomes(int[] biomes) { - if (biomes != null) { - if (dataVersion < 2202 && biomes.length != 256 || dataVersion >= 2202 && biomes.length != 1024) { - throw new IllegalArgumentException("biomes array must have a length of " + (dataVersion < 2202 ? "256" : "1024")); - } - } - this.biomes = biomes; - } + /** + * Sets the biome IDs for this chunk. + * + * @param biomes The biome ID matrix of this chunk. Must have a length of 256. + * @throws IllegalArgumentException When the biome matrix does not have a length of 256 + * or is null + */ + public void setBiomes(int[] biomes) { + if (biomes != null) { + if (dataVersion < 2202 && biomes.length != 256 || dataVersion >= 2202 && biomes.length != 1024) { + throw new IllegalArgumentException("biomes array must have a length of " + (dataVersion < 2202 ? "256" : "1024")); + } + } + this.biomes = biomes; + } - /** - * @return The height maps of this chunk. - */ - public CompoundTag getHeightMaps() { - return heightMaps; - } + /** + * @return The height maps of this chunk. + */ + public CompoundTag getHeightMaps() { + return heightMaps; + } - /** - * Sets the height maps of this chunk. - * @param heightMaps The height maps. - */ - public void setHeightMaps(CompoundTag heightMaps) { - this.heightMaps = heightMaps; - } + /** + * Sets the height maps of this chunk. + * + * @param heightMaps The height maps. + */ + public void setHeightMaps(CompoundTag heightMaps) { + this.heightMaps = heightMaps; + } - /** - * @return The carving masks of this chunk. - */ - public CompoundTag getCarvingMasks() { - return carvingMasks; - } + /** + * @return The carving masks of this chunk. + */ + public CompoundTag getCarvingMasks() { + return carvingMasks; + } - /** - * Sets the carving masks of this chunk. - * @param carvingMasks The carving masks. - */ - public void setCarvingMasks(CompoundTag carvingMasks) { - this.carvingMasks = carvingMasks; - } + /** + * Sets the carving masks of this chunk. + * + * @param carvingMasks The carving masks. + */ + public void setCarvingMasks(CompoundTag carvingMasks) { + this.carvingMasks = carvingMasks; + } - /** - * @return The entities of this chunk. - */ - public ListTag getEntities() { - return entities; - } + /** + * @return The entities of this chunk. + */ + public ListTag getEntities() { + return entities; + } - /** - * Sets the entities of this chunk. - * @param entities The entities. - */ - public void setEntities(ListTag entities) { - this.entities = entities; - } + /** + * Sets the entities of this chunk. + * + * @param entities The entities. + */ + public void setEntities(ListTag entities) { + this.entities = entities; + } - /** - * @return The tile entities of this chunk. - */ - public ListTag getTileEntities() { - return tileEntities; - } + /** + * @return The tile entities of this chunk. + */ + public ListTag getTileEntities() { + return tileEntities; + } - /** - * Sets the tile entities of this chunk. - * @param tileEntities The tile entities of this chunk. - */ - public void setTileEntities(ListTag tileEntities) { - this.tileEntities = tileEntities; - } + /** + * Sets the tile entities of this chunk. + * + * @param tileEntities The tile entities of this chunk. + */ + public void setTileEntities(ListTag tileEntities) { + this.tileEntities = tileEntities; + } - /** - * @return The tile ticks of this chunk. - */ - public ListTag getTileTicks() { - return tileTicks; - } + /** + * @return The tile ticks of this chunk. + */ + public ListTag getTileTicks() { + return tileTicks; + } - /** - * Sets the tile ticks of this chunk. - * @param tileTicks Thee tile ticks. - */ - public void setTileTicks(ListTag tileTicks) { - this.tileTicks = tileTicks; - } + /** + * Sets the tile ticks of this chunk. + * + * @param tileTicks Thee tile ticks. + */ + public void setTileTicks(ListTag tileTicks) { + this.tileTicks = tileTicks; + } - /** - * @return The liquid ticks of this chunk. - */ - public ListTag getLiquidTicks() { - return liquidTicks; - } + /** + * @return The liquid ticks of this chunk. + */ + public ListTag getLiquidTicks() { + return liquidTicks; + } - /** - * Sets the liquid ticks of this chunk. - * @param liquidTicks The liquid ticks. - */ - public void setLiquidTicks(ListTag liquidTicks) { - this.liquidTicks = liquidTicks; - } + /** + * Sets the liquid ticks of this chunk. + * + * @param liquidTicks The liquid ticks. + */ + public void setLiquidTicks(ListTag liquidTicks) { + this.liquidTicks = liquidTicks; + } - /** - * @return The light sources in this chunk. - */ - public ListTag> getLights() { - return lights; - } + /** + * @return The light sources in this chunk. + */ + public ListTag> getLights() { + return lights; + } - /** - * Sets the light sources in this chunk. - * @param lights The light sources. - */ - public void setLights(ListTag> lights) { - this.lights = lights; - } + /** + * Sets the light sources in this chunk. + * + * @param lights The light sources. + */ + public void setLights(ListTag> lights) { + this.lights = lights; + } - /** - * @return THe liquids to be ticked in this chunk. - */ - public ListTag> getLiquidsToBeTicked() { - return liquidsToBeTicked; - } + /** + * @return THe liquids to be ticked in this chunk. + */ + public ListTag> getLiquidsToBeTicked() { + return liquidsToBeTicked; + } - /** - * Sets the liquids to be ticked in this chunk. - * @param liquidsToBeTicked The liquids to be ticked. - */ - public void setLiquidsToBeTicked(ListTag> liquidsToBeTicked) { - this.liquidsToBeTicked = liquidsToBeTicked; - } + /** + * Sets the liquids to be ticked in this chunk. + * + * @param liquidsToBeTicked The liquids to be ticked. + */ + public void setLiquidsToBeTicked(ListTag> liquidsToBeTicked) { + this.liquidsToBeTicked = liquidsToBeTicked; + } - /** - * @return Stuff to be ticked in this chunk. - */ - public ListTag> getToBeTicked() { - return toBeTicked; - } + /** + * @return Stuff to be ticked in this chunk. + */ + public ListTag> getToBeTicked() { + return toBeTicked; + } - /** - * Sets stuff to be ticked in this chunk. - * @param toBeTicked The stuff to be ticked. - */ - public void setToBeTicked(ListTag> toBeTicked) { - this.toBeTicked = toBeTicked; - } + /** + * Sets stuff to be ticked in this chunk. + * + * @param toBeTicked The stuff to be ticked. + */ + public void setToBeTicked(ListTag> toBeTicked) { + this.toBeTicked = toBeTicked; + } - /** - * @return Things that are in post processing in this chunk. - */ - public ListTag> getPostProcessing() { - return postProcessing; - } + /** + * @return Things that are in post processing in this chunk. + */ + public ListTag> getPostProcessing() { + return postProcessing; + } - /** - * Sets things to be post processed in this chunk. - * @param postProcessing The things to be post processed. - */ - public void setPostProcessing(ListTag> postProcessing) { - this.postProcessing = postProcessing; - } + /** + * Sets things to be post processed in this chunk. + * + * @param postProcessing The things to be post processed. + */ + public void setPostProcessing(ListTag> postProcessing) { + this.postProcessing = postProcessing; + } - /** - * @return Data about structures in this chunk. - */ - public CompoundTag getStructures() { - return structures; - } + /** + * @return Data about structures in this chunk. + */ + public CompoundTag getStructures() { + return structures; + } - /** - * Sets data about structures in this chunk. - * @param structures The data about structures. - */ - public void setStructures(CompoundTag structures) { - this.structures = structures; - } + /** + * Sets data about structures in this chunk. + * + * @param structures The data about structures. + */ + public void setStructures(CompoundTag structures) { + this.structures = structures; + } - int getBlockIndex(int blockX, int blockZ) { - return (blockZ & 0xF) * 16 + (blockX & 0xF); - } + int getBlockIndex(int blockX, int blockZ) { + return (blockZ & 0xF) * 16 + (blockX & 0xF); + } - public void cleanupPalettesAndBlockStates() { - for (Section section : sections) { - if (section != null) { - section.cleanupPaletteAndBlockStates(); - } - } - } + public void cleanupPalettesAndBlockStates() { + for (Section section : sections) { + if (section != null) { + section.cleanupPaletteAndBlockStates(); + } + } + } - public static Chunk newChunk() { - Chunk c = new Chunk(0); - c.dataVersion = DEFAULT_DATA_VERSION; - c.data = new CompoundTag(); - c.data.put("Level", new CompoundTag()); - c.status = "mobs_spawned"; - return c; - } + public static Chunk newChunk() { + Chunk c = new Chunk(0); + c.dataVersion = DEFAULT_DATA_VERSION; + c.data = new CompoundTag(); + c.data.put("Level", new CompoundTag()); + c.status = "mobs_spawned"; + return c; + } - public CompoundTag updateHandle(int xPos, int zPos) { - data.putInt("DataVersion", dataVersion); - CompoundTag level = data.getCompoundTag("Level"); - level.putInt("xPos", xPos); - level.putInt("zPos", zPos); - level.putLong("LastUpdate", lastUpdate); - level.putLong("InhabitedTime", inhabitedTime); - if (dataVersion < 2202) { - if (biomes != null && biomes.length == 256) level.putIntArray("Biomes", biomes); - } else { - if (biomes != null && biomes.length == 1024) level.putIntArray("Biomes", biomes); - } - if (heightMaps != null) level.put("Heightmaps", heightMaps); - if (carvingMasks != null) level.put("CarvingMasks", carvingMasks); - if (entities != null) level.put("Entities", entities); - if (tileEntities != null) level.put("TileEntities", tileEntities); - if (tileTicks != null) level.put("TileTicks", tileTicks); - if (liquidTicks != null) level.put("LiquidTicks", liquidTicks); - if (lights != null) level.put("Lights", lights); - if (liquidsToBeTicked != null) level.put("LiquidsToBeTicked", liquidsToBeTicked); - if (toBeTicked != null) level.put("ToBeTicked", toBeTicked); - if (postProcessing != null) level.put("PostProcessing", postProcessing); - level.putString("Status", status); - if (structures != null) level.put("Structures", structures); - ListTag sections = new ListTag<>(CompoundTag.class); - for (int i = 0; i < this.sections.length; i++) { - if (this.sections[i] != null) { - sections.add(this.sections[i].updateHandle(i)); - } - } - level.put("Sections", sections); - return data; - } + public CompoundTag updateHandle(int xPos, int zPos) { + data.putInt("DataVersion", dataVersion); + CompoundTag level = data.getCompoundTag("Level"); + level.putInt("xPos", xPos); + level.putInt("zPos", zPos); + level.putLong("LastUpdate", lastUpdate); + level.putLong("InhabitedTime", inhabitedTime); + if (dataVersion < 2202) { + if (biomes != null && biomes.length == 256) level.putIntArray("Biomes", biomes); + } else { + if (biomes != null && biomes.length == 1024) level.putIntArray("Biomes", biomes); + } + if (heightMaps != null) level.put("Heightmaps", heightMaps); + if (carvingMasks != null) level.put("CarvingMasks", carvingMasks); + if (entities != null) level.put("Entities", entities); + if (tileEntities != null) level.put("TileEntities", tileEntities); + if (tileTicks != null) level.put("TileTicks", tileTicks); + if (liquidTicks != null) level.put("LiquidTicks", liquidTicks); + if (lights != null) level.put("Lights", lights); + if (liquidsToBeTicked != null) level.put("LiquidsToBeTicked", liquidsToBeTicked); + if (toBeTicked != null) level.put("ToBeTicked", toBeTicked); + if (postProcessing != null) level.put("PostProcessing", postProcessing); + level.putString("Status", status); + if (structures != null) level.put("Structures", structures); + ListTag sections = new ListTag<>(CompoundTag.class); + for (int i = 0; i < this.sections.length; i++) { + if (this.sections[i] != null) { + sections.add(this.sections[i].updateHandle(i)); + } + } + level.put("Sections", sections); + return data; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/mca/CompressionType.java b/src/main/java/com/volmit/iris/scaffold/data/mca/CompressionType.java index ef470ae3a..d50dd4add 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/mca/CompressionType.java +++ b/src/main/java/com/volmit/iris/scaffold/data/mca/CompressionType.java @@ -10,40 +10,40 @@ import java.util.zip.InflaterInputStream; public enum CompressionType { - NONE(0, t -> t, t -> t), - GZIP(1, GZIPOutputStream::new, GZIPInputStream::new), - ZLIB(2, DeflaterOutputStream::new, InflaterInputStream::new); + NONE(0, t -> t, t -> t), + GZIP(1, GZIPOutputStream::new, GZIPInputStream::new), + ZLIB(2, DeflaterOutputStream::new, InflaterInputStream::new); - private byte id; - private ExceptionFunction compressor; - private ExceptionFunction decompressor; + private final byte id; + private final ExceptionFunction compressor; + private final ExceptionFunction decompressor; - CompressionType(int id, - ExceptionFunction compressor, - ExceptionFunction decompressor) { - this.id = (byte) id; - this.compressor = compressor; - this.decompressor = decompressor; - } + CompressionType(int id, + ExceptionFunction compressor, + ExceptionFunction decompressor) { + this.id = (byte) id; + this.compressor = compressor; + this.decompressor = decompressor; + } - public byte getID() { - return id; - } + public byte getID() { + return id; + } - public OutputStream compress(OutputStream out) throws IOException { - return compressor.accept(out); - } + public OutputStream compress(OutputStream out) throws IOException { + return compressor.accept(out); + } - public InputStream decompress(InputStream in) throws IOException { - return decompressor.accept(in); - } + public InputStream decompress(InputStream in) throws IOException { + return decompressor.accept(in); + } - public static CompressionType getFromID(byte id) { - for (CompressionType c : CompressionType.values()) { - if (c.id == id) { - return c; - } - } - return null; - } + public static CompressionType getFromID(byte id) { + for (CompressionType c : CompressionType.values()) { + if (c.id == id) { + return c; + } + } + return null; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/mca/ExceptionFunction.java b/src/main/java/com/volmit/iris/scaffold/data/mca/ExceptionFunction.java index da09daac6..2b7afe1a0 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/mca/ExceptionFunction.java +++ b/src/main/java/com/volmit/iris/scaffold/data/mca/ExceptionFunction.java @@ -3,5 +3,5 @@ package com.volmit.iris.scaffold.data.mca; @FunctionalInterface public interface ExceptionFunction { - R accept(T t) throws E; + R accept(T t) throws E; } diff --git a/src/main/java/com/volmit/iris/scaffold/data/mca/LoadFlags.java b/src/main/java/com/volmit/iris/scaffold/data/mca/LoadFlags.java index 1cd570cb4..4b19a6d79 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/mca/LoadFlags.java +++ b/src/main/java/com/volmit/iris/scaffold/data/mca/LoadFlags.java @@ -2,23 +2,23 @@ package com.volmit.iris.scaffold.data.mca; public class LoadFlags { - public static long BIOMES = 0x0001; - public static long HEIGHTMAPS = 0x0002; - public static long CARVING_MASKS = 0x0004; - public static long ENTITIES = 0x0008; - public static long TILE_ENTITIES = 0x0010; - public static long TILE_TICKS = 0x0040; - public static long LIQUID_TICKS = 0x0080; - public static long TO_BE_TICKED = 0x0100; - public static long POST_PROCESSING = 0x0200; - public static long STRUCTURES = 0x0400; - public static long BLOCK_LIGHTS = 0x0800; - public static long BLOCK_STATES = 0x1000; - public static long SKY_LIGHT = 0x2000; - public static long LIGHTS = 0x4000; - public static long LIQUIDS_TO_BE_TICKED = 0x8000; + public static long BIOMES = 0x0001; + public static long HEIGHTMAPS = 0x0002; + public static long CARVING_MASKS = 0x0004; + public static long ENTITIES = 0x0008; + public static long TILE_ENTITIES = 0x0010; + public static long TILE_TICKS = 0x0040; + public static long LIQUID_TICKS = 0x0080; + public static long TO_BE_TICKED = 0x0100; + public static long POST_PROCESSING = 0x0200; + public static long STRUCTURES = 0x0400; + public static long BLOCK_LIGHTS = 0x0800; + public static long BLOCK_STATES = 0x1000; + public static long SKY_LIGHT = 0x2000; + public static long LIGHTS = 0x4000; + public static long LIQUIDS_TO_BE_TICKED = 0x8000; - public static long ALL_DATA = 0xffffffffffffffffL; + public static long ALL_DATA = 0xffffffffffffffffL; } diff --git a/src/main/java/com/volmit/iris/scaffold/data/mca/MCAFile.java b/src/main/java/com/volmit/iris/scaffold/data/mca/MCAFile.java index 449bb2734..c110be66b 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/mca/MCAFile.java +++ b/src/main/java/com/volmit/iris/scaffold/data/mca/MCAFile.java @@ -1,300 +1,314 @@ package com.volmit.iris.scaffold.data.mca; import com.volmit.iris.scaffold.data.nbt.tag.CompoundTag; + import java.io.IOException; import java.io.RandomAccessFile; public class MCAFile { - /** - * The default chunk data version used when no custom version is supplied. - * */ - public static final int DEFAULT_DATA_VERSION = 1628; + /** + * The default chunk data version used when no custom version is supplied. + */ + public static final int DEFAULT_DATA_VERSION = 1628; - private int regionX, regionZ; - private Chunk[] chunks; + private final int regionX; + private final int regionZ; + private Chunk[] chunks; - /** - * MCAFile represents a world save file used by Minecraft to store world - * data on the hard drive. - * This constructor needs the x- and z-coordinates of the stored region, - * which can usually be taken from the file name {@code r.x.z.mca} - * @param regionX The x-coordinate of this region. - * @param regionZ The z-coordinate of this region. - * */ - public MCAFile(int regionX, int regionZ) { - this.regionX = regionX; - this.regionZ = regionZ; - } + /** + * MCAFile represents a world save file used by Minecraft to store world + * data on the hard drive. + * This constructor needs the x- and z-coordinates of the stored region, + * which can usually be taken from the file name {@code r.x.z.mca} + * + * @param regionX The x-coordinate of this region. + * @param regionZ The z-coordinate of this region. + */ + public MCAFile(int regionX, int regionZ) { + this.regionX = regionX; + this.regionZ = regionZ; + } - /** - * Reads an .mca file from a {@code RandomAccessFile} into this object. - * This method does not perform any cleanups on the data. - * @param raf The {@code RandomAccessFile} to read from. - * @throws IOException If something went wrong during deserialization. - * */ - public void deserialize(RandomAccessFile raf) throws IOException { - deserialize(raf, LoadFlags.ALL_DATA); - } + /** + * Reads an .mca file from a {@code RandomAccessFile} into this object. + * This method does not perform any cleanups on the data. + * + * @param raf The {@code RandomAccessFile} to read from. + * @throws IOException If something went wrong during deserialization. + */ + public void deserialize(RandomAccessFile raf) throws IOException { + deserialize(raf, LoadFlags.ALL_DATA); + } - /** - * Reads an .mca file from a {@code RandomAccessFile} into this object. - * This method does not perform any cleanups on the data. - * @param raf The {@code RandomAccessFile} to read from. - * @param loadFlags A logical or of {@link LoadFlags} constants indicating what data should be loaded - * @throws IOException If something went wrong during deserialization. - * */ - public void deserialize(RandomAccessFile raf, long loadFlags) throws IOException { - chunks = new Chunk[1024]; - for (int i = 0; i < 1024; i++) { - raf.seek(i * 4); - int offset = raf.read() << 16; - offset |= (raf.read() & 0xFF) << 8; - offset |= raf.read() & 0xFF; - if (raf.readByte() == 0) { - continue; - } - raf.seek(4096 + i * 4); - int timestamp = raf.readInt(); - Chunk chunk = new Chunk(timestamp); - raf.seek(4096 * offset + 4); //+4: skip data size - chunk.deserialize(raf, loadFlags); - chunks[i] = chunk; - } - } + /** + * Reads an .mca file from a {@code RandomAccessFile} into this object. + * This method does not perform any cleanups on the data. + * + * @param raf The {@code RandomAccessFile} to read from. + * @param loadFlags A logical or of {@link LoadFlags} constants indicating what data should be loaded + * @throws IOException If something went wrong during deserialization. + */ + public void deserialize(RandomAccessFile raf, long loadFlags) throws IOException { + chunks = new Chunk[1024]; + for (int i = 0; i < 1024; i++) { + raf.seek(i * 4); + int offset = raf.read() << 16; + offset |= (raf.read() & 0xFF) << 8; + offset |= raf.read() & 0xFF; + if (raf.readByte() == 0) { + continue; + } + raf.seek(4096 + i * 4); + int timestamp = raf.readInt(); + Chunk chunk = new Chunk(timestamp); + raf.seek(4096 * offset + 4); //+4: skip data size + chunk.deserialize(raf, loadFlags); + chunks[i] = chunk; + } + } - public Chunk[] getChunks() - { - return chunks; - } + public Chunk[] getChunks() { + return chunks; + } - /** - * Calls {@link MCAFile#serialize(RandomAccessFile, boolean)} without updating any timestamps. - * @see MCAFile#serialize(RandomAccessFile, boolean) - * @param raf The {@code RandomAccessFile} to write to. - * @return The amount of chunks written to the file. - * @throws IOException If something went wrong during serialization. - * */ - public int serialize(RandomAccessFile raf) throws IOException { - return serialize(raf, false); - } + /** + * Calls {@link MCAFile#serialize(RandomAccessFile, boolean)} without updating any timestamps. + * + * @param raf The {@code RandomAccessFile} to write to. + * @return The amount of chunks written to the file. + * @throws IOException If something went wrong during serialization. + * @see MCAFile#serialize(RandomAccessFile, boolean) + */ + public int serialize(RandomAccessFile raf) throws IOException { + return serialize(raf, false); + } - /** - * Serializes this object to an .mca file. - * This method does not perform any cleanups on the data. - * @param raf The {@code RandomAccessFile} to write to. - * @param changeLastUpdate Whether it should update all timestamps that show - * when this file was last updated. - * @return The amount of chunks written to the file. - * @throws IOException If something went wrong during serialization. - * */ - public int serialize(RandomAccessFile raf, boolean changeLastUpdate) throws IOException { - int globalOffset = 2; - int lastWritten = 0; - int timestamp = (int) (System.currentTimeMillis() / 1000L); - int chunksWritten = 0; - int chunkXOffset = MCAUtil.regionToChunk(regionX); - int chunkZOffset = MCAUtil.regionToChunk(regionZ); + /** + * Serializes this object to an .mca file. + * This method does not perform any cleanups on the data. + * + * @param raf The {@code RandomAccessFile} to write to. + * @param changeLastUpdate Whether it should update all timestamps that show + * when this file was last updated. + * @return The amount of chunks written to the file. + * @throws IOException If something went wrong during serialization. + */ + public int serialize(RandomAccessFile raf, boolean changeLastUpdate) throws IOException { + int globalOffset = 2; + int lastWritten = 0; + int timestamp = (int) (System.currentTimeMillis() / 1000L); + int chunksWritten = 0; + int chunkXOffset = MCAUtil.regionToChunk(regionX); + int chunkZOffset = MCAUtil.regionToChunk(regionZ); - if (chunks == null) { - return 0; - } + if (chunks == null) { + return 0; + } - for (int cx = 0; cx < 32; cx++) { - for (int cz = 0; cz < 32; cz++) { - int index = getChunkIndex(cx, cz); - Chunk chunk = chunks[index]; - if (chunk == null) { - continue; - } - raf.seek(4096 * globalOffset); - lastWritten = chunk.serialize(raf, chunkXOffset + cx, chunkZOffset + cz); + for (int cx = 0; cx < 32; cx++) { + for (int cz = 0; cz < 32; cz++) { + int index = getChunkIndex(cx, cz); + Chunk chunk = chunks[index]; + if (chunk == null) { + continue; + } + raf.seek(4096 * globalOffset); + lastWritten = chunk.serialize(raf, chunkXOffset + cx, chunkZOffset + cz); - if (lastWritten == 0) { - continue; - } + if (lastWritten == 0) { + continue; + } - chunksWritten++; + chunksWritten++; - int sectors = (lastWritten >> 12) + (lastWritten % 4096 == 0 ? 0 : 1); + int sectors = (lastWritten >> 12) + (lastWritten % 4096 == 0 ? 0 : 1); - raf.seek(index * 4); - raf.writeByte(globalOffset >>> 16); - raf.writeByte(globalOffset >> 8 & 0xFF); - raf.writeByte(globalOffset & 0xFF); - raf.writeByte(sectors); + raf.seek(index * 4); + raf.writeByte(globalOffset >>> 16); + raf.writeByte(globalOffset >> 8 & 0xFF); + raf.writeByte(globalOffset & 0xFF); + raf.writeByte(sectors); - // write timestamp - raf.seek(index * 4 + 4096); - raf.writeInt(changeLastUpdate ? timestamp : chunk.getLastMCAUpdate()); + // write timestamp + raf.seek(index * 4 + 4096); + raf.writeInt(changeLastUpdate ? timestamp : chunk.getLastMCAUpdate()); - globalOffset += sectors; - } - } + globalOffset += sectors; + } + } - // padding - if (lastWritten % 4096 != 0) { - raf.seek(globalOffset * 4096 - 1); - raf.write(0); - } - return chunksWritten; - } + // padding + if (lastWritten % 4096 != 0) { + raf.seek(globalOffset * 4096 - 1); + raf.write(0); + } + return chunksWritten; + } - /** - * Set a specific Chunk at a specific index. The index must be in range of 0 - 1023. - * @param index The index of the Chunk. - * @param chunk The Chunk to be set. - * @throws IndexOutOfBoundsException If index is not in the range. - */ - public void setChunk(int index, Chunk chunk) { - checkIndex(index); - if (chunks == null) { - chunks = new Chunk[1024]; - } - chunks[index] = chunk; - } + /** + * Set a specific Chunk at a specific index. The index must be in range of 0 - 1023. + * + * @param index The index of the Chunk. + * @param chunk The Chunk to be set. + * @throws IndexOutOfBoundsException If index is not in the range. + */ + public void setChunk(int index, Chunk chunk) { + checkIndex(index); + if (chunks == null) { + chunks = new Chunk[1024]; + } + chunks[index] = chunk; + } - /** - * Set a specific Chunk at a specific chunk location. - * The x- and z-value can be absolute chunk coordinates or they can be relative to the region origin. - * @param chunkX The x-coordinate of the Chunk. - * @param chunkZ The z-coordinate of the Chunk. - * @param chunk The chunk to be set. - */ - public void setChunk(int chunkX, int chunkZ, Chunk chunk) { - setChunk(getChunkIndex(chunkX, chunkZ), chunk); - } + /** + * Set a specific Chunk at a specific chunk location. + * The x- and z-value can be absolute chunk coordinates or they can be relative to the region origin. + * + * @param chunkX The x-coordinate of the Chunk. + * @param chunkZ The z-coordinate of the Chunk. + * @param chunk The chunk to be set. + */ + public void setChunk(int chunkX, int chunkZ, Chunk chunk) { + setChunk(getChunkIndex(chunkX, chunkZ), chunk); + } - /** - * Returns the chunk data of a chunk at a specific index in this file. - * @param index The index of the chunk in this file. - * @return The chunk data. - * */ - public Chunk getChunk(int index) { - checkIndex(index); - if (chunks == null) { - return null; - } - return chunks[index]; - } + /** + * Returns the chunk data of a chunk at a specific index in this file. + * + * @param index The index of the chunk in this file. + * @return The chunk data. + */ + public Chunk getChunk(int index) { + checkIndex(index); + if (chunks == null) { + return null; + } + return chunks[index]; + } - /** - * Returns the chunk data of a chunk in this file. - * @param chunkX The x-coordinate of the chunk. - * @param chunkZ The z-coordinate of the chunk. - * @return The chunk data. - * */ - public Chunk getChunk(int chunkX, int chunkZ) { - return getChunk(getChunkIndex(chunkX, chunkZ)); - } + /** + * Returns the chunk data of a chunk in this file. + * + * @param chunkX The x-coordinate of the chunk. + * @param chunkZ The z-coordinate of the chunk. + * @return The chunk data. + */ + public Chunk getChunk(int chunkX, int chunkZ) { + return getChunk(getChunkIndex(chunkX, chunkZ)); + } - /** - * Calculates the index of a chunk from its x- and z-coordinates in this region. - * This works with absolute and relative coordinates. - * @param chunkX The x-coordinate of the chunk. - * @param chunkZ The z-coordinate of the chunk. - * @return The index of this chunk. - * */ - public static int getChunkIndex(int chunkX, int chunkZ) { - return (chunkX & 0x1F) + (chunkZ & 0x1F) * 32; - } + /** + * Calculates the index of a chunk from its x- and z-coordinates in this region. + * This works with absolute and relative coordinates. + * + * @param chunkX The x-coordinate of the chunk. + * @param chunkZ The z-coordinate of the chunk. + * @return The index of this chunk. + */ + public static int getChunkIndex(int chunkX, int chunkZ) { + return (chunkX & 0x1F) + (chunkZ & 0x1F) * 32; + } - private int checkIndex(int index) { - if (index < 0 || index > 1023) { - throw new IndexOutOfBoundsException(); - } - return index; - } + private int checkIndex(int index) { + if (index < 0 || index > 1023) { + throw new IndexOutOfBoundsException(); + } + return index; + } - private Chunk createChunkIfMissing(int blockX, int blockZ) { - int chunkX = MCAUtil.blockToChunk(blockX), chunkZ = MCAUtil.blockToChunk(blockZ); - Chunk chunk = getChunk(chunkX, chunkZ); - if (chunk == null) { - chunk = Chunk.newChunk(); - setChunk(getChunkIndex(chunkX, chunkZ), chunk); - } - return chunk; - } + private Chunk createChunkIfMissing(int blockX, int blockZ) { + int chunkX = MCAUtil.blockToChunk(blockX), chunkZ = MCAUtil.blockToChunk(blockZ); + Chunk chunk = getChunk(chunkX, chunkZ); + if (chunk == null) { + chunk = Chunk.newChunk(); + setChunk(getChunkIndex(chunkX, chunkZ), chunk); + } + return chunk; + } - /** - * @deprecated Use {@link #setBiomeAt(int, int, int, int)} instead - */ - @Deprecated - public void setBiomeAt(int blockX, int blockZ, int biomeID) { - createChunkIfMissing(blockX, blockZ).setBiomeAt(blockX, blockZ, biomeID); - } + /** + * @deprecated Use {@link #setBiomeAt(int, int, int, int)} instead + */ + @Deprecated + public void setBiomeAt(int blockX, int blockZ, int biomeID) { + createChunkIfMissing(blockX, blockZ).setBiomeAt(blockX, blockZ, biomeID); + } - public void setBiomeAt(int blockX, int blockY, int blockZ, int biomeID) { - createChunkIfMissing(blockX, blockZ).setBiomeAt(blockX, blockY, blockZ, biomeID); - } + public void setBiomeAt(int blockX, int blockY, int blockZ, int biomeID) { + createChunkIfMissing(blockX, blockZ).setBiomeAt(blockX, blockY, blockZ, biomeID); + } - /** - * @deprecated Use {@link #getBiomeAt(int, int, int)} instead - */ - @Deprecated - public int getBiomeAt(int blockX, int blockZ) { - int chunkX = MCAUtil.blockToChunk(blockX), chunkZ = MCAUtil.blockToChunk(blockZ); - Chunk chunk = getChunk(getChunkIndex(chunkX, chunkZ)); - if (chunk == null) { - return -1; - } - return chunk.getBiomeAt(blockX, blockZ); - } + /** + * @deprecated Use {@link #getBiomeAt(int, int, int)} instead + */ + @Deprecated + public int getBiomeAt(int blockX, int blockZ) { + int chunkX = MCAUtil.blockToChunk(blockX), chunkZ = MCAUtil.blockToChunk(blockZ); + Chunk chunk = getChunk(getChunkIndex(chunkX, chunkZ)); + if (chunk == null) { + return -1; + } + return chunk.getBiomeAt(blockX, blockZ); + } - /** - * Fetches the biome id at a specific block. - * @param blockX The x-coordinate of the block. - * @param blockY The y-coordinate of the block. - * @param blockZ The z-coordinate of the block. - * @return The biome id if the chunk exists and the chunk has biomes, otherwise -1. - */ - public int getBiomeAt(int blockX, int blockY, int blockZ) { - int chunkX = MCAUtil.blockToChunk(blockX), chunkZ = MCAUtil.blockToChunk(blockZ); - Chunk chunk = getChunk(getChunkIndex(chunkX, chunkZ)); - if (chunk == null) { - return -1; - } - return chunk.getBiomeAt(blockX,blockY, blockZ); - } + /** + * Fetches the biome id at a specific block. + * + * @param blockX The x-coordinate of the block. + * @param blockY The y-coordinate of the block. + * @param blockZ The z-coordinate of the block. + * @return The biome id if the chunk exists and the chunk has biomes, otherwise -1. + */ + public int getBiomeAt(int blockX, int blockY, int blockZ) { + int chunkX = MCAUtil.blockToChunk(blockX), chunkZ = MCAUtil.blockToChunk(blockZ); + Chunk chunk = getChunk(getChunkIndex(chunkX, chunkZ)); + if (chunk == null) { + return -1; + } + return chunk.getBiomeAt(blockX, blockY, blockZ); + } - /** - * Set a block state at a specific block location. - * The block coordinates can be absolute coordinates or they can be relative to the region. - * @param blockX The x-coordinate of the block. - * @param blockY The y-coordinate of the block. - * @param blockZ The z-coordinate of the block. - * @param state The block state to be set. - * @param cleanup Whether the Palette and the BLockStates should be recalculated after adding the block state. - */ - public void setBlockStateAt(int blockX, int blockY, int blockZ, CompoundTag state, boolean cleanup) { - createChunkIfMissing(blockX, blockZ).setBlockStateAt(blockX, blockY, blockZ, state, cleanup); - } + /** + * Set a block state at a specific block location. + * The block coordinates can be absolute coordinates or they can be relative to the region. + * + * @param blockX The x-coordinate of the block. + * @param blockY The y-coordinate of the block. + * @param blockZ The z-coordinate of the block. + * @param state The block state to be set. + * @param cleanup Whether the Palette and the BLockStates should be recalculated after adding the block state. + */ + public void setBlockStateAt(int blockX, int blockY, int blockZ, CompoundTag state, boolean cleanup) { + createChunkIfMissing(blockX, blockZ).setBlockStateAt(blockX, blockY, blockZ, state, cleanup); + } - /** - * Fetches a block state at a specific block location. - * The block coordinates can be absolute coordinates or they can be relative to the region. - * @param blockX The x-coordinate of the block. - * @param blockY The y-coordinate of the block. - * @param blockZ The z-coordinate of the block. - * @return The block state or null if the chunk or the section do not exist. - */ - public CompoundTag getBlockStateAt(int blockX, int blockY, int blockZ) { - int chunkX = MCAUtil.blockToChunk(blockX), chunkZ = MCAUtil.blockToChunk(blockZ); - Chunk chunk = getChunk(chunkX, chunkZ); - if (chunk == null) { - return null; - } - return chunk.getBlockStateAt(blockX, blockY, blockZ); - } + /** + * Fetches a block state at a specific block location. + * The block coordinates can be absolute coordinates or they can be relative to the region. + * + * @param blockX The x-coordinate of the block. + * @param blockY The y-coordinate of the block. + * @param blockZ The z-coordinate of the block. + * @return The block state or null if the chunk or the section do not exist. + */ + public CompoundTag getBlockStateAt(int blockX, int blockY, int blockZ) { + int chunkX = MCAUtil.blockToChunk(blockX), chunkZ = MCAUtil.blockToChunk(blockZ); + Chunk chunk = getChunk(chunkX, chunkZ); + if (chunk == null) { + return null; + } + return chunk.getBlockStateAt(blockX, blockY, blockZ); + } - /** - * Recalculates the Palette and the BlockStates of all chunks and sections of this region. - */ - public void cleanupPalettesAndBlockStates() { - for (Chunk chunk : chunks) { - if (chunk != null) { - chunk.cleanupPalettesAndBlockStates(); - } - } - } + /** + * Recalculates the Palette and the BlockStates of all chunks and sections of this region. + */ + public void cleanupPalettesAndBlockStates() { + for (Chunk chunk : chunks) { + if (chunk != null) { + chunk.cleanupPalettesAndBlockStates(); + } + } + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/mca/MCAUtil.java b/src/main/java/com/volmit/iris/scaffold/data/mca/MCAUtil.java index 5b7654d11..13523bcc5 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/mca/MCAUtil.java +++ b/src/main/java/com/volmit/iris/scaffold/data/mca/MCAUtil.java @@ -11,218 +11,232 @@ import java.util.regex.Pattern; /** * Provides main and utility functions to read and write .mca files and * to convert block, chunk and region coordinates. - * */ + */ public final class MCAUtil { - private MCAUtil() {} + private MCAUtil() { + } - /** - * @see MCAUtil#read(File) - * @param file The file to read the data from. - * @return An in-memory representation of the MCA file with decompressed chunk data. - * @throws IOException if something during deserialization goes wrong. - * */ - public static MCAFile read(String file) throws IOException { - return read(new File(file), LoadFlags.ALL_DATA); - } + /** + * @param file The file to read the data from. + * @return An in-memory representation of the MCA file with decompressed chunk data. + * @throws IOException if something during deserialization goes wrong. + * @see MCAUtil#read(File) + */ + public static MCAFile read(String file) throws IOException { + return read(new File(file), LoadFlags.ALL_DATA); + } - /** - * Reads an MCA file and loads all of its chunks. - * @param file The file to read the data from. - * @return An in-memory representation of the MCA file with decompressed chunk data. - * @throws IOException if something during deserialization goes wrong. - * */ - public static MCAFile read(File file) throws IOException { - return read(file, LoadFlags.ALL_DATA); - } + /** + * Reads an MCA file and loads all of its chunks. + * + * @param file The file to read the data from. + * @return An in-memory representation of the MCA file with decompressed chunk data. + * @throws IOException if something during deserialization goes wrong. + */ + public static MCAFile read(File file) throws IOException { + return read(file, LoadFlags.ALL_DATA); + } - /** - * @see MCAUtil#read(File) - * @param file The file to read the data from. - * @return An in-memory representation of the MCA file with decompressed chunk data. - * @param loadFlags A logical or of {@link LoadFlags} constants indicating what data should be loaded - * @throws IOException if something during deserialization goes wrong. - * */ - public static MCAFile read(String file, long loadFlags) throws IOException { - return read(new File(file), loadFlags); - } + /** + * @param file The file to read the data from. + * @param loadFlags A logical or of {@link LoadFlags} constants indicating what data should be loaded + * @return An in-memory representation of the MCA file with decompressed chunk data. + * @throws IOException if something during deserialization goes wrong. + * @see MCAUtil#read(File) + */ + public static MCAFile read(String file, long loadFlags) throws IOException { + return read(new File(file), loadFlags); + } - /** - * Reads an MCA file and loads all of its chunks. - * @param file The file to read the data from. - * @return An in-memory representation of the MCA file with decompressed chunk data - * @param loadFlags A logical or of {@link LoadFlags} constants indicating what data should be loaded - * @throws IOException if something during deserialization goes wrong. - * */ - public static MCAFile read(File file, long loadFlags) throws IOException { - MCAFile mcaFile = newMCAFile(file); - try (RandomAccessFile raf = new RandomAccessFile(file, "r")) { - mcaFile.deserialize(raf, loadFlags); - return mcaFile; - } - } + /** + * Reads an MCA file and loads all of its chunks. + * + * @param file The file to read the data from. + * @param loadFlags A logical or of {@link LoadFlags} constants indicating what data should be loaded + * @return An in-memory representation of the MCA file with decompressed chunk data + * @throws IOException if something during deserialization goes wrong. + */ + public static MCAFile read(File file, long loadFlags) throws IOException { + MCAFile mcaFile = newMCAFile(file); + try (RandomAccessFile raf = new RandomAccessFile(file, "r")) { + mcaFile.deserialize(raf, loadFlags); + return mcaFile; + } + } - /** - * Calls {@link MCAUtil#write(MCAFile, File, boolean)} without changing the timestamps. - * @see MCAUtil#write(MCAFile, File, boolean) - * @param file The file to write to. - * @param mcaFile The data of the MCA file to write. - * @return The amount of chunks written to the file. - * @throws IOException If something goes wrong during serialization. - * */ - public static int write(MCAFile mcaFile, String file) throws IOException { - return write(mcaFile, new File(file), false); - } + /** + * Calls {@link MCAUtil#write(MCAFile, File, boolean)} without changing the timestamps. + * + * @param file The file to write to. + * @param mcaFile The data of the MCA file to write. + * @return The amount of chunks written to the file. + * @throws IOException If something goes wrong during serialization. + * @see MCAUtil#write(MCAFile, File, boolean) + */ + public static int write(MCAFile mcaFile, String file) throws IOException { + return write(mcaFile, new File(file), false); + } - /** - * Calls {@link MCAUtil#write(MCAFile, File, boolean)} without changing the timestamps. - * @see MCAUtil#write(MCAFile, File, boolean) - * @param file The file to write to. - * @param mcaFile The data of the MCA file to write. - * @return The amount of chunks written to the file. - * @throws IOException If something goes wrong during serialization. - * */ - public static int write(MCAFile mcaFile, File file) throws IOException { - return write(mcaFile, file, false); - } + /** + * Calls {@link MCAUtil#write(MCAFile, File, boolean)} without changing the timestamps. + * + * @param file The file to write to. + * @param mcaFile The data of the MCA file to write. + * @return The amount of chunks written to the file. + * @throws IOException If something goes wrong during serialization. + * @see MCAUtil#write(MCAFile, File, boolean) + */ + public static int write(MCAFile mcaFile, File file) throws IOException { + return write(mcaFile, file, false); + } - /** - * @see MCAUtil#write(MCAFile, File, boolean) - * @param file The file to write to. - * @param mcaFile The data of the MCA file to write. - * @param changeLastUpdate Whether to adjust the timestamps of when the file was saved. - * @return The amount of chunks written to the file. - * @throws IOException If something goes wrong during serialization. - * */ - public static int write(MCAFile mcaFile, String file, boolean changeLastUpdate) throws IOException { - return write(mcaFile, new File(file), changeLastUpdate); - } + /** + * @param file The file to write to. + * @param mcaFile The data of the MCA file to write. + * @param changeLastUpdate Whether to adjust the timestamps of when the file was saved. + * @return The amount of chunks written to the file. + * @throws IOException If something goes wrong during serialization. + * @see MCAUtil#write(MCAFile, File, boolean) + */ + public static int write(MCAFile mcaFile, String file, boolean changeLastUpdate) throws IOException { + return write(mcaFile, new File(file), changeLastUpdate); + } - /** - * Writes an {@code MCAFile} object to disk. It optionally adjusts the timestamps - * when the file was last saved to the current date and time or leaves them at - * the value set by either loading an already existing MCA file or setting them manually.
- * If the file already exists, it is completely overwritten by the new file (no modification). - * @param file The file to write to. - * @param mcaFile The data of the MCA file to write. - * @param changeLastUpdate Whether to adjust the timestamps of when the file was saved. - * @return The amount of chunks written to the file. - * @throws IOException If something goes wrong during serialization. - * */ - public static int write(MCAFile mcaFile, File file, boolean changeLastUpdate) throws IOException { - if(mcaFile == null) - { - return 0; - } + /** + * Writes an {@code MCAFile} object to disk. It optionally adjusts the timestamps + * when the file was last saved to the current date and time or leaves them at + * the value set by either loading an already existing MCA file or setting them manually.
+ * If the file already exists, it is completely overwritten by the new file (no modification). + * + * @param file The file to write to. + * @param mcaFile The data of the MCA file to write. + * @param changeLastUpdate Whether to adjust the timestamps of when the file was saved. + * @return The amount of chunks written to the file. + * @throws IOException If something goes wrong during serialization. + */ + public static int write(MCAFile mcaFile, File file, boolean changeLastUpdate) throws IOException { + if (mcaFile == null) { + return 0; + } - File to = file; - if (file.exists()) { - to = File.createTempFile(to.getName(), null); - } - int chunks; - try (RandomAccessFile raf = new RandomAccessFile(to, "rw")) { - chunks = mcaFile.serialize(raf, changeLastUpdate); - } + File to = file; + if (file.exists()) { + to = File.createTempFile(to.getName(), null); + } + int chunks; + try (RandomAccessFile raf = new RandomAccessFile(to, "rw")) { + chunks = mcaFile.serialize(raf, changeLastUpdate); + } - if (chunks > 0 && to != file) { - Files.move(to.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING); - } - return chunks; - } + if (chunks > 0 && to != file) { + Files.move(to.toPath(), file.toPath(), StandardCopyOption.REPLACE_EXISTING); + } + return chunks; + } - /** - * Turns the chunks coordinates into region coordinates and calls - * {@link MCAUtil#createNameFromRegionLocation(int, int)} - * @param chunkX The x-value of the location of the chunk. - * @param chunkZ The z-value of the location of the chunk. - * @return A mca filename in the format "r.{regionX}.{regionZ}.mca" - * */ - public static String createNameFromChunkLocation(int chunkX, int chunkZ) { - return createNameFromRegionLocation( chunkToRegion(chunkX), chunkToRegion(chunkZ)); - } + /** + * Turns the chunks coordinates into region coordinates and calls + * {@link MCAUtil#createNameFromRegionLocation(int, int)} + * + * @param chunkX The x-value of the location of the chunk. + * @param chunkZ The z-value of the location of the chunk. + * @return A mca filename in the format "r.{regionX}.{regionZ}.mca" + */ + public static String createNameFromChunkLocation(int chunkX, int chunkZ) { + return createNameFromRegionLocation(chunkToRegion(chunkX), chunkToRegion(chunkZ)); + } - /** - * Turns the block coordinates into region coordinates and calls - * {@link MCAUtil#createNameFromRegionLocation(int, int)} - * @param blockX The x-value of the location of the block. - * @param blockZ The z-value of the location of the block. - * @return A mca filename in the format "r.{regionX}.{regionZ}.mca" - * */ - public static String createNameFromBlockLocation(int blockX, int blockZ) { - return createNameFromRegionLocation(blockToRegion(blockX), blockToRegion(blockZ)); - } + /** + * Turns the block coordinates into region coordinates and calls + * {@link MCAUtil#createNameFromRegionLocation(int, int)} + * + * @param blockX The x-value of the location of the block. + * @param blockZ The z-value of the location of the block. + * @return A mca filename in the format "r.{regionX}.{regionZ}.mca" + */ + public static String createNameFromBlockLocation(int blockX, int blockZ) { + return createNameFromRegionLocation(blockToRegion(blockX), blockToRegion(blockZ)); + } - /** - * Creates a filename string from provided chunk coordinates. - * @param regionX The x-value of the location of the region. - * @param regionZ The z-value of the location of the region. - * @return A mca filename in the format "r.{regionX}.{regionZ}.mca" - * */ - public static String createNameFromRegionLocation(int regionX, int regionZ) { - return "r." + regionX + "." + regionZ + ".mca"; - } + /** + * Creates a filename string from provided chunk coordinates. + * + * @param regionX The x-value of the location of the region. + * @param regionZ The z-value of the location of the region. + * @return A mca filename in the format "r.{regionX}.{regionZ}.mca" + */ + public static String createNameFromRegionLocation(int regionX, int regionZ) { + return "r." + regionX + "." + regionZ + ".mca"; + } - /** - * Turns a block coordinate value into a chunk coordinate value. - * @param block The block coordinate value. - * @return The chunk coordinate value. - * */ - public static int blockToChunk(int block) { - return block >> 4; - } + /** + * Turns a block coordinate value into a chunk coordinate value. + * + * @param block The block coordinate value. + * @return The chunk coordinate value. + */ + public static int blockToChunk(int block) { + return block >> 4; + } - /** - * Turns a block coordinate value into a region coordinate value. - * @param block The block coordinate value. - * @return The region coordinate value. - * */ - public static int blockToRegion(int block) { - return block >> 9; - } + /** + * Turns a block coordinate value into a region coordinate value. + * + * @param block The block coordinate value. + * @return The region coordinate value. + */ + public static int blockToRegion(int block) { + return block >> 9; + } - /** - * Turns a chunk coordinate value into a region coordinate value. - * @param chunk The chunk coordinate value. - * @return The region coordinate value. - * */ - public static int chunkToRegion(int chunk) { - return chunk >> 5; - } + /** + * Turns a chunk coordinate value into a region coordinate value. + * + * @param chunk The chunk coordinate value. + * @return The region coordinate value. + */ + public static int chunkToRegion(int chunk) { + return chunk >> 5; + } - /** - * Turns a region coordinate value into a chunk coordinate value. - * @param region The region coordinate value. - * @return The chunk coordinate value. - * */ - public static int regionToChunk(int region) { - return region << 5; - } + /** + * Turns a region coordinate value into a chunk coordinate value. + * + * @param region The region coordinate value. + * @return The chunk coordinate value. + */ + public static int regionToChunk(int region) { + return region << 5; + } - /** - * Turns a region coordinate value into a block coordinate value. - * @param region The region coordinate value. - * @return The block coordinate value. - * */ - public static int regionToBlock(int region) { - return region << 9; - } + /** + * Turns a region coordinate value into a block coordinate value. + * + * @param region The region coordinate value. + * @return The block coordinate value. + */ + public static int regionToBlock(int region) { + return region << 9; + } - /** - * Turns a chunk coordinate value into a block coordinate value. - * @param chunk The chunk coordinate value. - * @return The block coordinate value. - * */ - public static int chunkToBlock(int chunk) { - return chunk << 4; - } + /** + * Turns a chunk coordinate value into a block coordinate value. + * + * @param chunk The chunk coordinate value. + * @return The block coordinate value. + */ + public static int chunkToBlock(int chunk) { + return chunk << 4; + } - private static final Pattern mcaFilePattern = Pattern.compile("^.*r\\.(?-?\\d+)\\.(?-?\\d+)\\.mca$"); + private static final Pattern mcaFilePattern = Pattern.compile("^.*r\\.(?-?\\d+)\\.(?-?\\d+)\\.mca$"); - public static MCAFile newMCAFile(File file) { - Matcher m = mcaFilePattern.matcher(file.getName()); - if (m.find()) { - return new MCAFile(Integer.parseInt(m.group("regionX")), Integer.parseInt(m.group("regionZ"))); - } - throw new IllegalArgumentException("invalid mca file name: " + file.getName()); - } + public static MCAFile newMCAFile(File file) { + Matcher m = mcaFilePattern.matcher(file.getName()); + if (m.find()) { + return new MCAFile(Integer.parseInt(m.group("regionX")), Integer.parseInt(m.group("regionZ"))); + } + throw new IllegalArgumentException("invalid mca file name: " + file.getName()); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/mca/Section.java b/src/main/java/com/volmit/iris/scaffold/data/mca/Section.java index ad768d7e7..91003c0b2 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/mca/Section.java +++ b/src/main/java/com/volmit/iris/scaffold/data/mca/Section.java @@ -1,10 +1,10 @@ package com.volmit.iris.scaffold.data.mca; -import com.volmit.iris.util.KMap; import com.volmit.iris.scaffold.data.nbt.tag.ByteArrayTag; import com.volmit.iris.scaffold.data.nbt.tag.CompoundTag; import com.volmit.iris.scaffold.data.nbt.tag.ListTag; import com.volmit.iris.scaffold.data.nbt.tag.LongArrayTag; +import com.volmit.iris.util.KMap; import java.util.ArrayList; import java.util.HashMap; @@ -13,397 +13,405 @@ import java.util.Map; public class Section { - private CompoundTag data; - private Map> valueIndexedPalette = new KMap<>(); - private ListTag palette; - private byte[] blockLight; - private long[] blockStates; - private byte[] skyLight; - private int dataVersion; + private CompoundTag data; + private Map> valueIndexedPalette = new KMap<>(); + private ListTag palette; + private byte[] blockLight; + private long[] blockStates; + private byte[] skyLight; + private int dataVersion; - public Section(CompoundTag sectionRoot, int dataVersion) { - this(sectionRoot, dataVersion, LoadFlags.ALL_DATA); - } + public Section(CompoundTag sectionRoot, int dataVersion) { + this(sectionRoot, dataVersion, LoadFlags.ALL_DATA); + } - public Section(CompoundTag sectionRoot, int dataVersion, long loadFlags) { - data = sectionRoot; - this.dataVersion = dataVersion; - ListTag rawPalette = sectionRoot.getListTag("Palette"); - if (rawPalette == null) { - return; - } - palette = rawPalette.asCompoundTagList(); - for (int i = 0; i < palette.size(); i++) { - CompoundTag data = palette.get(i); - putValueIndexedPalette(data, i); - } + public Section(CompoundTag sectionRoot, int dataVersion, long loadFlags) { + data = sectionRoot; + this.dataVersion = dataVersion; + ListTag rawPalette = sectionRoot.getListTag("Palette"); + if (rawPalette == null) { + return; + } + palette = rawPalette.asCompoundTagList(); + for (int i = 0; i < palette.size(); i++) { + CompoundTag data = palette.get(i); + putValueIndexedPalette(data, i); + } - ByteArrayTag blockLight = sectionRoot.getByteArrayTag("BlockLight"); - LongArrayTag blockStates = sectionRoot.getLongArrayTag("BlockStates"); - ByteArrayTag skyLight = sectionRoot.getByteArrayTag("SkyLight"); + ByteArrayTag blockLight = sectionRoot.getByteArrayTag("BlockLight"); + LongArrayTag blockStates = sectionRoot.getLongArrayTag("BlockStates"); + ByteArrayTag skyLight = sectionRoot.getByteArrayTag("SkyLight"); - if ((loadFlags & LoadFlags.BLOCK_LIGHTS) != 0) { - this.blockLight = blockLight != null ? blockLight.getValue() : null; - } - if ((loadFlags & LoadFlags.BLOCK_STATES) != 0) { - this.blockStates = blockStates != null ? blockStates.getValue() : null; - } - if ((loadFlags & LoadFlags.SKY_LIGHT) != 0) { - this.skyLight = skyLight != null ? skyLight.getValue() : null; - } - } + if ((loadFlags & LoadFlags.BLOCK_LIGHTS) != 0) { + this.blockLight = blockLight != null ? blockLight.getValue() : null; + } + if ((loadFlags & LoadFlags.BLOCK_STATES) != 0) { + this.blockStates = blockStates != null ? blockStates.getValue() : null; + } + if ((loadFlags & LoadFlags.SKY_LIGHT) != 0) { + this.skyLight = skyLight != null ? skyLight.getValue() : null; + } + } - Section() {} + Section() { + } - void putValueIndexedPalette(CompoundTag data, int index) { - PaletteIndex leaf = new PaletteIndex(data, index); - String name = data.getString("Name"); - List leaves = valueIndexedPalette.get(name); - if (leaves == null) { - leaves = new ArrayList<>(1); - leaves.add(leaf); - valueIndexedPalette.put(name, leaves); - } else { - for (PaletteIndex pal : leaves) { - if (pal.data.equals(data)) { - return; - } - } - leaves.add(leaf); - } - } + void putValueIndexedPalette(CompoundTag data, int index) { + PaletteIndex leaf = new PaletteIndex(data, index); + String name = data.getString("Name"); + List leaves = valueIndexedPalette.get(name); + if (leaves == null) { + leaves = new ArrayList<>(1); + leaves.add(leaf); + valueIndexedPalette.put(name, leaves); + } else { + for (PaletteIndex pal : leaves) { + if (pal.data.equals(data)) { + return; + } + } + leaves.add(leaf); + } + } - PaletteIndex getValueIndexedPalette(CompoundTag data) { - List leaves = valueIndexedPalette.get(data.getString("Name")); - if (leaves == null) { - return null; - } - for (PaletteIndex leaf : leaves) { - if (leaf.data.equals(data)) { - return leaf; - } - } - return null; - } + PaletteIndex getValueIndexedPalette(CompoundTag data) { + List leaves = valueIndexedPalette.get(data.getString("Name")); + if (leaves == null) { + return null; + } + for (PaletteIndex leaf : leaves) { + if (leaf.data.equals(data)) { + return leaf; + } + } + return null; + } - private static class PaletteIndex { + private static class PaletteIndex { - CompoundTag data; - int index; + CompoundTag data; + int index; - PaletteIndex(CompoundTag data, int index) { - this.data = data; - this.index = index; - } - } + PaletteIndex(CompoundTag data, int index) { + this.data = data; + this.index = index; + } + } - /** - * Checks whether the data of this Section is empty. - * @return true if empty - */ - public boolean isEmpty() { - return data == null; - } + /** + * Checks whether the data of this Section is empty. + * + * @return true if empty + */ + public boolean isEmpty() { + return data == null; + } - /** - * Fetches a block state based on a block location from this section. - * The coordinates represent the location of the block inside of this Section. - * @param blockX The x-coordinate of the block in this Section - * @param blockY The y-coordinate of the block in this Section - * @param blockZ The z-coordinate of the block in this Section - * @return The block state data of this block. - */ - public CompoundTag getBlockStateAt(int blockX, int blockY, int blockZ) { - try - { - int index = getBlockIndex(blockX, blockY, blockZ); - int paletteIndex = getPaletteIndex(index); - return palette.get(paletteIndex); - } + /** + * Fetches a block state based on a block location from this section. + * The coordinates represent the location of the block inside of this Section. + * + * @param blockX The x-coordinate of the block in this Section + * @param blockY The y-coordinate of the block in this Section + * @param blockZ The z-coordinate of the block in this Section + * @return The block state data of this block. + */ + public CompoundTag getBlockStateAt(int blockX, int blockY, int blockZ) { + try { + int index = getBlockIndex(blockX, blockY, blockZ); + int paletteIndex = getPaletteIndex(index); + return palette.get(paletteIndex); + } catch (Throwable e) { - catch(Throwable e) - { + } - } + return null; + } - return null; - } + /** + * Attempts to add a block state for a specific block location in this Section. + * + * @param blockX The x-coordinate of the block in this Section + * @param blockY The y-coordinate of the block in this Section + * @param blockZ The z-coordinate of the block in this Section + * @param state The block state to be set + * @param cleanup When true, it will cleanup the palette of this section. + * This option should only be used moderately to avoid unnecessary recalculation of the palette indices. + * Recalculating the Palette should only be executed once right before saving the Section to file. + */ + public void setBlockStateAt(int blockX, int blockY, int blockZ, CompoundTag state, boolean cleanup) { + int paletteSizeBefore = palette.size(); + int paletteIndex = addToPalette(state); + //power of 2 --> bits must increase, but only if the palette size changed + //otherwise we would attempt to update all blockstates and the entire palette + //every time an existing blockstate was added while having 2^x blockstates in the palette + if (paletteSizeBefore != palette.size() && (paletteIndex & (paletteIndex - 1)) == 0) { + adjustBlockStateBits(null, blockStates); + cleanup = true; + } - /** - * Attempts to add a block state for a specific block location in this Section. - * @param blockX The x-coordinate of the block in this Section - * @param blockY The y-coordinate of the block in this Section - * @param blockZ The z-coordinate of the block in this Section - * @param state The block state to be set - * @param cleanup When true, it will cleanup the palette of this section. - * This option should only be used moderately to avoid unnecessary recalculation of the palette indices. - * Recalculating the Palette should only be executed once right before saving the Section to file. - */ - public void setBlockStateAt(int blockX, int blockY, int blockZ, CompoundTag state, boolean cleanup) { - int paletteSizeBefore = palette.size(); - int paletteIndex = addToPalette(state); - //power of 2 --> bits must increase, but only if the palette size changed - //otherwise we would attempt to update all blockstates and the entire palette - //every time an existing blockstate was added while having 2^x blockstates in the palette - if (paletteSizeBefore != palette.size() && (paletteIndex & (paletteIndex - 1)) == 0) { - adjustBlockStateBits(null, blockStates); - cleanup = true; - } + setPaletteIndex(getBlockIndex(blockX, blockY, blockZ), paletteIndex, blockStates); - setPaletteIndex(getBlockIndex(blockX, blockY, blockZ), paletteIndex, blockStates); + if (cleanup) { + cleanupPaletteAndBlockStates(); + } + } - if (cleanup) { - cleanupPaletteAndBlockStates(); - } - } + /** + * Returns the index of the block data in the palette. + * + * @param blockStateIndex The index of the block in this section, ranging from 0-4095. + * @return The index of the block data in the palette. + */ + public int getPaletteIndex(int blockStateIndex) { + int bits = blockStates.length >> 6; - /** - * Returns the index of the block data in the palette. - * @param blockStateIndex The index of the block in this section, ranging from 0-4095. - * @return The index of the block data in the palette. - * */ - public int getPaletteIndex(int blockStateIndex) { - int bits = blockStates.length >> 6; + if (dataVersion < 2527) { + double blockStatesIndex = blockStateIndex / (4096D / blockStates.length); + int longIndex = (int) blockStatesIndex; + int startBit = (int) ((blockStatesIndex - Math.floor(blockStatesIndex)) * 64D); + if (startBit + bits > 64) { + long prev = bitRange(blockStates[longIndex], startBit, 64); + long next = bitRange(blockStates[longIndex + 1], 0, startBit + bits - 64); + return (int) ((next << 64 - startBit) + prev); + } else { + return (int) bitRange(blockStates[longIndex], startBit, startBit + bits); + } + } else { + int indicesPerLong = (int) (64D / bits); + int blockStatesIndex = blockStateIndex / indicesPerLong; + int startBit = (blockStateIndex % indicesPerLong) * bits; + return (int) bitRange(blockStates[blockStatesIndex], startBit, startBit + bits); + } + } - if (dataVersion < 2527) { - double blockStatesIndex = blockStateIndex / (4096D / blockStates.length); - int longIndex = (int) blockStatesIndex; - int startBit = (int) ((blockStatesIndex - Math.floor(blockStatesIndex)) * 64D); - if (startBit + bits > 64) { - long prev = bitRange(blockStates[longIndex], startBit, 64); - long next = bitRange(blockStates[longIndex + 1], 0, startBit + bits - 64); - return (int) ((next << 64 - startBit) + prev); - } else { - return (int) bitRange(blockStates[longIndex], startBit, startBit + bits); - } - } else { - int indicesPerLong = (int) (64D / bits); - int blockStatesIndex = blockStateIndex / indicesPerLong; - int startBit = (blockStateIndex % indicesPerLong) * bits; - return (int) bitRange(blockStates[blockStatesIndex], startBit, startBit + bits); - } - } + /** + * Sets the index of the block data in the BlockStates. Does not adjust the size of the BlockStates array. + * + * @param blockIndex The index of the block in this section, ranging from 0-4095. + * @param paletteIndex The block state to be set (index of block data in the palette). + * @param blockStates The block states to be updated. + */ + public void setPaletteIndex(int blockIndex, int paletteIndex, long[] blockStates) { + int bits = blockStates.length >> 6; - /** - * Sets the index of the block data in the BlockStates. Does not adjust the size of the BlockStates array. - * @param blockIndex The index of the block in this section, ranging from 0-4095. - * @param paletteIndex The block state to be set (index of block data in the palette). - * @param blockStates The block states to be updated. - * */ - public void setPaletteIndex(int blockIndex, int paletteIndex, long[] blockStates) { - int bits = blockStates.length >> 6; + if (dataVersion < 2527) { + double blockStatesIndex = blockIndex / (4096D / blockStates.length); + int longIndex = (int) blockStatesIndex; + int startBit = (int) ((blockStatesIndex - Math.floor(longIndex)) * 64D); + if (startBit + bits > 64) { + blockStates[longIndex] = updateBits(blockStates[longIndex], paletteIndex, startBit, 64); + blockStates[longIndex + 1] = updateBits(blockStates[longIndex + 1], paletteIndex, startBit - 64, startBit + bits - 64); + } else { + blockStates[longIndex] = updateBits(blockStates[longIndex], paletteIndex, startBit, startBit + bits); + } + } else { + int indicesPerLong = (int) (64D / bits); + int blockStatesIndex = blockIndex / indicesPerLong; + int startBit = (blockIndex % indicesPerLong) * bits; + blockStates[blockStatesIndex] = updateBits(blockStates[blockStatesIndex], paletteIndex, startBit, startBit + bits); + } + } - if (dataVersion < 2527) { - double blockStatesIndex = blockIndex / (4096D / blockStates.length); - int longIndex = (int) blockStatesIndex; - int startBit = (int) ((blockStatesIndex - Math.floor(longIndex)) * 64D); - if (startBit + bits > 64) { - blockStates[longIndex] = updateBits(blockStates[longIndex], paletteIndex, startBit, 64); - blockStates[longIndex + 1] = updateBits(blockStates[longIndex + 1], paletteIndex, startBit - 64, startBit + bits - 64); - } else { - blockStates[longIndex] = updateBits(blockStates[longIndex], paletteIndex, startBit, startBit + bits); - } - } else { - int indicesPerLong = (int) (64D / bits); - int blockStatesIndex = blockIndex / indicesPerLong; - int startBit = (blockIndex % indicesPerLong) * bits; - blockStates[blockStatesIndex] = updateBits(blockStates[blockStatesIndex], paletteIndex, startBit, startBit + bits); - } - } + /** + * Fetches the palette of this Section. + * + * @return The palette of this Section. + */ + public ListTag getPalette() { + return palette; + } - /** - * Fetches the palette of this Section. - * @return The palette of this Section. - */ - public ListTag getPalette() { - return palette; - } + int addToPalette(CompoundTag data) { + PaletteIndex index; + if ((index = getValueIndexedPalette(data)) != null) { + return index.index; + } + palette.add(data); + putValueIndexedPalette(data, palette.size() - 1); + return palette.size() - 1; + } - int addToPalette(CompoundTag data) { - PaletteIndex index; - if ((index = getValueIndexedPalette(data)) != null) { - return index.index; - } - palette.add(data); - putValueIndexedPalette(data, palette.size() - 1); - return palette.size() - 1; - } + int getBlockIndex(int blockX, int blockY, int blockZ) { + return (blockY & 0xF) * 256 + (blockZ & 0xF) * 16 + (blockX & 0xF); + } - int getBlockIndex(int blockX, int blockY, int blockZ) { - return (blockY & 0xF) * 256 + (blockZ & 0xF) * 16 + (blockX & 0xF); - } + static long updateBits(long n, long m, int i, int j) { + //replace i to j in n with j - i bits of m + long mShifted = i > 0 ? (m & ((1L << j - i) - 1)) << i : (m & ((1L << j - i) - 1)) >>> -i; + return ((n & ((j > 63 ? 0 : (~0L << j)) | (i < 0 ? 0 : ((1L << i) - 1L)))) | mShifted); + } - static long updateBits(long n, long m, int i, int j) { - //replace i to j in n with j - i bits of m - long mShifted = i > 0 ? (m & ((1L << j - i) - 1)) << i : (m & ((1L << j - i) - 1)) >>> -i; - return ((n & ((j > 63 ? 0 : (~0L << j)) | (i < 0 ? 0 : ((1L << i) - 1L)))) | mShifted); - } + static long bitRange(long value, int from, int to) { + int waste = 64 - to; + return (value << waste) >>> (waste + from); + } - static long bitRange(long value, int from, int to) { - int waste = 64 - to; - return (value << waste) >>> (waste + from); - } + /** + * This method recalculates the palette and its indices. + * This should only be used moderately to avoid unnecessary recalculation of the palette indices. + * Recalculating the Palette should only be executed once right before saving the Section to file. + */ + public void cleanupPaletteAndBlockStates() { + Map oldToNewMapping = cleanupPalette(); + adjustBlockStateBits(oldToNewMapping, blockStates); + } - /** - * This method recalculates the palette and its indices. - * This should only be used moderately to avoid unnecessary recalculation of the palette indices. - * Recalculating the Palette should only be executed once right before saving the Section to file. - */ - public void cleanupPaletteAndBlockStates() { - Map oldToNewMapping = cleanupPalette(); - adjustBlockStateBits(oldToNewMapping, blockStates); - } + private Map cleanupPalette() { + //create index - palette mapping + Map allIndices = new HashMap<>(); + for (int i = 0; i < 4096; i++) { + int paletteIndex = getPaletteIndex(i); + allIndices.put(paletteIndex, paletteIndex); + } + //delete unused blocks from palette + //start at index 1 because we need to keep minecraft:air + int index = 1; + valueIndexedPalette = new HashMap<>(valueIndexedPalette.size()); + putValueIndexedPalette(palette.get(0), 0); + for (int i = 1; i < palette.size(); i++) { + if (!allIndices.containsKey(index)) { + palette.remove(i); + i--; + } else { + putValueIndexedPalette(palette.get(i), i); + allIndices.put(index, i); + } + index++; + } - private Map cleanupPalette() { - //create index - palette mapping - Map allIndices = new HashMap<>(); - for (int i = 0; i < 4096; i++) { - int paletteIndex = getPaletteIndex(i); - allIndices.put(paletteIndex, paletteIndex); - } - //delete unused blocks from palette - //start at index 1 because we need to keep minecraft:air - int index = 1; - valueIndexedPalette = new HashMap<>(valueIndexedPalette.size()); - putValueIndexedPalette(palette.get(0), 0); - for (int i = 1; i < palette.size(); i++) { - if (!allIndices.containsKey(index)) { - palette.remove(i); - i--; - } else { - putValueIndexedPalette(palette.get(i), i); - allIndices.put(index, i); - } - index++; - } + return allIndices; + } - return allIndices; - } + void adjustBlockStateBits(Map oldToNewMapping, long[] blockStates) { + //increases or decreases the amount of bits used per BlockState + //based on the size of the palette. oldToNewMapping can be used to update indices + //if the palette had been cleaned up before using MCAFile#cleanupPalette(). - void adjustBlockStateBits(Map oldToNewMapping, long[] blockStates) { - //increases or decreases the amount of bits used per BlockState - //based on the size of the palette. oldToNewMapping can be used to update indices - //if the palette had been cleaned up before using MCAFile#cleanupPalette(). + int newBits = 32 - Integer.numberOfLeadingZeros(palette.size() - 1); + newBits = Math.max(newBits, 4); - int newBits = 32 - Integer.numberOfLeadingZeros(palette.size() - 1); - newBits = Math.max(newBits, 4); + long[] newBlockStates; - long[] newBlockStates; + if (dataVersion < 2527) { + newBlockStates = newBits == blockStates.length / 64 ? blockStates : new long[newBits * 64]; + } else { + int newLength = (int) Math.ceil(4096D / (64D / newBits)); + newBlockStates = newBits == blockStates.length / 64 ? blockStates : new long[newLength]; + } + if (oldToNewMapping != null) { + for (int i = 0; i < 4096; i++) { + setPaletteIndex(i, oldToNewMapping.get(getPaletteIndex(i)), newBlockStates); + } + } else { + for (int i = 0; i < 4096; i++) { + setPaletteIndex(i, getPaletteIndex(i), newBlockStates); + } + } + this.blockStates = newBlockStates; + } - if (dataVersion < 2527) { - newBlockStates = newBits == blockStates.length / 64 ? blockStates : new long[newBits * 64]; - } else { - int newLength = (int) Math.ceil(4096D / (64D / newBits)); - newBlockStates = newBits == blockStates.length / 64 ? blockStates : new long[newLength]; - } - if (oldToNewMapping != null) { - for (int i = 0; i < 4096; i++) { - setPaletteIndex(i, oldToNewMapping.get(getPaletteIndex(i)), newBlockStates); - } - } else { - for (int i = 0; i < 4096; i++) { - setPaletteIndex(i, getPaletteIndex(i), newBlockStates); - } - } - this.blockStates = newBlockStates; - } + /** + * @return The block light array of this Section + */ + public byte[] getBlockLight() { + return blockLight; + } - /** - * @return The block light array of this Section - */ - public byte[] getBlockLight() { - return blockLight; - } + /** + * Sets the block light array for this section. + * + * @param blockLight The block light array + * @throws IllegalArgumentException When the length of the array is not 2048 + */ + public void setBlockLight(byte[] blockLight) { + if (blockLight != null && blockLight.length != 2048) { + throw new IllegalArgumentException("BlockLight array must have a length of 2048"); + } + this.blockLight = blockLight; + } - /** - * Sets the block light array for this section. - * @param blockLight The block light array - * @throws IllegalArgumentException When the length of the array is not 2048 - */ - public void setBlockLight(byte[] blockLight) { - if (blockLight != null && blockLight.length != 2048) { - throw new IllegalArgumentException("BlockLight array must have a length of 2048"); - } - this.blockLight = blockLight; - } + /** + * @return The indices of the block states of this Section. + */ + public long[] getBlockStates() { + return blockStates; + } - /** - * @return The indices of the block states of this Section. - */ - public long[] getBlockStates() { - return blockStates; - } + /** + * Sets the block state indices to a custom value. + * + * @param blockStates The block state indices. + * @throws NullPointerException If blockStates is null + * @throws IllegalArgumentException When blockStates' length is < 256 or > 4096 and is not a multiple of 64 + */ + public void setBlockStates(long[] blockStates) { + if (blockStates == null) { + throw new NullPointerException("BlockStates cannot be null"); + } else if (blockStates.length % 64 != 0 || blockStates.length < 256 || blockStates.length > 4096) { + throw new IllegalArgumentException("BlockStates must have a length > 255 and < 4097 and must be divisible by 64"); + } + this.blockStates = blockStates; + } - /** - * Sets the block state indices to a custom value. - * @param blockStates The block state indices. - * @throws NullPointerException If blockStates is null - * @throws IllegalArgumentException When blockStates' length is < 256 or > 4096 and is not a multiple of 64 - */ - public void setBlockStates(long[] blockStates) { - if (blockStates == null) { - throw new NullPointerException("BlockStates cannot be null"); - } else if (blockStates.length % 64 != 0 || blockStates.length < 256 || blockStates.length > 4096) { - throw new IllegalArgumentException("BlockStates must have a length > 255 and < 4097 and must be divisible by 64"); - } - this.blockStates = blockStates; - } + /** + * @return The sky light values of this Section + */ + public byte[] getSkyLight() { + return skyLight; + } - /** - * @return The sky light values of this Section - */ - public byte[] getSkyLight() { - return skyLight; - } + /** + * Sets the sky light values of this section. + * + * @param skyLight The custom sky light values + * @throws IllegalArgumentException If the length of the array is not 2048 + */ + public void setSkyLight(byte[] skyLight) { + if (skyLight != null && skyLight.length != 2048) { + throw new IllegalArgumentException("SkyLight array must have a length of 2048"); + } + this.skyLight = skyLight; + } - /** - * Sets the sky light values of this section. - * @param skyLight The custom sky light values - * @throws IllegalArgumentException If the length of the array is not 2048 - */ - public void setSkyLight(byte[] skyLight) { - if (skyLight != null && skyLight.length != 2048) { - throw new IllegalArgumentException("SkyLight array must have a length of 2048"); - } - this.skyLight = skyLight; - } + /** + * Creates an empty Section with base values. + * + * @return An empty Section + */ + public static Section newSection() { + Section s = new Section(); + s.blockStates = new long[256]; + s.palette = new ListTag<>(CompoundTag.class); + CompoundTag air = new CompoundTag(); + air.putString("Name", "minecraft:air"); + s.palette.add(air); + s.data = new CompoundTag(); + return s; + } - /** - * Creates an empty Section with base values. - * @return An empty Section - */ - public static Section newSection() { - Section s = new Section(); - s.blockStates = new long[256]; - s.palette = new ListTag<>(CompoundTag.class); - CompoundTag air = new CompoundTag(); - air.putString("Name", "minecraft:air"); - s.palette.add(air); - s.data = new CompoundTag(); - return s; - } - - /** - * Updates the raw CompoundTag that this Section is based on. - * This must be called before saving a Section to disk if the Section was manually created - * to set the Y of this Section. - * @param y The Y-value of this Section - * @return A reference to the raw CompoundTag this Section is based on - */ - public CompoundTag updateHandle(int y) { - data.putByte("Y", (byte) y); - if (palette != null) { - data.put("Palette", palette); - } - if (blockLight != null) { - data.putByteArray("BlockLight", blockLight); - } - if (blockStates != null) { - data.putLongArray("BlockStates", blockStates); - } - if (skyLight != null) { - data.putByteArray("SkyLight", skyLight); - } - return data; - } + /** + * Updates the raw CompoundTag that this Section is based on. + * This must be called before saving a Section to disk if the Section was manually created + * to set the Y of this Section. + * + * @param y The Y-value of this Section + * @return A reference to the raw CompoundTag this Section is based on + */ + public CompoundTag updateHandle(int y) { + data.putByte("Y", (byte) y); + if (palette != null) { + data.put("Palette", palette); + } + if (blockLight != null) { + data.putByteArray("BlockLight", blockLight); + } + if (blockStates != null) { + data.putLongArray("BlockStates", blockStates); + } + if (skyLight != null) { + data.putByteArray("SkyLight", skyLight); + } + return data; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NBTDeserializer.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NBTDeserializer.java index 90c6a7741..d9398b8a6 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NBTDeserializer.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NBTDeserializer.java @@ -2,30 +2,31 @@ package com.volmit.iris.scaffold.data.nbt.io; import com.volmit.iris.scaffold.data.io.Deserializer; import com.volmit.iris.scaffold.data.nbt.tag.Tag; + import java.io.IOException; import java.io.InputStream; import java.util.zip.GZIPInputStream; public class NBTDeserializer implements Deserializer { - private boolean compressed; + private final boolean compressed; - public NBTDeserializer() { - this(true); - } + public NBTDeserializer() { + this(true); + } - public NBTDeserializer(boolean compressed) { - this.compressed = compressed; - } + public NBTDeserializer(boolean compressed) { + this.compressed = compressed; + } - @Override - public NamedTag fromStream(InputStream stream) throws IOException { - NBTInputStream nbtIn; - if (compressed) { - nbtIn = new NBTInputStream(new GZIPInputStream(stream)); - } else { - nbtIn = new NBTInputStream(stream); - } - return nbtIn.readTag(Tag.DEFAULT_MAX_DEPTH); - } + @Override + public NamedTag fromStream(InputStream stream) throws IOException { + NBTInputStream nbtIn; + if (compressed) { + nbtIn = new NBTInputStream(new GZIPInputStream(stream)); + } else { + nbtIn = new NBTInputStream(stream); + } + return nbtIn.readTag(Tag.DEFAULT_MAX_DEPTH); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NBTInputStream.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NBTInputStream.java index 5a323620e..ddefc6fcb 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NBTInputStream.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NBTInputStream.java @@ -2,20 +2,8 @@ package com.volmit.iris.scaffold.data.nbt.io; import com.volmit.iris.scaffold.data.io.ExceptionBiFunction; import com.volmit.iris.scaffold.data.io.MaxDepthIO; -import com.volmit.iris.scaffold.data.nbt.tag.ByteArrayTag; -import com.volmit.iris.scaffold.data.nbt.tag.ByteTag; -import com.volmit.iris.scaffold.data.nbt.tag.CompoundTag; -import com.volmit.iris.scaffold.data.nbt.tag.DoubleTag; -import com.volmit.iris.scaffold.data.nbt.tag.EndTag; -import com.volmit.iris.scaffold.data.nbt.tag.FloatTag; -import com.volmit.iris.scaffold.data.nbt.tag.IntArrayTag; -import com.volmit.iris.scaffold.data.nbt.tag.IntTag; -import com.volmit.iris.scaffold.data.nbt.tag.ListTag; -import com.volmit.iris.scaffold.data.nbt.tag.LongArrayTag; -import com.volmit.iris.scaffold.data.nbt.tag.LongTag; -import com.volmit.iris.scaffold.data.nbt.tag.ShortTag; -import com.volmit.iris.scaffold.data.nbt.tag.StringTag; -import com.volmit.iris.scaffold.data.nbt.tag.Tag; +import com.volmit.iris.scaffold.data.nbt.tag.*; + import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; @@ -24,126 +12,126 @@ import java.util.Map; public class NBTInputStream extends DataInputStream implements MaxDepthIO { - private static Map, IOException>> readers = new HashMap<>(); - private static Map> idClassMapping = new HashMap<>(); + private static final Map, IOException>> readers = new HashMap<>(); + private static final Map> idClassMapping = new HashMap<>(); - static { - put(EndTag.ID, (i, d) -> EndTag.INSTANCE, EndTag.class); - put(ByteTag.ID, (i, d) -> readByte(i), ByteTag.class); - put(ShortTag.ID, (i, d) -> readShort(i), ShortTag.class); - put(IntTag.ID, (i, d) -> readInt(i), IntTag.class); - put(LongTag.ID, (i, d) -> readLong(i), LongTag.class); - put(FloatTag.ID, (i, d) -> readFloat(i), FloatTag.class); - put(DoubleTag.ID, (i, d) -> readDouble(i), DoubleTag.class); - put(ByteArrayTag.ID, (i, d) -> readByteArray(i), ByteArrayTag.class); - put(StringTag.ID, (i, d) -> readString(i), StringTag.class); - put(ListTag.ID, NBTInputStream::readListTag, ListTag.class); - put(CompoundTag.ID, NBTInputStream::readCompound, CompoundTag.class); - put(IntArrayTag.ID, (i, d) -> readIntArray(i), IntArrayTag.class); - put(LongArrayTag.ID, (i, d) -> readLongArray(i), LongArrayTag.class); - } + static { + put(EndTag.ID, (i, d) -> EndTag.INSTANCE, EndTag.class); + put(ByteTag.ID, (i, d) -> readByte(i), ByteTag.class); + put(ShortTag.ID, (i, d) -> readShort(i), ShortTag.class); + put(IntTag.ID, (i, d) -> readInt(i), IntTag.class); + put(LongTag.ID, (i, d) -> readLong(i), LongTag.class); + put(FloatTag.ID, (i, d) -> readFloat(i), FloatTag.class); + put(DoubleTag.ID, (i, d) -> readDouble(i), DoubleTag.class); + put(ByteArrayTag.ID, (i, d) -> readByteArray(i), ByteArrayTag.class); + put(StringTag.ID, (i, d) -> readString(i), StringTag.class); + put(ListTag.ID, NBTInputStream::readListTag, ListTag.class); + put(CompoundTag.ID, NBTInputStream::readCompound, CompoundTag.class); + put(IntArrayTag.ID, (i, d) -> readIntArray(i), IntArrayTag.class); + put(LongArrayTag.ID, (i, d) -> readLongArray(i), LongArrayTag.class); + } - private static void put(byte id, ExceptionBiFunction, IOException> reader, Class clazz) { - readers.put(id, reader); - idClassMapping.put(id, clazz); - } + private static void put(byte id, ExceptionBiFunction, IOException> reader, Class clazz) { + readers.put(id, reader); + idClassMapping.put(id, clazz); + } - public NBTInputStream(InputStream in) { - super(in); - } + public NBTInputStream(InputStream in) { + super(in); + } - public NamedTag readTag(int maxDepth) throws IOException { - byte id = readByte(); - return new NamedTag(readUTF(), readTag(id, maxDepth)); - } + public NamedTag readTag(int maxDepth) throws IOException { + byte id = readByte(); + return new NamedTag(readUTF(), readTag(id, maxDepth)); + } - public Tag readRawTag(int maxDepth) throws IOException { - byte id = readByte(); - return readTag(id, maxDepth); - } + public Tag readRawTag(int maxDepth) throws IOException { + byte id = readByte(); + return readTag(id, maxDepth); + } - private Tag readTag(byte type, int maxDepth) throws IOException { - ExceptionBiFunction, IOException> f; - if ((f = readers.get(type)) == null) { - throw new IOException("invalid tag id \"" + type + "\""); - } - return f.accept(this, maxDepth); - } + private Tag readTag(byte type, int maxDepth) throws IOException { + ExceptionBiFunction, IOException> f; + if ((f = readers.get(type)) == null) { + throw new IOException("invalid tag id \"" + type + "\""); + } + return f.accept(this, maxDepth); + } - private static ByteTag readByte(NBTInputStream in) throws IOException { - return new ByteTag(in.readByte()); - } + private static ByteTag readByte(NBTInputStream in) throws IOException { + return new ByteTag(in.readByte()); + } - private static ShortTag readShort(NBTInputStream in) throws IOException { - return new ShortTag(in.readShort()); - } + private static ShortTag readShort(NBTInputStream in) throws IOException { + return new ShortTag(in.readShort()); + } - private static IntTag readInt(NBTInputStream in) throws IOException { - return new IntTag(in.readInt()); - } + private static IntTag readInt(NBTInputStream in) throws IOException { + return new IntTag(in.readInt()); + } - private static LongTag readLong(NBTInputStream in) throws IOException { - return new LongTag(in.readLong()); - } + private static LongTag readLong(NBTInputStream in) throws IOException { + return new LongTag(in.readLong()); + } - private static FloatTag readFloat(NBTInputStream in) throws IOException { - return new FloatTag(in.readFloat()); - } + private static FloatTag readFloat(NBTInputStream in) throws IOException { + return new FloatTag(in.readFloat()); + } - private static DoubleTag readDouble(NBTInputStream in) throws IOException { - return new DoubleTag(in.readDouble()); - } + private static DoubleTag readDouble(NBTInputStream in) throws IOException { + return new DoubleTag(in.readDouble()); + } - private static StringTag readString(NBTInputStream in) throws IOException { - return new StringTag(in.readUTF()); - } + private static StringTag readString(NBTInputStream in) throws IOException { + return new StringTag(in.readUTF()); + } - private static ByteArrayTag readByteArray(NBTInputStream in) throws IOException { - ByteArrayTag bat = new ByteArrayTag(new byte[in.readInt()]); - in.readFully(bat.getValue()); - return bat; - } + private static ByteArrayTag readByteArray(NBTInputStream in) throws IOException { + ByteArrayTag bat = new ByteArrayTag(new byte[in.readInt()]); + in.readFully(bat.getValue()); + return bat; + } - private static IntArrayTag readIntArray(NBTInputStream in) throws IOException { - int l = in.readInt(); - int[] data = new int[l]; - IntArrayTag iat = new IntArrayTag(data); - for (int i = 0; i < l; i++) { - data[i] = in.readInt(); - } - return iat; - } + private static IntArrayTag readIntArray(NBTInputStream in) throws IOException { + int l = in.readInt(); + int[] data = new int[l]; + IntArrayTag iat = new IntArrayTag(data); + for (int i = 0; i < l; i++) { + data[i] = in.readInt(); + } + return iat; + } - private static LongArrayTag readLongArray(NBTInputStream in) throws IOException { - int l = in.readInt(); - long[] data = new long[l]; - LongArrayTag iat = new LongArrayTag(data); - for (int i = 0; i < l; i++) { - data[i] = in.readLong(); - } - return iat; - } + private static LongArrayTag readLongArray(NBTInputStream in) throws IOException { + int l = in.readInt(); + long[] data = new long[l]; + LongArrayTag iat = new LongArrayTag(data); + for (int i = 0; i < l; i++) { + data[i] = in.readLong(); + } + return iat; + } - private static ListTag readListTag(NBTInputStream in, int maxDepth) throws IOException { - byte listType = in.readByte(); - ListTag list = ListTag.createUnchecked(idClassMapping.get(listType)); - int length = in.readInt(); - if (length < 0) { - length = 0; - } - for (int i = 0; i < length; i++) { - list.addUnchecked(in.readTag(listType, in.decrementMaxDepth(maxDepth))); - } - return list; - } + private static ListTag readListTag(NBTInputStream in, int maxDepth) throws IOException { + byte listType = in.readByte(); + ListTag list = ListTag.createUnchecked(idClassMapping.get(listType)); + int length = in.readInt(); + if (length < 0) { + length = 0; + } + for (int i = 0; i < length; i++) { + list.addUnchecked(in.readTag(listType, in.decrementMaxDepth(maxDepth))); + } + return list; + } - private static CompoundTag readCompound(NBTInputStream in, int maxDepth) throws IOException { - CompoundTag comp = new CompoundTag(); - for (int id = in.readByte() & 0xFF; id != 0; id = in.readByte() & 0xFF) { - String key = in.readUTF(); - Tag element = in.readTag((byte) id, in.decrementMaxDepth(maxDepth)); - comp.put(key, element); - } - return comp; - } + private static CompoundTag readCompound(NBTInputStream in, int maxDepth) throws IOException { + CompoundTag comp = new CompoundTag(); + for (int id = in.readByte() & 0xFF; id != 0; id = in.readByte() & 0xFF) { + String key = in.readUTF(); + Tag element = in.readTag((byte) id, in.decrementMaxDepth(maxDepth)); + comp.put(key, element); + } + return comp; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NBTOutputStream.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NBTOutputStream.java index cdf054281..a9cc4f13a 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NBTOutputStream.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NBTOutputStream.java @@ -2,20 +2,8 @@ package com.volmit.iris.scaffold.data.nbt.io; import com.volmit.iris.scaffold.data.io.ExceptionTriConsumer; import com.volmit.iris.scaffold.data.io.MaxDepthIO; -import com.volmit.iris.scaffold.data.nbt.tag.ByteArrayTag; -import com.volmit.iris.scaffold.data.nbt.tag.ByteTag; -import com.volmit.iris.scaffold.data.nbt.tag.CompoundTag; -import com.volmit.iris.scaffold.data.nbt.tag.DoubleTag; -import com.volmit.iris.scaffold.data.nbt.tag.EndTag; -import com.volmit.iris.scaffold.data.nbt.tag.FloatTag; -import com.volmit.iris.scaffold.data.nbt.tag.IntArrayTag; -import com.volmit.iris.scaffold.data.nbt.tag.IntTag; -import com.volmit.iris.scaffold.data.nbt.tag.ListTag; -import com.volmit.iris.scaffold.data.nbt.tag.LongArrayTag; -import com.volmit.iris.scaffold.data.nbt.tag.LongTag; -import com.volmit.iris.scaffold.data.nbt.tag.ShortTag; -import com.volmit.iris.scaffold.data.nbt.tag.StringTag; -import com.volmit.iris.scaffold.data.nbt.tag.Tag; +import com.volmit.iris.scaffold.data.nbt.tag.*; + import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; @@ -24,130 +12,131 @@ import java.util.Map; public class NBTOutputStream extends DataOutputStream implements MaxDepthIO { - private static Map, Integer, IOException>> writers = new HashMap<>(); - private static Map, Byte> classIdMapping = new HashMap<>(); + private static final Map, Integer, IOException>> writers = new HashMap<>(); + private static final Map, Byte> classIdMapping = new HashMap<>(); - static { - put(EndTag.ID, (o, t, d) -> {}, EndTag.class); - put(ByteTag.ID, (o, t, d) -> writeByte(o, t), ByteTag.class); - put(ShortTag.ID, (o, t, d) -> writeShort(o, t), ShortTag.class); - put(IntTag.ID, (o, t, d) -> writeInt(o, t), IntTag.class); - put(LongTag.ID, (o, t, d) -> writeLong(o, t), LongTag.class); - put(FloatTag.ID, (o, t, d) -> writeFloat(o, t), FloatTag.class); - put(DoubleTag.ID, (o, t, d) -> writeDouble(o, t), DoubleTag.class); - put(ByteArrayTag.ID, (o, t, d) -> writeByteArray(o, t), ByteArrayTag.class); - put(StringTag.ID, (o, t, d) -> writeString(o, t), StringTag.class); - put(ListTag.ID, NBTOutputStream::writeList, ListTag.class); - put(CompoundTag.ID, NBTOutputStream::writeCompound, CompoundTag.class); - put(IntArrayTag.ID, (o, t, d) -> writeIntArray(o, t), IntArrayTag.class); - put(LongArrayTag.ID, (o, t, d) -> writeLongArray(o, t), LongArrayTag.class); - } + static { + put(EndTag.ID, (o, t, d) -> { + }, EndTag.class); + put(ByteTag.ID, (o, t, d) -> writeByte(o, t), ByteTag.class); + put(ShortTag.ID, (o, t, d) -> writeShort(o, t), ShortTag.class); + put(IntTag.ID, (o, t, d) -> writeInt(o, t), IntTag.class); + put(LongTag.ID, (o, t, d) -> writeLong(o, t), LongTag.class); + put(FloatTag.ID, (o, t, d) -> writeFloat(o, t), FloatTag.class); + put(DoubleTag.ID, (o, t, d) -> writeDouble(o, t), DoubleTag.class); + put(ByteArrayTag.ID, (o, t, d) -> writeByteArray(o, t), ByteArrayTag.class); + put(StringTag.ID, (o, t, d) -> writeString(o, t), StringTag.class); + put(ListTag.ID, NBTOutputStream::writeList, ListTag.class); + put(CompoundTag.ID, NBTOutputStream::writeCompound, CompoundTag.class); + put(IntArrayTag.ID, (o, t, d) -> writeIntArray(o, t), IntArrayTag.class); + put(LongArrayTag.ID, (o, t, d) -> writeLongArray(o, t), LongArrayTag.class); + } - private static void put(byte id, ExceptionTriConsumer, Integer, IOException> f, Class clazz) { - writers.put(id, f); - classIdMapping.put(clazz, id); - } + private static void put(byte id, ExceptionTriConsumer, Integer, IOException> f, Class clazz) { + writers.put(id, f); + classIdMapping.put(clazz, id); + } - public NBTOutputStream(OutputStream out) { - super(out); - } + public NBTOutputStream(OutputStream out) { + super(out); + } - public void writeTag(NamedTag tag, int maxDepth) throws IOException { - writeByte(tag.getTag().getID()); - if (tag.getTag().getID() != 0) { - writeUTF(tag.getName() == null ? "" : tag.getName()); - } - writeRawTag(tag.getTag(), maxDepth); - } + public void writeTag(NamedTag tag, int maxDepth) throws IOException { + writeByte(tag.getTag().getID()); + if (tag.getTag().getID() != 0) { + writeUTF(tag.getName() == null ? "" : tag.getName()); + } + writeRawTag(tag.getTag(), maxDepth); + } - public void writeTag(Tag tag, int maxDepth) throws IOException { - writeByte(tag.getID()); - if (tag.getID() != 0) { - writeUTF(""); - } - writeRawTag(tag, maxDepth); - } + public void writeTag(Tag tag, int maxDepth) throws IOException { + writeByte(tag.getID()); + if (tag.getID() != 0) { + writeUTF(""); + } + writeRawTag(tag, maxDepth); + } - public void writeRawTag(Tag tag, int maxDepth) throws IOException { - ExceptionTriConsumer, Integer, IOException> f; - if ((f = writers.get(tag.getID())) == null) { - throw new IOException("invalid tag \"" + tag.getID() + "\""); - } - f.accept(this, tag, maxDepth); - } + public void writeRawTag(Tag tag, int maxDepth) throws IOException { + ExceptionTriConsumer, Integer, IOException> f; + if ((f = writers.get(tag.getID())) == null) { + throw new IOException("invalid tag \"" + tag.getID() + "\""); + } + f.accept(this, tag, maxDepth); + } - static byte idFromClass(Class clazz) { - Byte id = classIdMapping.get(clazz); - if (id == null) { - throw new IllegalArgumentException("unknown Tag class " + clazz.getName()); - } - return id; - } + static byte idFromClass(Class clazz) { + Byte id = classIdMapping.get(clazz); + if (id == null) { + throw new IllegalArgumentException("unknown Tag class " + clazz.getName()); + } + return id; + } - private static void writeByte(NBTOutputStream out, Tag tag) throws IOException { - out.writeByte(((ByteTag) tag).asByte()); - } - - private static void writeShort(NBTOutputStream out, Tag tag) throws IOException { - out.writeShort(((ShortTag) tag).asShort()); - } - - private static void writeInt(NBTOutputStream out, Tag tag) throws IOException { - out.writeInt(((IntTag) tag).asInt()); - } + private static void writeByte(NBTOutputStream out, Tag tag) throws IOException { + out.writeByte(((ByteTag) tag).asByte()); + } - private static void writeLong(NBTOutputStream out, Tag tag) throws IOException { - out.writeLong(((LongTag) tag).asLong()); - } + private static void writeShort(NBTOutputStream out, Tag tag) throws IOException { + out.writeShort(((ShortTag) tag).asShort()); + } - private static void writeFloat(NBTOutputStream out, Tag tag) throws IOException { - out.writeFloat(((FloatTag) tag).asFloat()); - } + private static void writeInt(NBTOutputStream out, Tag tag) throws IOException { + out.writeInt(((IntTag) tag).asInt()); + } - private static void writeDouble(NBTOutputStream out, Tag tag) throws IOException { - out.writeDouble(((DoubleTag) tag).asDouble()); - } + private static void writeLong(NBTOutputStream out, Tag tag) throws IOException { + out.writeLong(((LongTag) tag).asLong()); + } - private static void writeString(NBTOutputStream out, Tag tag) throws IOException { - out.writeUTF(((StringTag) tag).getValue()); - } + private static void writeFloat(NBTOutputStream out, Tag tag) throws IOException { + out.writeFloat(((FloatTag) tag).asFloat()); + } - private static void writeByteArray(NBTOutputStream out, Tag tag) throws IOException { - out.writeInt(((ByteArrayTag) tag).length()); - out.write(((ByteArrayTag) tag).getValue()); - } + private static void writeDouble(NBTOutputStream out, Tag tag) throws IOException { + out.writeDouble(((DoubleTag) tag).asDouble()); + } - private static void writeIntArray(NBTOutputStream out, Tag tag) throws IOException { - out.writeInt(((IntArrayTag) tag).length()); - for (int i : ((IntArrayTag) tag).getValue()) { - out.writeInt(i); - } - } + private static void writeString(NBTOutputStream out, Tag tag) throws IOException { + out.writeUTF(((StringTag) tag).getValue()); + } - private static void writeLongArray(NBTOutputStream out, Tag tag) throws IOException { - out.writeInt(((LongArrayTag) tag).length()); - for (long l : ((LongArrayTag) tag).getValue()) { - out.writeLong(l); - } - } + private static void writeByteArray(NBTOutputStream out, Tag tag) throws IOException { + out.writeInt(((ByteArrayTag) tag).length()); + out.write(((ByteArrayTag) tag).getValue()); + } - private static void writeList(NBTOutputStream out, Tag tag, int maxDepth) throws IOException { - out.writeByte(idFromClass(((ListTag) tag).getTypeClass())); - out.writeInt(((ListTag) tag).size()); - for (Tag t : ((ListTag) tag)) { - out.writeRawTag(t, out.decrementMaxDepth(maxDepth)); - } - } + private static void writeIntArray(NBTOutputStream out, Tag tag) throws IOException { + out.writeInt(((IntArrayTag) tag).length()); + for (int i : ((IntArrayTag) tag).getValue()) { + out.writeInt(i); + } + } - private static void writeCompound(NBTOutputStream out, Tag tag, int maxDepth) throws IOException { - for (Map.Entry> entry : (CompoundTag) tag) { - if (entry.getValue().getID() == 0) { - throw new IOException("end tag not allowed"); - } - out.writeByte(entry.getValue().getID()); - out.writeUTF(entry.getKey()); - out.writeRawTag(entry.getValue(), out.decrementMaxDepth(maxDepth)); - } - out.writeByte(0); - } + private static void writeLongArray(NBTOutputStream out, Tag tag) throws IOException { + out.writeInt(((LongArrayTag) tag).length()); + for (long l : ((LongArrayTag) tag).getValue()) { + out.writeLong(l); + } + } + + private static void writeList(NBTOutputStream out, Tag tag, int maxDepth) throws IOException { + out.writeByte(idFromClass(((ListTag) tag).getTypeClass())); + out.writeInt(((ListTag) tag).size()); + for (Tag t : ((ListTag) tag)) { + out.writeRawTag(t, out.decrementMaxDepth(maxDepth)); + } + } + + private static void writeCompound(NBTOutputStream out, Tag tag, int maxDepth) throws IOException { + for (Map.Entry> entry : (CompoundTag) tag) { + if (entry.getValue().getID() == 0) { + throw new IOException("end tag not allowed"); + } + out.writeByte(entry.getValue().getID()); + out.writeUTF(entry.getKey()); + out.writeRawTag(entry.getValue(), out.decrementMaxDepth(maxDepth)); + } + out.writeByte(0); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NBTSerializer.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NBTSerializer.java index 74973e4fe..6f7cbb321 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NBTSerializer.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NBTSerializer.java @@ -2,31 +2,32 @@ package com.volmit.iris.scaffold.data.nbt.io; import com.volmit.iris.scaffold.data.io.Serializer; import com.volmit.iris.scaffold.data.nbt.tag.Tag; + import java.io.IOException; import java.io.OutputStream; import java.util.zip.GZIPOutputStream; public class NBTSerializer implements Serializer { - private boolean compressed; + private final boolean compressed; - public NBTSerializer() { - this(true); - } + public NBTSerializer() { + this(true); + } - public NBTSerializer(boolean compressed) { - this.compressed = compressed; - } + public NBTSerializer(boolean compressed) { + this.compressed = compressed; + } - @Override - public void toStream(NamedTag object, OutputStream out) throws IOException { - NBTOutputStream nbtOut; - if (compressed) { - nbtOut = new NBTOutputStream(new GZIPOutputStream(out, true)); - } else { - nbtOut = new NBTOutputStream(out); - } - nbtOut.writeTag(object, Tag.DEFAULT_MAX_DEPTH); - nbtOut.flush(); - } + @Override + public void toStream(NamedTag object, OutputStream out) throws IOException { + NBTOutputStream nbtOut; + if (compressed) { + nbtOut = new NBTOutputStream(new GZIPOutputStream(out, true)); + } else { + nbtOut = new NBTOutputStream(out); + } + nbtOut.writeTag(object, Tag.DEFAULT_MAX_DEPTH); + nbtOut.flush(); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NBTUtil.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NBTUtil.java index 05eb09b75..6f11e681f 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NBTUtil.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NBTUtil.java @@ -1,80 +1,77 @@ package com.volmit.iris.scaffold.data.nbt.io; import com.volmit.iris.scaffold.data.nbt.tag.Tag; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileOutputStream; -import java.io.IOException; -import java.io.InputStream; -import java.io.PushbackInputStream; + +import java.io.*; import java.util.zip.GZIPInputStream; public final class NBTUtil { - private NBTUtil() {} + private NBTUtil() { + } - public static void write(NamedTag tag, File file, boolean compressed) throws IOException { - try (FileOutputStream fos = new FileOutputStream(file)) { - new NBTSerializer(compressed).toStream(tag, fos); - } - } + public static void write(NamedTag tag, File file, boolean compressed) throws IOException { + try (FileOutputStream fos = new FileOutputStream(file)) { + new NBTSerializer(compressed).toStream(tag, fos); + } + } - public static void write(NamedTag tag, String file, boolean compressed) throws IOException { - write(tag, new File(file), compressed); - } + public static void write(NamedTag tag, String file, boolean compressed) throws IOException { + write(tag, new File(file), compressed); + } - public static void write(NamedTag tag, File file) throws IOException { - write(tag, file, true); - } + public static void write(NamedTag tag, File file) throws IOException { + write(tag, file, true); + } - public static void write(NamedTag tag, String file) throws IOException { - write(tag, new File(file), true); - } + public static void write(NamedTag tag, String file) throws IOException { + write(tag, new File(file), true); + } - public static void write(Tag tag, File file, boolean compressed) throws IOException { - write(new NamedTag(null, tag), file, compressed); - } + public static void write(Tag tag, File file, boolean compressed) throws IOException { + write(new NamedTag(null, tag), file, compressed); + } - public static void write(Tag tag, String file, boolean compressed) throws IOException { - write(new NamedTag(null, tag), new File(file), compressed); - } + public static void write(Tag tag, String file, boolean compressed) throws IOException { + write(new NamedTag(null, tag), new File(file), compressed); + } - public static void write(Tag tag, File file) throws IOException { - write(new NamedTag(null, tag), file, true); - } + public static void write(Tag tag, File file) throws IOException { + write(new NamedTag(null, tag), file, true); + } - public static void write(Tag tag, String file) throws IOException { - write(new NamedTag(null, tag), new File(file), true); - } + public static void write(Tag tag, String file) throws IOException { + write(new NamedTag(null, tag), new File(file), true); + } - public static NamedTag read(File file, boolean compressed) throws IOException { - try (FileInputStream fis = new FileInputStream(file)) { - return new NBTDeserializer(compressed).fromStream(fis); - } - } + public static NamedTag read(File file, boolean compressed) throws IOException { + try (FileInputStream fis = new FileInputStream(file)) { + return new NBTDeserializer(compressed).fromStream(fis); + } + } - public static NamedTag read(String file, boolean compressed) throws IOException { - return read(new File(file), compressed); - } + public static NamedTag read(String file, boolean compressed) throws IOException { + return read(new File(file), compressed); + } - public static NamedTag read(File file) throws IOException { - try (FileInputStream fis = new FileInputStream(file)) { - return new NBTDeserializer(false).fromStream(detectDecompression(fis)); - } - } + public static NamedTag read(File file) throws IOException { + try (FileInputStream fis = new FileInputStream(file)) { + return new NBTDeserializer(false).fromStream(detectDecompression(fis)); + } + } - public static NamedTag read(String file) throws IOException { - return read(new File(file)); - } + public static NamedTag read(String file) throws IOException { + return read(new File(file)); + } - private static InputStream detectDecompression(InputStream is) throws IOException { - PushbackInputStream pbis = new PushbackInputStream(is, 2); - int signature = (pbis.read() & 0xFF) + (pbis.read() << 8); - pbis.unread(signature >> 8); - pbis.unread(signature & 0xFF); - if (signature == GZIPInputStream.GZIP_MAGIC) { - return new GZIPInputStream(pbis); - } - return pbis; - } + private static InputStream detectDecompression(InputStream is) throws IOException { + PushbackInputStream pbis = new PushbackInputStream(is, 2); + int signature = (pbis.read() & 0xFF) + (pbis.read() << 8); + pbis.unread(signature >> 8); + pbis.unread(signature & 0xFF); + if (signature == GZIPInputStream.GZIP_MAGIC) { + return new GZIPInputStream(pbis); + } + return pbis; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NamedTag.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NamedTag.java index 2fafd76c0..27996f552 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NamedTag.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/NamedTag.java @@ -4,27 +4,27 @@ import com.volmit.iris.scaffold.data.nbt.tag.Tag; public class NamedTag { - private String name; - private Tag tag; + private String name; + private Tag tag; - public NamedTag(String name, Tag tag) { - this.name = name; - this.tag = tag; - } + public NamedTag(String name, Tag tag) { + this.name = name; + this.tag = tag; + } - public void setName(String name) { - this.name = name; - } + public void setName(String name) { + this.name = name; + } - public void setTag(Tag tag) { - this.tag = tag; - } + public void setTag(Tag tag) { + this.tag = tag; + } - public String getName() { - return name; - } + public String getName() { + return name; + } - public Tag getTag() { - return tag; - } + public Tag getTag() { + return tag; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/ParseException.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/ParseException.java index 91c20fc12..50d8b8614 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/ParseException.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/ParseException.java @@ -4,22 +4,22 @@ import java.io.IOException; public class ParseException extends IOException { - public ParseException(String msg) { - super(msg); - } + public ParseException(String msg) { + super(msg); + } - public ParseException(String msg, String value, int index) { - super(msg + " at: " + formatError(value, index)); - } + public ParseException(String msg, String value, int index) { + super(msg + " at: " + formatError(value, index)); + } - private static String formatError(String value, int index) { - StringBuilder builder = new StringBuilder(); - int i = Math.min(value.length(), index); - if (i > 35) { - builder.append("..."); - } - builder.append(value, Math.max(0, i - 35), i); - builder.append("<--[HERE]"); - return builder.toString(); - } + private static String formatError(String value, int index) { + StringBuilder builder = new StringBuilder(); + int i = Math.min(value.length(), index); + if (i > 35) { + builder.append("..."); + } + builder.append(value, Math.max(0, i - 35), i); + builder.append("<--[HERE]"); + return builder.toString(); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/SNBTDeserializer.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/SNBTDeserializer.java index aea21774a..4f5ddebbc 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/SNBTDeserializer.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/SNBTDeserializer.java @@ -2,6 +2,7 @@ package com.volmit.iris.scaffold.data.nbt.io; import com.volmit.iris.scaffold.data.io.StringDeserializer; import com.volmit.iris.scaffold.data.nbt.tag.Tag; + import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; @@ -9,18 +10,18 @@ import java.util.stream.Collectors; public class SNBTDeserializer implements StringDeserializer> { - @Override - public Tag fromReader(Reader reader) throws IOException { - return fromReader(reader, Tag.DEFAULT_MAX_DEPTH); - } + @Override + public Tag fromReader(Reader reader) throws IOException { + return fromReader(reader, Tag.DEFAULT_MAX_DEPTH); + } - public Tag fromReader(Reader reader, int maxDepth) throws IOException { - BufferedReader bufferedReader; - if (reader instanceof BufferedReader) { - bufferedReader = (BufferedReader) reader; - } else { - bufferedReader = new BufferedReader(reader); - } - return SNBTParser.parse(bufferedReader.lines().collect(Collectors.joining()), maxDepth); - } + public Tag fromReader(Reader reader, int maxDepth) throws IOException { + BufferedReader bufferedReader; + if (reader instanceof BufferedReader) { + bufferedReader = (BufferedReader) reader; + } else { + bufferedReader = new BufferedReader(reader); + } + return SNBTParser.parse(bufferedReader.lines().collect(Collectors.joining()), maxDepth); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/SNBTParser.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/SNBTParser.java index 46b3ed6d9..ed3c36001 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/SNBTParser.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/SNBTParser.java @@ -1,244 +1,231 @@ package com.volmit.iris.scaffold.data.nbt.io; import com.volmit.iris.scaffold.data.io.MaxDepthIO; -import com.volmit.iris.scaffold.data.nbt.tag.ArrayTag; -import com.volmit.iris.scaffold.data.nbt.tag.ByteArrayTag; -import com.volmit.iris.scaffold.data.nbt.tag.ByteTag; -import com.volmit.iris.scaffold.data.nbt.tag.CompoundTag; -import com.volmit.iris.scaffold.data.nbt.tag.DoubleTag; -import com.volmit.iris.scaffold.data.nbt.tag.EndTag; -import com.volmit.iris.scaffold.data.nbt.tag.FloatTag; -import com.volmit.iris.scaffold.data.nbt.tag.IntArrayTag; -import com.volmit.iris.scaffold.data.nbt.tag.IntTag; -import com.volmit.iris.scaffold.data.nbt.tag.ListTag; -import com.volmit.iris.scaffold.data.nbt.tag.LongArrayTag; -import com.volmit.iris.scaffold.data.nbt.tag.LongTag; -import com.volmit.iris.scaffold.data.nbt.tag.ShortTag; -import com.volmit.iris.scaffold.data.nbt.tag.StringTag; -import com.volmit.iris.scaffold.data.nbt.tag.Tag; +import com.volmit.iris.scaffold.data.nbt.tag.*; + import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; public final class SNBTParser implements MaxDepthIO { - private static final Pattern - FLOAT_LITERAL_PATTERN = Pattern.compile("^[-+]?(?:\\d+\\.?|\\d*\\.\\d+)(?:e[-+]?\\d+)?f$", Pattern.CASE_INSENSITIVE), - DOUBLE_LITERAL_PATTERN = Pattern.compile("^[-+]?(?:\\d+\\.?|\\d*\\.\\d+)(?:e[-+]?\\d+)?d$", Pattern.CASE_INSENSITIVE), - DOUBLE_LITERAL_NO_SUFFIX_PATTERN = Pattern.compile("^[-+]?(?:\\d+\\.|\\d*\\.\\d+)(?:e[-+]?\\d+)?$", Pattern.CASE_INSENSITIVE), - BYTE_LITERAL_PATTERN = Pattern.compile("^[-+]?\\d+b$", Pattern.CASE_INSENSITIVE), - SHORT_LITERAL_PATTERN = Pattern.compile("^[-+]?\\d+s$", Pattern.CASE_INSENSITIVE), - INT_LITERAL_PATTERN = Pattern.compile("^[-+]?\\d+$", Pattern.CASE_INSENSITIVE), - LONG_LITERAL_PATTERN = Pattern.compile("^[-+]?\\d+l$", Pattern.CASE_INSENSITIVE), - NUMBER_PATTERN = Pattern.compile("^[-+]?\\d+$"); + private static final Pattern + FLOAT_LITERAL_PATTERN = Pattern.compile("^[-+]?(?:\\d+\\.?|\\d*\\.\\d+)(?:e[-+]?\\d+)?f$", Pattern.CASE_INSENSITIVE), + DOUBLE_LITERAL_PATTERN = Pattern.compile("^[-+]?(?:\\d+\\.?|\\d*\\.\\d+)(?:e[-+]?\\d+)?d$", Pattern.CASE_INSENSITIVE), + DOUBLE_LITERAL_NO_SUFFIX_PATTERN = Pattern.compile("^[-+]?(?:\\d+\\.|\\d*\\.\\d+)(?:e[-+]?\\d+)?$", Pattern.CASE_INSENSITIVE), + BYTE_LITERAL_PATTERN = Pattern.compile("^[-+]?\\d+b$", Pattern.CASE_INSENSITIVE), + SHORT_LITERAL_PATTERN = Pattern.compile("^[-+]?\\d+s$", Pattern.CASE_INSENSITIVE), + INT_LITERAL_PATTERN = Pattern.compile("^[-+]?\\d+$", Pattern.CASE_INSENSITIVE), + LONG_LITERAL_PATTERN = Pattern.compile("^[-+]?\\d+l$", Pattern.CASE_INSENSITIVE), + NUMBER_PATTERN = Pattern.compile("^[-+]?\\d+$"); - private StringPointer ptr; + private final StringPointer ptr; - private SNBTParser(String string) { - this.ptr = new StringPointer(string); - } + private SNBTParser(String string) { + this.ptr = new StringPointer(string); + } - public static Tag parse(String string, int maxDepth) throws ParseException { - SNBTParser parser = new SNBTParser(string); - Tag tag = parser.parseAnything(maxDepth); - parser.ptr.skipWhitespace(); - if (parser.ptr.hasNext()) { - throw parser.ptr.parseException("invalid characters after end of snbt"); - } - return tag; - } + public static Tag parse(String string, int maxDepth) throws ParseException { + SNBTParser parser = new SNBTParser(string); + Tag tag = parser.parseAnything(maxDepth); + parser.ptr.skipWhitespace(); + if (parser.ptr.hasNext()) { + throw parser.ptr.parseException("invalid characters after end of snbt"); + } + return tag; + } - public static Tag parse(String string) throws ParseException { - return parse(string, Tag.DEFAULT_MAX_DEPTH); - } + public static Tag parse(String string) throws ParseException { + return parse(string, Tag.DEFAULT_MAX_DEPTH); + } - private Tag parseAnything(int maxDepth) throws ParseException { - ptr.skipWhitespace(); - switch (ptr.currentChar()) { - case '{': - return parseCompoundTag(maxDepth); - case '[': - if (ptr.hasCharsLeft(2) && ptr.lookAhead(1) != '"' && ptr.lookAhead(2) == ';') { - return parseNumArray(); - } - return parseListTag(maxDepth); - } - return parseStringOrLiteral(); - } + private Tag parseAnything(int maxDepth) throws ParseException { + ptr.skipWhitespace(); + switch (ptr.currentChar()) { + case '{': + return parseCompoundTag(maxDepth); + case '[': + if (ptr.hasCharsLeft(2) && ptr.lookAhead(1) != '"' && ptr.lookAhead(2) == ';') { + return parseNumArray(); + } + return parseListTag(maxDepth); + } + return parseStringOrLiteral(); + } - private Tag parseStringOrLiteral() throws ParseException { - ptr.skipWhitespace(); - if (ptr.currentChar() == '"') { - return new StringTag(ptr.parseQuotedString()); - } - String s = ptr.parseSimpleString(); - if (s.isEmpty()) { - throw new ParseException("expected non empty value"); - } - if (FLOAT_LITERAL_PATTERN.matcher(s).matches()) { - return new FloatTag(Float.parseFloat(s.substring(0, s.length() - 1))); - } else if (BYTE_LITERAL_PATTERN.matcher(s).matches()) { - try { - return new ByteTag(Byte.parseByte(s.substring(0, s.length() - 1))); - } catch (NumberFormatException ex) { - throw ptr.parseException("byte not in range: \"" + s.substring(0, s.length() - 1) + "\""); - } - } else if (SHORT_LITERAL_PATTERN.matcher(s).matches()) { - try { - return new ShortTag(Short.parseShort(s.substring(0, s.length() - 1))); - } catch (NumberFormatException ex) { - throw ptr.parseException("short not in range: \"" + s.substring(0, s.length() - 1) + "\""); - } - } else if (LONG_LITERAL_PATTERN.matcher(s).matches()) { - try { - return new LongTag(Long.parseLong(s.substring(0, s.length() - 1))); - } catch (NumberFormatException ex) { - throw ptr.parseException("long not in range: \"" + s.substring(0, s.length() - 1) + "\""); - } - } else if (INT_LITERAL_PATTERN.matcher(s).matches()) { - try { - return new IntTag(Integer.parseInt(s)); - } catch (NumberFormatException ex) { - throw ptr.parseException("int not in range: \"" + s.substring(0, s.length() - 1) + "\""); - } - } else if (DOUBLE_LITERAL_PATTERN.matcher(s).matches()) { - return new DoubleTag(Double.parseDouble(s.substring(0, s.length() - 1))); - } else if (DOUBLE_LITERAL_NO_SUFFIX_PATTERN.matcher(s).matches()) { - return new DoubleTag(Double.parseDouble(s)); - } else if ("true".equalsIgnoreCase(s)) { - return new ByteTag(true); - } else if ("false".equalsIgnoreCase(s)) { - return new ByteTag(false); - } - return new StringTag(s); - } + private Tag parseStringOrLiteral() throws ParseException { + ptr.skipWhitespace(); + if (ptr.currentChar() == '"') { + return new StringTag(ptr.parseQuotedString()); + } + String s = ptr.parseSimpleString(); + if (s.isEmpty()) { + throw new ParseException("expected non empty value"); + } + if (FLOAT_LITERAL_PATTERN.matcher(s).matches()) { + return new FloatTag(Float.parseFloat(s.substring(0, s.length() - 1))); + } else if (BYTE_LITERAL_PATTERN.matcher(s).matches()) { + try { + return new ByteTag(Byte.parseByte(s.substring(0, s.length() - 1))); + } catch (NumberFormatException ex) { + throw ptr.parseException("byte not in range: \"" + s.substring(0, s.length() - 1) + "\""); + } + } else if (SHORT_LITERAL_PATTERN.matcher(s).matches()) { + try { + return new ShortTag(Short.parseShort(s.substring(0, s.length() - 1))); + } catch (NumberFormatException ex) { + throw ptr.parseException("short not in range: \"" + s.substring(0, s.length() - 1) + "\""); + } + } else if (LONG_LITERAL_PATTERN.matcher(s).matches()) { + try { + return new LongTag(Long.parseLong(s.substring(0, s.length() - 1))); + } catch (NumberFormatException ex) { + throw ptr.parseException("long not in range: \"" + s.substring(0, s.length() - 1) + "\""); + } + } else if (INT_LITERAL_PATTERN.matcher(s).matches()) { + try { + return new IntTag(Integer.parseInt(s)); + } catch (NumberFormatException ex) { + throw ptr.parseException("int not in range: \"" + s.substring(0, s.length() - 1) + "\""); + } + } else if (DOUBLE_LITERAL_PATTERN.matcher(s).matches()) { + return new DoubleTag(Double.parseDouble(s.substring(0, s.length() - 1))); + } else if (DOUBLE_LITERAL_NO_SUFFIX_PATTERN.matcher(s).matches()) { + return new DoubleTag(Double.parseDouble(s)); + } else if ("true".equalsIgnoreCase(s)) { + return new ByteTag(true); + } else if ("false".equalsIgnoreCase(s)) { + return new ByteTag(false); + } + return new StringTag(s); + } - private CompoundTag parseCompoundTag(int maxDepth) throws ParseException { - ptr.expectChar('{'); + private CompoundTag parseCompoundTag(int maxDepth) throws ParseException { + ptr.expectChar('{'); - CompoundTag compoundTag = new CompoundTag(); + CompoundTag compoundTag = new CompoundTag(); - ptr.skipWhitespace(); - while (ptr.hasNext() && ptr.currentChar() != '}') { - ptr.skipWhitespace(); - String key = ptr.currentChar() == '"' ? ptr.parseQuotedString() : ptr.parseSimpleString(); - if (key.isEmpty()) { - throw new ParseException("empty keys are not allowed"); - } - ptr.expectChar(':'); + ptr.skipWhitespace(); + while (ptr.hasNext() && ptr.currentChar() != '}') { + ptr.skipWhitespace(); + String key = ptr.currentChar() == '"' ? ptr.parseQuotedString() : ptr.parseSimpleString(); + if (key.isEmpty()) { + throw new ParseException("empty keys are not allowed"); + } + ptr.expectChar(':'); - compoundTag.put(key, parseAnything(decrementMaxDepth(maxDepth))); + compoundTag.put(key, parseAnything(decrementMaxDepth(maxDepth))); - if (!ptr.nextArrayElement()) { - break; - } - } - ptr.expectChar('}'); - return compoundTag; - } + if (!ptr.nextArrayElement()) { + break; + } + } + ptr.expectChar('}'); + return compoundTag; + } - private ListTag parseListTag(int maxDepth) throws ParseException { - ptr.expectChar('['); - ptr.skipWhitespace(); - ListTag list = ListTag.createUnchecked(EndTag.class); - while (ptr.currentChar() != ']') { - Tag element = parseAnything(decrementMaxDepth(maxDepth)); - try { - list.addUnchecked(element); - } catch (IllegalArgumentException ex) { - throw ptr.parseException(ex.getMessage()); - } - if (!ptr.nextArrayElement()) { - break; - } - } - ptr.expectChar(']'); - return list; - } + private ListTag parseListTag(int maxDepth) throws ParseException { + ptr.expectChar('['); + ptr.skipWhitespace(); + ListTag list = ListTag.createUnchecked(EndTag.class); + while (ptr.currentChar() != ']') { + Tag element = parseAnything(decrementMaxDepth(maxDepth)); + try { + list.addUnchecked(element); + } catch (IllegalArgumentException ex) { + throw ptr.parseException(ex.getMessage()); + } + if (!ptr.nextArrayElement()) { + break; + } + } + ptr.expectChar(']'); + return list; + } - private ArrayTag parseNumArray() throws ParseException { - ptr.expectChar('['); - char arrayType = ptr.next(); - ptr.expectChar(';'); - ptr.skipWhitespace(); - switch (arrayType) { - case 'B': - return parseByteArrayTag(); - case 'I': - return parseIntArrayTag(); - case 'L': - return parseLongArrayTag(); - } - throw new ParseException("invalid array type '" + arrayType + "'"); - } + private ArrayTag parseNumArray() throws ParseException { + ptr.expectChar('['); + char arrayType = ptr.next(); + ptr.expectChar(';'); + ptr.skipWhitespace(); + switch (arrayType) { + case 'B': + return parseByteArrayTag(); + case 'I': + return parseIntArrayTag(); + case 'L': + return parseLongArrayTag(); + } + throw new ParseException("invalid array type '" + arrayType + "'"); + } - private ByteArrayTag parseByteArrayTag() throws ParseException { - List byteList = new ArrayList<>(); - while (ptr.currentChar() != ']') { - String s = ptr.parseSimpleString(); - ptr.skipWhitespace(); - if (NUMBER_PATTERN.matcher(s).matches()) { - try { - byteList.add(Byte.parseByte(s)); - } catch (NumberFormatException ex) { - throw ptr.parseException("byte not in range: \"" + s + "\""); - } - } else { - throw ptr.parseException("invalid byte in ByteArrayTag: \"" + s + "\""); - } - if (!ptr.nextArrayElement()) { - break; - } - } - ptr.expectChar(']'); - byte[] bytes = new byte[byteList.size()]; - for (int i = 0; i < byteList.size(); i++) { - bytes[i] = byteList.get(i); - } - return new ByteArrayTag(bytes); - } + private ByteArrayTag parseByteArrayTag() throws ParseException { + List byteList = new ArrayList<>(); + while (ptr.currentChar() != ']') { + String s = ptr.parseSimpleString(); + ptr.skipWhitespace(); + if (NUMBER_PATTERN.matcher(s).matches()) { + try { + byteList.add(Byte.parseByte(s)); + } catch (NumberFormatException ex) { + throw ptr.parseException("byte not in range: \"" + s + "\""); + } + } else { + throw ptr.parseException("invalid byte in ByteArrayTag: \"" + s + "\""); + } + if (!ptr.nextArrayElement()) { + break; + } + } + ptr.expectChar(']'); + byte[] bytes = new byte[byteList.size()]; + for (int i = 0; i < byteList.size(); i++) { + bytes[i] = byteList.get(i); + } + return new ByteArrayTag(bytes); + } - private IntArrayTag parseIntArrayTag() throws ParseException { - List intList = new ArrayList<>(); - while (ptr.currentChar() != ']') { - String s = ptr.parseSimpleString(); - ptr.skipWhitespace(); - if (NUMBER_PATTERN.matcher(s).matches()) { - try { - intList.add(Integer.parseInt(s)); - } catch (NumberFormatException ex) { - throw ptr.parseException("int not in range: \"" + s + "\""); - } - } else { - throw ptr.parseException("invalid int in IntArrayTag: \"" + s + "\""); - } - if (!ptr.nextArrayElement()) { - break; - } - } - ptr.expectChar(']'); - return new IntArrayTag(intList.stream().mapToInt(i -> i).toArray()); - } + private IntArrayTag parseIntArrayTag() throws ParseException { + List intList = new ArrayList<>(); + while (ptr.currentChar() != ']') { + String s = ptr.parseSimpleString(); + ptr.skipWhitespace(); + if (NUMBER_PATTERN.matcher(s).matches()) { + try { + intList.add(Integer.parseInt(s)); + } catch (NumberFormatException ex) { + throw ptr.parseException("int not in range: \"" + s + "\""); + } + } else { + throw ptr.parseException("invalid int in IntArrayTag: \"" + s + "\""); + } + if (!ptr.nextArrayElement()) { + break; + } + } + ptr.expectChar(']'); + return new IntArrayTag(intList.stream().mapToInt(i -> i).toArray()); + } - private LongArrayTag parseLongArrayTag() throws ParseException { - List longList = new ArrayList<>(); - while (ptr.currentChar() != ']') { - String s = ptr.parseSimpleString(); - ptr.skipWhitespace(); - if (NUMBER_PATTERN.matcher(s).matches()) { - try { - longList.add(Long.parseLong(s)); - } catch (NumberFormatException ex) { - throw ptr.parseException("long not in range: \"" + s + "\""); - } - } else { - throw ptr.parseException("invalid long in LongArrayTag: \"" + s + "\""); - } - if (!ptr.nextArrayElement()) { - break; - } - } - ptr.expectChar(']'); - return new LongArrayTag(longList.stream().mapToLong(l -> l).toArray()); - } + private LongArrayTag parseLongArrayTag() throws ParseException { + List longList = new ArrayList<>(); + while (ptr.currentChar() != ']') { + String s = ptr.parseSimpleString(); + ptr.skipWhitespace(); + if (NUMBER_PATTERN.matcher(s).matches()) { + try { + longList.add(Long.parseLong(s)); + } catch (NumberFormatException ex) { + throw ptr.parseException("long not in range: \"" + s + "\""); + } + } else { + throw ptr.parseException("invalid long in LongArrayTag: \"" + s + "\""); + } + if (!ptr.nextArrayElement()) { + break; + } + } + ptr.expectChar(']'); + return new LongArrayTag(longList.stream().mapToLong(l -> l).toArray()); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/SNBTSerializer.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/SNBTSerializer.java index 78653a673..14e8db35f 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/SNBTSerializer.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/SNBTSerializer.java @@ -8,12 +8,12 @@ import java.io.Writer; public class SNBTSerializer implements StringSerializer> { - @Override - public void toWriter(Tag tag, Writer writer) throws IOException { - SNBTWriter.write(tag, writer); - } + @Override + public void toWriter(Tag tag, Writer writer) throws IOException { + SNBTWriter.write(tag, writer); + } - public void toWriter(Tag tag, Writer writer, int maxDepth) throws IOException { - SNBTWriter.write(tag, writer, maxDepth); - } + public void toWriter(Tag tag, Writer writer, int maxDepth) throws IOException { + SNBTWriter.write(tag, writer, maxDepth); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/SNBTUtil.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/SNBTUtil.java index 48c5d8641..d50edaf4b 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/SNBTUtil.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/SNBTUtil.java @@ -6,11 +6,11 @@ import java.io.IOException; public class SNBTUtil { - public static String toSNBT(Tag tag) throws IOException { - return new SNBTSerializer().toString(tag); - } + public static String toSNBT(Tag tag) throws IOException { + return new SNBTSerializer().toString(tag); + } - public static Tag fromSNBT(String string) throws IOException { - return new SNBTDeserializer().fromString(string); - } + public static Tag fromSNBT(String string) throws IOException { + return new SNBTDeserializer().fromString(string); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/SNBTWriter.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/SNBTWriter.java index 9dbff0892..e9bf82fd3 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/SNBTWriter.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/SNBTWriter.java @@ -1,20 +1,8 @@ package com.volmit.iris.scaffold.data.nbt.io; import com.volmit.iris.scaffold.data.io.MaxDepthIO; -import com.volmit.iris.scaffold.data.nbt.tag.ByteArrayTag; -import com.volmit.iris.scaffold.data.nbt.tag.ByteTag; -import com.volmit.iris.scaffold.data.nbt.tag.CompoundTag; -import com.volmit.iris.scaffold.data.nbt.tag.DoubleTag; -import com.volmit.iris.scaffold.data.nbt.tag.EndTag; -import com.volmit.iris.scaffold.data.nbt.tag.FloatTag; -import com.volmit.iris.scaffold.data.nbt.tag.IntArrayTag; -import com.volmit.iris.scaffold.data.nbt.tag.IntTag; -import com.volmit.iris.scaffold.data.nbt.tag.ListTag; -import com.volmit.iris.scaffold.data.nbt.tag.LongArrayTag; -import com.volmit.iris.scaffold.data.nbt.tag.LongTag; -import com.volmit.iris.scaffold.data.nbt.tag.ShortTag; -import com.volmit.iris.scaffold.data.nbt.tag.StringTag; -import com.volmit.iris.scaffold.data.nbt.tag.Tag; +import com.volmit.iris.scaffold.data.nbt.tag.*; + import java.io.IOException; import java.io.Writer; import java.lang.reflect.Array; @@ -23,107 +11,106 @@ import java.util.regex.Pattern; /** * SNBTWriter creates an SNBT String. - * - * */ + */ public final class SNBTWriter implements MaxDepthIO { - private static final Pattern NON_QUOTE_PATTERN = Pattern.compile("[a-zA-Z_.+\\-]+"); + private static final Pattern NON_QUOTE_PATTERN = Pattern.compile("[a-zA-Z_.+\\-]+"); - private Writer writer; + private final Writer writer; - private SNBTWriter(Writer writer) { - this.writer = writer; - } + private SNBTWriter(Writer writer) { + this.writer = writer; + } - public static void write(Tag tag, Writer writer, int maxDepth) throws IOException { - new SNBTWriter(writer).writeAnything(tag, maxDepth); - } + public static void write(Tag tag, Writer writer, int maxDepth) throws IOException { + new SNBTWriter(writer).writeAnything(tag, maxDepth); + } - public static void write(Tag tag, Writer writer) throws IOException { - write(tag, writer, Tag.DEFAULT_MAX_DEPTH); - } + public static void write(Tag tag, Writer writer) throws IOException { + write(tag, writer, Tag.DEFAULT_MAX_DEPTH); + } - private void writeAnything(Tag tag, int maxDepth) throws IOException { - switch (tag.getID()) { - case EndTag.ID: - //do nothing - break; - case ByteTag.ID: - writer.append(Byte.toString(((ByteTag) tag).asByte())).write('b'); - break; - case ShortTag.ID: - writer.append(Short.toString(((ShortTag) tag).asShort())).write('s'); - break; - case IntTag.ID: - writer.write(Integer.toString(((IntTag) tag).asInt())); - break; - case LongTag.ID: - writer.append(Long.toString(((LongTag) tag).asLong())).write('l'); - break; - case FloatTag.ID: - writer.append(Float.toString(((FloatTag) tag).asFloat())).write('f'); - break; - case DoubleTag.ID: - writer.append(Double.toString(((DoubleTag) tag).asDouble())).write('d'); - break; - case ByteArrayTag.ID: - writeArray(((ByteArrayTag) tag).getValue(), ((ByteArrayTag) tag).length(), "B"); - break; - case StringTag.ID: - writer.write(escapeString(((StringTag) tag).getValue())); - break; - case ListTag.ID: - writer.write('['); - for (int i = 0; i < ((ListTag) tag).size(); i++) { - writer.write(i == 0 ? "" : ","); - writeAnything(((ListTag) tag).get(i), decrementMaxDepth(maxDepth)); - } - writer.write(']'); - break; - case CompoundTag.ID: - writer.write('{'); - boolean first = true; - for (Map.Entry> entry : (CompoundTag) tag) { - writer.write(first ? "" : ","); - writer.append(escapeString(entry.getKey())).write(':'); - writeAnything(entry.getValue(), decrementMaxDepth(maxDepth)); - first = false; - } - writer.write('}'); - break; - case IntArrayTag.ID: - writeArray(((IntArrayTag) tag).getValue(), ((IntArrayTag) tag).length(), "I"); - break; - case LongArrayTag.ID: - writeArray(((LongArrayTag) tag).getValue(), ((LongArrayTag) tag).length(), "L"); - break; - default: - throw new IOException("unknown tag with id \"" + tag.getID() + "\""); - } - } + private void writeAnything(Tag tag, int maxDepth) throws IOException { + switch (tag.getID()) { + case EndTag.ID: + //do nothing + break; + case ByteTag.ID: + writer.append(Byte.toString(((ByteTag) tag).asByte())).write('b'); + break; + case ShortTag.ID: + writer.append(Short.toString(((ShortTag) tag).asShort())).write('s'); + break; + case IntTag.ID: + writer.write(Integer.toString(((IntTag) tag).asInt())); + break; + case LongTag.ID: + writer.append(Long.toString(((LongTag) tag).asLong())).write('l'); + break; + case FloatTag.ID: + writer.append(Float.toString(((FloatTag) tag).asFloat())).write('f'); + break; + case DoubleTag.ID: + writer.append(Double.toString(((DoubleTag) tag).asDouble())).write('d'); + break; + case ByteArrayTag.ID: + writeArray(((ByteArrayTag) tag).getValue(), ((ByteArrayTag) tag).length(), "B"); + break; + case StringTag.ID: + writer.write(escapeString(((StringTag) tag).getValue())); + break; + case ListTag.ID: + writer.write('['); + for (int i = 0; i < ((ListTag) tag).size(); i++) { + writer.write(i == 0 ? "" : ","); + writeAnything(((ListTag) tag).get(i), decrementMaxDepth(maxDepth)); + } + writer.write(']'); + break; + case CompoundTag.ID: + writer.write('{'); + boolean first = true; + for (Map.Entry> entry : (CompoundTag) tag) { + writer.write(first ? "" : ","); + writer.append(escapeString(entry.getKey())).write(':'); + writeAnything(entry.getValue(), decrementMaxDepth(maxDepth)); + first = false; + } + writer.write('}'); + break; + case IntArrayTag.ID: + writeArray(((IntArrayTag) tag).getValue(), ((IntArrayTag) tag).length(), "I"); + break; + case LongArrayTag.ID: + writeArray(((LongArrayTag) tag).getValue(), ((LongArrayTag) tag).length(), "L"); + break; + default: + throw new IOException("unknown tag with id \"" + tag.getID() + "\""); + } + } - private void writeArray(Object array, int length, String prefix) throws IOException { - writer.append('[').append(prefix).write(';'); - for (int i = 0; i < length; i++) { - writer.append(i == 0 ? "" : ",").write(Array.get(array, i).toString()); - } - writer.write(']'); - } + private void writeArray(Object array, int length, String prefix) throws IOException { + writer.append('[').append(prefix).write(';'); + for (int i = 0; i < length; i++) { + writer.append(i == 0 ? "" : ",").write(Array.get(array, i).toString()); + } + writer.write(']'); + } - public static String escapeString(String s) { - if (!NON_QUOTE_PATTERN.matcher(s).matches()) { - StringBuilder sb = new StringBuilder(); - sb.append('"'); - for (int i = 0; i < s.length(); i++) { - char c = s.charAt(i); - if (c == '\\' || c == '"') { - sb.append('\\'); - } - sb.append(c); - } - sb.append('"'); - return sb.toString(); - } - return s; - } + public static String escapeString(String s) { + if (!NON_QUOTE_PATTERN.matcher(s).matches()) { + StringBuilder sb = new StringBuilder(); + sb.append('"'); + for (int i = 0; i < s.length(); i++) { + char c = s.charAt(i); + if (c == '\\' || c == '"') { + sb.append('\\'); + } + sb.append(c); + } + sb.append('"'); + return sb.toString(); + } + return s; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/StringPointer.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/StringPointer.java index 6d6b84c7c..eb1582a96 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/io/StringPointer.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/io/StringPointer.java @@ -2,113 +2,113 @@ package com.volmit.iris.scaffold.data.nbt.io; public class StringPointer { - private String value; - private int index; + private final String value; + private int index; - public StringPointer(String value) { - this.value = value; - } + public StringPointer(String value) { + this.value = value; + } - public String parseSimpleString() { - int oldIndex = index; - while (hasNext() && isSimpleChar(currentChar())) { - index++; - } - return value.substring(oldIndex, index); - } + public String parseSimpleString() { + int oldIndex = index; + while (hasNext() && isSimpleChar(currentChar())) { + index++; + } + return value.substring(oldIndex, index); + } - public String parseQuotedString() throws ParseException { - int oldIndex = ++index; //ignore beginning quotes - StringBuilder sb = null; - boolean escape = false; - while (hasNext()) { - char c = next(); - if (escape) { - if (c != '\\' && c != '"') { - throw parseException("invalid escape of '" + c + "'"); - } - escape = false; - } else { - if (c == '\\') { //escape - escape = true; - if (sb != null) { - continue; - } - sb = new StringBuilder(value.substring(oldIndex, index - 1)); - continue; - } - if (c == '"') { - return sb == null ? value.substring(oldIndex, index - 1) : sb.toString(); - } - } - if (sb != null) { - sb.append(c); - } - } - throw parseException("missing end quote"); - } + public String parseQuotedString() throws ParseException { + int oldIndex = ++index; //ignore beginning quotes + StringBuilder sb = null; + boolean escape = false; + while (hasNext()) { + char c = next(); + if (escape) { + if (c != '\\' && c != '"') { + throw parseException("invalid escape of '" + c + "'"); + } + escape = false; + } else { + if (c == '\\') { //escape + escape = true; + if (sb != null) { + continue; + } + sb = new StringBuilder(value.substring(oldIndex, index - 1)); + continue; + } + if (c == '"') { + return sb == null ? value.substring(oldIndex, index - 1) : sb.toString(); + } + } + if (sb != null) { + sb.append(c); + } + } + throw parseException("missing end quote"); + } - public boolean nextArrayElement() { - skipWhitespace(); - if (hasNext() && currentChar() == ',') { - index++; - skipWhitespace(); - return true; - } - return false; - } + public boolean nextArrayElement() { + skipWhitespace(); + if (hasNext() && currentChar() == ',') { + index++; + skipWhitespace(); + return true; + } + return false; + } - public void expectChar(char c) throws ParseException { - skipWhitespace(); - boolean hasNext = hasNext(); - if (hasNext && currentChar() == c) { - index++; - return; - } - throw parseException("expected '" + c + "' but got " + (hasNext ? "'" + currentChar() + "'" : "EOF")); - } + public void expectChar(char c) throws ParseException { + skipWhitespace(); + boolean hasNext = hasNext(); + if (hasNext && currentChar() == c) { + index++; + return; + } + throw parseException("expected '" + c + "' but got " + (hasNext ? "'" + currentChar() + "'" : "EOF")); + } - public void skipWhitespace() { - while (hasNext() && Character.isWhitespace(currentChar())) { - index++; - } - } + public void skipWhitespace() { + while (hasNext() && Character.isWhitespace(currentChar())) { + index++; + } + } - public boolean hasNext() { - return index < value.length(); - } + public boolean hasNext() { + return index < value.length(); + } - public boolean hasCharsLeft(int num) { - return this.index + num < value.length(); - } + public boolean hasCharsLeft(int num) { + return this.index + num < value.length(); + } - public char currentChar() { - return value.charAt(index); - } + public char currentChar() { + return value.charAt(index); + } - public char next() { - return value.charAt(index++); - } + public char next() { + return value.charAt(index++); + } - public void skip(int offset) { - index += offset; - } + public void skip(int offset) { + index += offset; + } - public char lookAhead(int offset) { - return value.charAt(index + offset); - } + public char lookAhead(int offset) { + return value.charAt(index + offset); + } - private static boolean isSimpleChar(char c) { - return c >= 'a' && c <= 'z' - || c >= 'A' && c <= 'Z' - || c >= '0' && c <= '9' - || c == '-' - || c == '+' - || c == '.' - || c == '_'; - } + private static boolean isSimpleChar(char c) { + return c >= 'a' && c <= 'z' + || c >= 'A' && c <= 'Z' + || c >= '0' && c <= '9' + || c == '-' + || c == '+' + || c == '.' + || c == '_'; + } - public ParseException parseException(String msg) { - return new ParseException(msg, value, index); - } + public ParseException parseException(String msg) { + return new ParseException(msg, value, index); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/ArrayTag.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/ArrayTag.java index 3645b248e..9b0527d4b 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/ArrayTag.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/ArrayTag.java @@ -5,42 +5,43 @@ import java.lang.reflect.Array; /** * ArrayTag is an abstract representation of any NBT array tag. * For implementations see {@link ByteArrayTag}, {@link IntArrayTag}, {@link LongArrayTag}. + * * @param The array type. - * */ + */ public abstract class ArrayTag extends Tag { - public ArrayTag(T value) { - super(value); - if (!value.getClass().isArray()) { - throw new UnsupportedOperationException("type of array tag must be an array"); - } - } + public ArrayTag(T value) { + super(value); + if (!value.getClass().isArray()) { + throw new UnsupportedOperationException("type of array tag must be an array"); + } + } - public int length() { - return Array.getLength(getValue()); - } + public int length() { + return Array.getLength(getValue()); + } - @Override - public T getValue() { - return super.getValue(); - } + @Override + public T getValue() { + return super.getValue(); + } - @Override - public void setValue(T value) { - super.setValue(value); - } + @Override + public void setValue(T value) { + super.setValue(value); + } - @Override - public String valueToString(int maxDepth) { - return arrayToString("", ""); - } + @Override + public String valueToString(int maxDepth) { + return arrayToString("", ""); + } - protected String arrayToString(String prefix, String suffix) { - StringBuilder sb = new StringBuilder("[").append(prefix).append("".equals(prefix) ? "" : ";"); - for (int i = 0; i < length(); i++) { - sb.append(i == 0 ? "" : ",").append(Array.get(getValue(), i)).append(suffix); - } - sb.append("]"); - return sb.toString(); - } + protected String arrayToString(String prefix, String suffix) { + StringBuilder sb = new StringBuilder("[").append(prefix).append("".equals(prefix) ? "" : ";"); + for (int i = 0; i < length(); i++) { + sb.append(i == 0 ? "" : ",").append(Array.get(getValue(), i)).append(suffix); + } + sb.append("]"); + return sb.toString(); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/ByteArrayTag.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/ByteArrayTag.java index 078e694aa..66fcacb38 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/ByteArrayTag.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/ByteArrayTag.java @@ -4,39 +4,39 @@ import java.util.Arrays; public class ByteArrayTag extends ArrayTag implements Comparable { - public static final byte ID = 7; - public static final byte[] ZERO_VALUE = new byte[0]; + public static final byte ID = 7; + public static final byte[] ZERO_VALUE = new byte[0]; - public ByteArrayTag() { - super(ZERO_VALUE); - } + public ByteArrayTag() { + super(ZERO_VALUE); + } - public ByteArrayTag(byte[] value) { - super(value); - } + public ByteArrayTag(byte[] value) { + super(value); + } - @Override - public byte getID() { - return ID; - } + @Override + public byte getID() { + return ID; + } - @Override - public boolean equals(Object other) { - return super.equals(other) && Arrays.equals(getValue(), ((ByteArrayTag) other).getValue()); - } + @Override + public boolean equals(Object other) { + return super.equals(other) && Arrays.equals(getValue(), ((ByteArrayTag) other).getValue()); + } - @Override - public int hashCode() { - return Arrays.hashCode(getValue()); - } + @Override + public int hashCode() { + return Arrays.hashCode(getValue()); + } - @Override - public int compareTo(ByteArrayTag other) { - return Integer.compare(length(), other.length()); - } + @Override + public int compareTo(ByteArrayTag other) { + return Integer.compare(length(), other.length()); + } - @Override - public ByteArrayTag clone() { - return new ByteArrayTag(Arrays.copyOf(getValue(), length())); - } + @Override + public ByteArrayTag clone() { + return new ByteArrayTag(Arrays.copyOf(getValue(), length())); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/ByteTag.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/ByteTag.java index e59d21be5..11fb41eb3 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/ByteTag.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/ByteTag.java @@ -2,46 +2,46 @@ package com.volmit.iris.scaffold.data.nbt.tag; public class ByteTag extends NumberTag implements Comparable { - public static final byte ID = 1; - public static final byte ZERO_VALUE = 0; + public static final byte ID = 1; + public static final byte ZERO_VALUE = 0; - public ByteTag() { - super(ZERO_VALUE); - } + public ByteTag() { + super(ZERO_VALUE); + } - public ByteTag(byte value) { - super(value); - } + public ByteTag(byte value) { + super(value); + } - public ByteTag(boolean value) { - super((byte) (value ? 1 : 0)); - } + public ByteTag(boolean value) { + super((byte) (value ? 1 : 0)); + } - @Override - public byte getID() { - return ID; - } + @Override + public byte getID() { + return ID; + } - public boolean asBoolean() { - return getValue() > 0; - } + public boolean asBoolean() { + return getValue() > 0; + } - public void setValue(byte value) { - super.setValue(value); - } + public void setValue(byte value) { + super.setValue(value); + } - @Override - public boolean equals(Object other) { - return super.equals(other) && asByte() == ((ByteTag) other).asByte(); - } + @Override + public boolean equals(Object other) { + return super.equals(other) && asByte() == ((ByteTag) other).asByte(); + } - @Override - public int compareTo(ByteTag other) { - return getValue().compareTo(other.getValue()); - } + @Override + public int compareTo(ByteTag other) { + return getValue().compareTo(other.getValue()); + } - @Override - public ByteTag clone() { - return new ByteTag(getValue()); - } + @Override + public ByteTag clone() { + return new ByteTag(getValue()); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/CompoundTag.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/CompoundTag.java index d6b6f2fd8..0dbcad873 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/CompoundTag.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/CompoundTag.java @@ -8,267 +8,267 @@ import java.util.function.BiConsumer; public class CompoundTag extends Tag>> implements Iterable>>, Comparable, MaxDepthIO { - public static final byte ID = 10; + public static final byte ID = 10; - public CompoundTag() { - super(createEmptyValue()); - } + public CompoundTag() { + super(createEmptyValue()); + } - @Override - public byte getID() { - return ID; - } + @Override + public byte getID() { + return ID; + } - private static Map> createEmptyValue() { - return new KMap<>(); - } + private static Map> createEmptyValue() { + return new KMap<>(); + } - public int size() { - return getValue().size(); - } + public int size() { + return getValue().size(); + } - public Tag remove(String key) { - return getValue().remove(key); - } + public Tag remove(String key) { + return getValue().remove(key); + } - public void clear() { - getValue().clear(); - } + public void clear() { + getValue().clear(); + } - public boolean containsKey(String key) { - return getValue().containsKey(key); - } + public boolean containsKey(String key) { + return getValue().containsKey(key); + } - public boolean containsValue(Tag value) { - return getValue().containsValue(value); - } + public boolean containsValue(Tag value) { + return getValue().containsValue(value); + } - public Collection> values() { - return getValue().values(); - } + public Collection> values() { + return getValue().values(); + } - public Set keySet() { - return getValue().keySet(); - } + public Set keySet() { + return getValue().keySet(); + } - public Set>> entrySet() { - return new NonNullEntrySet<>(getValue().entrySet()); - } + public Set>> entrySet() { + return new NonNullEntrySet<>(getValue().entrySet()); + } - @Override - public Iterator>> iterator() { - return entrySet().iterator(); - } + @Override + public Iterator>> iterator() { + return entrySet().iterator(); + } - public void forEach(BiConsumer> action) { - getValue().forEach(action); - } + public void forEach(BiConsumer> action) { + getValue().forEach(action); + } - public > C get(String key, Class type) { - Tag t = getValue().get(key); - if (t != null) { - return type.cast(t); - } - return null; - } + public > C get(String key, Class type) { + Tag t = getValue().get(key); + if (t != null) { + return type.cast(t); + } + return null; + } - public Tag get(String key) { - return getValue().get(key); - } + public Tag get(String key) { + return getValue().get(key); + } - public ByteTag getByteTag(String key) { - return get(key, ByteTag.class); - } + public ByteTag getByteTag(String key) { + return get(key, ByteTag.class); + } - public ShortTag getShortTag(String key) { - return get(key, ShortTag.class); - } + public ShortTag getShortTag(String key) { + return get(key, ShortTag.class); + } - public IntTag getIntTag(String key) { - return get(key, IntTag.class); - } + public IntTag getIntTag(String key) { + return get(key, IntTag.class); + } - public LongTag getLongTag(String key) { - return get(key, LongTag.class); - } + public LongTag getLongTag(String key) { + return get(key, LongTag.class); + } - public FloatTag getFloatTag(String key) { - return get(key, FloatTag.class); - } + public FloatTag getFloatTag(String key) { + return get(key, FloatTag.class); + } - public DoubleTag getDoubleTag(String key) { - return get(key, DoubleTag.class); - } + public DoubleTag getDoubleTag(String key) { + return get(key, DoubleTag.class); + } - public StringTag getStringTag(String key) { - return get(key, StringTag.class); - } + public StringTag getStringTag(String key) { + return get(key, StringTag.class); + } - public ByteArrayTag getByteArrayTag(String key) { - return get(key, ByteArrayTag.class); - } + public ByteArrayTag getByteArrayTag(String key) { + return get(key, ByteArrayTag.class); + } - public IntArrayTag getIntArrayTag(String key) { - return get(key, IntArrayTag.class); - } + public IntArrayTag getIntArrayTag(String key) { + return get(key, IntArrayTag.class); + } - public LongArrayTag getLongArrayTag(String key) { - return get(key, LongArrayTag.class); - } + public LongArrayTag getLongArrayTag(String key) { + return get(key, LongArrayTag.class); + } - public ListTag getListTag(String key) { - return get(key, ListTag.class); - } + public ListTag getListTag(String key) { + return get(key, ListTag.class); + } - public CompoundTag getCompoundTag(String key) { - return get(key, CompoundTag.class); - } + public CompoundTag getCompoundTag(String key) { + return get(key, CompoundTag.class); + } - public boolean getBoolean(String key) { - Tag t = get(key); - return t instanceof ByteTag && ((ByteTag) t).asByte() > 0; - } + public boolean getBoolean(String key) { + Tag t = get(key); + return t instanceof ByteTag && ((ByteTag) t).asByte() > 0; + } - public byte getByte(String key) { - ByteTag t = getByteTag(key); - return t == null ? ByteTag.ZERO_VALUE : t.asByte(); - } + public byte getByte(String key) { + ByteTag t = getByteTag(key); + return t == null ? ByteTag.ZERO_VALUE : t.asByte(); + } - public short getShort(String key) { - ShortTag t = getShortTag(key); - return t == null ? ShortTag.ZERO_VALUE : t.asShort(); - } + public short getShort(String key) { + ShortTag t = getShortTag(key); + return t == null ? ShortTag.ZERO_VALUE : t.asShort(); + } - public int getInt(String key) { - IntTag t = getIntTag(key); - return t == null ? IntTag.ZERO_VALUE : t.asInt(); - } + public int getInt(String key) { + IntTag t = getIntTag(key); + return t == null ? IntTag.ZERO_VALUE : t.asInt(); + } - public long getLong(String key) { - LongTag t = getLongTag(key); - return t == null ? LongTag.ZERO_VALUE : t.asLong(); - } + public long getLong(String key) { + LongTag t = getLongTag(key); + return t == null ? LongTag.ZERO_VALUE : t.asLong(); + } - public float getFloat(String key) { - FloatTag t = getFloatTag(key); - return t == null ? FloatTag.ZERO_VALUE : t.asFloat(); - } + public float getFloat(String key) { + FloatTag t = getFloatTag(key); + return t == null ? FloatTag.ZERO_VALUE : t.asFloat(); + } - public double getDouble(String key) { - DoubleTag t = getDoubleTag(key); - return t == null ? DoubleTag.ZERO_VALUE : t.asDouble(); - } + public double getDouble(String key) { + DoubleTag t = getDoubleTag(key); + return t == null ? DoubleTag.ZERO_VALUE : t.asDouble(); + } - public String getString(String key) { - StringTag t = getStringTag(key); - return t == null ? StringTag.ZERO_VALUE : t.getValue(); - } + public String getString(String key) { + StringTag t = getStringTag(key); + return t == null ? StringTag.ZERO_VALUE : t.getValue(); + } - public byte[] getByteArray(String key) { - ByteArrayTag t = getByteArrayTag(key); - return t == null ? ByteArrayTag.ZERO_VALUE : t.getValue(); - } + public byte[] getByteArray(String key) { + ByteArrayTag t = getByteArrayTag(key); + return t == null ? ByteArrayTag.ZERO_VALUE : t.getValue(); + } - public int[] getIntArray(String key) { - IntArrayTag t = getIntArrayTag(key); - return t == null ? IntArrayTag.ZERO_VALUE : t.getValue(); - } + public int[] getIntArray(String key) { + IntArrayTag t = getIntArrayTag(key); + return t == null ? IntArrayTag.ZERO_VALUE : t.getValue(); + } - public long[] getLongArray(String key) { - LongArrayTag t = getLongArrayTag(key); - return t == null ? LongArrayTag.ZERO_VALUE : t.getValue(); - } + public long[] getLongArray(String key) { + LongArrayTag t = getLongArrayTag(key); + return t == null ? LongArrayTag.ZERO_VALUE : t.getValue(); + } - public Tag put(String key, Tag tag) { - return getValue().put(Objects.requireNonNull(key), Objects.requireNonNull(tag)); - } + public Tag put(String key, Tag tag) { + return getValue().put(Objects.requireNonNull(key), Objects.requireNonNull(tag)); + } - public Tag putBoolean(String key, boolean value) { - return put(key, new ByteTag(value)); - } + public Tag putBoolean(String key, boolean value) { + return put(key, new ByteTag(value)); + } - public Tag putByte(String key, byte value) { - return put(key, new ByteTag(value)); - } + public Tag putByte(String key, byte value) { + return put(key, new ByteTag(value)); + } - public Tag putShort(String key, short value) { - return put(key, new ShortTag(value)); - } + public Tag putShort(String key, short value) { + return put(key, new ShortTag(value)); + } - public Tag putInt(String key, int value) { - return put(key, new IntTag(value)); - } + public Tag putInt(String key, int value) { + return put(key, new IntTag(value)); + } - public Tag putLong(String key, long value) { - return put(key, new LongTag(value)); - } + public Tag putLong(String key, long value) { + return put(key, new LongTag(value)); + } - public Tag putFloat(String key, float value) { - return put(key, new FloatTag(value)); - } + public Tag putFloat(String key, float value) { + return put(key, new FloatTag(value)); + } - public Tag putDouble(String key, double value) { - return put(key, new DoubleTag(value)); - } + public Tag putDouble(String key, double value) { + return put(key, new DoubleTag(value)); + } - public Tag putString(String key, String value) { - return put(key, new StringTag(value)); - } + public Tag putString(String key, String value) { + return put(key, new StringTag(value)); + } - public Tag putByteArray(String key, byte[] value) { - return put(key, new ByteArrayTag(value)); - } + public Tag putByteArray(String key, byte[] value) { + return put(key, new ByteArrayTag(value)); + } - public Tag putIntArray(String key, int[] value) { - return put(key, new IntArrayTag(value)); - } + public Tag putIntArray(String key, int[] value) { + return put(key, new IntArrayTag(value)); + } - public Tag putLongArray(String key, long[] value) { - return put(key, new LongArrayTag(value)); - } + public Tag putLongArray(String key, long[] value) { + return put(key, new LongArrayTag(value)); + } - @Override - public String valueToString(int maxDepth) { - StringBuilder sb = new StringBuilder("{"); - boolean first = true; - for (Map.Entry> e : getValue().entrySet()) { - sb.append(first ? "" : ",") - .append(escapeString(e.getKey(), false)).append(":") - .append(e.getValue().toString(decrementMaxDepth(maxDepth))); - first = false; - } - sb.append("}"); - return sb.toString(); - } + @Override + public String valueToString(int maxDepth) { + StringBuilder sb = new StringBuilder("{"); + boolean first = true; + for (Map.Entry> e : getValue().entrySet()) { + sb.append(first ? "" : ",") + .append(escapeString(e.getKey(), false)).append(":") + .append(e.getValue().toString(decrementMaxDepth(maxDepth))); + first = false; + } + sb.append("}"); + return sb.toString(); + } - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!super.equals(other) || size() != ((CompoundTag) other).size()) { - return false; - } - for (Map.Entry> e : getValue().entrySet()) { - Tag v; - if ((v = ((CompoundTag) other).get(e.getKey())) == null || !e.getValue().equals(v)) { - return false; - } - } - return true; - } + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!super.equals(other) || size() != ((CompoundTag) other).size()) { + return false; + } + for (Map.Entry> e : getValue().entrySet()) { + Tag v; + if ((v = ((CompoundTag) other).get(e.getKey())) == null || !e.getValue().equals(v)) { + return false; + } + } + return true; + } - @Override - public int compareTo(CompoundTag o) { - return Integer.compare(size(), o.getValue().size()); - } + @Override + public int compareTo(CompoundTag o) { + return Integer.compare(size(), o.getValue().size()); + } - @Override - public CompoundTag clone() { - CompoundTag copy = new CompoundTag(); - for (Map.Entry> e : getValue().entrySet()) { - copy.put(e.getKey(), e.getValue().clone()); - } - return copy; - } + @Override + public CompoundTag clone() { + CompoundTag copy = new CompoundTag(); + for (Map.Entry> e : getValue().entrySet()) { + copy.put(e.getKey(), e.getValue().clone()); + } + return copy; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/DoubleTag.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/DoubleTag.java index fade64869..5615c0dc1 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/DoubleTag.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/DoubleTag.java @@ -2,38 +2,38 @@ package com.volmit.iris.scaffold.data.nbt.tag; public class DoubleTag extends NumberTag implements Comparable { - public static final byte ID = 6; - public static final double ZERO_VALUE = 0.0D; + public static final byte ID = 6; + public static final double ZERO_VALUE = 0.0D; - public DoubleTag() { - super(ZERO_VALUE); - } + public DoubleTag() { + super(ZERO_VALUE); + } - public DoubleTag(double value) { - super(value); - } + public DoubleTag(double value) { + super(value); + } - @Override - public byte getID() { - return ID; - } + @Override + public byte getID() { + return ID; + } - public void setValue(double value) { - super.setValue(value); - } + public void setValue(double value) { + super.setValue(value); + } - @Override - public boolean equals(Object other) { - return super.equals(other) && getValue().equals(((DoubleTag) other).getValue()); - } + @Override + public boolean equals(Object other) { + return super.equals(other) && getValue().equals(((DoubleTag) other).getValue()); + } - @Override - public int compareTo(DoubleTag other) { - return getValue().compareTo(other.getValue()); - } + @Override + public int compareTo(DoubleTag other) { + return getValue().compareTo(other.getValue()); + } - @Override - public DoubleTag clone() { - return new DoubleTag(getValue()); - } + @Override + public DoubleTag clone() { + return new DoubleTag(getValue()); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/EndTag.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/EndTag.java index 6090d4483..7cfc6910b 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/EndTag.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/EndTag.java @@ -2,30 +2,30 @@ package com.volmit.iris.scaffold.data.nbt.tag; public final class EndTag extends Tag { - public static final byte ID = 0; - public static final EndTag INSTANCE = new EndTag(); + public static final byte ID = 0; + public static final EndTag INSTANCE = new EndTag(); - private EndTag() { - super(null); - } + private EndTag() { + super(null); + } - @Override - public byte getID() { - return ID; - } + @Override + public byte getID() { + return ID; + } - @Override - protected Void checkValue(Void value) { - return value; - } + @Override + protected Void checkValue(Void value) { + return value; + } - @Override - public String valueToString(int maxDepth) { - return "\"end\""; - } + @Override + public String valueToString(int maxDepth) { + return "\"end\""; + } - @Override - public EndTag clone() { - return INSTANCE; - } + @Override + public EndTag clone() { + return INSTANCE; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/FloatTag.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/FloatTag.java index 2adaed314..d70fea0c7 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/FloatTag.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/FloatTag.java @@ -2,38 +2,38 @@ package com.volmit.iris.scaffold.data.nbt.tag; public class FloatTag extends NumberTag implements Comparable { - public static final byte ID = 5; - public static final float ZERO_VALUE = 0.0F; + public static final byte ID = 5; + public static final float ZERO_VALUE = 0.0F; - public FloatTag() { - super(ZERO_VALUE); - } + public FloatTag() { + super(ZERO_VALUE); + } - public FloatTag(float value) { - super(value); - } + public FloatTag(float value) { + super(value); + } - @Override - public byte getID() { - return ID; - } + @Override + public byte getID() { + return ID; + } - public void setValue(float value) { - super.setValue(value); - } + public void setValue(float value) { + super.setValue(value); + } - @Override - public boolean equals(Object other) { - return super.equals(other) && getValue().equals(((FloatTag) other).getValue()); - } + @Override + public boolean equals(Object other) { + return super.equals(other) && getValue().equals(((FloatTag) other).getValue()); + } - @Override - public int compareTo(FloatTag other) { - return getValue().compareTo(other.getValue()); - } + @Override + public int compareTo(FloatTag other) { + return getValue().compareTo(other.getValue()); + } - @Override - public FloatTag clone() { - return new FloatTag(getValue()); - } + @Override + public FloatTag clone() { + return new FloatTag(getValue()); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/IntArrayTag.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/IntArrayTag.java index d1d6967c2..ebf2f6ae0 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/IntArrayTag.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/IntArrayTag.java @@ -4,39 +4,39 @@ import java.util.Arrays; public class IntArrayTag extends ArrayTag implements Comparable { - public static final byte ID = 11; - public static final int[] ZERO_VALUE = new int[0]; + public static final byte ID = 11; + public static final int[] ZERO_VALUE = new int[0]; - public IntArrayTag() { - super(ZERO_VALUE); - } + public IntArrayTag() { + super(ZERO_VALUE); + } - public IntArrayTag(int[] value) { - super(value); - } + public IntArrayTag(int[] value) { + super(value); + } - @Override - public byte getID() { - return ID; - } + @Override + public byte getID() { + return ID; + } - @Override - public boolean equals(Object other) { - return super.equals(other) && Arrays.equals(getValue(), ((IntArrayTag) other).getValue()); - } + @Override + public boolean equals(Object other) { + return super.equals(other) && Arrays.equals(getValue(), ((IntArrayTag) other).getValue()); + } - @Override - public int hashCode() { - return Arrays.hashCode(getValue()); - } + @Override + public int hashCode() { + return Arrays.hashCode(getValue()); + } - @Override - public int compareTo(IntArrayTag other) { - return Integer.compare(length(), other.length()); - } + @Override + public int compareTo(IntArrayTag other) { + return Integer.compare(length(), other.length()); + } - @Override - public IntArrayTag clone() { - return new IntArrayTag(Arrays.copyOf(getValue(), length())); - } + @Override + public IntArrayTag clone() { + return new IntArrayTag(Arrays.copyOf(getValue(), length())); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/IntTag.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/IntTag.java index 1e5b5a18d..52118e832 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/IntTag.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/IntTag.java @@ -2,38 +2,38 @@ package com.volmit.iris.scaffold.data.nbt.tag; public class IntTag extends NumberTag implements Comparable { - public static final byte ID = 3; - public static final int ZERO_VALUE = 0; + public static final byte ID = 3; + public static final int ZERO_VALUE = 0; - public IntTag() { - super(ZERO_VALUE); - } + public IntTag() { + super(ZERO_VALUE); + } - public IntTag(int value) { - super(value); - } + public IntTag(int value) { + super(value); + } - @Override - public byte getID() { - return ID; - } + @Override + public byte getID() { + return ID; + } - public void setValue(int value) { - super.setValue(value); - } + public void setValue(int value) { + super.setValue(value); + } - @Override - public boolean equals(Object other) { - return super.equals(other) && asInt() == ((IntTag) other).asInt(); - } + @Override + public boolean equals(Object other) { + return super.equals(other) && asInt() == ((IntTag) other).asInt(); + } - @Override - public int compareTo(IntTag other) { - return getValue().compareTo(other.getValue()); - } + @Override + public int compareTo(IntTag other) { + return getValue().compareTo(other.getValue()); + } - @Override - public IntTag clone() { - return new IntTag(getValue()); - } + @Override + public IntTag clone() { + return new IntTag(getValue()); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/ListTag.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/ListTag.java index 78473b011..55c529ec9 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/ListTag.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/ListTag.java @@ -12,312 +12,313 @@ import java.util.function.Consumer; * and returns an {@link EndTag}{@code .class} in {@link ListTag#getTypeClass()}. * The type of an empty untyped {@link ListTag} can be set by using any of the {@code add()} * methods or any of the {@code as...List()} methods. - * */ + */ public class ListTag> extends Tag> implements Iterable, Comparable>, MaxDepthIO { - public static final byte ID = 9; + public static final byte ID = 9; - private Class typeClass = null; + private Class typeClass = null; - private ListTag() { - super(createEmptyValue(3)); - } + private ListTag() { + super(createEmptyValue(3)); + } - @Override - public byte getID() { - return ID; - } - - /** - *

Creates a non-type-safe ListTag. Its element type will be set after the first - * element was added.

- * - *

This is an internal helper method for cases where the element type is not known - * at construction time. Use {@link #ListTag(Class)} when the type is known.

- * - * @return A new non-type-safe ListTag - */ - public static ListTag createUnchecked(Class typeClass) { - ListTag list = new ListTag<>(); - list.typeClass = typeClass; - return list; - } + @Override + public byte getID() { + return ID; + } - /** - *

Creates an empty mutable list to be used as empty value of ListTags.

- * - * @param Type of the list elements - * @param initialCapacity The initial capacity of the returned List - * @return An instance of {@link List} with an initial capacity of 3 - * */ - private static List createEmptyValue(int initialCapacity) { - return new KList<>(initialCapacity); - } + /** + *

Creates a non-type-safe ListTag. Its element type will be set after the first + * element was added.

+ * + *

This is an internal helper method for cases where the element type is not known + * at construction time. Use {@link #ListTag(Class)} when the type is known.

+ * + * @return A new non-type-safe ListTag + */ + public static ListTag createUnchecked(Class typeClass) { + ListTag list = new ListTag<>(); + list.typeClass = typeClass; + return list; + } - /** - * @param typeClass The exact class of the elements - * @throws IllegalArgumentException When {@code typeClass} is {@link EndTag}{@code .class} - * @throws NullPointerException When {@code typeClass} is {@code null} - */ - public ListTag(Class typeClass) throws IllegalArgumentException, NullPointerException { - super(createEmptyValue(3)); - if (typeClass == EndTag.class) { - throw new IllegalArgumentException("cannot create ListTag with EndTag elements"); - } - this.typeClass = Objects.requireNonNull(typeClass); - } + /** + *

Creates an empty mutable list to be used as empty value of ListTags.

+ * + * @param Type of the list elements + * @param initialCapacity The initial capacity of the returned List + * @return An instance of {@link List} with an initial capacity of 3 + */ + private static List createEmptyValue(int initialCapacity) { + return new KList<>(initialCapacity); + } - public Class getTypeClass() { - return typeClass == null ? EndTag.class : typeClass; - } + /** + * @param typeClass The exact class of the elements + * @throws IllegalArgumentException When {@code typeClass} is {@link EndTag}{@code .class} + * @throws NullPointerException When {@code typeClass} is {@code null} + */ + public ListTag(Class typeClass) throws IllegalArgumentException, NullPointerException { + super(createEmptyValue(3)); + if (typeClass == EndTag.class) { + throw new IllegalArgumentException("cannot create ListTag with EndTag elements"); + } + this.typeClass = Objects.requireNonNull(typeClass); + } - public int size() { - return getValue().size(); - } + public Class getTypeClass() { + return typeClass == null ? EndTag.class : typeClass; + } - public T remove(int index) { - return getValue().remove(index); - } + public int size() { + return getValue().size(); + } - public void clear() { - getValue().clear(); - } + public T remove(int index) { + return getValue().remove(index); + } - public boolean contains(T t) { - return getValue().contains(t); - } + public void clear() { + getValue().clear(); + } - public boolean containsAll(Collection> tags) { - return getValue().containsAll(tags); - } + public boolean contains(T t) { + return getValue().contains(t); + } - public void sort(Comparator comparator) { - getValue().sort(comparator); - } + public boolean containsAll(Collection> tags) { + return getValue().containsAll(tags); + } - @Override - public Iterator iterator() { - return getValue().iterator(); - } + public void sort(Comparator comparator) { + getValue().sort(comparator); + } - @Override - public void forEach(Consumer action) { - getValue().forEach(action); - } + @Override + public Iterator iterator() { + return getValue().iterator(); + } - public T set(int index, T t) { - return getValue().set(index, Objects.requireNonNull(t)); - } + @Override + public void forEach(Consumer action) { + getValue().forEach(action); + } - /** - * Adds a Tag to this ListTag after the last index. - * @param t The element to be added. - * */ - public void add(T t) { - add(size(), t); - } + public T set(int index, T t) { + return getValue().set(index, Objects.requireNonNull(t)); + } - public void add(int index, T t) { - Objects.requireNonNull(t); - if (typeClass == null || typeClass == EndTag.class) { - typeClass = t.getClass(); - } else if (typeClass != t.getClass()) { - throw new ClassCastException( - String.format("cannot add %s to ListTag<%s>", - t.getClass().getSimpleName(), - typeClass.getSimpleName())); - } - getValue().add(index, t); - } + /** + * Adds a Tag to this ListTag after the last index. + * + * @param t The element to be added. + */ + public void add(T t) { + add(size(), t); + } - public void addAll(Collection t) { - for (T tt : t) { - add(tt); - } - } + public void add(int index, T t) { + Objects.requireNonNull(t); + if (typeClass == null || typeClass == EndTag.class) { + typeClass = t.getClass(); + } else if (typeClass != t.getClass()) { + throw new ClassCastException( + String.format("cannot add %s to ListTag<%s>", + t.getClass().getSimpleName(), + typeClass.getSimpleName())); + } + getValue().add(index, t); + } - public void addAll(int index, Collection t) { - int i = 0; - for (T tt : t) { - add(index + i, tt); - i++; - } - } + public void addAll(Collection t) { + for (T tt : t) { + add(tt); + } + } - public void addBoolean(boolean value) { - addUnchecked(new ByteTag(value)); - } + public void addAll(int index, Collection t) { + int i = 0; + for (T tt : t) { + add(index + i, tt); + i++; + } + } - public void addByte(byte value) { - addUnchecked(new ByteTag(value)); - } + public void addBoolean(boolean value) { + addUnchecked(new ByteTag(value)); + } - public void addShort(short value) { - addUnchecked(new ShortTag(value)); - } + public void addByte(byte value) { + addUnchecked(new ByteTag(value)); + } - public void addInt(int value) { - addUnchecked(new IntTag(value)); - } + public void addShort(short value) { + addUnchecked(new ShortTag(value)); + } - public void addLong(long value) { - addUnchecked(new LongTag(value)); - } + public void addInt(int value) { + addUnchecked(new IntTag(value)); + } - public void addFloat(float value) { - addUnchecked(new FloatTag(value)); - } + public void addLong(long value) { + addUnchecked(new LongTag(value)); + } - public void addDouble(double value) { - addUnchecked(new DoubleTag(value)); - } + public void addFloat(float value) { + addUnchecked(new FloatTag(value)); + } - public void addString(String value) { - addUnchecked(new StringTag(value)); - } + public void addDouble(double value) { + addUnchecked(new DoubleTag(value)); + } - public void addByteArray(byte[] value) { - addUnchecked(new ByteArrayTag(value)); - } + public void addString(String value) { + addUnchecked(new StringTag(value)); + } - public void addIntArray(int[] value) { - addUnchecked(new IntArrayTag(value)); - } + public void addByteArray(byte[] value) { + addUnchecked(new ByteArrayTag(value)); + } - public void addLongArray(long[] value) { - addUnchecked(new LongArrayTag(value)); - } + public void addIntArray(int[] value) { + addUnchecked(new IntArrayTag(value)); + } - public T get(int index) { - return getValue().get(index); - } + public void addLongArray(long[] value) { + addUnchecked(new LongArrayTag(value)); + } - public int indexOf(T t) { - return getValue().indexOf(t); - } + public T get(int index) { + return getValue().get(index); + } - @SuppressWarnings("unchecked") - public > ListTag asTypedList(Class type) { - checkTypeClass(type); - typeClass = type; - return (ListTag) this; - } + public int indexOf(T t) { + return getValue().indexOf(t); + } - public ListTag asByteTagList() { - return asTypedList(ByteTag.class); - } + @SuppressWarnings("unchecked") + public > ListTag asTypedList(Class type) { + checkTypeClass(type); + typeClass = type; + return (ListTag) this; + } - public ListTag asShortTagList() { - return asTypedList(ShortTag.class); - } + public ListTag asByteTagList() { + return asTypedList(ByteTag.class); + } - public ListTag asIntTagList() { - return asTypedList(IntTag.class); - } + public ListTag asShortTagList() { + return asTypedList(ShortTag.class); + } - public ListTag asLongTagList() { - return asTypedList(LongTag.class); - } + public ListTag asIntTagList() { + return asTypedList(IntTag.class); + } - public ListTag asFloatTagList() { - return asTypedList(FloatTag.class); - } + public ListTag asLongTagList() { + return asTypedList(LongTag.class); + } - public ListTag asDoubleTagList() { - return asTypedList(DoubleTag.class); - } + public ListTag asFloatTagList() { + return asTypedList(FloatTag.class); + } - public ListTag asStringTagList() { - return asTypedList(StringTag.class); - } + public ListTag asDoubleTagList() { + return asTypedList(DoubleTag.class); + } - public ListTag asByteArrayTagList() { - return asTypedList(ByteArrayTag.class); - } + public ListTag asStringTagList() { + return asTypedList(StringTag.class); + } - public ListTag asIntArrayTagList() { - return asTypedList(IntArrayTag.class); - } + public ListTag asByteArrayTagList() { + return asTypedList(ByteArrayTag.class); + } - public ListTag asLongArrayTagList() { - return asTypedList(LongArrayTag.class); - } + public ListTag asIntArrayTagList() { + return asTypedList(IntArrayTag.class); + } - @SuppressWarnings("unchecked") - public ListTag> asListTagList() { - checkTypeClass(ListTag.class); - typeClass = ListTag.class; - return (ListTag>) this; - } + public ListTag asLongArrayTagList() { + return asTypedList(LongArrayTag.class); + } - public ListTag asCompoundTagList() { - return asTypedList(CompoundTag.class); - } + @SuppressWarnings("unchecked") + public ListTag> asListTagList() { + checkTypeClass(ListTag.class); + typeClass = ListTag.class; + return (ListTag>) this; + } - @Override - public String valueToString(int maxDepth) { - StringBuilder sb = new StringBuilder("{\"type\":\"").append(getTypeClass().getSimpleName()).append("\",\"list\":["); - for (int i = 0; i < size(); i++) { - sb.append(i > 0 ? "," : "").append(get(i).valueToString(decrementMaxDepth(maxDepth))); - } - sb.append("]}"); - return sb.toString(); - } + public ListTag asCompoundTagList() { + return asTypedList(CompoundTag.class); + } - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - if (!super.equals(other) || size() != ((ListTag) other).size() || getTypeClass() != ((ListTag) other).getTypeClass()) { - return false; - } - for (int i = 0; i < size(); i++) { - if (!get(i).equals(((ListTag) other).get(i))) { - return false; - } - } - return true; - } + @Override + public String valueToString(int maxDepth) { + StringBuilder sb = new StringBuilder("{\"type\":\"").append(getTypeClass().getSimpleName()).append("\",\"list\":["); + for (int i = 0; i < size(); i++) { + sb.append(i > 0 ? "," : "").append(get(i).valueToString(decrementMaxDepth(maxDepth))); + } + sb.append("]}"); + return sb.toString(); + } - @Override - public int hashCode() { - return Objects.hash(getTypeClass().hashCode(), getValue().hashCode()); - } + @Override + public boolean equals(Object other) { + if (this == other) { + return true; + } + if (!super.equals(other) || size() != ((ListTag) other).size() || getTypeClass() != ((ListTag) other).getTypeClass()) { + return false; + } + for (int i = 0; i < size(); i++) { + if (!get(i).equals(((ListTag) other).get(i))) { + return false; + } + } + return true; + } - @Override - public int compareTo(ListTag o) { - return Integer.compare(size(), o.getValue().size()); - } + @Override + public int hashCode() { + return Objects.hash(getTypeClass().hashCode(), getValue().hashCode()); + } - @SuppressWarnings("unchecked") - @Override - public ListTag clone() { - ListTag copy = new ListTag<>(); - // assure type safety for clone - copy.typeClass = typeClass; - for (T t : getValue()) { - copy.add((T) t.clone()); - } - return copy; - } + @Override + public int compareTo(ListTag o) { + return Integer.compare(size(), o.getValue().size()); + } - //TODO: make private - @SuppressWarnings("unchecked") - public void addUnchecked(Tag tag) { - if (typeClass != null && typeClass != tag.getClass() && typeClass != EndTag.class) { - throw new IllegalArgumentException(String.format( - "cannot add %s to ListTag<%s>", - tag.getClass().getSimpleName(), typeClass.getSimpleName())); - } - add(size(), (T) tag); - } + @SuppressWarnings("unchecked") + @Override + public ListTag clone() { + ListTag copy = new ListTag<>(); + // assure type safety for clone + copy.typeClass = typeClass; + for (T t : getValue()) { + copy.add((T) t.clone()); + } + return copy; + } - private void checkTypeClass(Class clazz) { - if (typeClass != null && typeClass != EndTag.class && typeClass != clazz) { - throw new ClassCastException(String.format( - "cannot cast ListTag<%s> to ListTag<%s>", - typeClass.getSimpleName(), clazz.getSimpleName())); - } - } + //TODO: make private + @SuppressWarnings("unchecked") + public void addUnchecked(Tag tag) { + if (typeClass != null && typeClass != tag.getClass() && typeClass != EndTag.class) { + throw new IllegalArgumentException(String.format( + "cannot add %s to ListTag<%s>", + tag.getClass().getSimpleName(), typeClass.getSimpleName())); + } + add(size(), (T) tag); + } + + private void checkTypeClass(Class clazz) { + if (typeClass != null && typeClass != EndTag.class && typeClass != clazz) { + throw new ClassCastException(String.format( + "cannot cast ListTag<%s> to ListTag<%s>", + typeClass.getSimpleName(), clazz.getSimpleName())); + } + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/LongArrayTag.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/LongArrayTag.java index 600b3e5c0..86ae5b5a4 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/LongArrayTag.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/LongArrayTag.java @@ -4,39 +4,39 @@ import java.util.Arrays; public class LongArrayTag extends ArrayTag implements Comparable { - public static final byte ID = 12; - public static final long[] ZERO_VALUE = new long[0]; + public static final byte ID = 12; + public static final long[] ZERO_VALUE = new long[0]; - public LongArrayTag() { - super(ZERO_VALUE); - } + public LongArrayTag() { + super(ZERO_VALUE); + } - public LongArrayTag(long[] value) { - super(value); - } + public LongArrayTag(long[] value) { + super(value); + } - @Override - public byte getID() { - return ID; - } + @Override + public byte getID() { + return ID; + } - @Override - public boolean equals(Object other) { - return super.equals(other) && Arrays.equals(getValue(), ((LongArrayTag) other).getValue()); - } + @Override + public boolean equals(Object other) { + return super.equals(other) && Arrays.equals(getValue(), ((LongArrayTag) other).getValue()); + } - @Override - public int hashCode() { - return Arrays.hashCode(getValue()); - } + @Override + public int hashCode() { + return Arrays.hashCode(getValue()); + } - @Override - public int compareTo(LongArrayTag other) { - return Integer.compare(length(), other.length()); - } + @Override + public int compareTo(LongArrayTag other) { + return Integer.compare(length(), other.length()); + } - @Override - public LongArrayTag clone() { - return new LongArrayTag(Arrays.copyOf(getValue(), length())); - } + @Override + public LongArrayTag clone() { + return new LongArrayTag(Arrays.copyOf(getValue(), length())); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/LongTag.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/LongTag.java index 4451a0044..5a1ce76d1 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/LongTag.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/LongTag.java @@ -2,38 +2,38 @@ package com.volmit.iris.scaffold.data.nbt.tag; public class LongTag extends NumberTag implements Comparable { - public static final byte ID = 4; - public static final long ZERO_VALUE = 0L; + public static final byte ID = 4; + public static final long ZERO_VALUE = 0L; - public LongTag() { - super(ZERO_VALUE); - } + public LongTag() { + super(ZERO_VALUE); + } - public LongTag(long value) { - super(value); - } + public LongTag(long value) { + super(value); + } - @Override - public byte getID() { - return ID; - } + @Override + public byte getID() { + return ID; + } - public void setValue(long value) { - super.setValue(value); - } + public void setValue(long value) { + super.setValue(value); + } - @Override - public boolean equals(Object other) { - return super.equals(other) && asLong() == ((LongTag) other).asLong(); - } + @Override + public boolean equals(Object other) { + return super.equals(other) && asLong() == ((LongTag) other).asLong(); + } - @Override - public int compareTo(LongTag other) { - return getValue().compareTo(other.getValue()); - } + @Override + public int compareTo(LongTag other) { + return getValue().compareTo(other.getValue()); + } - @Override - public LongTag clone() { - return new LongTag(getValue()); - } + @Override + public LongTag clone() { + return new LongTag(getValue()); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/NonNullEntrySet.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/NonNullEntrySet.java index 235ec232e..e94e90322 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/NonNullEntrySet.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/NonNullEntrySet.java @@ -8,133 +8,133 @@ import java.util.Set; /** * A decorator for the Set returned by CompoundTag#entrySet() * that disallows setting null values. - * */ + */ class NonNullEntrySet implements Set> { - private Set> set; + private final Set> set; - NonNullEntrySet(Set> set) { - this.set = set; - } + NonNullEntrySet(Set> set) { + this.set = set; + } - @Override - public int size() { - return set.size(); - } + @Override + public int size() { + return set.size(); + } - @Override - public boolean isEmpty() { - return set.isEmpty(); - } + @Override + public boolean isEmpty() { + return set.isEmpty(); + } - @Override - public boolean contains(Object o) { - return set.contains(o); - } + @Override + public boolean contains(Object o) { + return set.contains(o); + } - @Override - public Iterator> iterator() { - return new NonNullEntrySetIterator(set.iterator()); - } + @Override + public Iterator> iterator() { + return new NonNullEntrySetIterator(set.iterator()); + } - @Override - public Object[] toArray() { - return set.toArray(); - } + @Override + public Object[] toArray() { + return set.toArray(); + } - @Override - public T[] toArray(T[] a) { - return set.toArray(a); - } + @Override + public T[] toArray(T[] a) { + return set.toArray(a); + } - @Override - public boolean add(Map.Entry kvEntry) { - return set.add(kvEntry); - } + @Override + public boolean add(Map.Entry kvEntry) { + return set.add(kvEntry); + } - @Override - public boolean remove(Object o) { - return set.remove(o); - } + @Override + public boolean remove(Object o) { + return set.remove(o); + } - @Override - public boolean containsAll(Collection c) { - return set.containsAll(c); - } + @Override + public boolean containsAll(Collection c) { + return set.containsAll(c); + } - @Override - public boolean addAll(Collection> c) { - return set.addAll(c); - } + @Override + public boolean addAll(Collection> c) { + return set.addAll(c); + } - @Override - public boolean retainAll(Collection c) { - return set.retainAll(c); - } + @Override + public boolean retainAll(Collection c) { + return set.retainAll(c); + } - @Override - public boolean removeAll(Collection c) { - return set.removeAll(c); - } + @Override + public boolean removeAll(Collection c) { + return set.removeAll(c); + } - @Override - public void clear() { - set.clear(); - } + @Override + public void clear() { + set.clear(); + } - class NonNullEntrySetIterator implements Iterator> { + class NonNullEntrySetIterator implements Iterator> { - private Iterator> iterator; + private final Iterator> iterator; - NonNullEntrySetIterator(Iterator> iterator) { - this.iterator = iterator; - } + NonNullEntrySetIterator(Iterator> iterator) { + this.iterator = iterator; + } - @Override - public boolean hasNext() { - return iterator.hasNext(); - } + @Override + public boolean hasNext() { + return iterator.hasNext(); + } - @Override - public Map.Entry next() { - return new NonNullEntry(iterator.next()); - } - } + @Override + public Map.Entry next() { + return new NonNullEntry(iterator.next()); + } + } - class NonNullEntry implements Map.Entry { + class NonNullEntry implements Map.Entry { - private Map.Entry entry; + private final Map.Entry entry; - NonNullEntry(Map.Entry entry) { - this.entry = entry; - } + NonNullEntry(Map.Entry entry) { + this.entry = entry; + } - @Override - public K getKey() { - return entry.getKey(); - } + @Override + public K getKey() { + return entry.getKey(); + } - @Override - public V getValue() { - return entry.getValue(); - } + @Override + public V getValue() { + return entry.getValue(); + } - @Override - public V setValue(V value) { - if (value == null) { - throw new NullPointerException(getClass().getSimpleName() + " does not allow setting null"); - } - return entry.setValue(value); - } + @Override + public V setValue(V value) { + if (value == null) { + throw new NullPointerException(getClass().getSimpleName() + " does not allow setting null"); + } + return entry.setValue(value); + } - @Override - public boolean equals(Object o) { - return entry.equals(o); - } + @Override + public boolean equals(Object o) { + return entry.equals(o); + } - @Override - public int hashCode() { - return entry.hashCode(); - } - } + @Override + public int hashCode() { + return entry.hashCode(); + } + } } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/NumberTag.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/NumberTag.java index 76b85fd98..c1641f0a6 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/NumberTag.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/NumberTag.java @@ -2,36 +2,36 @@ package com.volmit.iris.scaffold.data.nbt.tag; public abstract class NumberTag> extends Tag { - public NumberTag(T value) { - super(value); - } + public NumberTag(T value) { + super(value); + } - public byte asByte() { - return getValue().byteValue(); - } + public byte asByte() { + return getValue().byteValue(); + } - public short asShort() { - return getValue().shortValue(); - } + public short asShort() { + return getValue().shortValue(); + } - public int asInt() { - return getValue().intValue(); - } + public int asInt() { + return getValue().intValue(); + } - public long asLong() { - return getValue().longValue(); - } + public long asLong() { + return getValue().longValue(); + } - public float asFloat() { - return getValue().floatValue(); - } + public float asFloat() { + return getValue().floatValue(); + } - public double asDouble() { - return getValue().doubleValue(); - } + public double asDouble() { + return getValue().doubleValue(); + } - @Override - public String valueToString(int maxDepth) { - return getValue().toString(); - } + @Override + public String valueToString(int maxDepth) { + return getValue().toString(); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/ShortTag.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/ShortTag.java index 290fec635..ea08f9c65 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/ShortTag.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/ShortTag.java @@ -2,38 +2,38 @@ package com.volmit.iris.scaffold.data.nbt.tag; public class ShortTag extends NumberTag implements Comparable { - public static final byte ID = 2; - public static final short ZERO_VALUE = 0; + public static final byte ID = 2; + public static final short ZERO_VALUE = 0; - public ShortTag() { - super(ZERO_VALUE); - } + public ShortTag() { + super(ZERO_VALUE); + } - public ShortTag(short value) { - super(value); - } + public ShortTag(short value) { + super(value); + } - @Override - public byte getID() { - return ID; - } + @Override + public byte getID() { + return ID; + } - public void setValue(short value) { - super.setValue(value); - } + public void setValue(short value) { + super.setValue(value); + } - @Override - public boolean equals(Object other) { - return super.equals(other) && asShort() == ((ShortTag) other).asShort(); - } + @Override + public boolean equals(Object other) { + return super.equals(other) && asShort() == ((ShortTag) other).asShort(); + } - @Override - public int compareTo(ShortTag other) { - return getValue().compareTo(other.getValue()); - } + @Override + public int compareTo(ShortTag other) { + return getValue().compareTo(other.getValue()); + } - @Override - public ShortTag clone() { - return new ShortTag(getValue()); - } + @Override + public ShortTag clone() { + return new ShortTag(getValue()); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/StringTag.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/StringTag.java index 490c4895e..c7f1f59d5 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/StringTag.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/StringTag.java @@ -2,49 +2,49 @@ package com.volmit.iris.scaffold.data.nbt.tag; public class StringTag extends Tag implements Comparable { - public static final byte ID = 8; - public static final String ZERO_VALUE = ""; + public static final byte ID = 8; + public static final String ZERO_VALUE = ""; - public StringTag() { - super(ZERO_VALUE); - } + public StringTag() { + super(ZERO_VALUE); + } - public StringTag(String value) { - super(value); - } + public StringTag(String value) { + super(value); + } - @Override - public byte getID() { - return ID; - } + @Override + public byte getID() { + return ID; + } - @Override - public String getValue() { - return super.getValue(); - } + @Override + public String getValue() { + return super.getValue(); + } - @Override - public void setValue(String value) { - super.setValue(value); - } + @Override + public void setValue(String value) { + super.setValue(value); + } - @Override - public String valueToString(int maxDepth) { - return escapeString(getValue(), false); - } + @Override + public String valueToString(int maxDepth) { + return escapeString(getValue(), false); + } - @Override - public boolean equals(Object other) { - return super.equals(other) && getValue().equals(((StringTag) other).getValue()); - } + @Override + public boolean equals(Object other) { + return super.equals(other) && getValue().equals(((StringTag) other).getValue()); + } - @Override - public int compareTo(StringTag o) { - return getValue().compareTo(o.getValue()); - } + @Override + public int compareTo(StringTag o) { + return getValue().compareTo(o.getValue()); + } - @Override - public StringTag clone() { - return new StringTag(getValue()); - } + @Override + public StringTag clone() { + return new StringTag(getValue()); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/Tag.java b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/Tag.java index 8949ad524..2f04eb65a 100644 --- a/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/Tag.java +++ b/src/main/java/com/volmit/iris/scaffold/data/nbt/tag/Tag.java @@ -11,178 +11,190 @@ import java.util.regex.Pattern; /** * Base class for all NBT tags. - * + * *

Nesting

- *

All methods serializing instances or deserializing data track the nesting levels to prevent - * circular references or malicious data which could, when deserialized, result in thousands + *

All methods serializing instances or deserializing data track the nesting levels to prevent + * circular references or malicious data which could, when deserialized, result in thousands * of instances causing a denial of service.

- * - *

These methods have a parameter for the maximum nesting depth they are allowed to traverse. A - * value of {@code 0} means that only the object itself, but no nested objects may be processed. + * + *

These methods have a parameter for the maximum nesting depth they are allowed to traverse. A + * value of {@code 0} means that only the object itself, but no nested objects may be processed. * If an instance is nested further than allowed, a {@link MaxDepthReachedException} will be thrown. - * Providing a negative maximum nesting depth will cause an {@code IllegalArgumentException} + * Providing a negative maximum nesting depth will cause an {@code IllegalArgumentException} * to be thrown.

- * - *

Some methods do not provide a parameter to specify the maximum nesting depth, but instead use - * {@link #DEFAULT_MAX_DEPTH}, which is also the maximum used by Minecraft. This is documented for + * + *

Some methods do not provide a parameter to specify the maximum nesting depth, but instead use + * {@link #DEFAULT_MAX_DEPTH}, which is also the maximum used by Minecraft. This is documented for * the respective methods.

- * - *

If custom NBT tags contain objects other than NBT tags, which can be nested as well, then there - * is no guarantee that {@code MaxDepthReachedException}s are thrown for them. The respective class + * + *

If custom NBT tags contain objects other than NBT tags, which can be nested as well, then there + * is no guarantee that {@code MaxDepthReachedException}s are thrown for them. The respective class * will document this behavior accordingly.

- * + * * @param The type of the contained value - * */ + */ public abstract class Tag implements Cloneable { - /** - * The default maximum depth of the NBT structure. - * */ - public static final int DEFAULT_MAX_DEPTH = 512; + /** + * The default maximum depth of the NBT structure. + */ + public static final int DEFAULT_MAX_DEPTH = 512; - private static final Map ESCAPE_CHARACTERS; - static { - final Map temp = new HashMap<>(); - temp.put("\\", "\\\\\\\\"); - temp.put("\n", "\\\\n"); - temp.put("\t", "\\\\t"); - temp.put("\r", "\\\\r"); - temp.put("\"", "\\\\\""); - ESCAPE_CHARACTERS = Collections.unmodifiableMap(temp); - } + private static final Map ESCAPE_CHARACTERS; - private static final Pattern ESCAPE_PATTERN = Pattern.compile("[\\\\\n\t\r\"]"); - private static final Pattern NON_QUOTE_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-+]+"); + static { + final Map temp = new HashMap<>(); + temp.put("\\", "\\\\\\\\"); + temp.put("\n", "\\\\n"); + temp.put("\t", "\\\\t"); + temp.put("\r", "\\\\r"); + temp.put("\"", "\\\\\""); + ESCAPE_CHARACTERS = Collections.unmodifiableMap(temp); + } - private T value; + private static final Pattern ESCAPE_PATTERN = Pattern.compile("[\\\\\n\t\r\"]"); + private static final Pattern NON_QUOTE_PATTERN = Pattern.compile("[a-zA-Z0-9_\\-+]+"); - /** - * Initializes this Tag with some value. If the value is {@code null}, it will - * throw a {@code NullPointerException} - * @param value The value to be set for this Tag. - * */ - public Tag(T value) { - setValue(value); - } + private T value; - /** - * @return This Tag's ID, usually used for serialization and deserialization. - * */ - public abstract byte getID(); + /** + * Initializes this Tag with some value. If the value is {@code null}, it will + * throw a {@code NullPointerException} + * + * @param value The value to be set for this Tag. + */ + public Tag(T value) { + setValue(value); + } - /** - * @return The value of this Tag. - * */ - protected T getValue() { - return value; - } + /** + * @return This Tag's ID, usually used for serialization and deserialization. + */ + public abstract byte getID(); - /** - * Sets the value for this Tag directly. - * @param value The value to be set. - * @throws NullPointerException If the value is null - * */ - protected void setValue(T value) { - this.value = checkValue(value); - } + /** + * @return The value of this Tag. + */ + protected T getValue() { + return value; + } - /** - * Checks if the value {@code value} is {@code null}. - * @param value The value to check - * @throws NullPointerException If {@code value} was {@code null} - * @return The parameter {@code value} - * */ - protected T checkValue(T value) { - return Objects.requireNonNull(value); - } + /** + * Sets the value for this Tag directly. + * + * @param value The value to be set. + * @throws NullPointerException If the value is null + */ + protected void setValue(T value) { + this.value = checkValue(value); + } - /** - * Calls {@link Tag#toString(int)} with an initial depth of {@code 0}. - * @see Tag#toString(int) - * @throws MaxDepthReachedException If the maximum nesting depth is exceeded. - * */ - @Override - public final String toString() { - return toString(DEFAULT_MAX_DEPTH); - } + /** + * Checks if the value {@code value} is {@code null}. + * + * @param value The value to check + * @return The parameter {@code value} + * @throws NullPointerException If {@code value} was {@code null} + */ + protected T checkValue(T value) { + return Objects.requireNonNull(value); + } - /** - * Creates a string representation of this Tag in a valid JSON format. - * @param maxDepth The maximum nesting depth. - * @return The string representation of this Tag. - * @throws MaxDepthReachedException If the maximum nesting depth is exceeded. - * */ - public String toString(int maxDepth) { - return "{\"type\":\""+ getClass().getSimpleName() + "\"," + - "\"value\":" + valueToString(maxDepth) + "}"; - } + /** + * Calls {@link Tag#toString(int)} with an initial depth of {@code 0}. + * + * @throws MaxDepthReachedException If the maximum nesting depth is exceeded. + * @see Tag#toString(int) + */ + @Override + public final String toString() { + return toString(DEFAULT_MAX_DEPTH); + } - /** - * Calls {@link Tag#valueToString(int)} with {@link Tag#DEFAULT_MAX_DEPTH}. - * @return The string representation of the value of this Tag. - * @throws MaxDepthReachedException If the maximum nesting depth is exceeded. - * */ - public String valueToString() { - return valueToString(DEFAULT_MAX_DEPTH); - } + /** + * Creates a string representation of this Tag in a valid JSON format. + * + * @param maxDepth The maximum nesting depth. + * @return The string representation of this Tag. + * @throws MaxDepthReachedException If the maximum nesting depth is exceeded. + */ + public String toString(int maxDepth) { + return "{\"type\":\"" + getClass().getSimpleName() + "\"," + + "\"value\":" + valueToString(maxDepth) + "}"; + } - /** - * Returns a JSON representation of the value of this Tag. - * @param maxDepth The maximum nesting depth. - * @return The string representation of the value of this Tag. - * @throws MaxDepthReachedException If the maximum nesting depth is exceeded. - * */ - public abstract String valueToString(int maxDepth); + /** + * Calls {@link Tag#valueToString(int)} with {@link Tag#DEFAULT_MAX_DEPTH}. + * + * @return The string representation of the value of this Tag. + * @throws MaxDepthReachedException If the maximum nesting depth is exceeded. + */ + public String valueToString() { + return valueToString(DEFAULT_MAX_DEPTH); + } - /** - * Returns whether this Tag and some other Tag are equal. - * They are equal if {@code other} is not {@code null} and they are of the same class. - * Custom Tag implementations should overwrite this but check the result - * of this {@code super}-method while comparing. - * @param other The Tag to compare to. - * @return {@code true} if they are equal based on the conditions mentioned above. - * */ - @Override - public boolean equals(Object other) { - return other != null && getClass() == other.getClass(); - } + /** + * Returns a JSON representation of the value of this Tag. + * + * @param maxDepth The maximum nesting depth. + * @return The string representation of the value of this Tag. + * @throws MaxDepthReachedException If the maximum nesting depth is exceeded. + */ + public abstract String valueToString(int maxDepth); - /** - * Calculates the hash code of this Tag. Tags which are equal according to {@link Tag#equals(Object)} - * must return an equal hash code. - * @return The hash code of this Tag. - * */ - @Override - public int hashCode() { - return value.hashCode(); - } + /** + * Returns whether this Tag and some other Tag are equal. + * They are equal if {@code other} is not {@code null} and they are of the same class. + * Custom Tag implementations should overwrite this but check the result + * of this {@code super}-method while comparing. + * + * @param other The Tag to compare to. + * @return {@code true} if they are equal based on the conditions mentioned above. + */ + @Override + public boolean equals(Object other) { + return other != null && getClass() == other.getClass(); + } - /** - * Creates a clone of this Tag. - * @return A clone of this Tag. - * */ - @SuppressWarnings("CloneDoesntDeclareCloneNotSupportedException") - public abstract Tag clone(); + /** + * Calculates the hash code of this Tag. Tags which are equal according to {@link Tag#equals(Object)} + * must return an equal hash code. + * + * @return The hash code of this Tag. + */ + @Override + public int hashCode() { + return value.hashCode(); + } - /** - * Escapes a string to fit into a JSON-like string representation for Minecraft - * or to create the JSON string representation of a Tag returned from {@link Tag#toString()} - * @param s The string to be escaped. - * @param lenient {@code true} if it should force double quotes ({@code "}) at the start and - * the end of the string. - * @return The escaped string. - * */ - protected static String escapeString(String s, boolean lenient) { - StringBuffer sb = new StringBuffer(); - Matcher m = ESCAPE_PATTERN.matcher(s); - while (m.find()) { - m.appendReplacement(sb, ESCAPE_CHARACTERS.get(m.group())); - } - m.appendTail(sb); - m = NON_QUOTE_PATTERN.matcher(s); - if (!lenient || !m.matches()) { - sb.insert(0, "\"").append("\""); - } - return sb.toString(); - } + /** + * Creates a clone of this Tag. + * + * @return A clone of this Tag. + */ + @SuppressWarnings("CloneDoesntDeclareCloneNotSupportedException") + public abstract Tag clone(); + + /** + * Escapes a string to fit into a JSON-like string representation for Minecraft + * or to create the JSON string representation of a Tag returned from {@link Tag#toString()} + * + * @param s The string to be escaped. + * @param lenient {@code true} if it should force double quotes ({@code "}) at the start and + * the end of the string. + * @return The escaped string. + */ + protected static String escapeString(String s, boolean lenient) { + StringBuffer sb = new StringBuffer(); + Matcher m = ESCAPE_PATTERN.matcher(s); + while (m.find()) { + m.appendReplacement(sb, ESCAPE_CHARACTERS.get(m.group())); + } + m.appendTail(sb); + m = NON_QUOTE_PATTERN.matcher(s); + if (!lenient || !m.matches()) { + sb.insert(0, "\"").append("\""); + } + return sb.toString(); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/BlockUpdater.java b/src/main/java/com/volmit/iris/scaffold/engine/BlockUpdater.java index e25bb9b62..2b408805e 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/BlockUpdater.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/BlockUpdater.java @@ -6,9 +6,9 @@ import org.bukkit.block.data.BlockData; public interface BlockUpdater { - public void catchBlockUpdates(int x, int y, int z, BlockData data); + void catchBlockUpdates(int x, int y, int z, BlockData data); - public void updateChunk(Chunk c); + void updateChunk(Chunk c); - public void update(int x, int y, int z, Chunk c, RNG rf); + void update(int x, int y, int z, Chunk c, RNG rf); } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/Engine.java b/src/main/java/com/volmit/iris/scaffold/engine/Engine.java index eb0a9656a..ea2fc678a 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/Engine.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/Engine.java @@ -1,6 +1,5 @@ package com.volmit.iris.scaffold.engine; -import com.volmit.iris.Iris; import com.volmit.iris.manager.IrisDataManager; import com.volmit.iris.manager.gui.Renderer; import com.volmit.iris.object.*; @@ -25,160 +24,140 @@ import java.awt.*; import java.util.Arrays; public interface Engine extends DataProvider, Fallible, GeneratorAccess, LootProvider, BlockUpdater, Renderer, Hotloadable { - public void close(); + void close(); - public boolean isClosed(); + boolean isClosed(); - public EngineWorldManager getWorldManager(); + EngineWorldManager getWorldManager(); - public void setParallelism(int parallelism); + void setParallelism(int parallelism); - public int getParallelism(); + int getParallelism(); - public EngineTarget getTarget(); + EngineTarget getTarget(); - public EngineFramework getFramework(); + EngineFramework getFramework(); - public void setMinHeight(int min); + void setMinHeight(int min); - public void recycle(); + void recycle(); - public int getIndex(); + int getIndex(); - public int getMinHeight(); + int getMinHeight(); - public double modifyX(double x); + double modifyX(double x); - public double modifyZ(double z); + double modifyZ(double z); - public void generate(int x, int z, Hunk blocks, Hunk biomes); + void generate(int x, int z, Hunk blocks, Hunk biomes); - public EngineMetrics getMetrics(); + EngineMetrics getMetrics(); - default void save() - { - getParallax().saveAll(); + default void save() { + getParallax().saveAll(); } - default void saveNow() - { + default void saveNow() { getParallax().saveAllNOW(); } - default String getName() - { + default String getName() { return getDimension().getName(); } - public default int getHeight() - { + default int getHeight() { return getTarget().getHeight(); } - public default IrisDataManager getData() - { + default IrisDataManager getData() { return getTarget().getData(); } - public default World getWorld() - { + default World getWorld() { return getTarget().getWorld(); } - public default IrisDimension getDimension() - { + default IrisDimension getDimension() { return getTarget().getDimension(); } - public default ParallaxAccess getParallax() - { + default ParallaxAccess getParallax() { return getTarget().getParallaxWorld(); } - public default Color draw(double x, double z) - { - IrisRegion region = getRegion((int)x, (int)z); - IrisBiome biome = getSurfaceBiome((int)x, (int)z); + default Color draw(double x, double z) { + IrisRegion region = getRegion((int) x, (int) z); + IrisBiome biome = getSurfaceBiome((int) x, (int) z); int height = getHeight((int) x, (int) z); double heightFactor = M.lerpInverse(0, getHeight(), height); IrisColor irc = region.getColor(); IrisColor ibc = biome.getColor(); Color rc = irc != null ? irc.getColor() : Color.GREEN.darker(); Color bc = ibc != null ? ibc.getColor() : biome.isAquatic() ? Color.BLUE : Color.YELLOW; - Color f = IrisColor.blend(rc, bc, bc, Color.getHSBColor(0, 0, (float)heightFactor)); + Color f = IrisColor.blend(rc, bc, bc, Color.getHSBColor(0, 0, (float) heightFactor)); return f; } @Override - public default IrisRegion getRegion(int x, int z) { + default IrisRegion getRegion(int x, int z) { return getFramework().getComplex().getRegionStream().get(x, z); } @Override - public default ParallaxAccess getParallaxAccess() - { + default ParallaxAccess getParallaxAccess() { return getParallax(); } @Override - public default IrisBiome getCaveBiome(int x, int z) - { + default IrisBiome getCaveBiome(int x, int z) { return getFramework().getComplex().getCaveBiomeStream().get(x, z); } @Override - public default IrisBiome getSurfaceBiome(int x, int z) - { + default IrisBiome getSurfaceBiome(int x, int z) { return getFramework().getComplex().getTrueBiomeStream().get(x, z); } @Override - public default int getHeight(int x, int z) - { + default int getHeight(int x, int z) { return getFramework().getEngineParallax().getHighest(x, z, true); } @Override - public default void catchBlockUpdates(int x, int y, int z, BlockData data) { - if(data == null) - { + default void catchBlockUpdates(int x, int y, int z, BlockData data) { + if (data == null) { return; } - if(B.isUpdatable(data)) - { - synchronized (getParallax()) - { - getParallax().updateBlock(x,y,z); - getParallax().getMetaRW(x>>4, z>>4).setUpdates(true); + if (B.isUpdatable(data)) { + synchronized (getParallax()) { + getParallax().updateBlock(x, y, z); + getParallax().getMetaRW(x >> 4, z >> 4).setUpdates(true); } } } - public default void placeTiles(Chunk c) { + default void placeTiles(Chunk c) { } @Override - public default void updateChunk(Chunk c) - { + default void updateChunk(Chunk c) { PrecisionStopwatch p = PrecisionStopwatch.start(); - if(getParallax().getMetaR(c.getX(), c.getZ()).isUpdates()) - { + if (getParallax().getMetaR(c.getX(), c.getZ()).isUpdates()) { Hunk b = getParallax().getUpdatesR(c.getX(), c.getZ()); - b.iterateSync((x,y,z,v) -> { + b.iterateSync((x, y, z, v) -> { - if(v != null && v) - { + if (v != null && v) { int vx = x & 15; int vz = z & 15; - update(x,y,z, c, new RNG(Cache.key(c.getX(), c.getZ()))); + update(x, y, z, c, new RNG(Cache.key(c.getX(), c.getZ()))); - if(vx > 0 && vx < 15 && vz > 0 && vz < 15) - { - updateLighting(x,y,z,c); + if (vx > 0 && vx < 15 && vz > 0 && vz < 15) { + updateLighting(x, y, z, c); } } }); @@ -187,51 +166,41 @@ public interface Engine extends DataProvider, Fallible, GeneratorAccess, LootPro getMetrics().getUpdates().put(p.getMilliseconds()); } - public default void updateLighting(int x, int y, int z, Chunk c) - { - Block block = c.getBlock(x,y,z); + default void updateLighting(int x, int y, int z, Chunk c) { + Block block = c.getBlock(x, y, z); BlockData data = block.getBlockData(); - if(B.isLit(data)) - { + if (B.isLit(data)) { try { block.setType(Material.AIR, false); block.setBlockData(data, true); - } catch (Exception e){ + } catch (Exception e) { // Issue when adding block data. Suppress massive warnings and stack-traces to console. } } } @Override - public default void update(int x, int y, int z, Chunk c, RNG rf) - { - Block block = c.getBlock(x,y,z); + default void update(int x, int y, int z, Chunk c, RNG rf) { + Block block = c.getBlock(x, y, z); BlockData data = block.getBlockData(); - if(B.isStorage(data)) - { + if (B.isStorage(data)) { RNG rx = rf.nextParallelRNG(BlockPosition.toLong(x, y, z)); InventorySlotType slot = null; - if(B.isStorageChest(data)) - { + if (B.isStorageChest(data)) { slot = InventorySlotType.STORAGE; } - if(slot != null) - { + if (slot != null) { KList tables = getLootTables(rx, block); InventorySlotType slott = slot; - try - { + try { InventoryHolder m = (InventoryHolder) block.getState(); addItems(false, m.getInventory(), rx, tables, slott, x, y, z, 15); - } - - catch(Throwable ignored) - { + } catch (Throwable ignored) { } } @@ -239,23 +208,19 @@ public interface Engine extends DataProvider, Fallible, GeneratorAccess, LootPro } @Override - public default void scramble(Inventory inventory, RNG rng) - { + default void scramble(Inventory inventory, RNG rng) { org.bukkit.inventory.ItemStack[] items = inventory.getContents(); org.bukkit.inventory.ItemStack[] nitems = new org.bukkit.inventory.ItemStack[inventory.getSize()]; System.arraycopy(items, 0, nitems, 0, items.length); boolean packedFull = false; - splitting: for(int i = 0; i < nitems.length; i++) - { + splitting: + for (int i = 0; i < nitems.length; i++) { ItemStack is = nitems[i]; - if(is != null && is.getAmount() > 1 && !packedFull) - { - for(int j = 0; j < nitems.length; j++) - { - if(nitems[j] == null) - { + if (is != null && is.getAmount() > 1 && !packedFull) { + for (int j = 0; j < nitems.length; j++) { + if (nitems[j] == null) { int take = rng.nextInt(is.getAmount()); take = take == 0 ? 1 : take; is.setAmount(is.getAmount() - take); @@ -269,16 +234,11 @@ public interface Engine extends DataProvider, Fallible, GeneratorAccess, LootPro } } - for(int i = 0; i < 4; i++) - { - try - { + for (int i = 0; i < 4; i++) { + try { Arrays.parallelSort(nitems, (a, b) -> rng.nextInt()); break; - } - - catch(Throwable e) - { + } catch (Throwable e) { } } @@ -287,10 +247,8 @@ public interface Engine extends DataProvider, Fallible, GeneratorAccess, LootPro } @Override - public default void injectTables(KList list, IrisLootReference r) - { - if(r.getMode().equals(LootMode.CLEAR) || r.getMode().equals(LootMode.REPLACE)) - { + default void injectTables(KList list, IrisLootReference r) { + if (r.getMode().equals(LootMode.CLEAR) || r.getMode().equals(LootMode.REPLACE)) { list.clear(); } @@ -298,16 +256,14 @@ public interface Engine extends DataProvider, Fallible, GeneratorAccess, LootPro } @Override - public default KList getLootTables(RNG rng, Block b) - { + default KList getLootTables(RNG rng, Block b) { int rx = b.getX(); int rz = b.getZ(); double he = getFramework().getComplex().getHeightStream().get(rx, rz); PlacedObject po = getFramework().getEngine().getObjectPlacement(rx, b.getY(), rz); if (po != null && po.getPlacement() != null) { - if(B.isStorageChest(b.getBlockData())) - { + if (B.isStorageChest(b.getBlockData())) { IrisLootTable table = po.getPlacement().getTable(b.getBlockData(), getData()); if (table != null) { return new KList<>(table); @@ -324,17 +280,14 @@ public interface Engine extends DataProvider, Fallible, GeneratorAccess, LootPro injectTables(tables, biomeSurface.getLoot()); injectTables(tables, biomeUnder.getLoot()); - if(tables.isNotEmpty()) - { + if (tables.isNotEmpty()) { int target = (int) Math.round(tables.size() * multiplier); - while(tables.size() < target && tables.isNotEmpty()) - { + while (tables.size() < target && tables.isNotEmpty()) { tables.add(tables.get(rng.i(tables.size() - 1))); } - while(tables.size() > target && tables.isNotEmpty()) - { + while (tables.size() > target && tables.isNotEmpty()) { tables.remove(rng.i(tables.size() - 1)); } } @@ -343,56 +296,47 @@ public interface Engine extends DataProvider, Fallible, GeneratorAccess, LootPro } @Override - public default void addItems(boolean debug, Inventory inv, RNG rng, KList tables, InventorySlotType slot, int x, int y, int z, int mgf) - { + default void addItems(boolean debug, Inventory inv, RNG rng, KList tables, InventorySlotType slot, int x, int y, int z, int mgf) { KList items = new KList<>(); int b = 4; - for(IrisLootTable i : tables) - { + for (IrisLootTable i : tables) { b++; items.addAll(i.getLoot(debug, items.isEmpty(), rng, slot, x, y, z, b + b, mgf + b)); } - for(ItemStack i : items) - { + for (ItemStack i : items) { inv.addItem(i); } scramble(inv, rng); } - public default int getMaxHeight() - { + default int getMaxHeight() { return getHeight() + getMinHeight(); } - public EngineEffects getEffects(); + EngineEffects getEffects(); - public EngineCompound getCompound(); + EngineCompound getCompound(); - public default boolean isStudio() - { + default boolean isStudio() { return getCompound().isStudio(); } - public default void clean() - { + default void clean() { MultiBurst.burst.lazy(() -> getParallax().cleanup()); } - default IrisBiome getBiome(Location l) - { + default IrisBiome getBiome(Location l) { return getBiome(l.getBlockX(), l.getBlockY(), l.getBlockZ()); } - default IrisRegion getRegion(Location l) - { + default IrisRegion getRegion(Location l) { return getRegion(l.getBlockX(), l.getBlockZ()); } - default boolean contains(Location l) - { + default boolean contains(Location l) { return l.getBlockY() >= getMinHeight() && l.getBlockY() <= getMaxHeight(); } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/EngineActuator.java b/src/main/java/com/volmit/iris/scaffold/engine/EngineActuator.java index a906876a2..5c4557740 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/EngineActuator.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/EngineActuator.java @@ -2,7 +2,6 @@ package com.volmit.iris.scaffold.engine; import com.volmit.iris.scaffold.hunk.Hunk; -public interface EngineActuator extends EngineComponent -{ - public void actuate(int x, int z, Hunk output); +public interface EngineActuator extends EngineComponent { + void actuate(int x, int z, Hunk output); } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/EngineAssignedActuator.java b/src/main/java/com/volmit/iris/scaffold/engine/EngineAssignedActuator.java index 7021fe70b..054677dab 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/EngineAssignedActuator.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/EngineAssignedActuator.java @@ -2,10 +2,8 @@ package com.volmit.iris.scaffold.engine; import com.volmit.iris.scaffold.hunk.Hunk; -public abstract class EngineAssignedActuator extends EngineAssignedComponent implements EngineActuator -{ - public EngineAssignedActuator(Engine engine, String name) - { +public abstract class EngineAssignedActuator extends EngineAssignedComponent implements EngineActuator { + public EngineAssignedActuator(Engine engine, String name) { super(engine, name); } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/EngineAssignedBiModifier.java b/src/main/java/com/volmit/iris/scaffold/engine/EngineAssignedBiModifier.java index 1ef322b06..6fa933e45 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/EngineAssignedBiModifier.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/EngineAssignedBiModifier.java @@ -2,10 +2,8 @@ package com.volmit.iris.scaffold.engine; import com.volmit.iris.scaffold.hunk.Hunk; -public abstract class EngineAssignedBiModifier extends EngineAssignedComponent implements EngineBiModifier -{ - public EngineAssignedBiModifier(Engine engine, String name) - { +public abstract class EngineAssignedBiModifier extends EngineAssignedComponent implements EngineBiModifier { + public EngineAssignedBiModifier(Engine engine, String name) { super(engine, name); } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/EngineAssignedComponent.java b/src/main/java/com/volmit/iris/scaffold/engine/EngineAssignedComponent.java index 5b9db41c0..51e57859a 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/EngineAssignedComponent.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/EngineAssignedComponent.java @@ -9,8 +9,7 @@ public class EngineAssignedComponent implements EngineComponent { private final RollingSequence metrics; private final String name; - public EngineAssignedComponent(Engine engine, String name) - { + public EngineAssignedComponent(Engine engine, String name) { this.engine = engine; this.metrics = new RollingSequence(16); this.name = name; diff --git a/src/main/java/com/volmit/iris/scaffold/engine/EngineAssignedModifier.java b/src/main/java/com/volmit/iris/scaffold/engine/EngineAssignedModifier.java index 0a51449cb..4015763b1 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/EngineAssignedModifier.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/EngineAssignedModifier.java @@ -2,10 +2,8 @@ package com.volmit.iris.scaffold.engine; import com.volmit.iris.scaffold.hunk.Hunk; -public abstract class EngineAssignedModifier extends EngineAssignedComponent implements EngineModifier -{ - public EngineAssignedModifier(Engine engine, String name) - { +public abstract class EngineAssignedModifier extends EngineAssignedComponent implements EngineModifier { + public EngineAssignedModifier(Engine engine, String name) { super(engine, name); } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/EngineAssignedWorldManager.java b/src/main/java/com/volmit/iris/scaffold/engine/EngineAssignedWorldManager.java index ecfbd4478..3225c54e0 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/EngineAssignedWorldManager.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/EngineAssignedWorldManager.java @@ -20,46 +20,36 @@ public abstract class EngineAssignedWorldManager extends EngineAssignedComponent } @EventHandler - public void on(WorldSaveEvent e) - { - if(e.getWorld().equals(getTarget().getWorld())) - { + public void on(WorldSaveEvent e) { + if (e.getWorld().equals(getTarget().getWorld())) { onSave(); } } @EventHandler - public void on(WorldUnloadEvent e) - { - if(e.getWorld().equals(getTarget().getWorld())) - { + public void on(WorldUnloadEvent e) { + if (e.getWorld().equals(getTarget().getWorld())) { getEngine().close(); } } @EventHandler - public void on(EntitySpawnEvent e) - { - if(e.getEntity().getWorld().equals(getTarget().getWorld())) - { + public void on(EntitySpawnEvent e) { + if (e.getEntity().getWorld().equals(getTarget().getWorld())) { onEntitySpawn(e); } } @EventHandler - public void on(BlockBreakEvent e) - { - if(e.getPlayer().getWorld().equals(getTarget().getWorld())) - { + public void on(BlockBreakEvent e) { + if (e.getPlayer().getWorld().equals(getTarget().getWorld())) { onBlockBreak(e); } } @EventHandler - public void on(BlockPlaceEvent e) - { - if(e.getPlayer().getWorld().equals(getTarget().getWorld())) - { + public void on(BlockPlaceEvent e) { + if (e.getPlayer().getWorld().equals(getTarget().getWorld())) { onBlockPlace(e); } } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/EngineBiModifier.java b/src/main/java/com/volmit/iris/scaffold/engine/EngineBiModifier.java index 188bde30c..a75552b37 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/EngineBiModifier.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/EngineBiModifier.java @@ -2,6 +2,6 @@ package com.volmit.iris.scaffold.engine; import com.volmit.iris.scaffold.hunk.Hunk; -public interface EngineBiModifier extends EngineComponent { - public void modify(int x, int z, Hunk a, Hunk b); +public interface EngineBiModifier extends EngineComponent { + void modify(int x, int z, Hunk a, Hunk b); } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/EngineComponent.java b/src/main/java/com/volmit/iris/scaffold/engine/EngineComponent.java index e4d0b44b8..2b5bc1e4f 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/EngineComponent.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/EngineComponent.java @@ -1,83 +1,67 @@ package com.volmit.iris.scaffold.engine; import com.volmit.iris.Iris; +import com.volmit.iris.generator.IrisComplex; import com.volmit.iris.manager.IrisDataManager; import com.volmit.iris.object.IrisDimension; -import com.volmit.iris.util.RollingSequence; -import com.volmit.iris.generator.IrisComplex; import com.volmit.iris.scaffold.parallax.ParallaxAccess; +import com.volmit.iris.util.RollingSequence; import org.bukkit.event.Listener; public interface EngineComponent { - public Engine getEngine(); + Engine getEngine(); - public RollingSequence getMetrics(); + RollingSequence getMetrics(); - public String getName(); + String getName(); - default void close() - { - try - { - if(this instanceof Listener) - { + default void close() { + try { + if (this instanceof Listener) { Iris.instance.unregisterListener((Listener) this); } - } - - catch(Throwable ignored) - { + } catch (Throwable ignored) { } } - default double modX(double x) - { + default double modX(double x) { return getEngine().modifyX(x); } - default double modZ(double z) - { + default double modZ(double z) { return getEngine().modifyZ(z); } - public default IrisDataManager getData() - { + default IrisDataManager getData() { return getEngine().getData(); } - public default ParallaxAccess getParallax() - { + default ParallaxAccess getParallax() { return getEngine().getParallax(); } - public default EngineTarget getTarget() - { + default EngineTarget getTarget() { return getEngine().getTarget(); } - public default IrisDimension getDimension() - { + default IrisDimension getDimension() { return getEngine().getDimension(); } - public default long getSeed() - { + default long getSeed() { return getTarget().getWorld().getSeed(); } - public default EngineFramework getFramework() - { + default EngineFramework getFramework() { return getEngine().getFramework(); } - public default int getParallelism() - { + default int getParallelism() { return getEngine().getParallelism(); } - public default IrisComplex getComplex() - { + default IrisComplex getComplex() { return getFramework().getComplex(); } } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/EngineCompositeGenerator.java b/src/main/java/com/volmit/iris/scaffold/engine/EngineCompositeGenerator.java index 2a40f6131..c7bb9255f 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/EngineCompositeGenerator.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/EngineCompositeGenerator.java @@ -32,12 +32,7 @@ import java.io.File; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; -import java.util.Random; -import java.util.Set; +import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicBoolean; @@ -51,11 +46,11 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce private int generated = 0; private int lgenerated = 0; private final KMap chunkCache; - private ChronoLatch hotloadcd; - private AtomicBoolean fake; + private final ChronoLatch hotloadcd; + private final AtomicBoolean fake; @Getter private double generatedPerSecond = 0; - private int art; + private final int art; private ReactiveFolder hotloader = null; public EngineCompositeGenerator() { @@ -75,10 +70,8 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce populators = new KList().qadd(new BlockPopulator() { @Override public void populate(@NotNull World world, @NotNull Random random, @NotNull Chunk chunk) { - if(compound != null) - { - for(BlockPopulator i : compound.getPopulators()) - { + if (compound != null) { + for (BlockPopulator i : compound.getPopulators()) { i.populate(world, random, chunk); } } @@ -86,24 +79,17 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce }); } - public void hotload() - { - if(isStudio()) - { + public void hotload() { + if (isStudio()) { Iris.proj.updateWorkspace(); getData().dump(); J.s(() -> { - try - { - for(Player i : getTarget().getWorld().getPlayers()) - { + try { + for (Player i : getTarget().getWorld().getPlayers()) { new MortarSender(i, Iris.instance.getTag()).sendMessage("Dimension Hotloaded"); i.playSound(i.getLocation(), Sound.ITEM_BOTTLE_FILL, 1f, 1.25f); } - } - - catch(Throwable e) - { + } catch (Throwable e) { } }); @@ -111,34 +97,26 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce } } - public void tick() - { - if(isClosed()) - { + public void tick() { + if (isClosed()) { return; } - if(!initialized.get()) - { + if (!initialized.get()) { return; } - try - { + try { if (hotloader != null) { J.a(() -> hotloader.check()); getComposite().clean(); } - } - - catch(Throwable e) - { + } catch (Throwable e) { } - if(M.ms() - mst > 1000) - { - generatedPerSecond = (double)(generated - lgenerated) / ((double)(M.ms() - mst) / 1000D); + if (M.ms() - mst > 1000) { + generatedPerSecond = (double) (generated - lgenerated) / ((double) (M.ms() - mst) / 1000D); mst = M.ms(); lgenerated = generated; } @@ -153,8 +131,7 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce if (query == null) { File iris = new File(world.getWorldFolder(), "iris"); - if(iris.exists() && iris.isDirectory()) - { + if (iris.exists() && iris.isDirectory()) { searching: for (File i : iris.listFiles()) { // Look for v1 location @@ -189,13 +166,9 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce Iris.proj.downloadSearch(new MortarSender(Bukkit.getConsoleSender(), Iris.instance.getTag()), query, false); dim = IrisDataManager.loadAnyDimension(query); - if(dim == null) - { + if (dim == null) { throw new RuntimeException("Cannot find dimension: " + query); - } - - else - { + } else { Iris.info("Download pack: " + query); } } @@ -209,8 +182,7 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce Iris.proj.installIntoWorld(new MortarSender(Bukkit.getConsoleSender(), Iris.instance.getTag()), od.getLoadKey(), world.getWorldFolder()); dim = new IrisDataManager(getDataFolder(world)).getDimensionLoader().load(od.getLoadKey()); - if(dim == null) - { + if (dim == null) { throw new RuntimeException("Cannot find dimension: " + query); } } @@ -224,10 +196,9 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce IrisDimension dim = null; if (query == null) { - File iris = new File(world +"/iris"); + File iris = new File(world + "/iris"); - if(iris.exists() && iris.isDirectory()) - { + if (iris.exists() && iris.isDirectory()) { for (File i : Objects.requireNonNull(iris.listFiles())) { // Look for v1 location if (i.isDirectory() && i.getName().equals("dimensions")) { @@ -261,13 +232,9 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce Iris.proj.downloadSearch(new MortarSender(Bukkit.getConsoleSender(), Iris.instance.getTag()), query, false); dim = IrisDataManager.loadAnyDimension(query); - if(dim == null) - { + if (dim == null) { throw new RuntimeException("Cannot find dimension: " + query); - } - - else - { + } else { Iris.info("Download pack: " + query); } } @@ -281,8 +248,7 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce Iris.proj.installIntoWorld(new MortarSender(Bukkit.getConsoleSender(), Iris.instance.getTag()), od.getLoadKey(), new File(world)); dim = new IrisDataManager(getDataFolder(world)).getDimensionLoader().load(od.getLoadKey()); - if(dim == null) - { + if (dim == null) { throw new RuntimeException("Cannot find dimension: " + query); } } @@ -294,15 +260,13 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce } public synchronized void initialize(World world) { - if(!(world instanceof FakeWorld) && fake.get() && this.compound != null) - { + if (!(world instanceof FakeWorld) && fake.get() && this.compound != null) { fake.set(false); this.compound.updateWorld(world); getTarget().updateWorld(world); placeStrongholds(world); - for(int i = 0; i < getComposite().getSize(); i++) - { + for (int i = 0; i < getComposite().getSize(); i++) { getComposite().getEngine(i).getTarget().updateWorld(world); } @@ -313,8 +277,7 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce return; } - try - { + try { initialized.set(true); IrisDimension dim = getDimension(world); IrisDataManager data = production ? new IrisDataManager(getDataFolder(world)) : dim.getLoader().copy(); @@ -323,10 +286,7 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce populators.clear(); populators.addAll(compound.getPopulators()); hotloader = new ReactiveFolder(data.getDataFolder(), (a, c, d) -> hotload()); - } - - catch(Throwable e) - { + } catch (Throwable e) { e.printStackTrace(); Iris.error("FAILED TO INITIALIZE DIMENSION FROM " + world.toString()); } @@ -334,91 +294,91 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce /** * Place strongholds in the world + * * @param world */ public void placeStrongholds(World world) { EngineData metadata = getComposite().getEngineMetadata(); // TODO: In nms class, not here. Also it doesnt work - if(metadata.getStrongholdPositions() == null || metadata.getStrongholdPositions().size() == 0) - { + if (metadata.getStrongholdPositions() == null || metadata.getStrongholdPositions().size() == 0) { - List strongholds = new ArrayList<>(); - Object nmsWorld = new V(world).invoke("getHandle"); - Object chunkProvider = new V(nmsWorld).invoke("getChunkProvider"); - Object chunkGenerator = new V(chunkProvider).invoke("getChunkGenerator"); - try { - Class clazz = Class.forName("net.minecraft.world.level.chunk.ChunkGenerator"); - Class clazzSG = Class.forName("net.minecraft.world.level.levelgen.feature.StructureGenerator"); - Class clazzBP = Class.forName("net.minecraft.core.BlockPosition"); - Constructor bpCon = clazzBP.getConstructor(int.class, int.class, int.class); + List strongholds = new ArrayList<>(); + Object nmsWorld = new V(world).invoke("getHandle"); + Object chunkProvider = new V(nmsWorld).invoke("getChunkProvider"); + Object chunkGenerator = new V(chunkProvider).invoke("getChunkGenerator"); + try { + Class clazz = Class.forName("net.minecraft.world.level.chunk.ChunkGenerator"); + Class clazzSG = Class.forName("net.minecraft.world.level.levelgen.feature.StructureGenerator"); + Class clazzBP = Class.forName("net.minecraft.core.BlockPosition"); + Constructor bpCon = clazzBP.getConstructor(int.class, int.class, int.class); - //By default, we place 9 strongholds. One near 0,0 and 8 all around it at about 10_000 blocks out - int coords[][] = {{0, 0}, {7000, -7000}, {10000, 0}, {7000, 7000}, {0, 10000}, {-7000, 7000}, {-10000, 0}, {-7000, -7000}, {0, -10000}}; + //By default, we place 9 strongholds. One near 0,0 and 8 all around it at about 10_000 blocks out + int[][] coords = {{0, 0}, {7000, -7000}, {10000, 0}, {7000, 7000}, {0, 10000}, {-7000, 7000}, {-10000, 0}, {-7000, -7000}, {0, -10000}}; - //Set of stronghold locations so we don't place 2 strongholds at the same location - Set existing = new ConcurrentSet<>(); - Set> futures = new HashSet<>(); - for (int[] currCoords : coords) { - //Create a NMS BlockPosition - Object blockPosToTest = bpCon.newInstance(currCoords[0], 0, currCoords[1]); - //Create a CompletableFuture so we can track once the sync code is complete + //Set of stronghold locations so we don't place 2 strongholds at the same location + Set existing = new ConcurrentSet<>(); + Set> futures = new HashSet<>(); + for (int[] currCoords : coords) { + //Create a NMS BlockPosition + Object blockPosToTest = bpCon.newInstance(currCoords[0], 0, currCoords[1]); + //Create a CompletableFuture so we can track once the sync code is complete - CompletableFuture future = new CompletableFuture<>(); - futures.add(future); + CompletableFuture future = new CompletableFuture<>(); + futures.add(future); + + //We have to run this code synchronously because it uses NMS + J.s(() -> { + try { + Object o = getBP(clazz, clazzSG, clazzBP, nmsWorld, blockPosToTest, chunkGenerator); + future.complete(o); + } catch (Exception e) { + e.printStackTrace(); + future.complete(e); + } + }); + } + + CompletableFuture all = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])); + all.thenAccept((_void) -> { //Once all futures for all 9 strongholds have completed + for (CompletableFuture future : futures) { + try { + Object pos = future.getNow(null); + if (pos != null) { + IrisPosition ipos = new IrisPosition((int) new V(pos, false).invoke("getX"), (int) new V(pos, + false).invoke("getY"), (int) new V(pos, false).invoke("getZ")); + long xz = (((long) ipos.getX()) << 32) | (ipos.getZ() & 0xffffffffL); + if (existing.contains(xz)) return; //Make sure we don't double up on stronghold locs + existing.add(xz); + strongholds.add(ipos); - //We have to run this code synchronously because it uses NMS - J.s(() -> { - try { - Object o = getBP(clazz, clazzSG, clazzBP, nmsWorld, blockPosToTest, chunkGenerator); - future.complete(o); - } catch (Exception e) { - e.printStackTrace(); - future.complete(e); } - }); + } catch (Exception e) { + e.printStackTrace(); + } } - CompletableFuture all = CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])); - all.thenAccept((_void) -> { //Once all futures for all 9 strongholds have completed - for (CompletableFuture future : futures) { - try { - Object pos = future.getNow(null); - if (pos != null) { - IrisPosition ipos = new IrisPosition((int) new V(pos, false).invoke("getX"), (int) new V(pos, - false).invoke("getY"), (int) new V(pos, false).invoke("getZ")); - long xz = (((long)ipos.getX()) << 32) | (ipos.getZ() & 0xffffffffL); - if (existing.contains(xz)) return; //Make sure we don't double up on stronghold locs - existing.add(xz); - strongholds.add(ipos); - - } - } catch (Exception e) { - e.printStackTrace(); - } - } - - StringBuilder positions = new StringBuilder(); - for (IrisPosition pos : strongholds){ - positions.append("(").append(pos.getX()).append(",").append(pos.getY()).append(",").append(pos.getZ()).append(") "); - } - Iris.info("Strongholds (" + strongholds.size() + ") found at [" + positions + "]"); - - metadata.setStrongholdPositions(strongholds); - getComposite().saveEngineMetadata(); - }); - - } catch (Exception e) { - strongholds.add( new IrisPosition(1337, 32, -1337) ); - metadata.setStrongholdPositions(strongholds); - Iris.warn("Couldn't properly find the stronghold position for this world. Is this headless mode? Are you not using 1.16 or higher?"); - Iris.warn(" -> Setting default stronghold position"); - e.printStackTrace(); StringBuilder positions = new StringBuilder(); - for (IrisPosition pos : strongholds){ + for (IrisPosition pos : strongholds) { positions.append("(").append(pos.getX()).append(",").append(pos.getY()).append(",").append(pos.getZ()).append(") "); } - Iris.info("Strongholds (" + metadata.getStrongholdPositions().size() + ") found at [" + positions + "]"); + Iris.info("Strongholds (" + strongholds.size() + ") found at [" + positions + "]"); + + metadata.setStrongholdPositions(strongholds); + getComposite().saveEngineMetadata(); + }); + + } catch (Exception e) { + strongholds.add(new IrisPosition(1337, 32, -1337)); + metadata.setStrongholdPositions(strongholds); + Iris.warn("Couldn't properly find the stronghold position for this world. Is this headless mode? Are you not using 1.16 or higher?"); + Iris.warn(" -> Setting default stronghold position"); + e.printStackTrace(); + StringBuilder positions = new StringBuilder(); + for (IrisPosition pos : strongholds) { + positions.append("(").append(pos.getX()).append(",").append(pos.getY()).append(",").append(pos.getZ()).append(") "); } + Iris.info("Strongholds (" + metadata.getStrongholdPositions().size() + ") found at [" + positions + "]"); + } } } @@ -465,17 +425,14 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce return tc.getRaw(); } - public void directWriteMCA(World w, int x, int z, DirectWorldWriter writer, MultiBurst burst) - { + public void directWriteMCA(World w, int x, int z, DirectWorldWriter writer, MultiBurst burst) { BurstExecutor e = burst.burst(1024); int mcaox = x << 5; int mcaoz = z << 5; - for(int i = 0; i < 32; i++) - { + for (int i = 0; i < 32; i++) { int ii = i; - for(int j = 0; j < 32; j++) - { + for (int j = 0; j < 32; j++) { int jj = j; e.queue(() -> directWriteChunk(w, ii + mcaox, jj + mcaoz, writer)); } @@ -484,8 +441,7 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce e.complete(); } - public void directWriteChunk(World w, int x, int z, DirectWorldWriter writer) - { + public void directWriteChunk(World w, int x, int z, DirectWorldWriter writer) { int ox = x << 4; int oz = z << 4; com.volmit.iris.scaffold.data.mca.Chunk cc = writer.getChunk(x, z); @@ -527,30 +483,27 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce @Override public void setBlock(int x, int y, int z, BlockData blockData) { - int xx = (x+ox)&15; - int zz = (z+oz)&15; + int xx = (x + ox) & 15; + int zz = (z + oz) & 15; - if(y > 255 || y < 0) - { + if (y > 255 || y < 0) { return; } - cc.setBlockStateAt(xx, y, zz, writer.getCompound(blockData), false); + cc.setBlockStateAt(xx, y, zz, DirectWorldWriter.getCompound(blockData), false); } @Override public BlockData getBlockData(int x, int y, int z) { - if(y > getMaxHeight()) - { + if (y > getMaxHeight()) { y = getMaxHeight(); } - if(y < 0) - { + if (y < 0) { y = 0; } - return writer.getBlockData(cc.getBlockStateAt((x+ox)&15, y, (z+oz)&15)); + return DirectWorldWriter.getBlockData(cc.getBlockStateAt((x + ox) & 15, y, (z + oz) & 15)); } @Override @@ -607,33 +560,27 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce }).run(); } - public Chunk generatePaper(World world, int x, int z) - { + public Chunk generatePaper(World world, int x, int z) { precache(world, x, z); Chunk c = PaperLib.getChunkAtAsync(world, x, z, true).join(); chunkCache.remove(Cache.key(x, z)); return c; } - public void precache(World world, int x, int z) - { - synchronized (this) - { + public void precache(World world, int x, int z) { + synchronized (this) { initialize(world); } - synchronized (chunkCache) - { - if(chunkCache.containsKey(Cache.key(x, z))) - { + synchronized (chunkCache) { + if (chunkCache.containsKey(Cache.key(x, z))) { return; } } - PregeneratedData data = new PregeneratedData(getComposite().getHeight()-1); + PregeneratedData data = new PregeneratedData(getComposite().getHeight() - 1); compound.generate(x * 16, z * 16, data.getBlocks(), data.getPost(), data.getBiomes()); - synchronized (chunkCache) - { + synchronized (chunkCache) { chunkCache.put(Cache.key(x, z), data); } } @@ -643,20 +590,16 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce return chunkCache.size(); } - public int getCachedChunks() - { + public int getCachedChunks() { return chunkCache.size(); } - public Runnable generateChunkRawData(World world, int x, int z, TerrainChunk tc) - { + public Runnable generateChunkRawData(World world, int x, int z, TerrainChunk tc) { initialize(world); - synchronized (chunkCache) - { + synchronized (chunkCache) { long g = Cache.key(x, z); - if(chunkCache.containsKey(g)) - { + if (chunkCache.containsKey(g)) { generated++; return chunkCache.remove(g).inject(tc); } @@ -668,7 +611,7 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce compound.generate(x * 16, z * 16, blocks, post, biomes); generated++; - return () -> blocks.insertSoftly(0,0,0, post, (b) -> b == null || B.isAirOrFluid(b)); + return () -> blocks.insertSoftly(0, 0, 0, post, (b) -> b == null || B.isAirOrFluid(b)); } @Override @@ -752,7 +695,7 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce @Override public IrisBiome getBiome(int x, int y, int z) { // TODO: REMOVE GET ABS BIOME OR THIS ONE - return getEngineAccess(y).getBiome(x, y-getComposite().getEngineForHeight(y).getMinHeight(), z); + return getEngineAccess(y).getBiome(x, y - getComposite().getEngineForHeight(y).getMinHeight(), z); } @Override @@ -767,7 +710,7 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce @Override public IrisDataManager getData() { - if (getCompound() == null){ + if (getCompound() == null) { return null; } return getComposite().getData(); @@ -790,8 +733,7 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce @Override public void clearRegeneratedLists(int x, int z) { - for(int i = 0; i < getComposite().getSize(); i++) - { + for (int i = 0; i < getComposite().getSize(); i++) { getComposite().getEngine(i).getParallax().delete(x, z); } } @@ -800,8 +742,8 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce public void regenerate(int x, int z) { clearRegeneratedLists(x, z); - int xx = x*16; - int zz = z*16; + int xx = x * 16; + int zz = z * 16; generateChunkRawData(getComposite().getWorld(), x, z, new TerrainChunk() { @Override public void setRaw(ChunkData data) { @@ -840,15 +782,14 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce @Override public void setBlock(int x, int y, int z, BlockData blockData) { - if(!getBlockData(x,y,z).matches(blockData)) - { - Iris.edit.set(compound.getWorld(), x+xx, y, z+zz, blockData); + if (!getBlockData(x, y, z).matches(blockData)) { + Iris.edit.set(compound.getWorld(), x + xx, y, z + zz, blockData); } } @Override public BlockData getBlockData(int x, int y, int z) { - return Iris.edit.get(compound.getWorld(), x+xx, y, z+zz); + return Iris.edit.get(compound.getWorld(), x + xx, y, z + zz); } @Override @@ -925,12 +866,9 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce @Override public boolean isClosed() { - try - { + try { return getComposite().getEngine(0).isClosed(); - } - catch(Throwable e) - { + } catch (Throwable e) { return false; } } @@ -939,7 +877,7 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce public EngineTarget getTarget() { try { return getComposite().getEngine(0).getTarget(); - } catch (NullPointerException e){ + } catch (NullPointerException e) { Iris.info("Failed to get composite engine. Please re-create the world in case you notice issues"); return null; } @@ -952,8 +890,7 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce @Override public boolean isFailing() { - if(getComposite() == null) - { + if (getComposite() == null) { return false; } @@ -970,24 +907,16 @@ public class EngineCompositeGenerator extends ChunkGenerator implements IrisAcce } public KList getAllBiomes(String worldName) { - if(getComposite() != null) - { + if (getComposite() != null) { return getComposite().getAllBiomes(); - } - - else - { + } else { KMap v = new KMap<>(); IrisDimension dim = getDimension(worldName); dim.getAllAnyBiomes().forEach((i) -> v.put(i.getLoadKey(), i)); - try - { + try { dim.getDimensionalComposite().forEach((m) -> IrisDataManager.loadAnyDimension(m.getDimension()).getAllAnyBiomes().forEach((i) -> v.put(i.getLoadKey(), i))); - } - - catch(Throwable e) - { + } catch (Throwable e) { } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/EngineCompound.java b/src/main/java/com/volmit/iris/scaffold/engine/EngineCompound.java index e98bdea4b..1c33e34fd 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/EngineCompound.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/EngineCompound.java @@ -19,52 +19,46 @@ import org.bukkit.generator.BlockPopulator; import java.util.List; -public interface EngineCompound extends Listener, Hotloadable, DataProvider -{ - public IrisDimension getRootDimension(); +public interface EngineCompound extends Listener, Hotloadable, DataProvider { + IrisDimension getRootDimension(); - public void generate(int x, int z, Hunk blocks, Hunk postblocks, Hunk biomes); + void generate(int x, int z, Hunk blocks, Hunk postblocks, Hunk biomes); - public World getWorld(); + World getWorld(); - public List getStrongholdPositions(); + List getStrongholdPositions(); - public void printMetrics(CommandSender sender); + void printMetrics(CommandSender sender); - public int getSize(); + int getSize(); - public default int getHeight() - { + default int getHeight() { // TODO: WARNING HEIGHT return 256; } - public Engine getEngine(int index); + Engine getEngine(int index); - public MultiBurst getBurster(); + MultiBurst getBurster(); - public EngineData getEngineMetadata(); + EngineData getEngineMetadata(); - public void saveEngineMetadata(); + void saveEngineMetadata(); - public KList getPopulators(); + KList getPopulators(); - default Engine getEngineForHeight(int height) - { - if(getSize() == 1) - { + default Engine getEngineForHeight(int height) { + if (getSize() == 1) { return getEngine(0); } int buf = 0; - for(int i = 0; i < getSize(); i++) - { + for (int i = 0; i < getSize(); i++) { Engine e = getEngine(i); buf += e.getHeight(); - if(buf >= height) - { + if (buf >= height) { return e; } } @@ -72,101 +66,81 @@ public interface EngineCompound extends Listener, Hotloadable, DataProvider return getEngine(getSize() - 1); } - public default void recycle() - { - for(int i = 0; i < getSize(); i++) - { + default void recycle() { + for (int i = 0; i < getSize(); i++) { getEngine(i).recycle(); } } - public default void save() - { + default void save() { saveEngineMetadata(); - for(int i = 0; i < getSize(); i++) - { + for (int i = 0; i < getSize(); i++) { getEngine(i).save(); } } - public default void saveNOW() - { + default void saveNOW() { saveEngineMetadata(); - for(int i = 0; i < getSize(); i++) - { + for (int i = 0; i < getSize(); i++) { getEngine(i).saveNow(); } } - public IrisDataManager getData(int height); + IrisDataManager getData(int height); - public default IrisDataManager getData() - { + default IrisDataManager getData() { return getData(0); } - public default void close() - { - for(int i = 0; i < getSize(); i++) - { + default void close() { + for (int i = 0; i < getSize(); i++) { getEngine(i).close(); } } - public boolean isFailing(); + boolean isFailing(); - public int getThreadCount(); + int getThreadCount(); - public boolean isStudio(); + boolean isStudio(); - public void setStudio(boolean std); + void setStudio(boolean std); - public default void clean() - { - for(int i = 0; i < getSize(); i++) - { + default void clean() { + for (int i = 0; i < getSize(); i++) { getEngine(i).clean(); } } - public Engine getDefaultEngine(); + Engine getDefaultEngine(); - public default KList getAllBiomes() - { + default KList getAllBiomes() { KMap v = new KMap<>(); IrisDimension dim = getRootDimension(); dim.getAllBiomes(this).forEach((i) -> v.put(i.getLoadKey(), i)); - try - { - dim.getDimensionalComposite().forEach((m) -> getData().getDimensionLoader().load(m.getDimension()).getAllBiomes(this).forEach((i) -> v.put(i.getLoadKey(), i))); - } + try { + dim.getDimensionalComposite().forEach((m) -> getData().getDimensionLoader().load(m.getDimension()).getAllBiomes(this).forEach((i) -> v.put(i.getLoadKey(), i))); + } catch (Throwable e) { - catch(Throwable e) - { - - } + } return v.v(); } void updateWorld(World world); - default int getLowestBedrock() - { + default int getLowestBedrock() { int f = Integer.MAX_VALUE; - for(int i = 0; i < getSize(); i++) - { + for (int i = 0; i < getSize(); i++) { Engine e = getEngine(i); - if(e.getDimension().isBedrock()) - { - int m = ((IrisTerrainActuator)e.getFramework().getTerrainActuator()).getLastBedrock(); + if (e.getDimension().isBedrock()) { + int m = ((IrisTerrainActuator) e.getFramework().getTerrainActuator()).getLastBedrock(); - if(f > m) - { + if (f > m) { f = m; } } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/EngineData.java b/src/main/java/com/volmit/iris/scaffold/engine/EngineData.java index 0cd8e42ca..8da659d4d 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/EngineData.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/EngineData.java @@ -15,8 +15,7 @@ public class EngineData { private String lastVersion; private List strongholdPositions; - public void save(File f) - { + public void save(File f) { try { f.getParentFile().mkdirs(); IO.writeAll(f, new Gson().toJson(this)); @@ -25,16 +24,11 @@ public class EngineData { } } - public static EngineData load(File f) - { - try - { + public static EngineData load(File f) { + try { f.getParentFile().mkdirs(); return new Gson().fromJson(IO.readAll(f), EngineData.class); - } - - catch(Throwable e) - { + } catch (Throwable e) { } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/EngineDecorator.java b/src/main/java/com/volmit/iris/scaffold/engine/EngineDecorator.java index 3c9eba158..4f862579d 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/EngineDecorator.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/EngineDecorator.java @@ -1,22 +1,19 @@ package com.volmit.iris.scaffold.engine; import com.volmit.iris.object.IrisBiome; -import com.volmit.iris.util.B; import com.volmit.iris.scaffold.hunk.Hunk; +import com.volmit.iris.util.B; import org.bukkit.block.data.BlockData; public interface EngineDecorator extends EngineComponent { - 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); + 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); - default void decorate(int x, int z, int realX, int realZ, Hunk data, IrisBiome biome, int height, int max) - { + default void decorate(int x, int z, int realX, int realZ, Hunk data, IrisBiome biome, int height, int max) { decorate(x, z, realX, realX, realX, realZ, realZ, realZ, data, biome, height, max); } - default boolean canGoOn(BlockData decorant, BlockData atop) - { - if(atop == null || B.isAir(atop)) - { + default boolean canGoOn(BlockData decorant, BlockData atop) { + if (atop == null || B.isAir(atop)) { return false; } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/EngineEffects.java b/src/main/java/com/volmit/iris/scaffold/engine/EngineEffects.java index 5d4a52545..3d7d7b416 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/EngineEffects.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/EngineEffects.java @@ -1,7 +1,7 @@ package com.volmit.iris.scaffold.engine; public interface EngineEffects extends EngineComponent { - public void updatePlayerMap(); + void updatePlayerMap(); - public void tickRandomPlayer(); + void tickRandomPlayer(); } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/EngineFramework.java b/src/main/java/com/volmit/iris/scaffold/engine/EngineFramework.java index 71b3b7e97..9378d1b86 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/EngineFramework.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/EngineFramework.java @@ -6,37 +6,35 @@ import com.volmit.iris.scaffold.data.DataProvider; import org.bukkit.block.Biome; import org.bukkit.block.data.BlockData; -public interface EngineFramework extends DataProvider -{ - public Engine getEngine(); +public interface EngineFramework extends DataProvider { + Engine getEngine(); - public IrisComplex getComplex(); - - public EngineParallaxManager getEngineParallax(); + IrisComplex getComplex(); + + EngineParallaxManager getEngineParallax(); default IrisDataManager getData() { return getComplex().getData(); } - default void recycle() - { + default void recycle() { getEngine().getParallax().cleanup(); getData().getObjectLoader().clean(); } - public EngineActuator getTerrainActuator(); + EngineActuator getTerrainActuator(); - public EngineActuator getDecorantActuator(); + EngineActuator getDecorantActuator(); - public EngineActuator getBiomeActuator(); + EngineActuator getBiomeActuator(); - public EngineModifier getCaveModifier(); + EngineModifier getCaveModifier(); - public EngineModifier getRavineModifier(); + EngineModifier getRavineModifier(); - public EngineModifier getDepositModifier(); + EngineModifier getDepositModifier(); - public EngineModifier getPostModifier(); + EngineModifier getPostModifier(); void close(); } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/EngineMetrics.java b/src/main/java/com/volmit/iris/scaffold/engine/EngineMetrics.java index e8d75903d..d17c0174d 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/EngineMetrics.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/EngineMetrics.java @@ -18,8 +18,7 @@ public class EngineMetrics { private final AtomicRollingSequence ravine; private final AtomicRollingSequence deposit; - public EngineMetrics(int mem) - { + public EngineMetrics(int mem) { this.total = new AtomicRollingSequence(mem); this.terrain = new AtomicRollingSequence(mem); this.biome = new AtomicRollingSequence(mem); diff --git a/src/main/java/com/volmit/iris/scaffold/engine/EngineModifier.java b/src/main/java/com/volmit/iris/scaffold/engine/EngineModifier.java index 98fe710e8..7834a8a2e 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/EngineModifier.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/EngineModifier.java @@ -2,6 +2,6 @@ package com.volmit.iris.scaffold.engine; import com.volmit.iris.scaffold.hunk.Hunk; -public interface EngineModifier extends EngineComponent { - public void modify(int x, int z, Hunk t); +public interface EngineModifier extends EngineComponent { + void modify(int x, int z, Hunk t); } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/EngineParallaxManager.java b/src/main/java/com/volmit/iris/scaffold/engine/EngineParallaxManager.java index 18012d652..5b0bd832e 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/EngineParallaxManager.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/EngineParallaxManager.java @@ -81,28 +81,25 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { * Verifies the chunk correctly has all the parallax objects it should. * This method should not have to be written but why not. * Thread Safe, Designed to run async + * * @param c the bukkit chunk */ - default int repairChunk(Chunk c) - { + default int repairChunk(Chunk c) { ParallaxChunkMeta m = getParallaxAccess().getMetaR(c.getX(), c.getZ()); Hunk o = getParallaxAccess().getObjectsR(c.getX(), c.getZ()); Hunk b = getParallaxAccess().getBlocksR(c.getX(), c.getZ()); ChunkSnapshot snapshot = c.getChunkSnapshot(false, false, false); KList queue = new KList<>(); - o.iterateSync((x,y,z,s) -> { - if(s != null) - { + o.iterateSync((x, y, z, s) -> { + if (s != null) { - BlockData bd = b.get(x,y,z); - if(bd != null) - { - BlockData bdx = snapshot.getBlockData(x,y,z); + BlockData bd = b.get(x, y, z); + if (bd != null) { + BlockData bdx = snapshot.getBlockData(x, y, z); - if(!bdx.getMaterial().equals(bd.getMaterial())) - { - queue.add(() -> c.getBlock(x,y,z).setBlockData(bd, false)); + if (!bdx.getMaterial().equals(bd.getMaterial())) { + queue.add(() -> c.getBlock(x, y, z).setBlockData(bd, false)); } } } @@ -114,16 +111,14 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { bx.set(true); }); - while(!bx.get()) - { + while (!bx.get()) { J.sleep(50); } return queue.size(); } - default void insertTileEntities(int x, int z, Consumer4> consumer) - { + default void insertTileEntities(int x, int z, Consumer4> consumer) { ParallaxChunkMeta meta = getParallaxAccess().getMetaRW(x >> 4, z >> 4); if (meta.isTilesGenerated()) { @@ -132,10 +127,9 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { meta.setTilesGenerated(true); - getParallaxAccess().getTilesRW(x>>4, z>>4).iterateSync((a,b,c,d) -> { - if(d != null) - { - consumer.accept(a,b,c,d); + getParallaxAccess().getTilesRW(x >> 4, z >> 4).iterateSync((a, b, c, d) -> { + if (d != null) { + consumer.accept(a, b, c, d); } }); } @@ -155,9 +149,8 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { return; } - getParallaxAccess().getBlocksR(x>>4,z>>4).iterateSync((a,b,c,d) -> { - if(d != null) - { + getParallaxAccess().getBlocksR(x >> 4, z >> 4).iterateSync((a, b, c, d) -> { + if (d != null) { data.set(a, b, c, d); } }); @@ -185,21 +178,15 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { for (j = -s; j <= s; j++) { ParallaxChunkMeta m = getParallaxAccess().getMetaR(i + cx, j + cz); - try - { - synchronized (m.getFeatures()) - { - for(IrisFeaturePositional k : m.getFeatures()) - { + try { + synchronized (m.getFeatures()) { + for (IrisFeaturePositional k : m.getFeatures()) { if (k.shouldFilter(x, z)) { f.accept(k); } } } - } - - catch(Throwable e) - { + } catch (Throwable e) { e.printStackTrace(); Iris.warn("Failed to read positional features in chunk " + (i + cx) + " " + (j + cz) + "(" + e.getClass().getSimpleName() + ")"); } @@ -207,24 +194,22 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { } } - default void generateParallaxArea(int x, int z) - { - try - { + default void generateParallaxArea(int x, int z) { + try { PrecisionStopwatch p = PrecisionStopwatch.start(); int s = (int) Math.ceil(getParallaxSize() / 2D); - int i,j; + int i, j; KList after = new KList<>(); int bs = (int) Math.pow((s * 2) + 1, 2); BurstExecutor burst = MultiBurst.burst.burst(bs); for (i = -s; i <= s; i++) { for (j = -s; j <= s; j++) { - int xx = i +x; - int zz = j +z; + int xx = i + x; + int zz = j + z; int xxx = xx << 4; int zzz = zz << 4; - if (!getParallaxAccess().isFeatureGenerated(xx, zz)){ + if (!getParallaxAccess().isFeatureGenerated(xx, zz)) { burst.queue(() -> { getParallaxAccess().setFeatureGenerated(xx, zz); RNG rng = new RNG(Cache.key(xx, zz)).nextParallelRNG(getEngine().getTarget().getWorld().getSeed()); @@ -244,9 +229,8 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { for (j = -s; j <= s; j++) { int jj = j; burst.queue(() -> { - KList a = generateParallaxVacuumLayer(ii +x, jj +z); - synchronized (a) - { + KList a = generateParallaxVacuumLayer(ii + x, jj + z); + synchronized (a) { after.addAll(a); } }); @@ -260,7 +244,7 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { int ii = i; for (j = -s; j <= s; j++) { int jj = j; - burst.queue(() -> generateParallaxLayer(ii +x, jj +z)); + burst.queue(() -> generateParallaxLayer(ii + x, jj + z)); } } @@ -269,94 +253,77 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { getParallaxAccess().setChunkGenerated(x, z); p.end(); getEngine().getMetrics().getParallax().put(p.getMilliseconds()); - } - - catch(Throwable e) - { + } catch (Throwable e) { Iris.error("Failed to generate parallax in " + x + " " + z); e.printStackTrace(); } } - default KList generateParallaxVacuumLayer(int x, int z) - { + default KList generateParallaxVacuumLayer(int x, int z) { KList after = new KList<>(); - if(getParallaxAccess().isParallaxGenerated(x, z)) - { + if (getParallaxAccess().isParallaxGenerated(x, z)) { return after; } - int xx = x<<4; - int zz = z<<4; + int xx = x << 4; + int zz = z << 4; RNG rng = new RNG(Cache.key(x, z)).nextParallelRNG(getEngine().getTarget().getWorld().getSeed()); - IrisRegion region = getComplex().getRegionStream().get(xx+8, zz+8); - IrisBiome biome = getComplex().getTrueBiomeStream().get(xx+8, zz+8); + IrisRegion region = getComplex().getRegionStream().get(xx + 8, zz + 8); + IrisBiome biome = getComplex().getTrueBiomeStream().get(xx + 8, zz + 8); after.addAll(generateParallaxJigsaw(rng, x, z, biome, region)); generateParallaxSurface(rng, x, z, biome, region, true); generateParallaxMutations(rng, x, z, true); return after; } - default void generateParallaxLayer(int x, int z, boolean force) - { - if(!force && getParallaxAccess().isParallaxGenerated(x, z)) - { + default void generateParallaxLayer(int x, int z, boolean force) { + if (!force && getParallaxAccess().isParallaxGenerated(x, z)) { return; } - int xx = x<<4; - int zz = z<<4; + int xx = x << 4; + int zz = z << 4; getParallaxAccess().setParallaxGenerated(x, z); RNG rng = new RNG(Cache.key(x, z)).nextParallelRNG(getEngine().getTarget().getWorld().getSeed()); - IrisBiome biome = getComplex().getTrueBiomeStream().get(xx+8, zz+8); - IrisRegion region = getComplex().getRegionStream().get(xx+8,zz+8); - generateParallaxSurface(rng, x, z, biome, region,false); + IrisBiome biome = getComplex().getTrueBiomeStream().get(xx + 8, zz + 8); + IrisRegion region = getComplex().getRegionStream().get(xx + 8, zz + 8); + generateParallaxSurface(rng, x, z, biome, region, false); generateParallaxMutations(rng, x, z, false); } - default void generateParallaxFeatures(RNG rng, int cx, int cz, IrisRegion region, IrisBiome biome) - { - for(IrisFeaturePotential i : getEngine().getDimension().getFeatures()) - { + default void generateParallaxFeatures(RNG rng, int cx, int cz, IrisRegion region, IrisBiome biome) { + for (IrisFeaturePotential i : getEngine().getDimension().getFeatures()) { placeZone(rng, cx, cz, i); } - for(IrisFeaturePotential i : region.getFeatures()) - { + for (IrisFeaturePotential i : region.getFeatures()) { placeZone(rng, cx, cz, i); } - for(IrisFeaturePotential i : biome.getFeatures()) - { + for (IrisFeaturePotential i : biome.getFeatures()) { placeZone(rng, cx, cz, i); } } - default void placeZone(RNG rng, int cx, int cz, IrisFeaturePotential i) - { - if(i.hasZone(rng, cx, cz)) - { - getParallaxAccess().getMetaRW(cx, cz).getFeatures().add(new IrisFeaturePositional((cx << 4) + rng.nextInt(16), (cz << 4)+ rng.nextInt(16), i.getZone())); + default void placeZone(RNG rng, int cx, int cz, IrisFeaturePotential i) { + if (i.hasZone(rng, cx, cz)) { + getParallaxAccess().getMetaRW(cx, cz).getFeatures().add(new IrisFeaturePositional((cx << 4) + rng.nextInt(16), (cz << 4) + rng.nextInt(16), i.getZone())); } } - default void generateParallaxLayer(int x, int z) - { + default void generateParallaxLayer(int x, int z) { generateParallaxLayer(x, z, false); } - default KList placeStructure(IrisPosition position, IrisJigsawStructure structure, RNG rng) - { + default KList placeStructure(IrisPosition position, IrisJigsawStructure structure, RNG rng) { KList placeAfter = new KList<>(); - if (structure == null){ + if (structure == null) { return null; } - if(structure.getFeature() != null) - { - if(structure.getFeature().getBlockRadius() == 32) - { - structure.getFeature().setBlockRadius((double)structure.getMaxDimension()/3); + if (structure.getFeature() != null) { + if (structure.getFeature().getBlockRadius() == 32) { + structure.getFeature().setBlockRadius((double) structure.getMaxDimension() / 3); } getParallaxAccess().getMetaRW(position.getX() >> 4, position.getZ() >> 4).getFeatures() @@ -371,12 +338,10 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { KList placeAfter = new KList<>(); boolean placed = false; - if(getEngine().getDimension().getStronghold() != null) - { + if (getEngine().getDimension().getStronghold() != null) { List poss = getEngine().getCompound().getStrongholdPositions(); - if(poss != null) - { + if (poss != null) { for (IrisPosition pos : poss) { if (x == pos.getX() >> 4 && z == pos.getZ() >> 4) { IrisJigsawStructure structure = getData().getJigsawStructureLoader().load(getEngine().getDimension().getStronghold()); @@ -387,13 +352,10 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { } } - if(!placed) - { - for (IrisJigsawStructurePlacement i : biome.getJigsawStructures()) - { - if(rng.nextInt(i.getRarity()) == 0) - { - IrisPosition position = new IrisPosition((x<<4) + rng.nextInt(15),0,(z<<4) + rng.nextInt(15)); + if (!placed) { + for (IrisJigsawStructurePlacement i : biome.getJigsawStructures()) { + if (rng.nextInt(i.getRarity()) == 0) { + IrisPosition position = new IrisPosition((x << 4) + rng.nextInt(15), 0, (z << 4) + rng.nextInt(15)); IrisJigsawStructure structure = getData().getJigsawStructureLoader().load(i.getStructure()); placeAfter.addAll(placeStructure(position, structure, rng)); placed = true; @@ -401,13 +363,10 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { } } - if(!placed) - { - for (IrisJigsawStructurePlacement i : region.getJigsawStructures()) - { - if(rng.nextInt(i.getRarity()) == 0) - { - IrisPosition position = new IrisPosition((x<<4) + rng.nextInt(15),0,(z<<4) + rng.nextInt(15)); + if (!placed) { + for (IrisJigsawStructurePlacement i : region.getJigsawStructures()) { + if (rng.nextInt(i.getRarity()) == 0) { + IrisPosition position = new IrisPosition((x << 4) + rng.nextInt(15), 0, (z << 4) + rng.nextInt(15)); IrisJigsawStructure structure = getData().getJigsawStructureLoader().load(i.getStructure()); placeAfter.addAll(placeStructure(position, structure, rng)); placed = true; @@ -415,13 +374,10 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { } } - if(!placed) - { - for (IrisJigsawStructurePlacement i : getEngine().getDimension().getJigsawStructures()) - { - if(rng.nextInt(i.getRarity()) == 0) - { - IrisPosition position = new IrisPosition((x<<4) + rng.nextInt(15),0,(z<<4) + rng.nextInt(15)); + if (!placed) { + for (IrisJigsawStructurePlacement i : getEngine().getDimension().getJigsawStructures()) { + if (rng.nextInt(i.getRarity()) == 0) { + IrisPosition position = new IrisPosition((x << 4) + rng.nextInt(15), 0, (z << 4) + rng.nextInt(15)); IrisJigsawStructure structure = getData().getJigsawStructureLoader().load(i.getStructure()); placeAfter.addAll(placeStructure(position, structure, rng)); placed = true; @@ -434,18 +390,15 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { default void generateParallaxSurface(RNG rng, int x, int z, IrisBiome biome, IrisRegion region, boolean vacuum) { - for (IrisObjectPlacement i : biome.getSurfaceObjects()) - { - if(i.isVacuum() != vacuum) - { + for (IrisObjectPlacement i : biome.getSurfaceObjects()) { + if (i.isVacuum() != vacuum) { continue; } - if(rng.chance(i.getChance() + rng.d(-0.005, 0.005)) && rng.chance(getComplex().getObjectChanceStream().get(x<<4, z<<4))) - { + if (rng.chance(i.getChance() + rng.d(-0.005, 0.005)) && rng.chance(getComplex().getObjectChanceStream().get(x << 4, z << 4))) { try { place(rng, x << 4, z << 4, i); - } catch(Throwable e) { + } catch (Throwable e) { Iris.error("Failed to place objects in the following biome: " + biome.getName()); Iris.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ")."); Iris.error("Are these objects missing?"); @@ -454,18 +407,15 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { } } - for (IrisObjectPlacement i : region.getSurfaceObjects()) - { - if(i.isVacuum() != vacuum) - { + for (IrisObjectPlacement i : region.getSurfaceObjects()) { + if (i.isVacuum() != vacuum) { continue; } - if(rng.chance(i.getChance() + rng.d(-0.005, 0.005)) && rng.chance(getComplex().getObjectChanceStream().get(x<<4, z<<4))) - { + if (rng.chance(i.getChance() + rng.d(-0.005, 0.005)) && rng.chance(getComplex().getObjectChanceStream().get(x << 4, z << 4))) { try { place(rng, x << 4, z << 4, i); - } catch(Throwable e) { + } catch (Throwable e) { Iris.error("Failed to place objects in the following biome: " + biome.getName()); Iris.error("Object(s) " + i.getPlace().toString(", ") + " (" + e.getClass().getSimpleName() + ")."); Iris.error("Are these objects missing?"); @@ -476,29 +426,23 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { } default void generateParallaxMutations(RNG rng, int x, int z, boolean vacuum) { - if(getEngine().getDimension().getMutations().isEmpty()) - { + if (getEngine().getDimension().getMutations().isEmpty()) { return; } - searching: for(IrisBiomeMutation k : getEngine().getDimension().getMutations()) - { - for(int l = 0; l < k.getChecks(); l++) - { + searching: + for (IrisBiomeMutation k : getEngine().getDimension().getMutations()) { + for (int l = 0; l < k.getChecks(); l++) { IrisBiome sa = getComplex().getTrueBiomeStream().get(((x * 16) + rng.nextInt(16)) + rng.i(-k.getRadius(), k.getRadius()), ((z * 16) + rng.nextInt(16)) + rng.i(-k.getRadius(), k.getRadius())); IrisBiome sb = getComplex().getTrueBiomeStream().get(((x * 16) + rng.nextInt(16)) + rng.i(-k.getRadius(), k.getRadius()), ((z * 16) + rng.nextInt(16)) + rng.i(-k.getRadius(), k.getRadius())); - if(sa.getLoadKey().equals(sb.getLoadKey())) - { + if (sa.getLoadKey().equals(sb.getLoadKey())) { continue; } - if(k.getRealSideA(this).contains(sa.getLoadKey()) && k.getRealSideB(this).contains(sb.getLoadKey())) - { - for(IrisObjectPlacement m : k.getObjects()) - { - if(m.isVacuum() != vacuum) - { + if (k.getRealSideA(this).contains(sa.getLoadKey()) && k.getRealSideB(this).contains(sb.getLoadKey())) { + for (IrisObjectPlacement m : k.getObjects()) { + if (m.isVacuum() != vacuum) { continue; } @@ -511,13 +455,11 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { } } - default void place(RNG rng, int x, int z, IrisObjectPlacement objectPlacement) - { - place(rng, x,-1, z, objectPlacement); + default void place(RNG rng, int x, int z, IrisObjectPlacement objectPlacement) { + place(rng, x, -1, z, objectPlacement); } - default void placePiece(RNG rng, int xx, int forceY, int zz, IrisObject v, IrisObjectPlacement p) - { + default void placePiece(RNG rng, int xx, int forceY, int zz, IrisObject v, IrisObjectPlacement p) { int id = rng.i(0, Integer.MAX_VALUE); int maxf = 10000; AtomicBoolean pl = new AtomicBoolean(false); @@ -528,36 +470,33 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { int yf = b.getY(); int zf = b.getZ(); getParallaxAccess().setObject(xf, yf, zf, v.getLoadKey() + "@" + id); - ParallaxChunkMeta meta = getParallaxAccess().getMetaRW(xf>>4, zf>>4); + ParallaxChunkMeta meta = getParallaxAccess().getMetaRW(xf >> 4, zf >> 4); meta.setObjects(true); meta.setMinObject(Math.min(Math.max(meta.getMinObject(), 0), yf)); meta.setMaxObject(Math.max(Math.max(meta.getMaxObject(), 0), yf)); }, null, getData()); - if(p.isVacuum()) - { + if (p.isVacuum()) { double a = Math.max(v.getW(), v.getD()); IrisFeature f = new IrisFeature(); - f.setConvergeToHeight(h-(v.getH() >> 1)); + f.setConvergeToHeight(h - (v.getH() >> 1)); f.setBlockRadius(a); - f.setInterpolationRadius(a/4); + f.setInterpolationRadius(a / 4); f.setInterpolator(InterpolationMethod.BILINEAR_STARCAST_9); f.setStrength(1D); - getParallaxAccess().getMetaRW(xx>>4, zz>>4).getFeatures().add(new IrisFeaturePositional(xx, zz, f)); + getParallaxAccess().getMetaRW(xx >> 4, zz >> 4).getFeatures().add(new IrisFeaturePositional(xx, zz, f)); } } - default void place(RNG rng, int x, int forceY, int z, IrisObjectPlacement objectPlacement) - { - for(int i = 0; i < objectPlacement.getDensity(); i++) - { + default void place(RNG rng, int x, int forceY, int z, IrisObjectPlacement objectPlacement) { + for (int i = 0; i < objectPlacement.getDensity(); i++) { IrisObject v = objectPlacement.getScale().get(rng, objectPlacement.getObject(getComplex(), rng)); - if (v == null){ + if (v == null) { return; } - int xx = rng.i(x, x+16); - int zz = rng.i(z, z+16); + int xx = rng.i(x, x + 16); + int zz = rng.i(z, z + 16); int id = rng.i(0, Integer.MAX_VALUE); int maxf = 10000; AtomicBoolean pl = new AtomicBoolean(false); @@ -568,29 +507,27 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { int yf = b.getY(); int zf = b.getZ(); getParallaxAccess().setObject(xf, yf, zf, v.getLoadKey() + "@" + id); - ParallaxChunkMeta meta = getParallaxAccess().getMetaRW(xf>>4, zf>>4); + ParallaxChunkMeta meta = getParallaxAccess().getMetaRW(xf >> 4, zf >> 4); meta.setObjects(true); meta.setMinObject(Math.min(Math.max(meta.getMinObject(), 0), yf)); meta.setMaxObject(Math.max(Math.max(meta.getMaxObject(), 0), yf)); }, null, getData()); - if(objectPlacement.isVacuum()) - { + if (objectPlacement.isVacuum()) { double a = Math.max(v.getW(), v.getD()); IrisFeature f = new IrisFeature(); - f.setConvergeToHeight(h-(v.getH() >> 1)); + f.setConvergeToHeight(h - (v.getH() >> 1)); f.setBlockRadius(a); - f.setInterpolationRadius(a/4); + f.setInterpolationRadius(a / 4); f.setInterpolator(InterpolationMethod.BILINEAR_STARCAST_9); f.setStrength(1D); - getParallaxAccess().getMetaRW(xx>>4, zz>>4).getFeatures().add(new IrisFeaturePositional(xx, zz, f)); + getParallaxAccess().getMetaRW(xx >> 4, zz >> 4).getFeatures().add(new IrisFeaturePositional(xx, zz, f)); } } } - default void updateParallaxChunkObjectData(int minY, int maxY, int x, int z, IrisObject v) - { + default void updateParallaxChunkObjectData(int minY, int maxY, int x, int z, IrisObject v) { ParallaxChunkMeta meta = getParallaxAccess().getMetaRW(x >> 4, z >> 4); meta.setObjects(true); meta.setMaxObject(Math.max(maxY, meta.getMaxObject())); @@ -611,13 +548,9 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { for (IrisBiome i : b) { for (IrisObjectPlacement j : i.getObjects()) { - if(j.getScale().canScaleBeyond()) - { + if (j.getScale().canScaleBeyond()) { scalars.put(j.getScale(), j.getPlace()); - } - - else - { + } else { objects.addAll(j.getPlace()); } } @@ -627,40 +560,28 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { } } - for (IrisRegion i : r) - { + for (IrisRegion i : r) { for (IrisObjectPlacement j : i.getObjects()) { - if(j.getScale().canScaleBeyond()) - { + if (j.getScale().canScaleBeyond()) { scalars.put(j.getScale(), j.getPlace()); - } - - else - { + } else { objects.addAll(j.getPlace()); } } - for(IrisJigsawStructurePlacement j : i.getJigsawStructures()) - { + for (IrisJigsawStructurePlacement j : i.getJigsawStructures()) { jig = Math.max(jig, getData().getJigsawStructureLoader().load(j.getStructure()).getMaxDimension()); } } - for(IrisJigsawStructurePlacement j : getEngine().getDimension().getJigsawStructures()) - { + for (IrisJigsawStructurePlacement j : getEngine().getDimension().getJigsawStructures()) { jig = Math.max(jig, getData().getJigsawStructureLoader().load(j.getStructure()).getMaxDimension()); } - if(getEngine().getDimension().getStronghold() != null) - { - try - { + if (getEngine().getDimension().getStronghold() != null) { + try { jig = Math.max(jig, getData().getJigsawStructureLoader().load(getEngine().getDimension().getStronghold()).getMaxDimension()); - } - - catch(Throwable e) - { + } catch (Throwable e) { Iris.error("THIS IS THE ONE"); e.printStackTrace(); } @@ -669,14 +590,11 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { Iris.verbose("Checking sizes for " + Form.f(objects.size()) + " referenced objects."); BurstExecutor e = MultiBurst.burst.burst(objects.size()); KMap sizeCache = new KMap<>(); - for(String i : objects) - { + for (String i : objects) { e.queue(() -> { - try - { - BlockVector bv = sizeCache.compute(i, (k,v) -> { - if(v != null) - { + try { + BlockVector bv = sizeCache.compute(i, (k, v) -> { + if (v != null) { return v; } @@ -689,42 +607,32 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { return null; }); - if(bv == null) - { + if (bv == null) { throw new RuntimeException(); } warn(i, bv); - synchronized (xg) - { + synchronized (xg) { xg.getAndSet(Math.max(bv.getBlockX(), xg.get())); } - synchronized (zg) - { + synchronized (zg) { zg.getAndSet(Math.max(bv.getBlockZ(), zg.get())); } - } - - catch(Throwable ignored) - { + } catch (Throwable ignored) { } }); } - for(IrisObjectScale i : scalars.keySet()) - { + for (IrisObjectScale i : scalars.keySet()) { double ms = i.getMaximumScale(); - for(String j : scalars.get(i)) - { + for (String j : scalars.get(i)) { e.queue(() -> { - try - { - BlockVector bv = sizeCache.compute(j, (k,v) -> { - if(v != null) - { + try { + BlockVector bv = sizeCache.compute(j, (k, v) -> { + if (v != null) { return v; } @@ -737,26 +645,20 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { return null; }); - if(bv == null) - { + if (bv == null) { throw new RuntimeException(); } warnScaled(j, bv, ms); - synchronized (xg) - { + synchronized (xg) { xg.getAndSet((int) Math.max(Math.ceil(bv.getBlockX() * ms), xg.get())); } - synchronized (zg) - { - zg.getAndSet((int) Math.max(Math.ceil(bv.getBlockZ()* ms), zg.get())); + synchronized (zg) { + zg.getAndSet((int) Math.max(Math.ceil(bv.getBlockZ() * ms), zg.get())); } - } - - catch(Throwable ignored) - { + } catch (Throwable ignored) { } }); @@ -768,27 +670,22 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { int x = xg.get(); int z = zg.get(); - for(IrisDepositGenerator i : getEngine().getDimension().getDeposits()) - { + for (IrisDepositGenerator i : getEngine().getDimension().getDeposits()) { int max = i.getMaxDimension(); x = Math.max(max, x); z = Math.max(max, z); } - for(IrisRegion v : r) - { - for(IrisDepositGenerator i : v.getDeposits()) - { + for (IrisRegion v : r) { + for (IrisDepositGenerator i : v.getDeposits()) { int max = i.getMaxDimension(); x = Math.max(max, x); z = Math.max(max, z); } } - for(IrisBiome v : b) - { - for(IrisDepositGenerator i : v.getDeposits()) - { + for (IrisBiome v : b) { + for (IrisDepositGenerator i : v.getDeposits()) { int max = i.getMaxDimension(); x = Math.max(max, x); z = Math.max(max, z); @@ -810,37 +707,31 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { return x; } - default int computeFeatureRange() - { + default int computeFeatureRange() { int m = 0; - for(IrisFeaturePotential i : getAllFeatures()) - { + for (IrisFeaturePotential i : getAllFeatures()) { m = Math.max(m, i.getZone().getRealSize()); } return m; } - default void warn(String ob, BlockVector bv) - { - if(Math.max(bv.getBlockX(), bv.getBlockZ()) > 128) - { - Iris.warn("Object " + ob + " has a large size (" + bv.toString() + ") and may increase memory usage!"); + default void warn(String ob, BlockVector bv) { + if (Math.max(bv.getBlockX(), bv.getBlockZ()) > 128) { + Iris.warn("Object " + ob + " has a large size (" + bv + ") and may increase memory usage!"); } } - default void warnScaled(String ob, BlockVector bv, double ms) - { - if(Math.max(bv.getBlockX(), bv.getBlockZ()) > 128) - { - Iris.warn("Object " + ob + " has a large size (" + bv.toString() + ") and may increase memory usage! (Object scaled up to "+Form.pc(ms, 2)+")"); + default void warnScaled(String ob, BlockVector bv, double ms) { + if (Math.max(bv.getBlockX(), bv.getBlockZ()) > 128) { + Iris.warn("Object " + ob + " has a large size (" + bv + ") and may increase memory usage! (Object scaled up to " + Form.pc(ms, 2) + ")"); } } @Override default int getHighest(int x, int z) { - return getHighest(x,z,false); + return getHighest(x, z, false); } @Override @@ -848,27 +739,25 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { return ignoreFluid ? trueHeight(x, z) : Math.max(trueHeight(x, z), getEngine().getDimension().getFluidHeight()); } - default int trueHeight(int x, int z) - { + default int trueHeight(int x, int z) { return getComplex().getTrueHeightStream().get(x, z); } @Override default void set(int x, int y, int z, BlockData d) { - getParallaxAccess().setBlock(x,y,z,d); + getParallaxAccess().setBlock(x, y, z, d); } @Override default void setTile(int x, int y, int z, TileData d) { - getParallaxAccess().setTile(x,y,z,d); + getParallaxAccess().setTile(x, y, z, d); } @Override default BlockData get(int x, int y, int z) { - BlockData block = getParallaxAccess().getBlock(x,y,z); + BlockData block = getParallaxAccess().getBlock(x, y, z); - if(block == null) - { + if (block == null) { return AIR; } @@ -882,7 +771,7 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { @Override default boolean isSolid(int x, int y, int z) { - return B.isSolid(get(x,y,z)); + return B.isSolid(get(x, y, z)); } @Override @@ -900,8 +789,7 @@ public interface EngineParallaxManager extends DataProvider, IObjectPlacer { return getEngine().getDimension().isDebugSmartBore(); } - default void close() - { + default void close() { } } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/EnginePlayer.java b/src/main/java/com/volmit/iris/scaffold/engine/EnginePlayer.java index 65c9d50e4..850d461aa 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/EnginePlayer.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/EnginePlayer.java @@ -18,8 +18,7 @@ public class EnginePlayer { private Location lastLocation; private long lastSample; - public EnginePlayer(Engine engine, Player player) - { + public EnginePlayer(Engine engine, Player player) { this.engine = engine; this.player = player; lastLocation = player.getLocation().clone(); @@ -27,15 +26,12 @@ public class EnginePlayer { sample(); } - public void tick() - { + public void tick() { sample(); J.a(() -> { - if(region != null) - { - for(IrisEffect j : region.getEffects()) - { + if (region != null) { + for (IrisEffect j : region.getEffects()) { try { j.apply(player, getEngine()); } catch (Throwable e) { @@ -44,10 +40,8 @@ public class EnginePlayer { } } - if(biome != null) - { - for(IrisEffect j : biome.getEffects()) - { + if (biome != null) { + for (IrisEffect j : biome.getEffects()) { try { j.apply(player, getEngine()); } catch (Throwable e) { @@ -58,24 +52,18 @@ public class EnginePlayer { }); } - public long ticksSinceLastSample() - { + public long ticksSinceLastSample() { return M.ms() - lastSample; } public void sample() { - try - { - if(ticksSinceLastSample() > 55 && player.getLocation().distanceSquared(lastLocation) > 9 * 9) - { + try { + if (ticksSinceLastSample() > 55 && player.getLocation().distanceSquared(lastLocation) > 9 * 9) { lastLocation = player.getLocation().clone(); lastSample = M.ms(); sampleBiomeRegion(); } - } - - catch(Throwable ew) - { + } catch (Throwable ew) { } } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/EngineTarget.java b/src/main/java/com/volmit/iris/scaffold/engine/EngineTarget.java index 0912c8226..603635509 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/EngineTarget.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/EngineTarget.java @@ -10,8 +10,7 @@ import org.bukkit.World; import java.io.File; @Data -public class EngineTarget -{ +public class EngineTarget { private final MultiBurst burster; private final IrisDimension dimension; private World world; @@ -20,8 +19,7 @@ public class EngineTarget private final ParallaxWorld parallaxWorld; private final boolean inverted; - public EngineTarget(World world, IrisDimension dimension, IrisDataManager data, int height, boolean inverted, int threads) - { + public EngineTarget(World world, IrisDimension dimension, IrisDataManager data, int height, boolean inverted, int threads) { this.world = world; this.height = height; this.dimension = dimension; @@ -32,13 +30,11 @@ public class EngineTarget this.burster = new MultiBurst(threads); } - public void updateWorld(World world) - { + public void updateWorld(World world) { this.world = world; } - public EngineTarget(World world, IrisDimension dimension, IrisDataManager data, int height, int threads) - { + public EngineTarget(World world, IrisDimension dimension, IrisDataManager data, int height, int threads) { this(world, dimension, data, height, false, threads); } } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/EngineWorldManager.java b/src/main/java/com/volmit/iris/scaffold/engine/EngineWorldManager.java index c3347bd48..aefc66d1f 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/EngineWorldManager.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/EngineWorldManager.java @@ -5,19 +5,18 @@ import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.entity.EntitySpawnEvent; -public interface EngineWorldManager -{ - public void close(); +public interface EngineWorldManager { + void close(); - public void onEntitySpawn(EntitySpawnEvent e); + void onEntitySpawn(EntitySpawnEvent e); - public void onTick(); + void onTick(); - public void onSave(); + void onSave(); - public void spawnInitialEntities(Chunk chunk); + void spawnInitialEntities(Chunk chunk); - public void onBlockBreak(BlockBreakEvent e); + void onBlockBreak(BlockBreakEvent e); - public void onBlockPlace(BlockPlaceEvent e); + void onBlockPlace(BlockPlaceEvent e); } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/Fallible.java b/src/main/java/com/volmit/iris/scaffold/engine/Fallible.java index 157b5e123..5dc94c894 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/Fallible.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/Fallible.java @@ -1,26 +1,19 @@ package com.volmit.iris.scaffold.engine; -public interface Fallible -{ - public default void fail(String error) - { - try - { +public interface Fallible { + default void fail(String error) { + try { throw new RuntimeException(); - } - - catch(Throwable e) - { + } catch (Throwable e) { fail(error, e); } } - public default void fail(Throwable e) - { + default void fail(Throwable e) { fail("Failed to generate", e); } - public void fail(String error, Throwable e); + void fail(String error, Throwable e); - public boolean hasFailed(); + boolean hasFailed(); } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/GeneratorAccess.java b/src/main/java/com/volmit/iris/scaffold/engine/GeneratorAccess.java index c3f2cae32..8d1caa834 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/GeneratorAccess.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/GeneratorAccess.java @@ -8,35 +8,31 @@ import com.volmit.iris.object.IrisRegion; import com.volmit.iris.scaffold.data.DataProvider; import com.volmit.iris.scaffold.parallax.ParallaxAccess; -public interface GeneratorAccess extends DataProvider, Renderer -{ - public IrisRegion getRegion(int x, int z); +public interface GeneratorAccess extends DataProvider, Renderer { + IrisRegion getRegion(int x, int z); - public ParallaxAccess getParallaxAccess(); + ParallaxAccess getParallaxAccess(); - public IrisDataManager getData(); + IrisDataManager getData(); - public IrisBiome getCaveBiome(int x, int z); + IrisBiome getCaveBiome(int x, int z); - public IrisBiome getSurfaceBiome(int x, int z); + IrisBiome getSurfaceBiome(int x, int z); - public int getHeight(int x, int z); + int getHeight(int x, int z); - public default IrisBiome getBiome(int x, int y, int z) - { - if(y <= getHeight(x, z) - 2) - { + default IrisBiome getBiome(int x, int y, int z) { + if (y <= getHeight(x, z) - 2) { return getCaveBiome(x, z); } return getSurfaceBiome(x, z); } - public default PlacedObject getObjectPlacement(int x, int y, int z) - { + + default PlacedObject getObjectPlacement(int x, int y, int z) { String objectAt = getParallaxAccess().getObject(x, y, z); - if(objectAt == null || objectAt.isEmpty()) - { + if (objectAt == null || objectAt.isEmpty()) { return null; } @@ -45,20 +41,16 @@ public interface GeneratorAccess extends DataProvider, Renderer int id = Integer.parseInt(v[1]); IrisRegion region = getRegion(x, z); - for(IrisObjectPlacement i : region.getObjects()) - { - if(i.getPlace().contains(object)) - { + for (IrisObjectPlacement i : region.getObjects()) { + if (i.getPlace().contains(object)) { return new PlacedObject(i, getData().getObjectLoader().load(object), id, x, z); } } IrisBiome biome = getBiome(x, y, z); - for(IrisObjectPlacement i : biome.getObjects()) - { - if(i.getPlace().contains(object)) - { + for (IrisObjectPlacement i : biome.getObjects()) { + if (i.getPlace().contains(object)) { return new PlacedObject(i, getData().getObjectLoader().load(object), id, x, z); } } @@ -66,5 +58,5 @@ public interface GeneratorAccess extends DataProvider, Renderer return new PlacedObject(null, getData().getObjectLoader().load(object), id, x, z); } - public int getCacheID(); + int getCacheID(); } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/Hotloadable.java b/src/main/java/com/volmit/iris/scaffold/engine/Hotloadable.java index 13d53a218..a51d4a2f6 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/Hotloadable.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/Hotloadable.java @@ -1,5 +1,5 @@ package com.volmit.iris.scaffold.engine; public interface Hotloadable { - public void hotload(); + void hotload(); } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/IrisAccess.java b/src/main/java/com/volmit/iris/scaffold/engine/IrisAccess.java index 282e157d6..4f22459d4 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/IrisAccess.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/IrisAccess.java @@ -1,7 +1,8 @@ package com.volmit.iris.scaffold.engine; import com.volmit.iris.manager.IrisDataManager; -import com.volmit.iris.object.*; +import com.volmit.iris.object.IrisBiome; +import com.volmit.iris.object.IrisRegion; import com.volmit.iris.pregen.DirectWorldWriter; import com.volmit.iris.scaffold.data.DataProvider; import com.volmit.iris.scaffold.parallel.MultiBurst; @@ -18,65 +19,61 @@ import java.util.function.Consumer; public interface IrisAccess extends Hotloadable, DataProvider { - public void directWriteMCA(World w, int x, int z, DirectWorldWriter writer, MultiBurst burst); + void directWriteMCA(World w, int x, int z, DirectWorldWriter writer, MultiBurst burst); - public void directWriteChunk(World w, int x, int z, DirectWorldWriter writer); + void directWriteChunk(World w, int x, int z, DirectWorldWriter writer); - public int getGenerated(); + int getGenerated(); - public double getGeneratedPerSecond(); + double getGeneratedPerSecond(); - public void printMetrics(CommandSender sender); + void printMetrics(CommandSender sender); - public IrisBiome getBiome(int x, int y, int z); + IrisBiome getBiome(int x, int y, int z); - public IrisBiome getCaveBiome(int x, int y, int z); + IrisBiome getCaveBiome(int x, int y, int z); - public IrisBiome getBiome(int x, int z); + IrisBiome getBiome(int x, int z); - public IrisBiome getCaveBiome(int x, int z); + IrisBiome getCaveBiome(int x, int z); - public GeneratorAccess getEngineAccess(int y); + GeneratorAccess getEngineAccess(int y); - public IrisDataManager getData(); + IrisDataManager getData(); - public int getHeight(int x, int y, int z); + int getHeight(int x, int y, int z); - public int getThreadCount(); + int getThreadCount(); - public void changeThreadCount(int m); + void changeThreadCount(int m); - public void regenerate(int x, int z); + void regenerate(int x, int z); - public void close(); + void close(); - public boolean isClosed(); + boolean isClosed(); - public EngineTarget getTarget(); + EngineTarget getTarget(); - public EngineCompound getCompound(); + EngineCompound getCompound(); - public boolean isFailing(); + boolean isFailing(); - public boolean isStudio(); + boolean isStudio(); - public default Location lookForBiome(IrisBiome biome, long timeout, Consumer triesc) - { + default Location lookForBiome(IrisBiome biome, long timeout, Consumer triesc) { ChronoLatch cl = new ChronoLatch(250, false); long s = M.ms(); - int cpus = 2+(Runtime.getRuntime().availableProcessors()/2); + int cpus = 2 + (Runtime.getRuntime().availableProcessors() / 2); KList engines = new KList<>(); - for(int i = 0; i < getCompound().getSize(); i++) - { + for (int i = 0; i < getCompound().getSize(); i++) { Engine e = getCompound().getEngine(i); - if(e.getDimension().getAllBiomes(e).contains(biome)) - { + if (e.getDimension().getAllBiomes(e).contains(biome)) { engines.add(e); } } - if(engines.isEmpty()) - { + if (engines.isEmpty()) { return null; } @@ -84,67 +81,53 @@ public interface IrisAccess extends Hotloadable, DataProvider { AtomicBoolean found = new AtomicBoolean(false); AtomicReference location = new AtomicReference<>(); - for(int i = 0; i < cpus; i++) - { + for (int i = 0; i < cpus; i++) { J.a(() -> { - try - { - Engine e; - IrisBiome b; - int x,y,z; + try { + Engine e; + IrisBiome b; + int x, y, z; - while(!found.get()) - { - try { - synchronized (engines) { - e = engines.getRandom(); - x = RNG.r.i(-29999970, 29999970); - y = RNG.r.i(0, e.getHeight()-1); - z = RNG.r.i(-29999970, 29999970); + while (!found.get()) { + try { + synchronized (engines) { + e = engines.getRandom(); + x = RNG.r.i(-29999970, 29999970); + y = RNG.r.i(0, e.getHeight() - 1); + z = RNG.r.i(-29999970, 29999970); - b = e.getBiome(x, y, z); - } + b = e.getBiome(x, y, z); + } - if(b != null && b.getLoadKey() == null) - { - continue; - } + if (b != null && b.getLoadKey() == null) { + continue; + } - if(b != null && b.getLoadKey().equals(biome.getLoadKey())) - { - found.lazySet(true); - location.lazySet(new Location(e.getWorld(), x,y,z)); - } + if (b != null && b.getLoadKey().equals(biome.getLoadKey())) { + found.lazySet(true); + location.lazySet(new Location(e.getWorld(), x, y, z)); + } - tries.getAndIncrement(); - } - - catch(Throwable ex) - { - ex.printStackTrace(); - return; - } - } - } - - catch(Throwable e) - { - e.printStackTrace(); - } + tries.getAndIncrement(); + } catch (Throwable ex) { + ex.printStackTrace(); + return; + } + } + } catch (Throwable e) { + e.printStackTrace(); + } }); } - while(!found.get() || location.get() == null) - { + while (!found.get() || location.get() == null) { J.sleep(50); - if(cl.flip()) - { + if (cl.flip()) { triesc.accept(tries.get()); } - if(M.ms() - s > timeout) - { + if (M.ms() - s > timeout) { return null; } } @@ -152,23 +135,19 @@ public interface IrisAccess extends Hotloadable, DataProvider { return location.get(); } - public default Location lookForRegion(IrisRegion reg, long timeout, Consumer triesc) - { + default Location lookForRegion(IrisRegion reg, long timeout, Consumer triesc) { ChronoLatch cl = new ChronoLatch(3000, false); long s = M.ms(); - int cpus = 2+(Runtime.getRuntime().availableProcessors()/2); + int cpus = 2 + (Runtime.getRuntime().availableProcessors() / 2); KList engines = new KList<>(); - for(int i = 0; i < getCompound().getSize(); i++) - { + for (int i = 0; i < getCompound().getSize(); i++) { Engine e = getCompound().getEngine(i); - if(e.getDimension().getRegions().contains(reg.getLoadKey())) - { + if (e.getDimension().getRegions().contains(reg.getLoadKey())) { engines.add(e); } } - if(engines.isEmpty()) - { + if (engines.isEmpty()) { return null; } @@ -176,32 +155,26 @@ public interface IrisAccess extends Hotloadable, DataProvider { AtomicBoolean found = new AtomicBoolean(false); AtomicReference location = new AtomicReference<>(); - for(int i = 0; i < cpus; i++) - { + for (int i = 0; i < cpus; i++) { J.a(() -> { Engine e; IrisRegion b; - int x,z; + int x, z; - while(!found.get()) - { + while (!found.get()) { try { e = engines.getRandom(); x = RNG.r.i(-29999970, 29999970); z = RNG.r.i(-29999970, 29999970); b = e.getRegion(x, z); - if(b != null && b.getLoadKey() != null && b.getLoadKey().equals(reg.getLoadKey())) - { + if (b != null && b.getLoadKey() != null && b.getLoadKey().equals(reg.getLoadKey())) { found.lazySet(true); - location.lazySet(new Location(e.getWorld(), x, e.getHeight(x, z) + e.getMinHeight() ,z)); + location.lazySet(new Location(e.getWorld(), x, e.getHeight(x, z) + e.getMinHeight(), z)); } tries.getAndIncrement(); - } - - catch(Throwable xe) - { + } catch (Throwable xe) { xe.printStackTrace(); return; } @@ -209,17 +182,14 @@ public interface IrisAccess extends Hotloadable, DataProvider { }); } - while(!found.get() || location.get() != null) - { + while (!found.get() || location.get() != null) { J.sleep(50); - if(cl.flip()) - { + if (cl.flip()) { triesc.accept(tries.get()); } - if(M.ms() - s > timeout) - { + if (M.ms() - s > timeout) { triesc.accept(tries.get()); return null; } @@ -229,7 +199,7 @@ public interface IrisAccess extends Hotloadable, DataProvider { return location.get(); } - public void clearRegeneratedLists(int x, int z); + void clearRegeneratedLists(int x, int z); void precache(World world, int x, int z); @@ -237,12 +207,10 @@ public interface IrisAccess extends Hotloadable, DataProvider { Chunk generatePaper(World world, int cx, int cz); - default int getParallaxChunkCount() - { - int v= 0; + default int getParallaxChunkCount() { + int v = 0; - for(int i = 0; i < getCompound().getSize(); i++) - { + for (int i = 0; i < getCompound().getSize(); i++) { v += getCompound().getEngine(i).getParallax().getChunkCount(); } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/IrisAccessProvider.java b/src/main/java/com/volmit/iris/scaffold/engine/IrisAccessProvider.java index b6be7c237..b94f25f83 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/IrisAccessProvider.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/IrisAccessProvider.java @@ -1,5 +1,5 @@ package com.volmit.iris.scaffold.engine; public interface IrisAccessProvider { - public IrisAccess getAccess(); + IrisAccess getAccess(); } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/LootProvider.java b/src/main/java/com/volmit/iris/scaffold/engine/LootProvider.java index 80e65d254..a913d1f52 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/LootProvider.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/LootProvider.java @@ -9,11 +9,11 @@ import org.bukkit.block.Block; import org.bukkit.inventory.Inventory; public interface LootProvider { - public void scramble(Inventory inventory, RNG rng); + void scramble(Inventory inventory, RNG rng); - public void injectTables(KList list, IrisLootReference r); + void injectTables(KList list, IrisLootReference r); - public KList getLootTables(RNG rng, Block b); + KList getLootTables(RNG rng, Block b); - public void addItems(boolean debug, Inventory inv, RNG rng, KList tables, InventorySlotType slot, int x, int y, int z, int mgf); + void addItems(boolean debug, Inventory inv, RNG rng, KList tables, InventorySlotType slot, int x, int y, int z, int mgf); } diff --git a/src/main/java/com/volmit/iris/scaffold/engine/PregeneratedData.java b/src/main/java/com/volmit/iris/scaffold/engine/PregeneratedData.java index 466f37697..0ba6582e5 100644 --- a/src/main/java/com/volmit/iris/scaffold/engine/PregeneratedData.java +++ b/src/main/java/com/volmit/iris/scaffold/engine/PregeneratedData.java @@ -17,8 +17,7 @@ public class PregeneratedData { private final Hunk biomes; private final AtomicBoolean postMod; - public PregeneratedData(int height) - { + public PregeneratedData(int height) { postMod = new AtomicBoolean(false); blocks = Hunk.newAtomicHunk(16, height, 16); biomes = Hunk.newAtomicHunk(16, height, 16); @@ -28,23 +27,21 @@ public class PregeneratedData { public Runnable inject(TerrainChunk tc) { blocks.iterateSync((x, y, z, b) -> { - if(b != null) - { + if (b != null) { tc.setBlock(x, y, z, b); } - Biome bf = biomes.get(x,y,z); - if(bf != null) - { - tc.setBiome(x,y,z,bf); + Biome bf = biomes.get(x, y, z); + if (bf != null) { + tc.setBiome(x, y, z, bf); } }); - if(postMod.get()) - { - return () -> Hunk.view((ChunkGenerator.ChunkData) tc).insertSoftly(0,0,0, post, (b) -> b == null || B.isAirOrFluid(b)); + if (postMod.get()) { + return () -> Hunk.view((ChunkGenerator.ChunkData) tc).insertSoftly(0, 0, 0, post, (b) -> b == null || B.isAirOrFluid(b)); } - return () -> {}; + return () -> { + }; } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/Hunk.java b/src/main/java/com/volmit/iris/scaffold/hunk/Hunk.java index 436ba892c..99914e65d 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/Hunk.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/Hunk.java @@ -1,6 +1,5 @@ package com.volmit.iris.scaffold.hunk; -import com.volmit.iris.Iris; import com.volmit.iris.scaffold.hunk.io.HunkIOAdapter; import com.volmit.iris.scaffold.hunk.storage.*; import com.volmit.iris.scaffold.hunk.view.*; @@ -21,1418 +20,1167 @@ import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; import java.util.function.Predicate; -public interface Hunk -{ - /** - * Create a hunk view from a source hunk. This view reads and writes through to - * the source hunk. Its is not a copy. - * - * @param - * the type - * @param src - * the source hunk - * @return the hunk view - */ - public static Hunk view(Hunk src) - { - return new HunkView(src); - } - - public static Hunk view(BiomeGrid biome) - { - return new BiomeGridHunkView(biome); - } - - public static Hunk fringe(Hunk i, Hunk o) - { - return new FringedHunkView<>(i, o); - } - - public static Hunk view(ChunkData src) - { - return new ChunkDataHunkView(src); - } - - public static Hunk viewBlocks(Chunk src) - { - return new ChunkHunkView(src); - } - - public static Hunk viewBiomes(Chunk src) - { - return new ChunkBiomeHunkView(src); - } - - public static Hunk newHunk(int w, int h, int d) - { - return newArrayHunk(w, h, d); - } - - @SafeVarargs - public static Hunk newCombinedHunk(Hunk... hunks) - { - return newCombinedArrayHunk(hunks); - } - - default Hunk listen(Consumer4 l) - { - return new ListeningHunk<>(this, l); - } - - default Hunk synchronize() - { - return new SynchronizedHunkView<>(this); - } - - default Hunk trackWrite(AtomicBoolean b) - { - return new WriteTrackHunk(this, b); - } - - public static Hunk newArrayHunk(int w, int h, int d) - { - return new ArrayHunk<>(w, h, d); - } - - @SafeVarargs - public static Hunk newCombinedArrayHunk(Hunk... hunks) - { - return combined(Hunk::newArrayHunk, hunks); - } - - public static Hunk newSynchronizedArrayHunk(int w, int h, int d) - { - return new SynchronizedArrayHunk<>(w, h, d); - } - - @SafeVarargs - public static Hunk newCombinedSynchronizedArrayHunk(Hunk... hunks) - { - return combined(Hunk::newSynchronizedArrayHunk, hunks); - } - - public static Hunk newMappedHunk(int w, int h, int d) - { - return new MappedHunk<>(w, h, d); - } - - public static Hunk newMappedHunkSynced(int w, int h, int d) - { - return new MappedHunk(w, h, d).synchronize(); - } - - @SafeVarargs - public static Hunk newCombinedMappedHunk(Hunk... hunks) - { - return combined(Hunk::newMappedHunk, hunks); - } - - public static Hunk newAtomicHunk(int w, int h, int d) - { - return new AtomicHunk<>(w, h, d); - } - - @SafeVarargs - public static Hunk newCombinedAtomicHunk(Hunk... hunks) - { - return combined(Hunk::newAtomicHunk, hunks); - } - - public static Hunk newAtomicDoubleHunk(int w, int h, int d) - { - return new AtomicDoubleHunk(w, h, d); - } - - @SafeVarargs - public static Hunk newCombinedAtomicDoubleHunk(Hunk... hunks) - { - return combined(Hunk::newAtomicDoubleHunk, hunks); - } - - public static Hunk newAtomicLongHunk(int w, int h, int d) - { - return new AtomicLongHunk(w, h, d); - } - - @SafeVarargs - public static Hunk newCombinedAtomicLongHunk(Hunk... hunks) - { - return combined(Hunk::newAtomicLongHunk, hunks); - } - - public static Hunk newAtomicIntegerHunk(int w, int h, int d) - { - return new AtomicIntegerHunk(w, h, d); - } - - @SafeVarargs - public static Hunk newCombinedAtomicIntegerHunk(Hunk... hunks) - { - return combined(Hunk::newAtomicIntegerHunk, hunks); - } - - /** - * Creates a new bounding hunk from the given hunks - * - * @param - * the type - * @param factory - * the factory that creates a hunk - * @param hunks - * the hunks - * @return the new bounding hunk - */ - @SafeVarargs - public static Hunk combined(Function3> factory, Hunk... hunks) - { - int w = 0; - int h = 0; - int d = 0; - - for(Hunk i : hunks) - { - w = Math.max(w, i.getWidth()); - h = Math.max(h, i.getHeight()); - d = Math.max(d, i.getDepth()); - } - - Hunk b = factory.apply(w, h, d); - - for(Hunk i : hunks) - { - b.insert(i); - } - - return b; - } - - default Hunk readOnly() - { - return new ReadOnlyHunk<>(this); - } - - default int getNonNullEntries() - { - AtomicInteger count = new AtomicInteger(); - iterate((x, y, z, v) -> count.getAndAdd(1)); - - return count.get(); - } - - default void write(OutputStream s, HunkIOAdapter h) throws IOException - { - h.write(this, s); - } - - default ByteArrayTag writeByteArrayTag(HunkIOAdapter h, String name) throws IOException - { - return h.writeByteArrayTag(this, name); - } - - default void write(File s, HunkIOAdapter h) throws IOException - { - h.write(this, s); - } - - default boolean isAtomic() - { - return false; - } - - default Hunk invertY() - { - return new InvertedHunkView(this); - } - - default Hunk rotateX(double degrees) - { - return new RotatedXHunkView(this, degrees); - } - - default Hunk rotateY(double degrees) - { - return new RotatedYHunkView(this, degrees); - } - - default Hunk rotateZ(double degrees) - { - return new RotatedZHunkView(this, degrees); - } - - default int getMaximumDimension() - { - return Math.max(getWidth(), Math.max(getHeight(), getDepth())); - } - - default int getIdeal2DParallelism() - { - return getMax2DParallelism() / 4; - } - - default int getIdeal3DParallelism() - { - return getMax3DParallelism() / 8; - } - - default int getMinimumDimension() - { - return Math.min(getWidth(), Math.min(getHeight(), getDepth())); - } - - default int getMax2DParallelism() - { - return (int) Math.pow(getMinimumDimension() / 2, 2); - } - - default int getMax3DParallelism() - { - return (int) Math.pow(getMinimumDimension() / 2, 3); - } - - default int filterDimension(int dim) - { - if(dim <= 1) - { - return 1; - } - - dim = dim % 2 != 0 ? dim + 1 : dim; - - if(dim > getMinimumDimension() / 2) - { - if(dim <= 2) - { - return 1; - } - - dim -= 2; - } - - return dim; - } - - default int get2DDimension(int sections) - { - if(sections <= 1) - { - return 1; - } - - return filterDimension((int) Math.ceil(Math.sqrt(sections))); - } - - default int get3DDimension(int sections) - { - if(sections <= 1) - { - return 1; - } - - return filterDimension((int) Math.ceil(Math.cbrt(sections))); - } - - /** - * Iterate surfaces on 2d. Raytraces with a front and a back which stretches - * through surfaces. Essentially what is returned is the following (in - * order)
- *
- * - * The predicate is used to determine if the given block type is solid or not. - * - *
- *
- * ================================================
- * AX, AZ: Hunk Relative X and Z - * - *
- *
- * HX, HZ: Hunk Positional X and Z (in its parent hunk) - * - *
- *
- * TOP: The top of this surface (top+1 is air above a surface) - * - *
- *
- * BOTTOM: The bottom of this surface (bottom is the lowest SOLID surface before - * either air or bedrock going down further) - * - *
- *
- * LAST_BOTTOM: The previous bottom. If your surface is the top surface, this - * will be -1 as there is no bottom-of-surface above you. However if you are not - * the top surface, this value is equal to the next solid layer above TOP, such - * that ((LAST_BOTTOM - 1) - (TOP + 1)) is how many air blocks are between your - * surface and the surface above you - * - *
- *
- * HUNK: The hunk to set data to.
- * ================================================
- *
- * If we assume your chunk coordinates are x and z, then
- *
- * bX = (x * 16)
- * bZ = (z * 16)
- *
- * (ax, az, hx, hz, top, bottom, lastBottom, hunk) {
- * actualBlockX = ax+hx;
- * actualBlockZ = az+hz;
- *
- * hunkX = ax;
- * hunkZ = az;
- *
- * hunk.set(hunkX, ?, hunkZ, noise(actualBlockX, ?, actualBlockZ));
- * }
- * - * @param p - * the predicate - * @param c - * the consumer - * @return this - */ - default Hunk iterateSurfaces2D(Predicate p, Consumer8> c) - { - return iterateSurfaces2D(getIdeal2DParallelism(), p, c); - } - - /** - * Iterate surfaces on 2d. Raytraces with a front and a back which stretches - * through surfaces. Essentially what is returned is the following (in - * order)
- *
- * - * The predicate is used to determine if the given block type is solid or not. - * - *
- *
- * ================================================
- * AX, AZ: Hunk Relative X and Z - * - *
- *
- * HX, HZ: Hunk Positional X and Z (in its parent hunk) - * - *
- *
- * TOP: The top of this surface (top+1 is air above a surface) - * - *
- *
- * BOTTOM: The bottom of this surface (bottom is the lowest SOLID surface before - * either air or bedrock going down further) - * - *
- *
- * LAST_BOTTOM: The previous bottom. If your surface is the top surface, this - * will be -1 as there is no bottom-of-surface above you. However if you are not - * the top surface, this value is equal to the next solid layer above TOP, such - * that ((LAST_BOTTOM - 1) - (TOP + 1)) is how many air blocks are between your - * surface and the surface above you - * - *
- *
- * HUNK: The hunk to set data to.
- * ================================================
- *
- * If we assume your chunk coordinates are x and z, then
- *
- * bX = (x * 16)
- * bZ = (z * 16)
- *
- * (ax, az, hx, hz, top, bottom, lastBottom, hunk) {
- * actualBlockX = ax+hx;
- * actualBlockZ = az+hz;
- *
- * hunkX = ax;
- * hunkZ = az;
- *
- * hunk.set(hunkX, ?, hunkZ, noise(actualBlockX, ?, actualBlockZ));
- * }
- * - * @param parallelism - * the ideal threads to use on this - * @param p - * the predicate - * @param c - * the consumer - * @return this - */ - default Hunk iterateSurfaces2D(int parallelism, Predicate p, Consumer8> c) - { - iterate2DTop(parallelism, (ax, az, hox, hoz, h) -> - { - int last = -1; - int in = getHeight() - 1; - boolean hitting = false; - for(int i = getHeight() - 1; i >= 0; i--) - { - boolean solid = p.test(h.get(ax, i, az)); - - if(!hitting && solid) - { - in = i; - hitting = true; - } - - else if(hitting && !solid) - { - hitting = false; - c.accept(ax, az, hox, hoz, in, i - 1, last, h); - last = i - 1; - } - } - - if(hitting) - { - c.accept(ax, az, hox, hoz, in, 0, last, h); - } - }); - - return this; - } - - /** - * Iterate on the xz top of this hunk. When using this consumer, given - * - * consumer: (ax, az, hx, hz, hunk) - * - * hunk.set(ax, ?, az, NOISE.get(ax+hx, az+hz)); - * - * @param c - * the consumer hunkX, hunkZ, hunkOffsetX, hunkOffsetZ. - * @return this - */ - default Hunk iterate2DTop(Consumer5> c) - { - return iterate2DTop(getIdeal2DParallelism(), c); - } - - default Hunk drift(int x, int y, int z) - { - return new DriftHunkView<>(this, x, y, z); - } - - /** - * Iterate on the xz top of this hunk. When using this consumer, given - * - * consumer: (ax, az, hx, hz, hunk) - * - * hunk.set(ax, ?, az, NOISE.get(ax+hx, az+hz)); - * - * @param parallelism - * the target parallelism value or 0 to disable - * @param c - * the consumer hunkX, hunkZ, hunkOffsetX, hunkOffsetZ. - * @return this - */ - default Hunk iterate2DTop(int parallelism, Consumer5> c) - { - compute2D(parallelism, (x, y, z, h) -> - { - for(int i = 0; i < h.getWidth(); i++) - { - for(int k = 0; k < h.getDepth(); k++) - { - c.accept(i, k, x, z, h); - } - } - }); - - return this; - } - - default Hunk iterate(Predicate p, Consumer3 c) - { - return iterate(getIdeal3DParallelism(), p, c); - } - - default Hunk iterate(int parallelism, Predicate p, Consumer3 c) - { - iterate(parallelism, (x, y, z, t) -> - { - if(p.test(t)) - { - c.accept(x, y, z); - } - }); - - return this; - } - - default Hunk iterate(Predicate p, Consumer4 c) - { - return iterate(getIdeal3DParallelism(), p, c); - } - - default Hunk iterate(int parallelism, Predicate p, Consumer4 c) - { - iterate(parallelism, (x, y, z, t) -> - { - if(p.test(t)) - { - c.accept(x, y, z, t); - } - }); - - return this; - } - - default Hunk iterate(Consumer3 c) - { - return iterate(getIdeal3DParallelism(), c); - } - - default Hunk iterateSync(Consumer3 c) - { - for(int i = 0; i < getWidth(); i++) - { - for(int j = 0; j < getHeight(); j++) - { - for(int k = 0; k < getDepth(); k++) - { - c.accept(i, j, k); - } - } - } - - return this; - } - - default Hunk iterateSync(Consumer4 c) - { - for(int i = 0; i < getWidth(); i++) - { - for(int j = 0; j < getHeight(); j++) - { - for(int k = 0; k < getDepth(); k++) - { - c.accept(i, j, k, get(i,j,k)); - } - } - } - - return this; - } - - default Hunk iterate(int parallelism, Consumer3 c) - { - compute3D(parallelism, (x, y, z, h) -> - { - for(int i = 0; i < h.getWidth(); i++) - { - for(int j = 0; j < h.getHeight(); j++) - { - for(int k = 0; k < h.getDepth(); k++) - { - c.accept(i + x, j + y, k + z); - } - } - } - }); - - return this; - } - - default Hunk iterate(Consumer4 c) - { - return iterate(getIdeal3DParallelism(), c); - } - - default Hunk iterate(int parallelism, Consumer4 c) - { - compute3D(parallelism, (x, y, z, h) -> - { - for(int i = 0; i < h.getWidth(); i++) - { - for(int j = 0; j < h.getHeight(); j++) - { - for(int k = 0; k < h.getDepth(); k++) - { - c.accept(i + x, j + y, k + z, h.get(i, j, k)); - } - } - } - }); - - return this; - } - - default Hunk compute2D(Consumer4> v) - { - return compute2D(getIdeal2DParallelism(), v); - } - - public static void computeDual2D(int parallelism, Hunk a, Hunk b, Consumer5, Hunk> v) - { - if(a.getWidth() != b.getWidth() || a.getHeight() != b.getHeight() || a.getDepth() != b.getDepth()) - { - throw new RuntimeException("Hunk sizes must match!"); - } - - if(a.get2DDimension(parallelism) == 1) - { - v.accept(0, 0, 0, a, b); - return; - } - - BurstExecutor e = MultiBurst.burst.burst(parallelism); - KList rq = new KList(parallelism); - getDualSections2D(parallelism, a, b, (xx, yy, zz, ha, hr, r) -> e.queue(() -> - { - v.accept(xx, yy, zz, ha, hr); - - synchronized(rq) - { - rq.add(r); - } - }), (x, y, z, hax, hbx) -> - { - a.insert(x, y, z, hax); - b.insert(x, y, z, hbx); - }); - e.complete(); - rq.forEach(Runnable::run); - return; - } - - public static void getDualSections2D(int sections, Hunk a, Hunk b, Consumer6, Hunk, Runnable> v, Consumer5, Hunk> inserterAB) - { - if(a.getWidth() != b.getWidth() || a.getHeight() != b.getHeight() || a.getDepth() != b.getDepth()) - { - throw new RuntimeException("Hunk sizes must match!"); - } - - int dim = a.get2DDimension(sections); - - if(sections <= 1) - { - getDualSection(0, 0, 0, a.getWidth(), a.getHeight(), a.getDepth(), a, b, (ha, hr, r) -> v.accept(0, 0, 0, ha, hr, r), inserterAB); - return; - } - - int w = a.getWidth() / dim; - int wr = a.getWidth() - (w * dim); - int d = a.getDepth() / dim; - int dr = a.getDepth() - (d * dim); - int i, j; - - for(i = 0; i < a.getWidth(); i += w) - { - int ii = i; - - for(j = 0; j < a.getDepth(); j += d) - { - int jj = j; - getDualSection(i, 0, j, i + w + (i == 0 ? wr : 0), a.getHeight(), j + d + (j == 0 ? dr : 0), a, b, (ha, hr, r) -> v.accept(ii, 0, jj, ha, hr, r), inserterAB); - i = i == 0 ? i + wr : i; - j = j == 0 ? j + dr : j; - } - } - } - - static void getDualSection(int x, int y, int z, int x1, int y1, int z1, Hunk a, Hunk b, Consumer3, Hunk, Runnable> v, Consumer5, Hunk> inserter) - { - Hunk copya = a.crop(x, y, z, x1, y1, z1); - Hunk copyb = b.crop(x, y, z, x1, y1, z1); - v.accept(copya, copyb, () -> inserter.accept(x, y, z, copya, copyb)); - } - - default Hunk compute2D(int parallelism, Consumer4> v) - { - if(get2DDimension(parallelism) == 1) - { - v.accept(0, 0, 0, this); - return this; - } - - BurstExecutor e = MultiBurst.burst.burst(parallelism); - - if(isAtomic()) - { - getSectionsAtomic2D(parallelism, (xx, yy, zz, h) -> e.queue(() -> - { - v.accept(xx, yy, zz, h); - })); - - e.complete(); - } - - else - { - KList rq = new KList(parallelism); - - getSections2D(parallelism, (xx, yy, zz, h, r) -> e.queue(() -> - { - v.accept(xx, yy, zz, h); - - synchronized(rq) - { - rq.add(r); - } - }), this::insert); - - e.complete(); - rq.forEach(Runnable::run); - } - - return this; - } - - default Hunk compute2DYRange(int parallelism, int ymin, int ymax, Consumer4> v) - { - if(get2DDimension(parallelism) == 1) - { - v.accept(0, 0, 0, this); - return this; - } - - BurstExecutor e = MultiBurst.burst.burst(parallelism); - KList rq = new KList(parallelism); - getSections2DYLimit(parallelism, ymin, ymax, (xx, yy, zz, h, r) -> e.queue(() -> - { - v.accept(xx, yy, zz, h); - - synchronized(rq) - { - rq.add(r); - } - }), this::insert); - e.complete(); - rq.forEach(Runnable::run); - return this; - } - - default Hunk compute3D(Consumer4> v) - { - return compute3D(getIdeal3DParallelism(), v); - } - - default Hunk compute3D(int parallelism, Consumer4> v) - { - if(get3DDimension(parallelism) == 1) - { - v.accept(0, 0, 0, this); - return this; - } - - BurstExecutor e = MultiBurst.burst.burst(parallelism); - KList rq = new KList(parallelism); - getSections3D(parallelism, (xx, yy, zz, h, r) -> e.queue(() -> - { - v.accept(xx, yy, zz, h); - synchronized(rq) - { - rq.add(r); - } - }), this::insert); - e.complete(); - rq.forEach(Runnable::run); - return this; - } - - default Hunk getSections2D(int sections, Consumer5, Runnable> v) - { - return getSections2D(sections, v, this::insert); - } - - default Hunk getSectionsAtomic2D(int sections, Consumer4> v) - { - int dim = (int) get2DDimension(sections); - - if(sections <= 1) - { - getAtomicSection(0, 0, 0, getWidth(), getHeight(), getDepth(), (hh) -> v.accept(0, 0, 0, hh)); - return this; - } - - int w = getWidth() / dim; - int wr = getWidth() - (w * dim); - int d = getDepth() / dim; - int dr = getDepth() - (d * dim); - int i, j; - - for(i = 0; i < getWidth(); i += w) - { - int ii = i; - - for(j = 0; j < getDepth(); j += d) - { - int jj = j; - getAtomicSection(i, 0, j, i + w + (i == 0 ? wr : 0), getHeight(), j + d + (j == 0 ? dr : 0), (h) -> v.accept(ii, 0, jj, h)); - i = i == 0 ? i + wr : i; - j = j == 0 ? j + dr : j; - } - } - ; - - return this; - } - - default Hunk getSections2D(int sections, Consumer5, Runnable> v, Consumer4> inserter) - { - int dim = (int) get2DDimension(sections); - - if(sections <= 1) - { - getSection(0, 0, 0, getWidth(), getHeight(), getDepth(), (hh, r) -> v.accept(0, 0, 0, hh, r), inserter); - return this; - } - - int w = getWidth() / dim; - int wr = getWidth() - (w * dim); - int d = getDepth() / dim; - int dr = getDepth() - (d * dim); - int i, j; - - for(i = 0; i < getWidth(); i += w) - { - int ii = i; - - for(j = 0; j < getDepth(); j += d) - { - int jj = j; - getSection(i, 0, j, i + w + (i == 0 ? wr : 0), getHeight(), j + d + (j == 0 ? dr : 0), (h, r) -> v.accept(ii, 0, jj, h, r), inserter); - i = i == 0 ? i + wr : i; - j = j == 0 ? j + dr : j; - } - } - ; - - return this; - } - - default Hunk getSections2DYLimit(int sections, int ymin, int ymax, Consumer5, Runnable> v, Consumer4> inserter) - { - int dim = (int) get2DDimension(sections); - - if(sections <= 1) - { - getSection(0, 0, 0, getWidth(), getHeight(), getDepth(), (hh, r) -> v.accept(0, 0, 0, hh, r), inserter); - return this; - } - - int w = getWidth() / dim; - int wr = getWidth() - (w * dim); - int d = getDepth() / dim; - int dr = getDepth() - (d * dim); - int i, j; - - for(i = 0; i < getWidth(); i += w) - { - int ii = i; - - for(j = 0; j < getDepth(); j += d) - { - int jj = j; - getSection(i, ymin, j, i + w + (i == 0 ? wr : 0), ymax, j + d + (j == 0 ? dr : 0), (h, r) -> v.accept(ii, ymin, jj, h, r), inserter); - i = i == 0 ? i + wr : i; - j = j == 0 ? j + dr : j; - } - } - - return this; - } - - default Hunk getSections3D(int sections, Consumer5, Runnable> v) - { - return getSections3D(sections, v, (xx, yy, zz, c) -> insert(xx, yy, zz, c)); - } - - default Hunk getSections3D(int sections, Consumer5, Runnable> v, Consumer4> inserter) - { - int dim = (int) get3DDimension(sections); - - if(sections <= 1) - { - getSection(0, 0, 0, getWidth(), getHeight(), getDepth(), (hh, r) -> v.accept(0, 0, 0, hh, r), inserter); - return this; - } - - int w = getWidth() / dim; - int h = getHeight() / dim; - int d = getDepth() / dim; - int wr = getWidth() - (w * dim); - int hr = getHeight() - (h * dim); - int dr = getDepth() - (d * dim); - int i, j, k; - - for(i = 0; i < getWidth(); i += w) - { - int ii = i; - - for(j = 0; j < getHeight(); j += d) - { - int jj = j; - - for(k = 0; k < getDepth(); k += d) - { - int kk = k; - getSection(ii, jj, kk, i + w + (i == 0 ? wr : 0), j + h + (j == 0 ? hr : 0), k + d + (k == 0 ? dr : 0), (hh, r) -> v.accept(ii, jj, kk, hh, r), inserter); - i = i == 0 ? i + wr : i; - j = j == 0 ? j + hr : j; - k = k == 0 ? k + dr : k; - } - } - } - - return this; - } - - default Hunk getSection(int x, int y, int z, int x1, int y1, int z1, Consumer2, Runnable> v) - { - return getSection(x, y, z, x1, y1, z1, v, (xx, yy, zz, c) -> insert(xx, yy, zz, c)); - } - - default Hunk getSection(int x, int y, int z, int x1, int y1, int z1, Consumer2, Runnable> v, Consumer4> inserter) - { - Hunk copy = crop(x, y, z, x1, y1, z1); - v.accept(copy, () -> inserter.accept(x, y, z, copy)); - return this; - } - - default Hunk getAtomicSection(int x, int y, int z, int x1, int y1, int z1, Consumer> v) - { - Hunk copy = croppedView(x, y, z, x1, y1, z1); - v.accept(copy); - return this; - } - - default void enforceBounds(int x, int y, int z) - { - if(x < 0 || x >= getWidth() || y < 0 || y >= getHeight() || z < 0 || z >= getDepth()) - { - //Iris.warn(x + "," + y + "," + z + " does not fit within size " + getWidth() + "," + getHeight() + "," + getDepth() + " (0,0,0 to " + (getWidth() - 1) + "," + (getHeight() - 1) + "," + (getDepth() - 1) + ")"); - } - } - - default void enforceBounds(int x, int y, int z, int w, int h, int d) - { - if(x < 0 || x >= getWidth() || y < 0 || y >= getHeight() || z < 0 || z >= getDepth() || x + w < 0 || x + w > getWidth() || y + h < 0 || y + h > getHeight() || z + d < 0 || z + d > getDepth()) - { - //Iris.warn("The hunk " + w + "," + h + "," + d + " with an offset of " + x + "," + y + "," + z + " does not fit within the parent hunk " + getWidth() + "," + getHeight() + "," + getDepth() + " (0,0,0 to " + (getWidth() - 1) + "," + (getHeight() - 1) + "," + (getDepth() - 1) + ")"); - } - } - - /** - * Create a new hunk from a section of this hunk. - * - * - * @param x1 - * The min x (inclusive) - * @param y1 - * The min y (inclusive) - * @param z1 - * The min z (inclusive) - * @param x2 - * The max x (exclusive) - * @param y2 - * The max y (exclusive) - * @param z2 - * The max z (exclusive) - * @return the new hunk (x2-x1, y2-y1, z2-z1) - */ - default ArrayHunk crop(int x1, int y1, int z1, int x2, int y2, int z2) - { - ArrayHunk h = new ArrayHunk(x2 - x1, y2 - y1, z2 - z1); - enforceBounds(x1, y1, z1, x2 - x1, y2 - y1, z2 - z1); - - for(int i = x1; i < x2; i++) - { - for(int j = y1; j < y2; j++) - { - for(int k = z1; k < z2; k++) - { - h.setRaw(i - x1, j - y1, k - z1, getRaw(i, j, k)); - } - } - } - - return h; - } - - /** - * Create a new view of this same hunk from a section of this hunk. - * Modifications are routed to this hunk! - * - * @param x1 - * The min x (inclusive) - * @param y1 - * The min y (inclusive) - * @param z1 - * The min z (inclusive) - * @param x2 - * The max x (exclusive) - * @param y2 - * The max y (exclusive) - * @param z2 - * The max z (exclusive) - * @return the cropped view of this hunk (x2-x1, y2-y1, z2-z1) - */ - default Hunk croppedView(int x1, int y1, int z1, int x2, int y2, int z2) - { - enforceBounds(x1, y1, z1, x2 - x1, y2 - y1, z2 - z1); - return new HunkView(this, x2 - x1, y2 - y1, z2 - z1, x1, y1, z1); - } - - /** - * @return The X length - */ - public int getWidth(); - - /** - * @return The Z length - */ - public int getDepth(); - - /** - * @return The Y length - */ - public int getHeight(); - - /** - * Set a region - * - * @param x1 - * inclusive 1st x - * @param y1 - * inclusive 1st y - * @param z1 - * inclusive 1st z - * @param x2 - * inclusive 2nd x - * @param y2 - * inclusive 2nd y - * @param z2 - * inclusive 2nd z - * @param t - * the value to set - */ - default void set(int x1, int y1, int z1, int x2, int y2, int z2, T t) - { - enforceBounds(x1, y1, z1, x2 - x1, y2 - y1, z2 - z1); - for(int i = x1; i <= x2; i++) - { - for(int j = y1; j <= y2; j++) - { - for(int k = z1; k <= z2; k++) - { - setRaw(i, j, k, t); - } - } - } - } - - /** - * Get the value to the closest valid position - * - * @param x - * the x - * @param y - * the y - * @param z - * the z - * @return the value closest to the border of the hunk - */ - default T getClosest(int x, int y, int z) - { - return getRaw(x >= getWidth() ? getWidth() - 1 : x < 0 ? 0 : x, y >= getHeight() ? getHeight() - 1 : y < 0 ? 0 : y, z >= getDepth() ? getDepth() - 1 : z < 0 ? 0 : z); - } - - default void fill(T t) - { - set(0, 0, 0, getWidth() - 1, getHeight() - 1, getDepth() - 1, t); - } - - /** - * Get a 1 node thick hunk representing the face of this hunk - * - * @param f - * the face - * @return the hunk view of this hunk - */ - default Hunk viewFace(HunkFace f) - { - switch(f) - { - case BOTTOM: - return croppedView(0, 0, 0, getWidth() - 1, 0, getDepth() - 1); - case EAST: - return croppedView(getWidth() - 1, 0, 0, getWidth() - 1, getHeight() - 1, getDepth() - 1); - case NORTH: - return croppedView(0, 0, 0, getWidth() - 1, getHeight() - 1, 0); - case SOUTH: - return croppedView(0, 0, 0, 0, getHeight() - 1, getDepth() - 1); - case TOP: - return croppedView(0, getHeight() - 1, 0, getWidth() - 1, getHeight() - 1, getDepth() - 1); - case WEST: - return croppedView(0, 0, getDepth() - 1, getWidth() - 1, getHeight() - 1, getDepth() - 1); - default: - break; - } - - return null; - } - - /** - * Crop (copy) a 1 node thick hunk representing the face of this hunk - * - * @param f - * the face - * @return the hunk copy (face) of this hunk - */ - default Hunk cropFace(HunkFace f) - { - switch(f) - { - case BOTTOM: - return crop(0, 0, 0, getWidth() - 1, 0, getDepth() - 1); - case EAST: - return crop(getWidth() - 1, 0, 0, getWidth() - 1, getHeight() - 1, getDepth() - 1); - case NORTH: - return crop(0, 0, 0, getWidth() - 1, getHeight() - 1, 0); - case SOUTH: - return crop(0, 0, 0, 0, getHeight() - 1, getDepth() - 1); - case TOP: - return crop(0, getHeight() - 1, 0, getWidth() - 1, getHeight() - 1, getDepth() - 1); - case WEST: - return crop(0, 0, getDepth() - 1, getWidth() - 1, getHeight() - 1, getDepth() - 1); - default: - break; - } - - return null; - } - - /** - * Set a value at the given position - * - * @param x - * the x - * @param y - * the y - * @param z - * the z - * @param t - * the value - */ - default void set(int x, int y, int z, T t) - { - enforceBounds(x, y, z); - setRaw(x, y, z, t); - } - - default void setIfExists(int x, int y, int z, T t) - { - if(x < 0 || x >= getWidth() || y < 0 || y >= getHeight() || z < 0 || z >= getDepth()) - { - return; - } - - setRaw(x, y, z, t); - } - - default T getIfExists(int x, int y, int z, T t) - { - if(x < 0 || x >= getWidth() || y < 0 || y >= getHeight() || z < 0 || z >= getDepth()) - { - return t; - } - - return getOr(x, y, z, t); - } - - default T getIfExists(int x, int y, int z) - { - return getIfExists(x, y, z, null); - } - - /** - * Set a value at the given position without checking coordinate bounds - * - * @param x - * the x - * @param y - * the y - * @param z - * the z - * @param t - * the value - */ - public void setRaw(int x, int y, int z, T t); - - /** - * Get a value at the given position without checking coordinate bounds - * - * @param x - * the x - * @param y - * the y - * @param z - * the z - * @return the value or null - */ - public T getRaw(int x, int y, int z); - - /** - * Get a value at the given position - * - * @param x - * the x - * @param y - * the y - * @param z - * the z - * @return the value or null - */ - default T get(int x, int y, int z) - { - enforceBounds(x, y, z); - return getRaw(x, y, z); - } - - default T getOr(int x, int y, int z, T t) - { - enforceBounds(x, y, z); - T v = getRaw(x, y, z); - - if(v == null) - { - return t; - } - - return v; - } - - /** - * Insert a hunk into this one with an offset the inserted hunk - * - * @param offX - * the offset from zero for x - * @param offY - * the offset from zero for y - * @param offZ - * the offset from zero for z - * @param hunk - * the hunk to insert - */ - default void insert(int offX, int offY, int offZ, Hunk hunk) - { - insert(offX, offY, offZ, hunk, false); - } - - default void insertSoftly(int offX, int offY, int offZ, Hunk hunk, Predicate shouldOverwrite) - { - insertSoftly(offX, offY, offZ, hunk, false, shouldOverwrite); - } - - /** - * Insert a hunk into this one - * - * @param hunk - * the hunk to insert - */ - default void insert(Hunk hunk) - { - insert(0, 0, 0, hunk, false); - } - - /** - * Returns the source of this hunk view. This could return another hunk view, - * not an actual source, however it does return it's underlying data source. If - * this hunk is a data source and not a view, it will return null. - * - * @return the source or null if this is already the source - */ - default Hunk getSource() - { - return null; - } - - /** - * Insert a hunk into this one - * - * @param hunk - * the hunk to insert - * @param inverted - * invert the inserted hunk or not - */ - default void insert(Hunk hunk, boolean inverted) - { - insert(0, 0, 0, hunk, inverted); - } - - /** - * Insert a hunk into this one with an offset and possibly inverting the y of - * the inserted hunk - * - * @param offX - * the offset from zero for x - * @param offY - * the offset from zero for y - * @param offZ - * the offset from zero for z - * @param hunk - * the hunk to insert - * @param invertY - * should the inserted hunk be inverted - */ - default void insert(int offX, int offY, int offZ, Hunk hunk, boolean invertY) - { - enforceBounds(offX, offY, offZ, hunk.getWidth(), hunk.getHeight(), hunk.getDepth()); - - for(int i = offX; i < offX + hunk.getWidth(); i++) - { - for(int j = offY; j < offY + hunk.getHeight(); j++) - { - for(int k = offZ; k < offZ + hunk.getDepth(); k++) - { - setRaw(i, j, k, hunk.getRaw(i - offX, j - offY, k - offZ)); - } - } - } - } - - /** - * Insert a hunk into this one with an offset and possibly inverting the y of. Will never insert a node if its already used - * the inserted hunk - * - * @param offX - * the offset from zero for x - * @param offY - * the offset from zero for y - * @param offZ - * the offset from zero for z - * @param hunk - * the hunk to insert - * @param invertY - * should the inserted hunk be inverted - */ - default void insertSoftly(int offX, int offY, int offZ, Hunk hunk, boolean invertY, Predicate shouldOverwrite) - { - enforceBounds(offX, offY, offZ, hunk.getWidth(), hunk.getHeight(), hunk.getDepth()); - - for(int i = offX; i < offX + hunk.getWidth(); i++) - { - for(int j = offY; j < offY + hunk.getHeight(); j++) - { - for(int k = offZ; k < offZ + hunk.getDepth(); k++) - { - if(shouldOverwrite.test(getRaw(i, j, k))) - { - setRaw(i, j, k, hunk.getRaw(i - offX, j - offY, k - offZ)); - } - } - } - } - } - - /** - * Acts like fill, however if used by a mapped hunk, will simply clear it - * @param b the data to use for fill - */ - default void empty(T b) - { - fill(b); - } +public interface Hunk { + /** + * Create a hunk view from a source hunk. This view reads and writes through to + * the source hunk. Its is not a copy. + * + * @param the type + * @param src the source hunk + * @return the hunk view + */ + static Hunk view(Hunk src) { + return new HunkView(src); + } + + static Hunk view(BiomeGrid biome) { + return new BiomeGridHunkView(biome); + } + + static Hunk fringe(Hunk i, Hunk o) { + return new FringedHunkView<>(i, o); + } + + static Hunk view(ChunkData src) { + return new ChunkDataHunkView(src); + } + + static Hunk viewBlocks(Chunk src) { + return new ChunkHunkView(src); + } + + static Hunk viewBiomes(Chunk src) { + return new ChunkBiomeHunkView(src); + } + + static Hunk newHunk(int w, int h, int d) { + return newArrayHunk(w, h, d); + } + + @SafeVarargs + static Hunk newCombinedHunk(Hunk... hunks) { + return newCombinedArrayHunk(hunks); + } + + default Hunk listen(Consumer4 l) { + return new ListeningHunk<>(this, l); + } + + default Hunk synchronize() { + return new SynchronizedHunkView<>(this); + } + + default Hunk trackWrite(AtomicBoolean b) { + return new WriteTrackHunk(this, b); + } + + static Hunk newArrayHunk(int w, int h, int d) { + return new ArrayHunk<>(w, h, d); + } + + @SafeVarargs + static Hunk newCombinedArrayHunk(Hunk... hunks) { + return combined(Hunk::newArrayHunk, hunks); + } + + static Hunk newSynchronizedArrayHunk(int w, int h, int d) { + return new SynchronizedArrayHunk<>(w, h, d); + } + + @SafeVarargs + static Hunk newCombinedSynchronizedArrayHunk(Hunk... hunks) { + return combined(Hunk::newSynchronizedArrayHunk, hunks); + } + + static Hunk newMappedHunk(int w, int h, int d) { + return new MappedHunk<>(w, h, d); + } + + static Hunk newMappedHunkSynced(int w, int h, int d) { + return new MappedHunk(w, h, d).synchronize(); + } + + @SafeVarargs + static Hunk newCombinedMappedHunk(Hunk... hunks) { + return combined(Hunk::newMappedHunk, hunks); + } + + static Hunk newAtomicHunk(int w, int h, int d) { + return new AtomicHunk<>(w, h, d); + } + + @SafeVarargs + static Hunk newCombinedAtomicHunk(Hunk... hunks) { + return combined(Hunk::newAtomicHunk, hunks); + } + + static Hunk newAtomicDoubleHunk(int w, int h, int d) { + return new AtomicDoubleHunk(w, h, d); + } + + @SafeVarargs + static Hunk newCombinedAtomicDoubleHunk(Hunk... hunks) { + return combined(Hunk::newAtomicDoubleHunk, hunks); + } + + static Hunk newAtomicLongHunk(int w, int h, int d) { + return new AtomicLongHunk(w, h, d); + } + + @SafeVarargs + static Hunk newCombinedAtomicLongHunk(Hunk... hunks) { + return combined(Hunk::newAtomicLongHunk, hunks); + } + + static Hunk newAtomicIntegerHunk(int w, int h, int d) { + return new AtomicIntegerHunk(w, h, d); + } + + @SafeVarargs + static Hunk newCombinedAtomicIntegerHunk(Hunk... hunks) { + return combined(Hunk::newAtomicIntegerHunk, hunks); + } + + /** + * Creates a new bounding hunk from the given hunks + * + * @param the type + * @param factory the factory that creates a hunk + * @param hunks the hunks + * @return the new bounding hunk + */ + @SafeVarargs + static Hunk combined(Function3> factory, Hunk... hunks) { + int w = 0; + int h = 0; + int d = 0; + + for (Hunk i : hunks) { + w = Math.max(w, i.getWidth()); + h = Math.max(h, i.getHeight()); + d = Math.max(d, i.getDepth()); + } + + Hunk b = factory.apply(w, h, d); + + for (Hunk i : hunks) { + b.insert(i); + } + + return b; + } + + default Hunk readOnly() { + return new ReadOnlyHunk<>(this); + } + + default int getNonNullEntries() { + AtomicInteger count = new AtomicInteger(); + iterate((x, y, z, v) -> count.getAndAdd(1)); + + return count.get(); + } + + default void write(OutputStream s, HunkIOAdapter h) throws IOException { + h.write(this, s); + } + + default ByteArrayTag writeByteArrayTag(HunkIOAdapter h, String name) throws IOException { + return h.writeByteArrayTag(this, name); + } + + default void write(File s, HunkIOAdapter h) throws IOException { + h.write(this, s); + } + + default boolean isAtomic() { + return false; + } + + default Hunk invertY() { + return new InvertedHunkView(this); + } + + default Hunk rotateX(double degrees) { + return new RotatedXHunkView(this, degrees); + } + + default Hunk rotateY(double degrees) { + return new RotatedYHunkView(this, degrees); + } + + default Hunk rotateZ(double degrees) { + return new RotatedZHunkView(this, degrees); + } + + default int getMaximumDimension() { + return Math.max(getWidth(), Math.max(getHeight(), getDepth())); + } + + default int getIdeal2DParallelism() { + return getMax2DParallelism() / 4; + } + + default int getIdeal3DParallelism() { + return getMax3DParallelism() / 8; + } + + default int getMinimumDimension() { + return Math.min(getWidth(), Math.min(getHeight(), getDepth())); + } + + default int getMax2DParallelism() { + return (int) Math.pow(getMinimumDimension() / 2, 2); + } + + default int getMax3DParallelism() { + return (int) Math.pow(getMinimumDimension() / 2, 3); + } + + default int filterDimension(int dim) { + if (dim <= 1) { + return 1; + } + + dim = dim % 2 != 0 ? dim + 1 : dim; + + if (dim > getMinimumDimension() / 2) { + if (dim <= 2) { + return 1; + } + + dim -= 2; + } + + return dim; + } + + default int get2DDimension(int sections) { + if (sections <= 1) { + return 1; + } + + return filterDimension((int) Math.ceil(Math.sqrt(sections))); + } + + default int get3DDimension(int sections) { + if (sections <= 1) { + return 1; + } + + return filterDimension((int) Math.ceil(Math.cbrt(sections))); + } + + /** + * Iterate surfaces on 2d. Raytraces with a front and a back which stretches + * through surfaces. Essentially what is returned is the following (in + * order)
+ *
+ *

+ * The predicate is used to determine if the given block type is solid or not. + * + *
+ *
+ * ================================================
+ * AX, AZ: Hunk Relative X and Z + * + *
+ *
+ * HX, HZ: Hunk Positional X and Z (in its parent hunk) + * + *
+ *
+ * TOP: The top of this surface (top+1 is air above a surface) + * + *
+ *
+ * BOTTOM: The bottom of this surface (bottom is the lowest SOLID surface before + * either air or bedrock going down further) + * + *
+ *
+ * LAST_BOTTOM: The previous bottom. If your surface is the top surface, this + * will be -1 as there is no bottom-of-surface above you. However if you are not + * the top surface, this value is equal to the next solid layer above TOP, such + * that ((LAST_BOTTOM - 1) - (TOP + 1)) is how many air blocks are between your + * surface and the surface above you + * + *
+ *
+ * HUNK: The hunk to set data to.
+ * ================================================
+ *
+ * If we assume your chunk coordinates are x and z, then
+ *
+ * bX = (x * 16)
+ * bZ = (z * 16)
+ *
+ * (ax, az, hx, hz, top, bottom, lastBottom, hunk) {
+ * actualBlockX = ax+hx;
+ * actualBlockZ = az+hz;
+ *
+ * hunkX = ax;
+ * hunkZ = az;
+ *
+ * hunk.set(hunkX, ?, hunkZ, noise(actualBlockX, ?, actualBlockZ));
+ * }
+ * + * @param p the predicate + * @param c the consumer + * @return this + */ + default Hunk iterateSurfaces2D(Predicate p, Consumer8> c) { + return iterateSurfaces2D(getIdeal2DParallelism(), p, c); + } + + /** + * Iterate surfaces on 2d. Raytraces with a front and a back which stretches + * through surfaces. Essentially what is returned is the following (in + * order)
+ *
+ *

+ * The predicate is used to determine if the given block type is solid or not. + * + *
+ *
+ * ================================================
+ * AX, AZ: Hunk Relative X and Z + * + *
+ *
+ * HX, HZ: Hunk Positional X and Z (in its parent hunk) + * + *
+ *
+ * TOP: The top of this surface (top+1 is air above a surface) + * + *
+ *
+ * BOTTOM: The bottom of this surface (bottom is the lowest SOLID surface before + * either air or bedrock going down further) + * + *
+ *
+ * LAST_BOTTOM: The previous bottom. If your surface is the top surface, this + * will be -1 as there is no bottom-of-surface above you. However if you are not + * the top surface, this value is equal to the next solid layer above TOP, such + * that ((LAST_BOTTOM - 1) - (TOP + 1)) is how many air blocks are between your + * surface and the surface above you + * + *
+ *
+ * HUNK: The hunk to set data to.
+ * ================================================
+ *
+ * If we assume your chunk coordinates are x and z, then
+ *
+ * bX = (x * 16)
+ * bZ = (z * 16)
+ *
+ * (ax, az, hx, hz, top, bottom, lastBottom, hunk) {
+ * actualBlockX = ax+hx;
+ * actualBlockZ = az+hz;
+ *
+ * hunkX = ax;
+ * hunkZ = az;
+ *
+ * hunk.set(hunkX, ?, hunkZ, noise(actualBlockX, ?, actualBlockZ));
+ * }
+ * + * @param parallelism the ideal threads to use on this + * @param p the predicate + * @param c the consumer + * @return this + */ + default Hunk iterateSurfaces2D(int parallelism, Predicate p, Consumer8> c) { + iterate2DTop(parallelism, (ax, az, hox, hoz, h) -> + { + int last = -1; + int in = getHeight() - 1; + boolean hitting = false; + for (int i = getHeight() - 1; i >= 0; i--) { + boolean solid = p.test(h.get(ax, i, az)); + + if (!hitting && solid) { + in = i; + hitting = true; + } else if (hitting && !solid) { + hitting = false; + c.accept(ax, az, hox, hoz, in, i - 1, last, h); + last = i - 1; + } + } + + if (hitting) { + c.accept(ax, az, hox, hoz, in, 0, last, h); + } + }); + + return this; + } + + /** + * Iterate on the xz top of this hunk. When using this consumer, given + *

+ * consumer: (ax, az, hx, hz, hunk) + *

+ * hunk.set(ax, ?, az, NOISE.get(ax+hx, az+hz)); + * + * @param c the consumer hunkX, hunkZ, hunkOffsetX, hunkOffsetZ. + * @return this + */ + default Hunk iterate2DTop(Consumer5> c) { + return iterate2DTop(getIdeal2DParallelism(), c); + } + + default Hunk drift(int x, int y, int z) { + return new DriftHunkView<>(this, x, y, z); + } + + /** + * Iterate on the xz top of this hunk. When using this consumer, given + *

+ * consumer: (ax, az, hx, hz, hunk) + *

-	 * {
-	 *    Method: "POST" (for example),
-	 *    "Request-URI": "/" (for example),
-	 *    "HTTP-Version": "HTTP/1.1" (for example)
-	 * }
-	 * 
- * - * A response header will contain - * - *
-	 * {
-	 *    "HTTP-Version": "HTTP/1.1" (for example),
-	 *    "Status-Code": "200" (for example),
-	 *    "Reason-Phrase": "OK" (for example)
-	 * }
-	 * 
- * - * In addition, the other parameters in the header will be captured, using - * the HTTP field names as JSON names, so that - * - *
-	 *    Date: Sun, 26 May 2002 18:06:04 GMT
-	 *    Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s
-	 *    Cache-Control: no-cache
-	 * 
- * - * become - * - *
-	 * {...
-	 *    Date: "Sun, 26 May 2002 18:06:04 GMT",
-	 *    Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s",
-	 *    "Cache-Control": "no-cache",
-	 * ...}
-	 * 
- * - * It does no further checking or conversion. It does not parse dates. It - * does not do '%' transforms on URLs. - * - * @param string - * An HTTP header string. - * @return A JSONObject containing the elements and attributes of the XML - * string. - * @throws JSONException - */ - public static JSONObject toJSONObject(String string) throws JSONException - { - JSONObject jo = new JSONObject(); - HTTPTokener x = new HTTPTokener(string); - String token; - - token = x.nextToken(); - if(token.toUpperCase().startsWith("HTTP")) - { - - // Response - - jo.put("HTTP-Version", token); - jo.put("Status-Code", x.nextToken()); - jo.put("Reason-Phrase", x.nextTo('\0')); - x.next(); - - } else - { - - // Request - - jo.put("Method", token); - jo.put("Request-URI", x.nextToken()); - jo.put("HTTP-Version", x.nextToken()); - } - - // Fields - - while(x.more()) - { - String name = x.nextTo(':'); - x.next(':'); - jo.put(name, x.nextTo('\0')); - x.next(); - } - return jo; - } - - /** - * Convert a JSONObject into an HTTP header. A request header must contain - * - *
-	 * {
-	 *    Method: "POST" (for example),
-	 *    "Request-URI": "/" (for example),
-	 *    "HTTP-Version": "HTTP/1.1" (for example)
-	 * }
-	 * 
- * - * A response header must contain - * - *
-	 * {
-	 *    "HTTP-Version": "HTTP/1.1" (for example),
-	 *    "Status-Code": "200" (for example),
-	 *    "Reason-Phrase": "OK" (for example)
-	 * }
-	 * 
- * - * Any other members of the JSONObject will be output as HTTP fields. The - * result will end with two CRLF pairs. - * - * @param jo - * A JSONObject - * @return An HTTP header string. - * @throws JSONException - * if the object does not contain enough information. - */ - public static String toString(JSONObject jo) throws JSONException - { - Iterator keys = jo.keys(); - String string; - StringBuilder sb = new StringBuilder(); - if(jo.has("Status-Code") && jo.has("Reason-Phrase")) - { - sb.append(jo.getString("HTTP-Version")); - sb.append(' '); - sb.append(jo.getString("Status-Code")); - sb.append(' '); - sb.append(jo.getString("Reason-Phrase")); - } else if(jo.has("Method") && jo.has("Request-URI")) - { - sb.append(jo.getString("Method")); - sb.append(' '); - sb.append('"'); - sb.append(jo.getString("Request-URI")); - sb.append('"'); - sb.append(' '); - sb.append(jo.getString("HTTP-Version")); - } else - { - throw new JSONException("Not enough material for an HTTP header."); - } - sb.append(CRLF); - while(keys.hasNext()) - { - string = keys.next(); - if(!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && !"Reason-Phrase".equals(string) && !"Method".equals(string) && !"Request-URI".equals(string) && !jo.isNull(string)) - { - sb.append(string); - sb.append(": "); - sb.append(jo.getString(string)); - sb.append(CRLF); - } - } - sb.append(CRLF); - return sb.toString(); - } +public class HTTP { + + /** + * Carriage return/line feed. + */ + public static final String CRLF = "\r\n"; + + /** + * Convert an HTTP header string into a JSONObject. It can be a request + * header or a response header. A request header will contain + * + *
+     * {
+     *    Method: "POST" (for example),
+     *    "Request-URI": "/" (for example),
+     *    "HTTP-Version": "HTTP/1.1" (for example)
+     * }
+     * 
+ *

+ * A response header will contain + * + *

+     * {
+     *    "HTTP-Version": "HTTP/1.1" (for example),
+     *    "Status-Code": "200" (for example),
+     *    "Reason-Phrase": "OK" (for example)
+     * }
+     * 
+ *

+ * In addition, the other parameters in the header will be captured, using + * the HTTP field names as JSON names, so that + * + *

+     *    Date: Sun, 26 May 2002 18:06:04 GMT
+     *    Cookie: Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s
+     *    Cache-Control: no-cache
+     * 
+ *

+ * become + * + *

+     * {...
+     *    Date: "Sun, 26 May 2002 18:06:04 GMT",
+     *    Cookie: "Q=q2=PPEAsg--; B=677gi6ouf29bn&b=2&f=s",
+     *    "Cache-Control": "no-cache",
+     * ...}
+     * 
+ *

+ * It does no further checking or conversion. It does not parse dates. It + * does not do '%' transforms on URLs. + * + * @param string An HTTP header string. + * @return A JSONObject containing the elements and attributes of the XML + * string. + * @throws JSONException + */ + public static JSONObject toJSONObject(String string) throws JSONException { + JSONObject jo = new JSONObject(); + HTTPTokener x = new HTTPTokener(string); + String token; + + token = x.nextToken(); + if (token.toUpperCase().startsWith("HTTP")) { + + // Response + + jo.put("HTTP-Version", token); + jo.put("Status-Code", x.nextToken()); + jo.put("Reason-Phrase", x.nextTo('\0')); + x.next(); + + } else { + + // Request + + jo.put("Method", token); + jo.put("Request-URI", x.nextToken()); + jo.put("HTTP-Version", x.nextToken()); + } + + // Fields + + while (x.more()) { + String name = x.nextTo(':'); + x.next(':'); + jo.put(name, x.nextTo('\0')); + x.next(); + } + return jo; + } + + /** + * Convert a JSONObject into an HTTP header. A request header must contain + * + *

+     * {
+     *    Method: "POST" (for example),
+     *    "Request-URI": "/" (for example),
+     *    "HTTP-Version": "HTTP/1.1" (for example)
+     * }
+     * 
+ *

+ * A response header must contain + * + *

+     * {
+     *    "HTTP-Version": "HTTP/1.1" (for example),
+     *    "Status-Code": "200" (for example),
+     *    "Reason-Phrase": "OK" (for example)
+     * }
+     * 
+ *

+ * Any other members of the JSONObject will be output as HTTP fields. The + * result will end with two CRLF pairs. + * + * @param jo A JSONObject + * @return An HTTP header string. + * @throws JSONException if the object does not contain enough information. + */ + public static String toString(JSONObject jo) throws JSONException { + Iterator keys = jo.keys(); + String string; + StringBuilder sb = new StringBuilder(); + if (jo.has("Status-Code") && jo.has("Reason-Phrase")) { + sb.append(jo.getString("HTTP-Version")); + sb.append(' '); + sb.append(jo.getString("Status-Code")); + sb.append(' '); + sb.append(jo.getString("Reason-Phrase")); + } else if (jo.has("Method") && jo.has("Request-URI")) { + sb.append(jo.getString("Method")); + sb.append(' '); + sb.append('"'); + sb.append(jo.getString("Request-URI")); + sb.append('"'); + sb.append(' '); + sb.append(jo.getString("HTTP-Version")); + } else { + throw new JSONException("Not enough material for an HTTP header."); + } + sb.append(CRLF); + while (keys.hasNext()) { + string = keys.next(); + if (!"HTTP-Version".equals(string) && !"Status-Code".equals(string) && !"Reason-Phrase".equals(string) && !"Method".equals(string) && !"Request-URI".equals(string) && !jo.isNull(string)) { + sb.append(string); + sb.append(": "); + sb.append(jo.getString(string)); + sb.append(CRLF); + } + } + sb.append(CRLF); + return sb.toString(); + } } diff --git a/src/main/java/com/volmit/iris/util/HTTPTokener.java b/src/main/java/com/volmit/iris/util/HTTPTokener.java index 562f86109..4da1c5176 100644 --- a/src/main/java/com/volmit/iris/util/HTTPTokener.java +++ b/src/main/java/com/volmit/iris/util/HTTPTokener.java @@ -28,64 +28,53 @@ SOFTWARE. /** * The HTTPTokener extends the JSONTokener to provide additional methods for the * parsing of HTTP headers. - * + * * @author JSON.org * @version 2014-05-03 */ -public class HTTPTokener extends JSONTokener -{ - - /** - * Construct an HTTPTokener from a string. - * - * @param string - * A source string. - */ - public HTTPTokener(String string) - { - super(string); - } - - /** - * Get the next token or string. This is used in parsing HTTP headers. - * - * @throws JSONException - * @return A String. - */ - public String nextToken() throws JSONException - { - char c; - char q; - StringBuilder sb = new StringBuilder(); - do - { - c = next(); - } while(Character.isWhitespace(c)); - if(c == '"' || c == '\'') - { - q = c; - for(;;) - { - c = next(); - if(c < ' ') - { - throw syntaxError("Unterminated string."); - } - if(c == q) - { - return sb.toString(); - } - sb.append(c); - } - } - for(;;) - { - if(c == 0 || Character.isWhitespace(c)) - { - return sb.toString(); - } - sb.append(c); - c = next(); - } - } +public class HTTPTokener extends JSONTokener { + + /** + * Construct an HTTPTokener from a string. + * + * @param string A source string. + */ + public HTTPTokener(String string) { + super(string); + } + + /** + * Get the next token or string. This is used in parsing HTTP headers. + * + * @return A String. + * @throws JSONException + */ + public String nextToken() throws JSONException { + char c; + char q; + StringBuilder sb = new StringBuilder(); + do { + c = next(); + } while (Character.isWhitespace(c)); + if (c == '"' || c == '\'') { + q = c; + for (; ; ) { + c = next(); + if (c < ' ') { + throw syntaxError("Unterminated string."); + } + if (c == q) { + return sb.toString(); + } + sb.append(c); + } + } + for (; ; ) { + if (c == 0 || Character.isWhitespace(c)) { + return sb.toString(); + } + sb.append(c); + c = next(); + } + } } diff --git a/src/main/java/com/volmit/iris/util/HeightMap.java b/src/main/java/com/volmit/iris/util/HeightMap.java index ea9f4dd13..b9f6b1a78 100644 --- a/src/main/java/com/volmit/iris/util/HeightMap.java +++ b/src/main/java/com/volmit/iris/util/HeightMap.java @@ -2,23 +2,19 @@ package com.volmit.iris.util; import java.util.Arrays; -public class HeightMap -{ - private final byte[] height; +public class HeightMap { + private final byte[] height; - public HeightMap() - { - height = new byte[256]; - Arrays.fill(height, Byte.MIN_VALUE); - } + public HeightMap() { + height = new byte[256]; + Arrays.fill(height, Byte.MIN_VALUE); + } - public void setHeight(int x, int z, int h) - { - height[x * 16 + z] = (byte) (h + Byte.MIN_VALUE); - } + public void setHeight(int x, int z, int h) { + height[x * 16 + z] = (byte) (h + Byte.MIN_VALUE); + } - public int getHeight(int x, int z) - { - return height[x * 16 + z] - Byte.MIN_VALUE; - } + public int getHeight(int x, int z) { + return height[x * 16 + z] - Byte.MIN_VALUE; + } } diff --git a/src/main/java/com/volmit/iris/util/HeightedFakeWorld.java b/src/main/java/com/volmit/iris/util/HeightedFakeWorld.java index 12c8bc9c0..4c8ec100c 100644 --- a/src/main/java/com/volmit/iris/util/HeightedFakeWorld.java +++ b/src/main/java/com/volmit/iris/util/HeightedFakeWorld.java @@ -1,45 +1,12 @@ package com.volmit.iris.util; -import java.io.File; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.UUID; -import java.util.function.Predicate; - -import org.bukkit.BlockChangeDelegate; -import org.bukkit.Chunk; -import org.bukkit.ChunkSnapshot; -import org.bukkit.Difficulty; -import org.bukkit.Effect; -import org.bukkit.FluidCollisionMode; -import org.bukkit.GameRule; import org.bukkit.HeightMap; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.Particle; -import org.bukkit.Raid; -import org.bukkit.Sound; -import org.bukkit.SoundCategory; -import org.bukkit.StructureType; -import org.bukkit.TreeType; -import org.bukkit.World; -import org.bukkit.WorldBorder; -import org.bukkit.WorldType; +import org.bukkit.*; import org.bukkit.block.Biome; import org.bukkit.block.Block; import org.bukkit.block.data.BlockData; import org.bukkit.boss.DragonBattle; -import org.bukkit.entity.AbstractArrow; -import org.bukkit.entity.Arrow; -import org.bukkit.entity.Entity; -import org.bukkit.entity.EntityType; -import org.bukkit.entity.FallingBlock; -import org.bukkit.entity.Item; -import org.bukkit.entity.LightningStrike; -import org.bukkit.entity.LivingEntity; -import org.bukkit.entity.Player; +import org.bukkit.entity.*; import org.bukkit.generator.BlockPopulator; import org.bukkit.generator.ChunkGenerator; import org.bukkit.inventory.ItemStack; @@ -53,1287 +20,1113 @@ import org.bukkit.util.Vector; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.io.File; +import java.util.*; +import java.util.function.Predicate; + @SuppressWarnings("deprecation") -public class HeightedFakeWorld implements World -{ - private final int height; +public class HeightedFakeWorld implements World { + private final int height; - public HeightedFakeWorld(int height) - { - this.height = height; - } + public HeightedFakeWorld(int height) { + this.height = height; + } - @Override - public void sendPluginMessage(Plugin source, String channel, byte[] message) - { + @Override + public void sendPluginMessage(Plugin source, String channel, byte[] message) { - } + } - @Override - public Set getListeningPluginChannels() - { + @Override + public Set getListeningPluginChannels() { - return null; - } + return null; + } - @Override - public void setMetadata(String metadataKey, MetadataValue newMetadataValue) - { + @Override + public void setMetadata(String metadataKey, MetadataValue newMetadataValue) { - } + } - @Override - public List getMetadata(String metadataKey) - { + @Override + public List getMetadata(String metadataKey) { - return null; - } + return null; + } - @Override - public boolean hasMetadata(String metadataKey) - { + @Override + public boolean hasMetadata(String metadataKey) { - return false; - } + return false; + } - @Override - public void removeMetadata(String metadataKey, Plugin owningPlugin) - { + @Override + public void removeMetadata(String metadataKey, Plugin owningPlugin) { - } + } - @Override - public Block getBlockAt(int x, int y, int z) - { + @Override + public Block getBlockAt(int x, int y, int z) { - return null; - } + return null; + } - @Override - public Block getBlockAt(Location location) - { + @Override + public Block getBlockAt(Location location) { - return null; - } + return null; + } - @Override - public int getHighestBlockYAt(int x, int z) - { + @Override + public int getHighestBlockYAt(int x, int z) { - return 0; - } + return 0; + } - @Override - public int getHighestBlockYAt(Location location) - { + @Override + public int getHighestBlockYAt(Location location) { - return 0; - } + return 0; + } - @Override - public Block getHighestBlockAt(int x, int z) - { + @Override + public Block getHighestBlockAt(int x, int z) { - return null; - } + return null; + } - @Override - public Block getHighestBlockAt(Location location) - { + @Override + public Block getHighestBlockAt(Location location) { - return null; - } + return null; + } - @Override - public int getHighestBlockYAt(int x, int z, HeightMap heightMap) - { + @Override + public int getHighestBlockYAt(int x, int z, HeightMap heightMap) { - return 0; - } + return 0; + } - @Override - public int getHighestBlockYAt(Location location, HeightMap heightMap) - { + @Override + public int getHighestBlockYAt(Location location, HeightMap heightMap) { - return 0; - } + return 0; + } - @Override - public Block getHighestBlockAt(int x, int z, HeightMap heightMap) - { + @Override + public Block getHighestBlockAt(int x, int z, HeightMap heightMap) { - return null; - } + return null; + } - @Override - public Block getHighestBlockAt(Location location, HeightMap heightMap) - { + @Override + public Block getHighestBlockAt(Location location, HeightMap heightMap) { - return null; - } + return null; + } - @Override - public Chunk getChunkAt(int x, int z) - { + @Override + public Chunk getChunkAt(int x, int z) { - return null; - } + return null; + } - @Override - public Chunk getChunkAt(Location location) - { + @Override + public Chunk getChunkAt(Location location) { - return null; - } + return null; + } - @Override - public Chunk getChunkAt(Block block) - { + @Override + public Chunk getChunkAt(Block block) { - return null; - } + return null; + } - @Override - public boolean isChunkLoaded(Chunk chunk) - { + @Override + public boolean isChunkLoaded(Chunk chunk) { - return false; - } + return false; + } - @Override - public Chunk[] getLoadedChunks() - { + @Override + public Chunk[] getLoadedChunks() { - return null; - } + return null; + } - @Override - public void loadChunk(Chunk chunk) - { + @Override + public void loadChunk(Chunk chunk) { - } + } - @Override - public boolean isChunkLoaded(int x, int z) - { + @Override + public boolean isChunkLoaded(int x, int z) { - return false; - } + return false; + } - @Override - public boolean isChunkGenerated(int x, int z) - { + @Override + public boolean isChunkGenerated(int x, int z) { - return false; - } + return false; + } - @Override - public boolean isChunkInUse(int x, int z) - { + @Override + public boolean isChunkInUse(int x, int z) { - return false; - } + return false; + } - @Override - public void loadChunk(int x, int z) - { + @Override + public void loadChunk(int x, int z) { - } + } - @Override - public boolean loadChunk(int x, int z, boolean generate) - { + @Override + public boolean loadChunk(int x, int z, boolean generate) { - return false; - } + return false; + } - @Override - public boolean unloadChunk(Chunk chunk) - { + @Override + public boolean unloadChunk(Chunk chunk) { - return false; - } + return false; + } - @Override - public boolean unloadChunk(int x, int z) - { + @Override + public boolean unloadChunk(int x, int z) { - return false; - } + return false; + } - @Override - public boolean unloadChunk(int x, int z, boolean save) - { + @Override + public boolean unloadChunk(int x, int z, boolean save) { - return false; - } + return false; + } - @Override - public boolean unloadChunkRequest(int x, int z) - { + @Override + public boolean unloadChunkRequest(int x, int z) { - return false; - } + return false; + } - @Override - public boolean regenerateChunk(int x, int z) - { + @Override + public boolean regenerateChunk(int x, int z) { - return false; - } + return false; + } - @Override - public boolean refreshChunk(int x, int z) - { + @Override + public boolean refreshChunk(int x, int z) { - return false; - } + return false; + } - @Override - public boolean isChunkForceLoaded(int x, int z) - { + @Override + public boolean isChunkForceLoaded(int x, int z) { - return false; - } + return false; + } - @Override - public void setChunkForceLoaded(int x, int z, boolean forced) - { + @Override + public void setChunkForceLoaded(int x, int z, boolean forced) { - } + } - @Override - public Collection getForceLoadedChunks() - { + @Override + public Collection getForceLoadedChunks() { - return null; - } + return null; + } - @Override - public boolean addPluginChunkTicket(int x, int z, Plugin plugin) - { + @Override + public boolean addPluginChunkTicket(int x, int z, Plugin plugin) { - return false; - } + return false; + } - @Override - public boolean removePluginChunkTicket(int x, int z, Plugin plugin) - { + @Override + public boolean removePluginChunkTicket(int x, int z, Plugin plugin) { - return false; - } + return false; + } - @Override - public void removePluginChunkTickets(Plugin plugin) - { + @Override + public void removePluginChunkTickets(Plugin plugin) { - } + } - @Override - public Collection getPluginChunkTickets(int x, int z) - { + @Override + public Collection getPluginChunkTickets(int x, int z) { - return null; - } + return null; + } - @Override - public Map> getPluginChunkTickets() - { + @Override + public Map> getPluginChunkTickets() { - return null; - } + return null; + } - @Override - public Item dropItem(Location location, ItemStack item) - { + @Override + public Item dropItem(Location location, ItemStack item) { - return null; - } + return null; + } - @NotNull @Override public Item dropItem(@NotNull Location location, @NotNull ItemStack itemStack, @Nullable Consumer consumer) { - return null; - } + @NotNull + @Override + public Item dropItem(@NotNull Location location, @NotNull ItemStack itemStack, @Nullable Consumer consumer) { + return null; + } - @Override - public Item dropItemNaturally(Location location, ItemStack item) - { + @Override + public Item dropItemNaturally(Location location, ItemStack item) { - return null; - } + return null; + } - @NotNull @Override public Item dropItemNaturally(@NotNull Location location, @NotNull ItemStack itemStack, @Nullable Consumer consumer) { - return null; - } + @NotNull + @Override + public Item dropItemNaturally(@NotNull Location location, @NotNull ItemStack itemStack, @Nullable Consumer consumer) { + return null; + } - @Override - public Arrow spawnArrow(Location location, Vector direction, float speed, float spread) - { + @Override + public Arrow spawnArrow(Location location, Vector direction, float speed, float spread) { - return null; - } + return null; + } - @Override - public T spawnArrow(Location location, Vector direction, float speed, float spread, Class clazz) - { + @Override + public T spawnArrow(Location location, Vector direction, float speed, float spread, Class clazz) { - return null; - } + return null; + } - @Override - public boolean generateTree(Location location, TreeType type) - { + @Override + public boolean generateTree(Location location, TreeType type) { - return false; - } + return false; + } - @Override - public boolean generateTree(Location loc, TreeType type, BlockChangeDelegate delegate) - { + @Override + public boolean generateTree(Location loc, TreeType type, BlockChangeDelegate delegate) { - return false; - } + return false; + } - @Override - public Entity spawnEntity(Location loc, EntityType type) - { + @Override + public Entity spawnEntity(Location loc, EntityType type) { - return null; - } + return null; + } - @Override - public LightningStrike strikeLightning(Location loc) - { + @Override + public LightningStrike strikeLightning(Location loc) { - return null; - } + return null; + } - @Override - public LightningStrike strikeLightningEffect(Location loc) - { + @Override + public LightningStrike strikeLightningEffect(Location loc) { - return null; - } + return null; + } - @Override - public List getEntities() - { + @Override + public List getEntities() { - return null; - } + return null; + } - @Override - public List getLivingEntities() - { + @Override + public List getLivingEntities() { - return null; - } + return null; + } - @Override - public Collection getEntitiesByClass(@SuppressWarnings("unchecked") Class... classes) - { + @Override + public Collection getEntitiesByClass(@SuppressWarnings("unchecked") Class... classes) { - return null; - } + return null; + } - @Override - public Collection getEntitiesByClass(Class cls) - { + @Override + public Collection getEntitiesByClass(Class cls) { - return null; - } + return null; + } - @Override - public Collection getEntitiesByClasses(Class... classes) - { + @Override + public Collection getEntitiesByClasses(Class... classes) { - return null; - } + return null; + } - @Override - public List getPlayers() - { + @Override + public List getPlayers() { - return null; - } + return null; + } - @Override - public Collection getNearbyEntities(Location location, double x, double y, double z) - { + @Override + public Collection getNearbyEntities(Location location, double x, double y, double z) { - return null; - } + return null; + } - @Override - public Collection getNearbyEntities(Location location, double x, double y, double z, Predicate filter) - { + @Override + public Collection getNearbyEntities(Location location, double x, double y, double z, Predicate filter) { - return null; - } + return null; + } - @Override - public Collection getNearbyEntities(BoundingBox boundingBox) - { + @Override + public Collection getNearbyEntities(BoundingBox boundingBox) { - return null; - } + return null; + } - @Override - public Collection getNearbyEntities(BoundingBox boundingBox, Predicate filter) - { + @Override + public Collection getNearbyEntities(BoundingBox boundingBox, Predicate filter) { - return null; - } + return null; + } - @Override - public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance) - { + @Override + public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance) { - return null; - } + return null; + } - @Override - public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance, double raySize) - { + @Override + public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance, double raySize) { - return null; - } + return null; + } - @Override - public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance, Predicate filter) - { + @Override + public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance, Predicate filter) { - return null; - } + return null; + } - @Override - public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance, double raySize, Predicate filter) - { + @Override + public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance, double raySize, Predicate filter) { - return null; - } + return null; + } - @Override - public RayTraceResult rayTraceBlocks(Location start, Vector direction, double maxDistance) - { + @Override + public RayTraceResult rayTraceBlocks(Location start, Vector direction, double maxDistance) { - return null; - } + return null; + } - @Override - public RayTraceResult rayTraceBlocks(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode) - { + @Override + public RayTraceResult rayTraceBlocks(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode) { - return null; - } + return null; + } - @Override - public RayTraceResult rayTraceBlocks(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode, boolean ignorePassableBlocks) - { + @Override + public RayTraceResult rayTraceBlocks(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode, boolean ignorePassableBlocks) { - return null; - } + return null; + } - @Override - public RayTraceResult rayTrace(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode, boolean ignorePassableBlocks, double raySize, Predicate filter) - { + @Override + public RayTraceResult rayTrace(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode, boolean ignorePassableBlocks, double raySize, Predicate filter) { - return null; - } + return null; + } - @Override - public String getName() - { + @Override + public String getName() { - return null; - } + return null; + } - @Override - public UUID getUID() - { + @Override + public UUID getUID() { - return null; - } + return null; + } - @Override - public Location getSpawnLocation() - { + @Override + public Location getSpawnLocation() { - return null; - } + return null; + } - @Override - public boolean setSpawnLocation(Location location) - { + @Override + public boolean setSpawnLocation(Location location) { - return false; - } + return false; + } - @Override public boolean setSpawnLocation(int i, int i1, int i2, float v) { - return false; - } + @Override + public boolean setSpawnLocation(int i, int i1, int i2, float v) { + return false; + } - @Override - public boolean setSpawnLocation(int x, int y, int z) - { + @Override + public boolean setSpawnLocation(int x, int y, int z) { - return false; - } + return false; + } - @Override - public long getTime() - { + @Override + public long getTime() { - return 0; - } + return 0; + } - @Override - public void setTime(long time) - { + @Override + public void setTime(long time) { - } + } - @Override - public long getFullTime() - { + @Override + public long getFullTime() { - return 0; - } + return 0; + } - @Override - public void setFullTime(long time) - { + @Override + public void setFullTime(long time) { - } + } - @Override public long getGameTime() { - return 0; - } + @Override + public long getGameTime() { + return 0; + } - @Override - public boolean hasStorm() - { + @Override + public boolean hasStorm() { - return false; - } + return false; + } - @Override - public void setStorm(boolean hasStorm) - { + @Override + public void setStorm(boolean hasStorm) { - } + } - @Override - public int getWeatherDuration() - { + @Override + public int getWeatherDuration() { - return 0; - } + return 0; + } - @Override - public void setWeatherDuration(int duration) - { + @Override + public void setWeatherDuration(int duration) { - } + } - @Override - public boolean isThundering() - { + @Override + public boolean isThundering() { - return false; - } + return false; + } - @Override - public void setThundering(boolean thundering) - { + @Override + public void setThundering(boolean thundering) { - } + } - @Override - public int getThunderDuration() - { + @Override + public int getThunderDuration() { - return 0; - } + return 0; + } - @Override - public void setThunderDuration(int duration) - { + @Override + public void setThunderDuration(int duration) { - } + } - @Override public boolean isClearWeather() { - return false; - } + @Override + public boolean isClearWeather() { + return false; + } - @Override public void setClearWeatherDuration(int i) { + @Override + public void setClearWeatherDuration(int i) { - } + } - @Override public int getClearWeatherDuration() { - return 0; - } + @Override + public int getClearWeatherDuration() { + return 0; + } - @Override - public boolean createExplosion(double x, double y, double z, float power) - { + @Override + public boolean createExplosion(double x, double y, double z, float power) { - return false; - } + return false; + } - @Override - public boolean createExplosion(double x, double y, double z, float power, boolean setFire) - { + @Override + public boolean createExplosion(double x, double y, double z, float power, boolean setFire) { - return false; - } + return false; + } - @Override - public boolean createExplosion(double x, double y, double z, float power, boolean setFire, boolean breakBlocks) - { + @Override + public boolean createExplosion(double x, double y, double z, float power, boolean setFire, boolean breakBlocks) { - return false; - } + return false; + } - @Override - public boolean createExplosion(double x, double y, double z, float power, boolean setFire, boolean breakBlocks, Entity source) - { + @Override + public boolean createExplosion(double x, double y, double z, float power, boolean setFire, boolean breakBlocks, Entity source) { - return false; - } + return false; + } - @Override - public boolean createExplosion(Location loc, float power) - { + @Override + public boolean createExplosion(Location loc, float power) { - return false; - } + return false; + } - @Override - public boolean createExplosion(Location loc, float power, boolean setFire) - { + @Override + public boolean createExplosion(Location loc, float power, boolean setFire) { - return false; - } + return false; + } - @Override - public boolean createExplosion(Location loc, float power, boolean setFire, boolean breakBlocks) - { + @Override + public boolean createExplosion(Location loc, float power, boolean setFire, boolean breakBlocks) { - return false; - } + return false; + } - @Override - public boolean createExplosion(Location loc, float power, boolean setFire, boolean breakBlocks, Entity source) - { + @Override + public boolean createExplosion(Location loc, float power, boolean setFire, boolean breakBlocks, Entity source) { - return false; - } + return false; + } - @Override - public Environment getEnvironment() - { + @Override + public Environment getEnvironment() { - return null; - } + return null; + } - @Override - public long getSeed() - { + @Override + public long getSeed() { - return 0; - } + return 0; + } - @Override - public boolean getPVP() - { + @Override + public boolean getPVP() { - return false; - } + return false; + } - @Override - public void setPVP(boolean pvp) - { + @Override + public void setPVP(boolean pvp) { - } + } - @Override - public ChunkGenerator getGenerator() - { + @Override + public ChunkGenerator getGenerator() { - return null; - } + return null; + } - @Override - public void save() - { + @Override + public void save() { - } + } - @Override - public List getPopulators() - { + @Override + public List getPopulators() { - return null; - } + return null; + } - @Override - public T spawn(Location location, Class clazz) throws IllegalArgumentException - { + @Override + public T spawn(Location location, Class clazz) throws IllegalArgumentException { - return null; - } + return null; + } - @Override - public T spawn(Location location, Class clazz, Consumer function) throws IllegalArgumentException - { + @Override + public T spawn(Location location, Class clazz, Consumer function) throws IllegalArgumentException { - return null; - } + return null; + } - @Override - public FallingBlock spawnFallingBlock(Location location, MaterialData data) throws IllegalArgumentException - { + @Override + public FallingBlock spawnFallingBlock(Location location, MaterialData data) throws IllegalArgumentException { - return null; - } + return null; + } - @Override - public FallingBlock spawnFallingBlock(Location location, BlockData data) throws IllegalArgumentException - { + @Override + public FallingBlock spawnFallingBlock(Location location, BlockData data) throws IllegalArgumentException { - return null; - } + return null; + } - @Override - public FallingBlock spawnFallingBlock(Location location, Material material, byte data) throws IllegalArgumentException - { + @Override + public FallingBlock spawnFallingBlock(Location location, Material material, byte data) throws IllegalArgumentException { - return null; - } + return null; + } - @Override - public void playEffect(Location location, Effect effect, int data) - { + @Override + public void playEffect(Location location, Effect effect, int data) { - } + } - @Override - public void playEffect(Location location, Effect effect, int data, int radius) - { + @Override + public void playEffect(Location location, Effect effect, int data, int radius) { - } + } - @Override - public void playEffect(Location location, Effect effect, T data) - { + @Override + public void playEffect(Location location, Effect effect, T data) { - } + } - @Override - public void playEffect(Location location, Effect effect, T data, int radius) - { + @Override + public void playEffect(Location location, Effect effect, T data, int radius) { - } + } - @Override - public ChunkSnapshot getEmptyChunkSnapshot(int x, int z, boolean includeBiome, boolean includeBiomeTemp) - { + @Override + public ChunkSnapshot getEmptyChunkSnapshot(int x, int z, boolean includeBiome, boolean includeBiomeTemp) { - return null; - } + return null; + } - @Override - public void setSpawnFlags(boolean allowMonsters, boolean allowAnimals) - { + @Override + public void setSpawnFlags(boolean allowMonsters, boolean allowAnimals) { - } + } - @Override - public boolean getAllowAnimals() - { + @Override + public boolean getAllowAnimals() { - return false; - } + return false; + } - @Override - public boolean getAllowMonsters() - { + @Override + public boolean getAllowMonsters() { - return false; - } + return false; + } - @Override - public Biome getBiome(int x, int z) - { + @Override + public Biome getBiome(int x, int z) { - return null; - } + return null; + } - @Override - public Biome getBiome(int x, int y, int z) - { + @Override + public Biome getBiome(int x, int y, int z) { - return null; - } + return null; + } - @Override - public void setBiome(int x, int z, Biome bio) - { + @Override + public void setBiome(int x, int z, Biome bio) { - } + } - @Override - public void setBiome(int x, int y, int z, Biome bio) - { + @Override + public void setBiome(int x, int y, int z, Biome bio) { - } + } - @Override - public double getTemperature(int x, int z) - { + @Override + public double getTemperature(int x, int z) { - return 0; - } + return 0; + } - @Override - public double getTemperature(int x, int y, int z) - { + @Override + public double getTemperature(int x, int y, int z) { - return 0; - } + return 0; + } - @Override - public double getHumidity(int x, int z) - { + @Override + public double getHumidity(int x, int z) { - return 0; - } + return 0; + } - @Override - public double getHumidity(int x, int y, int z) - { + @Override + public double getHumidity(int x, int y, int z) { - return 0; - } + return 0; + } - @Override public int getMinHeight() { - return 0; - } + @Override + public int getMinHeight() { + return 0; + } - @Override - public int getMaxHeight() - { + @Override + public int getMaxHeight() { - return height; - } + return height; + } - @Override - public int getSeaLevel() - { + @Override + public int getSeaLevel() { - return 0; - } + return 0; + } - @Override - public boolean getKeepSpawnInMemory() - { + @Override + public boolean getKeepSpawnInMemory() { - return false; - } + return false; + } - @Override - public void setKeepSpawnInMemory(boolean keepLoaded) - { + @Override + public void setKeepSpawnInMemory(boolean keepLoaded) { - } + } - @Override - public boolean isAutoSave() - { + @Override + public boolean isAutoSave() { - return false; - } + return false; + } - @Override - public void setAutoSave(boolean value) - { + @Override + public void setAutoSave(boolean value) { - } + } - @Override - public void setDifficulty(Difficulty difficulty) - { + @Override + public void setDifficulty(Difficulty difficulty) { - } + } - @Override - public Difficulty getDifficulty() - { + @Override + public Difficulty getDifficulty() { - return null; - } + return null; + } - @Override - public File getWorldFolder() - { + @Override + public File getWorldFolder() { - return null; - } + return null; + } - @Override - public WorldType getWorldType() - { + @Override + public WorldType getWorldType() { - return null; - } + return null; + } - @Override - public boolean canGenerateStructures() - { + @Override + public boolean canGenerateStructures() { - return false; - } + return false; + } - @Override - public boolean isHardcore() - { + @Override + public boolean isHardcore() { - return false; - } + return false; + } - @Override - public void setHardcore(boolean hardcore) - { + @Override + public void setHardcore(boolean hardcore) { - } + } - @Override - public long getTicksPerAnimalSpawns() - { + @Override + public long getTicksPerAnimalSpawns() { - return 0; - } + return 0; + } - @Override - public void setTicksPerAnimalSpawns(int ticksPerAnimalSpawns) - { + @Override + public void setTicksPerAnimalSpawns(int ticksPerAnimalSpawns) { - } + } - @Override - public long getTicksPerMonsterSpawns() - { + @Override + public long getTicksPerMonsterSpawns() { - return 0; - } + return 0; + } - @Override - public void setTicksPerMonsterSpawns(int ticksPerMonsterSpawns) - { + @Override + public void setTicksPerMonsterSpawns(int ticksPerMonsterSpawns) { - } + } - @Override - public long getTicksPerWaterSpawns() - { + @Override + public long getTicksPerWaterSpawns() { - return 0; - } + return 0; + } - @Override - public void setTicksPerWaterSpawns(int ticksPerWaterSpawns) - { + @Override + public void setTicksPerWaterSpawns(int ticksPerWaterSpawns) { - } + } - @Override - public long getTicksPerWaterAmbientSpawns() - { + @Override + public long getTicksPerWaterAmbientSpawns() { - return 0; - } + return 0; + } - @Override - public void setTicksPerWaterAmbientSpawns(int ticksPerAmbientSpawns) - { + @Override + public void setTicksPerWaterAmbientSpawns(int ticksPerAmbientSpawns) { - } + } - @Override - public long getTicksPerAmbientSpawns() - { + @Override + public long getTicksPerAmbientSpawns() { - return 0; - } + return 0; + } - @Override - public void setTicksPerAmbientSpawns(int ticksPerAmbientSpawns) - { + @Override + public void setTicksPerAmbientSpawns(int ticksPerAmbientSpawns) { - } + } - @Override - public int getMonsterSpawnLimit() - { + @Override + public int getMonsterSpawnLimit() { - return 0; - } + return 0; + } - @Override - public void setMonsterSpawnLimit(int limit) - { + @Override + public void setMonsterSpawnLimit(int limit) { - } + } - @Override - public int getAnimalSpawnLimit() - { + @Override + public int getAnimalSpawnLimit() { - return 0; - } + return 0; + } - @Override - public void setAnimalSpawnLimit(int limit) - { + @Override + public void setAnimalSpawnLimit(int limit) { - } + } - @Override - public int getWaterAnimalSpawnLimit() - { + @Override + public int getWaterAnimalSpawnLimit() { - return 0; - } + return 0; + } - @Override - public void setWaterAnimalSpawnLimit(int limit) - { + @Override + public void setWaterAnimalSpawnLimit(int limit) { - } + } - @Override - public int getWaterAmbientSpawnLimit() - { + @Override + public int getWaterAmbientSpawnLimit() { - return 0; - } + return 0; + } - @Override - public void setWaterAmbientSpawnLimit(int limit) - { + @Override + public void setWaterAmbientSpawnLimit(int limit) { - } + } - @Override - public int getAmbientSpawnLimit() - { + @Override + public int getAmbientSpawnLimit() { - return 0; - } + return 0; + } - @Override - public void setAmbientSpawnLimit(int limit) - { + @Override + public void setAmbientSpawnLimit(int limit) { - } + } - @Override - public void playSound(Location location, Sound sound, float volume, float pitch) - { + @Override + public void playSound(Location location, Sound sound, float volume, float pitch) { - } + } - @Override - public void playSound(Location location, String sound, float volume, float pitch) - { + @Override + public void playSound(Location location, String sound, float volume, float pitch) { - } + } - @Override - public void playSound(Location location, Sound sound, SoundCategory category, float volume, float pitch) - { + @Override + public void playSound(Location location, Sound sound, SoundCategory category, float volume, float pitch) { - } + } - @Override - public void playSound(Location location, String sound, SoundCategory category, float volume, float pitch) - { + @Override + public void playSound(Location location, String sound, SoundCategory category, float volume, float pitch) { - } + } - @Override - public String[] getGameRules() - { + @Override + public String[] getGameRules() { - return null; - } + return null; + } - @Override - public String getGameRuleValue(String rule) - { + @Override + public String getGameRuleValue(String rule) { - return null; - } + return null; + } - @Override - public boolean setGameRuleValue(String rule, String value) - { + @Override + public boolean setGameRuleValue(String rule, String value) { - return false; - } + return false; + } - @Override - public boolean isGameRule(String rule) - { + @Override + public boolean isGameRule(String rule) { - return false; - } + return false; + } - @Override - public T getGameRuleValue(GameRule rule) - { + @Override + public T getGameRuleValue(GameRule rule) { - return null; - } + return null; + } - @Override - public T getGameRuleDefault(GameRule rule) - { + @Override + public T getGameRuleDefault(GameRule rule) { - return null; - } + return null; + } - @Override - public boolean setGameRule(GameRule rule, T newValue) - { + @Override + public boolean setGameRule(GameRule rule, T newValue) { - return false; - } + return false; + } - @Override - public WorldBorder getWorldBorder() - { + @Override + public WorldBorder getWorldBorder() { - return null; - } + return null; + } - @Override - public void spawnParticle(Particle particle, Location location, int count) - { + @Override + public void spawnParticle(Particle particle, Location location, int count) { - } + } - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count) - { + @Override + public void spawnParticle(Particle particle, double x, double y, double z, int count) { - } + } - @Override - public void spawnParticle(Particle particle, Location location, int count, T data) - { + @Override + public void spawnParticle(Particle particle, Location location, int count, T data) { - } + } - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, T data) - { + @Override + public void spawnParticle(Particle particle, double x, double y, double z, int count, T data) { - } + } - @Override - public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ) - { + @Override + public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ) { - } + } - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ) - { + @Override + public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ) { - } + } - @Override - public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, T data) - { + @Override + public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, T data) { - } + } - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, T data) - { + @Override + public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, T data) { - } + } - @Override - public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra) - { + @Override + public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra) { - } + } - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra) - { + @Override + public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra) { - } + } - @Override - public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, T data) - { + @Override + public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, T data) { - } + } - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, T data) - { + @Override + public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, T data) { - } + } - @Override - public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, T data, boolean force) - { + @Override + public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, T data, boolean force) { - } + } - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, T data, boolean force) - { + @Override + public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, T data, boolean force) { - } + } - @Override - public Location locateNearestStructure(Location origin, StructureType structureType, int radius, boolean findUnexplored) - { - return null; - } + @Override + public Location locateNearestStructure(Location origin, StructureType structureType, int radius, boolean findUnexplored) { + return null; + } - @Override - public int getViewDistance() - { - return 0; - } + @Override + public int getViewDistance() { + return 0; + } - @Override - public Spigot spigot() - { - return null; - } + @Override + public Spigot spigot() { + return null; + } - @Override - public Raid locateNearestRaid(Location location, int radius) - { - return null; - } + @Override + public Raid locateNearestRaid(Location location, int radius) { + return null; + } - @Override - public List getRaids() - { - return null; - } + @Override + public List getRaids() { + return null; + } - @Override - public DragonBattle getEnderDragonBattle() - { - return null; - } + @Override + public DragonBattle getEnderDragonBattle() { + return null; + } } diff --git a/src/main/java/com/volmit/iris/util/IActivator.java b/src/main/java/com/volmit/iris/util/IActivator.java index 61768b1ef..434d5ef0e 100644 --- a/src/main/java/com/volmit/iris/util/IActivator.java +++ b/src/main/java/com/volmit/iris/util/IActivator.java @@ -1,6 +1,5 @@ package com.volmit.iris.util; -public interface IActivator -{ +public interface IActivator { } diff --git a/src/main/java/com/volmit/iris/util/ICommand.java b/src/main/java/com/volmit/iris/util/ICommand.java index f7a7a6da1..f2b207973 100644 --- a/src/main/java/com/volmit/iris/util/ICommand.java +++ b/src/main/java/com/volmit/iris/util/ICommand.java @@ -4,52 +4,47 @@ package com.volmit.iris.util; * Represents a pawn command * * @author cyberpwn - * */ -public interface ICommand -{ - public KList getRequiredPermissions(); +public interface ICommand { + KList getRequiredPermissions(); - /** - * Get the name of this command (node) - * - * @return the node - */ - public String getNode(); + /** + * Get the name of this command (node) + * + * @return the node + */ + String getNode(); - /** - * Get all (realized) nodes of this command - * - * @return the nodes - */ - public KList getNodes(); + /** + * Get all (realized) nodes of this command + * + * @return the nodes + */ + KList getNodes(); - /** - * Get all (every) node in this command - * - * @return all nodes - */ - public KList getAllNodes(); + /** + * Get all (every) node in this command + * + * @return all nodes + */ + KList getAllNodes(); - /** - * Add a node to this command - * - * @param node - * the node - */ - public void addNode(String node); + /** + * Add a node to this command + * + * @param node the node + */ + void addNode(String node); - /** - * Handle a command. If this is a subcommand, parameters after the subcommand - * will be adapted in args for you - * - * @param sender - * the volume sender (pre-tagged) - * @param args - * the arguments after this command node - * @return return true to mark it as handled - */ - public boolean handle(MortarSender sender, String[] args); + /** + * Handle a command. If this is a subcommand, parameters after the subcommand + * will be adapted in args for you + * + * @param sender the volume sender (pre-tagged) + * @param args the arguments after this command node + * @return return true to mark it as handled + */ + boolean handle(MortarSender sender, String[] args); - public KList handleTab(MortarSender sender, String[] args); + KList handleTab(MortarSender sender, String[] args); } diff --git a/src/main/java/com/volmit/iris/util/IController.java b/src/main/java/com/volmit/iris/util/IController.java index 03bf662d9..9f1e3133e 100644 --- a/src/main/java/com/volmit/iris/util/IController.java +++ b/src/main/java/com/volmit/iris/util/IController.java @@ -2,23 +2,22 @@ package com.volmit.iris.util; import org.bukkit.event.Listener; -public interface IController extends Listener -{ - public String getName(); +public interface IController extends Listener { + String getName(); - public void start(); + void start(); - public void stop(); + void stop(); - public void tick(); + void tick(); - public int getTickInterval(); + int getTickInterval(); - public void l(Object l); + void l(Object l); - public void w(Object l); + void w(Object l); - public void f(Object l); + void f(Object l); - public void v(Object l); + void v(Object l); } diff --git a/src/main/java/com/volmit/iris/util/ING.java b/src/main/java/com/volmit/iris/util/ING.java index 326a05b4e..8fe0930a9 100644 --- a/src/main/java/com/volmit/iris/util/ING.java +++ b/src/main/java/com/volmit/iris/util/ING.java @@ -1,9 +1,7 @@ package com.volmit.iris.util; -public class ING -{ - public ING(RNG rng) - { - - } +public class ING { + public ING(RNG rng) { + + } } diff --git a/src/main/java/com/volmit/iris/util/IO.java b/src/main/java/com/volmit/iris/util/IO.java index a19722976..212cbb5d4 100644 --- a/src/main/java/com/volmit/iris/util/IO.java +++ b/src/main/java/com/volmit/iris/util/IO.java @@ -1,1938 +1,1511 @@ package com.volmit.iris.util; -import java.io.BufferedInputStream; -import java.io.BufferedReader; -import java.io.ByteArrayInputStream; -import java.io.ByteArrayOutputStream; -import java.io.CharArrayWriter; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.FileOutputStream; -import java.io.FileReader; -import java.io.FileWriter; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.OutputStream; -import java.io.OutputStreamWriter; -import java.io.PrintWriter; -import java.io.Reader; -import java.io.StringWriter; -import java.io.Writer; +import java.io.*; import java.nio.charset.StandardCharsets; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; -import java.util.ArrayList; -import java.util.Base64; -import java.util.Collection; -import java.util.Enumeration; -import java.util.Iterator; -import java.util.List; +import java.util.*; import java.util.function.Consumer; import java.util.zip.GZIPInputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipException; import java.util.zip.ZipFile; -public class IO -{ - /** - * The Unix directory separator character. - */ - public static final char DIR_SEPARATOR_UNIX = '/'; - /** - * The Windows directory separator character. - */ - public static final char DIR_SEPARATOR_WINDOWS = '\\'; - /** - * The system directory separator character. - */ - public static final char DIR_SEPARATOR = File.separatorChar; - /** - * The Unix line separator string. - */ - public static final String LINE_SEPARATOR_UNIX = "\n"; - /** - * The Windows line separator string. - */ - public static final String LINE_SEPARATOR_WINDOWS = "\r\n"; - /** - * The system line separator string. - */ - public static final String LINE_SEPARATOR; - - /** - * The default buffer size to use. - */ - private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; - private final static char[] hexArray = "0123456789ABCDEF".toCharArray(); - - public static String decompress(String gz) throws IOException - { - ByteArrayInputStream bin = new ByteArrayInputStream(Base64.getUrlDecoder().decode(gz)); - GZIPInputStream gzi = new GZIPInputStream(bin); - ByteArrayOutputStream boas = new ByteArrayOutputStream(); - IO.fullTransfer(gzi, boas, 256); - gzi.close(); - - return new String(boas.toByteArray(), StandardCharsets.UTF_8); - } - - public static byte[] sdecompress(String compressed) throws IOException - { - ByteArrayInputStream bin = new ByteArrayInputStream(Base64.getUrlDecoder().decode(compressed)); - GZIPInputStream gzi = new GZIPInputStream(bin); - ByteArrayOutputStream boas = new ByteArrayOutputStream(); - IO.fullTransfer(gzi, boas, 256); - gzi.close(); - - return boas.toByteArray(); - } - - public static String encode(byte[] data) - { - return Base64.getUrlEncoder().encodeToString(data); - } - - public static byte[] decode(String u) - { - return Base64.getUrlDecoder().decode(u); - } - - public static String hash(String b) - { - try - { - MessageDigest d = MessageDigest.getInstance("SHA-256"); - return bytesToHex(d.digest(b.getBytes(StandardCharsets.UTF_8))); - } - - catch(NoSuchAlgorithmException e) - { - e.printStackTrace(); - } - - return "¯\\_(ツ)_/¯"; - } - - public static String hash(File b) - { - try - { - MessageDigest d = MessageDigest.getInstance("SHA-256"); - DigestInputStream din = new DigestInputStream(new FileInputStream(b), d); - fullTransfer(din, new VoidOutputStream(), 8192); - din.close(); - return bytesToHex(din.getMessageDigest().digest()); - } - - catch(Throwable e) - { - e.printStackTrace(); - } - - return "¯\\_(ツ)_/¯"; - } - - public static String bytesToHex(byte[] bytes) - { - char[] hexChars = new char[bytes.length * 2]; - for(int j = 0; j < bytes.length; j++) - { - int v = bytes[j] & 0xFF; - hexChars[j * 2] = hexArray[v >>> 4]; - hexChars[j * 2 + 1] = hexArray[v & 0x0F]; - } - - return new String(hexChars).toUpperCase(); - } - - /** - * Transfers the length of the buffer amount of data from the input stream to - * the output stream - * - * @param in - * the input - * @param out - * the output - * @param amount - * the buffer and size to use - * @return the actual transfered amount - * @throws IOException - * shit happens - */ - public static int transfer(InputStream in, OutputStream out, byte[] buffer) throws IOException - { - int r = in.read(buffer); - - if(r != -1) - { - out.write(buffer, 0, r); - } - - return r; - } - - /** - * Transfers the length of the buffer amount of data from the input stream to - * the output stream - * - * @param in - * the input - * @param out - * the output - * @param targetBuffer - * the buffer and size to use - * @param totalSize - * the total amount to transfer - * @return the actual transfered amount - * @throws IOException - * shit happens - */ - public static long transfer(InputStream in, OutputStream out, int targetBuffer, long totalSize) throws IOException - { - long total = totalSize; - long wrote = 0; - byte[] buf = new byte[targetBuffer]; - int r = 0; - - while((r = in.read(buf, 0, (int) (total < targetBuffer ? total : targetBuffer))) != -1) - { - total -= r; - out.write(buf, 0, r); - wrote += r; - - if(total <= 0) - { - break; - } - } - - return wrote; - } - - /** - * Fully move data from a finite inputstream to an output stream using a buffer - * size of 8192. This does NOT close streams. - * - * @param in - * @param out - * @return total size transfered - * @throws IOException - */ - public static long fillTransfer(InputStream in, OutputStream out) throws IOException - { - return fullTransfer(in, out, 8192); - } - - public static void deleteUp(File f) - { - if(f.exists()) - { - f.delete(); - - if(f.getParentFile().list().length == 0) - { - deleteUp(f.getParentFile()); - } - } - } - - /** - * Fully move data from a finite inputstream to an output stream using a given - * buffer size. This does NOT close streams. - * - * @param in - * the input stream to read from - * @param out - * the output stream to write to - * @param bufferSize - * the target buffer size - * @return total size transfered - * @throws IOException - * shit happens - */ - public static long fullTransfer(InputStream in, OutputStream out, int bufferSize) throws IOException - { - long wrote = 0; - byte[] buf = new byte[bufferSize]; - int r = 0; - - while((r = in.read(buf)) != -1) - { - out.write(buf, 0, r); - wrote += r; - } - - return wrote; - } - - /** - * Recursive delete (deleting folders) - * - * @param f - * the file to delete (and subfiles if folder) - */ - public static void delete(File f) - { - if(f == null || !f.exists()) - { - return; - } - - if(f.isDirectory()) - { - for(File i : f.listFiles()) - { - delete(i); - } - } - - f.delete(); - } - - public static long size(File file) - { - long s = 0; - - if(file.exists()) - { - if(file.isDirectory()) - { - for(File i : file.listFiles()) - { - s += size(i); - } - } - - else - { - s += file.length(); - } - } - - return s; - } - - public static long count(File file) - { - long s = 0; - - if(file.exists()) - { - if(file.isDirectory()) - { - for(File i : file.listFiles()) - { - s += count(i); - } - } - - else - { - s++; - } - } - - return s; - } - - public static long transfer(InputStream in, OutputStream out, byte[] buf, int totalSize) throws IOException - { - long total = totalSize; - long wrote = 0; - int r = 0; - - while((r = in.read(buf, 0, (int) (total < buf.length ? total : buf.length))) != -1) - { - total -= r; - out.write(buf, 0, r); - wrote += r; - - if(total <= 0) - { - break; - } - } - - return wrote; - } - - public static void readEntry(File zipfile, String entryname, Consumer v) throws ZipException, IOException - { - ZipFile file = new ZipFile(zipfile); - Throwable x = null; - - try - { - Enumeration entries = file.entries(); - while(entries.hasMoreElements()) - { - ZipEntry entry = entries.nextElement(); - - if(entryname.equals(entry.getName())) - { - InputStream in = file.getInputStream(entry); - v.accept(in); - } - } - } - - catch(Exception ex) - { - x = ex.getCause(); - } - - finally - { - file.close(); - } - - if(x != null) - { - throw new IOException("Failed to read zip entry, however it has been closed safely.", x); - } - } - - public static void writeAll(File f, Object c) throws IOException - { - f.getParentFile().mkdirs(); - PrintWriter pw = new PrintWriter(new FileWriter(f)); - pw.println(c.toString()); - pw.close(); - } - - public static String readAll(File f) throws IOException - { - FileReader fr; - try { - fr = new FileReader(f); - } catch (IOException e) { - throw e; - } - BufferedReader bu = new BufferedReader(fr); - String c = ""; - String l = ""; - - while((l = bu.readLine()) != null) - { - c += l + "\n"; - } - - bu.close(); - - return c; - } - - public static String readAll(InputStream in) throws IOException - { - BufferedReader bu = new BufferedReader(new InputStreamReader(in)); - String c = ""; - String l = ""; - - while((l = bu.readLine()) != null) - { - c += l + "\n"; - } - - bu.close(); - - return c; - } - - /** - * Implements the same behaviour as the "touch" utility on Unix. It creates a - * new file with size 0 or, if the file exists already, it is opened and closed - * without modifying it, but updating the file date and time. - * - * @param file - * the File to touch - * @throws IOException - * If an I/O problem occurs - */ - public static void touch(File file) throws IOException - { - if(!file.exists()) - { - OutputStream out = new FileOutputStream(file); - out.close(); - } - file.setLastModified(System.currentTimeMillis()); - } - - /** - * Copies a file to a new location preserving the file date. - *

- * This method copies the contents of the specified source file to the specified - * destination file. The directory holding the destination file is created if it - * does not exist. If the destination file exists, then this method will - * overwrite it. - * - * @param srcFile - * an existing file to copy, must not be null - * @param destFile - * the new file, must not be null - * - * @throws NullPointerException - * if source or destination is null - * @throws IOException - * if source or destination is invalid - * @throws IOException - * if an IO error occurs during copying - * @see #copyFileToDirectory - */ - public static void copyFile(File srcFile, File destFile) throws IOException - { - copyFile(srcFile, destFile, true); - } - - /** - * Copies a file to a new location. - *

- * This method copies the contents of the specified source file to the specified - * destination file. The directory holding the destination file is created if it - * does not exist. If the destination file exists, then this method will - * overwrite it. - * - * @param srcFile - * an existing file to copy, must not be null - * @param destFile - * the new file, must not be null - * @param preserveFileDate - * true if the file date of the copy should be the same as the - * original - * - * @throws NullPointerException - * if source or destination is null - * @throws IOException - * if source or destination is invalid - * @throws IOException - * if an IO error occurs during copying - * @see #copyFileToDirectory - */ - public static void copyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException - { - if(srcFile == null) - { - throw new NullPointerException("Source must not be null"); - } - if(destFile == null) - { - throw new NullPointerException("Destination must not be null"); - } - if(srcFile.exists() == false) - { - throw new FileNotFoundException("Source '" + srcFile + "' does not exist"); - } - if(srcFile.isDirectory()) - { - throw new IOException("Source '" + srcFile + "' exists but is a directory"); - } - if(srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) - { - throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same"); - } - if(destFile.getParentFile() != null && destFile.getParentFile().exists() == false) - { - if(destFile.getParentFile().mkdirs() == false) - { - throw new IOException("Destination '" + destFile + "' directory cannot be created"); - } - } - if(destFile.exists() && destFile.canWrite() == false) - { - throw new IOException("Destination '" + destFile + "' exists but is read-only"); - } - doCopyFile(srcFile, destFile, preserveFileDate); - } - - /** - * Internal copy file method. - * - * @param srcFile - * the validated source file, not null - * @param destFile - * the validated destination file, not null - * @param preserveFileDate - * whether to preserve the file date - * @throws IOException - * if an error occurs - */ - private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException - { - if(destFile.exists() && destFile.isDirectory()) - { - throw new IOException("Destination '" + destFile + "' exists but is a directory"); - } - - FileInputStream input = new FileInputStream(srcFile); - try - { - FileOutputStream output = new FileOutputStream(destFile); - try - { - IO.copy(input, output); - } - finally - { - output.close(); - } - } - finally - { - input.close(); - } - - if(srcFile.length() != destFile.length()) - { - throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); - } - if(preserveFileDate) - { - destFile.setLastModified(srcFile.lastModified()); - } - } - - // ----------------------------------------------------------------------- - /** - * Unconditionally close an Reader. - *

- * Equivalent to {@link Reader#close()}, except any exceptions will be ignored. - * This is typically used in finally blocks. - * - * @param input - * the Reader to close, may be null or already closed - */ - public static void closeQuietly(Reader input) - { - try - { - if(input != null) - { - input.close(); - } - } - catch(IOException ioe) - { - // ignore - } - } - - /** - * Unconditionally close a Writer. - *

- * Equivalent to {@link Writer#close()}, except any exceptions will be ignored. - * This is typically used in finally blocks. - * - * @param output - * the Writer to close, may be null or already closed - */ - public static void closeQuietly(Writer output) - { - try - { - if(output != null) - { - output.close(); - } - } - catch(IOException ioe) - { - // ignore - } - } - - /** - * Unconditionally close an InputStream. - *

- * Equivalent to {@link InputStream#close()}, except any exceptions will be - * ignored. This is typically used in finally blocks. - * - * @param input - * the InputStream to close, may be null or already closed - */ - public static void closeQuietly(InputStream input) - { - try - { - if(input != null) - { - input.close(); - } - } - catch(IOException ioe) - { - // ignore - } - } - - /** - * Unconditionally close an OutputStream. - *

- * Equivalent to {@link OutputStream#close()}, except any exceptions will be - * ignored. This is typically used in finally blocks. - * - * @param output - * the OutputStream to close, may be null or already closed - */ - public static void closeQuietly(OutputStream output) - { - try - { - if(output != null) - { - output.close(); - } - } - catch(IOException ioe) - { - // ignore - } - } - - // read toByteArray - // ----------------------------------------------------------------------- - /** - * Get the contents of an InputStream as a byte[]. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input - * the InputStream to read from - * @return the requested byte array - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - */ - public static byte[] toByteArray(InputStream input) throws IOException - { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - copy(input, output); - return output.toByteArray(); - } - - /** - * Get the contents of a Reader as a byte[] using the - * default character encoding of the platform. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - * - * @param input - * the Reader to read from - * @return the requested byte array - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - */ - public static byte[] toByteArray(Reader input) throws IOException - { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - copy(input, output); - return output.toByteArray(); - } - - /** - * Get the contents of a Reader as a byte[] using the - * specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - * - * @param input - * the Reader to read from - * @param encoding - * the encoding to use, null means platform default - * @return the requested byte array - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static byte[] toByteArray(Reader input, String encoding) throws IOException - { - ByteArrayOutputStream output = new ByteArrayOutputStream(); - copy(input, output, encoding); - return output.toByteArray(); - } - - /** - * Get the contents of a String as a byte[] using the - * default character encoding of the platform. - *

- * This is the same as {@link String#getBytes()}. - * - * @param input - * the String to convert - * @return the requested byte array - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs (never occurs) - * @deprecated Use {@link String#getBytes()} - */ - public static byte[] toByteArray(String input) throws IOException - { - return input.getBytes(); - } - - // read char[] - // ----------------------------------------------------------------------- - /** - * Get the contents of an InputStream as a character array using - * the default character encoding of the platform. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param is - * the InputStream to read from - * @return the requested character array - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static char[] toCharArray(InputStream is) throws IOException - { - CharArrayWriter output = new CharArrayWriter(); - copy(is, output); - return output.toCharArray(); - } - - /** - * Get the contents of an InputStream as a character array using - * the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param is - * the InputStream to read from - * @param encoding - * the encoding to use, null means platform default - * @return the requested character array - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static char[] toCharArray(InputStream is, String encoding) throws IOException - { - CharArrayWriter output = new CharArrayWriter(); - copy(is, output, encoding); - return output.toCharArray(); - } - - /** - * Get the contents of a Reader as a character array. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - * - * @param input - * the Reader to read from - * @return the requested character array - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static char[] toCharArray(Reader input) throws IOException - { - CharArrayWriter sw = new CharArrayWriter(); - copy(input, sw); - return sw.toCharArray(); - } - - // read toString - // ----------------------------------------------------------------------- - /** - * Get the contents of an InputStream as a String using the default - * character encoding of the platform. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input - * the InputStream to read from - * @return the requested String - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - */ - public static String toString(InputStream input) throws IOException - { - StringWriter sw = new StringWriter(); - copy(input, sw); - return sw.toString(); - } - - /** - * Get the contents of an InputStream as a String using the - * specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input - * the InputStream to read from - * @param encoding - * the encoding to use, null means platform default - * @return the requested String - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - */ - public static String toString(InputStream input, String encoding) throws IOException - { - StringWriter sw = new StringWriter(); - copy(input, sw, encoding); - return sw.toString(); - } - - /** - * Get the contents of a Reader as a String. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - * - * @param input - * the Reader to read from - * @return the requested String - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - */ - public static String toString(Reader input) throws IOException - { - StringWriter sw = new StringWriter(); - copy(input, sw); - return sw.toString(); - } - - /** - * Get the contents of a byte[] as a String using the default - * character encoding of the platform. - * - * @param input - * the byte array to read from - * @return the requested String - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs (never occurs) - * @deprecated Use {@link String#String(byte[])} - */ - public static String toString(byte[] input) throws IOException - { - return new String(input); - } - - /** - * Get the contents of a byte[] as a String using the specified - * character encoding. - *

- * Character encoding names can be found at - * IANA. - * - * @param input - * the byte array to read from - * @param encoding - * the encoding to use, null means platform default - * @return the requested String - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs (never occurs) - * @deprecated Use {@link String#String(byte[],String)} - */ - public static String toString(byte[] input, String encoding) throws IOException - { - if(encoding == null) - { - return new String(input); - } - else - { - return new String(input, encoding); - } - } - - // readLines - // ----------------------------------------------------------------------- - /** - * Get the contents of an InputStream as a list of Strings, one - * entry per line, using the default character encoding of the platform. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input - * the InputStream to read from, not null - * @return the list of Strings, never null - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static List readLines(InputStream input) throws IOException - { - InputStreamReader reader = new InputStreamReader(input); - return readLines(reader); - } - - /** - * Get the contents of an InputStream as a list of Strings, one - * entry per line, using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input - * the InputStream to read from, not null - * @param encoding - * the encoding to use, null means platform default - * @return the list of Strings, never null - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static List readLines(InputStream input, String encoding) throws IOException - { - if(encoding == null) - { - return readLines(input); - } - else - { - InputStreamReader reader = new InputStreamReader(input, encoding); - return readLines(reader); - } - } - - /** - * Get the contents of a Reader as a list of Strings, one entry per - * line. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - * - * @param input - * the Reader to read from, not null - * @return the list of Strings, never null - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static List readLines(Reader input) throws IOException - { - BufferedReader reader = new BufferedReader(input); - List list = new ArrayList(); - String line = reader.readLine(); - while(line != null) - { - list.add(line); - line = reader.readLine(); - } - return list; - } - - // ----------------------------------------------------------------------- - /** - * Convert the specified string to an input stream, encoded as bytes using the - * default character encoding of the platform. - * - * @param input - * the string to convert - * @return an input stream - * @since Commons IO 1.1 - */ - public static InputStream toInputStream(String input) - { - byte[] bytes = input.getBytes(); - return new ByteArrayInputStream(bytes); - } - - /** - * Convert the specified string to an input stream, encoded as bytes using the - * specified character encoding. - *

- * Character encoding names can be found at - * IANA. - * - * @param input - * the string to convert - * @param encoding - * the encoding to use, null means platform default - * @throws IOException - * if the encoding is invalid - * @return an input stream - * @since Commons IO 1.1 - */ - public static InputStream toInputStream(String input, String encoding) throws IOException - { - byte[] bytes = encoding != null ? input.getBytes(encoding) : input.getBytes(); - return new ByteArrayInputStream(bytes); - } - - // write byte[] - // ----------------------------------------------------------------------- - /** - * Writes bytes from a byte[] to an OutputStream. - * - * @param data - * the byte array to write, do not modify during output, null ignored - * @param output - * the OutputStream to write to - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(byte[] data, OutputStream output) throws IOException - { - if(data != null) - { - output.write(data); - } - } - - /** - * Writes bytes from a byte[] to chars on a Writer - * using the default character encoding of the platform. - *

- * This method uses {@link String#String(byte[])}. - * - * @param data - * the byte array to write, do not modify during output, null ignored - * @param output - * the Writer to write to - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(byte[] data, Writer output) throws IOException - { - if(data != null) - { - output.write(new String(data)); - } - } - - /** - * Writes bytes from a byte[] to chars on a Writer - * using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method uses {@link String#String(byte[], String)}. - * - * @param data - * the byte array to write, do not modify during output, null ignored - * @param output - * the Writer to write to - * @param encoding - * the encoding to use, null means platform default - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(byte[] data, Writer output, String encoding) throws IOException - { - if(data != null) - { - if(encoding == null) - { - write(data, output); - } - else - { - output.write(new String(data, encoding)); - } - } - } - - // write char[] - // ----------------------------------------------------------------------- - /** - * Writes chars from a char[] to a Writer using the - * default character encoding of the platform. - * - * @param data - * the char array to write, do not modify during output, null ignored - * @param output - * the Writer to write to - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(char[] data, Writer output) throws IOException - { - if(data != null) - { - output.write(data); - } - } - - /** - * Writes chars from a char[] to bytes on an - * OutputStream. - *

- * This method uses {@link String#String(char[])} and {@link String#getBytes()}. - * - * @param data - * the char array to write, do not modify during output, null ignored - * @param output - * the OutputStream to write to - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(char[] data, OutputStream output) throws IOException - { - if(data != null) - { - output.write(new String(data).getBytes()); - } - } - - /** - * Writes chars from a char[] to bytes on an - * OutputStream using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method uses {@link String#String(char[])} and - * {@link String#getBytes(String)}. - * - * @param data - * the char array to write, do not modify during output, null ignored - * @param output - * the OutputStream to write to - * @param encoding - * the encoding to use, null means platform default - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(char[] data, OutputStream output, String encoding) throws IOException - { - if(data != null) - { - if(encoding == null) - { - write(data, output); - } - else - { - output.write(new String(data).getBytes(encoding)); - } - } - } - - // write String - // ----------------------------------------------------------------------- - /** - * Writes chars from a String to a Writer. - * - * @param data - * the String to write, null ignored - * @param output - * the Writer to write to - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(String data, Writer output) throws IOException - { - if(data != null) - { - output.write(data); - } - } - - /** - * Writes chars from a String to bytes on an - * OutputStream using the default character encoding of the - * platform. - *

- * This method uses {@link String#getBytes()}. - * - * @param data - * the String to write, null ignored - * @param output - * the OutputStream to write to - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(String data, OutputStream output) throws IOException - { - if(data != null) - { - output.write(data.getBytes()); - } - } - - /** - * Writes chars from a String to bytes on an - * OutputStream using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method uses {@link String#getBytes(String)}. - * - * @param data - * the String to write, null ignored - * @param output - * the OutputStream to write to - * @param encoding - * the encoding to use, null means platform default - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(String data, OutputStream output, String encoding) throws IOException - { - if(data != null) - { - if(encoding == null) - { - write(data, output); - } - else - { - output.write(data.getBytes(encoding)); - } - } - } - - // write StringBuffer - // ----------------------------------------------------------------------- - /** - * Writes chars from a StringBuffer to a Writer. - * - * @param data - * the StringBuffer to write, null ignored - * @param output - * the Writer to write to - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(StringBuffer data, Writer output) throws IOException - { - if(data != null) - { - output.write(data.toString()); - } - } - - /** - * Writes chars from a StringBuffer to bytes on an - * OutputStream using the default character encoding of the - * platform. - *

- * This method uses {@link String#getBytes()}. - * - * @param data - * the StringBuffer to write, null ignored - * @param output - * the OutputStream to write to - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(StringBuffer data, OutputStream output) throws IOException - { - if(data != null) - { - output.write(data.toString().getBytes()); - } - } - - /** - * Writes chars from a StringBuffer to bytes on an - * OutputStream using the specified character encoding. - *

- * Character encoding names can be found at - * IANA. - *

- * This method uses {@link String#getBytes(String)}. - * - * @param data - * the StringBuffer to write, null ignored - * @param output - * the OutputStream to write to - * @param encoding - * the encoding to use, null means platform default - * @throws NullPointerException - * if output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void write(StringBuffer data, OutputStream output, String encoding) throws IOException - { - if(data != null) - { - if(encoding == null) - { - write(data, output); - } - else - { - output.write(data.toString().getBytes(encoding)); - } - } - } - - // writeLines - // ----------------------------------------------------------------------- - /** - * Writes the toString() value of each item in a collection to an - * OutputStream line by line, using the default character encoding - * of the platform and the specified line ending. - * - * @param lines - * the lines to write, null entries produce blank lines - * @param lineEnding - * the line separator to use, null is system default - * @param output - * the OutputStream to write to, not null, not closed - * @throws NullPointerException - * if the output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void writeLines(Collection lines, String lineEnding, OutputStream output) throws IOException - { - if(lines == null) - { - return; - } - if(lineEnding == null) - { - lineEnding = LINE_SEPARATOR; - } - for(Iterator it = lines.iterator(); it.hasNext();) - { - Object line = it.next(); - if(line != null) - { - output.write(line.toString().getBytes()); - } - output.write(lineEnding.getBytes()); - } - } - - /** - * Writes the toString() value of each item in a collection to an - * OutputStream line by line, using the specified character - * encoding and the specified line ending. - *

- * Character encoding names can be found at - * IANA. - * - * @param lines - * the lines to write, null entries produce blank lines - * @param lineEnding - * the line separator to use, null is system default - * @param output - * the OutputStream to write to, not null, not closed - * @param encoding - * the encoding to use, null means platform default - * @throws NullPointerException - * if the output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void writeLines(Collection lines, String lineEnding, OutputStream output, String encoding) throws IOException - { - if(encoding == null) - { - writeLines(lines, lineEnding, output); - } - else - { - if(lines == null) - { - return; - } - if(lineEnding == null) - { - lineEnding = LINE_SEPARATOR; - } - for(Iterator it = lines.iterator(); it.hasNext();) - { - Object line = it.next(); - if(line != null) - { - output.write(line.toString().getBytes(encoding)); - } - output.write(lineEnding.getBytes(encoding)); - } - } - } - - /** - * Writes the toString() value of each item in a collection to a - * Writer line by line, using the specified line ending. - * - * @param lines - * the lines to write, null entries produce blank lines - * @param lineEnding - * the line separator to use, null is system default - * @param writer - * the Writer to write to, not null, not closed - * @throws NullPointerException - * if the input is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void writeLines(Collection lines, String lineEnding, Writer writer) throws IOException - { - if(lines == null) - { - return; - } - if(lineEnding == null) - { - lineEnding = LINE_SEPARATOR; - } - for(Iterator it = lines.iterator(); it.hasNext();) - { - Object line = it.next(); - if(line != null) - { - writer.write(line.toString()); - } - writer.write(lineEnding); - } - } - - // copy from InputStream - // ----------------------------------------------------------------------- - /** - * Copy bytes from an InputStream to an OutputStream. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - *

- * Large streams (over 2GB) will return a bytes copied value of -1 - * after the copy has completed since the correct number of bytes cannot be - * returned as an int. For large streams use the - * copyLarge(InputStream, OutputStream) method. - * - * @param input - * the InputStream to read from - * @param output - * the OutputStream to write to - * @return the number of bytes copied - * @throws NullPointerException - * if the input or output is null - * @throws IOException - * if an I/O error occurs - * @throws ArithmeticException - * if the byte count is too large - * @since Commons IO 1.1 - */ - public static int copy(InputStream input, OutputStream output) throws IOException - { - long count = copyLarge(input, output); - if(count > Integer.MAX_VALUE) - { - return -1; - } - return (int) count; - } - - /** - * Copy bytes from a large (over 2GB) InputStream to an - * OutputStream. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - * - * @param input - * the InputStream to read from - * @param output - * the OutputStream to write to - * @return the number of bytes copied - * @throws NullPointerException - * if the input or output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.3 - */ - public static long copyLarge(InputStream input, OutputStream output) throws IOException - { - byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; - long count = 0; - int n = 0; - while(-1 != (n = input.read(buffer))) - { - output.write(buffer, 0, n); - count += n; - } - return count; - } - - /** - * Copy bytes from an InputStream to chars on a Writer - * using the default character encoding of the platform. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - *

- * This method uses {@link InputStreamReader}. - * - * @param input - * the InputStream to read from - * @param output - * the Writer to write to - * @throws NullPointerException - * if the input or output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void copy(InputStream input, Writer output) throws IOException - { - InputStreamReader in = new InputStreamReader(input); - copy(in, output); - } - - /** - * Copy bytes from an InputStream to chars on a Writer - * using the specified character encoding. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedInputStream. - *

- * Character encoding names can be found at - * IANA. - *

- * This method uses {@link InputStreamReader}. - * - * @param input - * the InputStream to read from - * @param output - * the Writer to write to - * @param encoding - * the encoding to use, null means platform default - * @throws NullPointerException - * if the input or output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void copy(InputStream input, Writer output, String encoding) throws IOException - { - if(encoding == null) - { - copy(input, output); - } - else - { - InputStreamReader in = new InputStreamReader(input, encoding); - copy(in, output); - } - } - - // copy from Reader - // ----------------------------------------------------------------------- - /** - * Copy chars from a Reader to a Writer. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - *

- * Large streams (over 2GB) will return a chars copied value of -1 - * after the copy has completed since the correct number of chars cannot be - * returned as an int. For large streams use the - * copyLarge(Reader, Writer) method. - * - * @param input - * the Reader to read from - * @param output - * the Writer to write to - * @return the number of characters copied - * @throws NullPointerException - * if the input or output is null - * @throws IOException - * if an I/O error occurs - * @throws ArithmeticException - * if the character count is too large - * @since Commons IO 1.1 - */ - public static int copy(Reader input, Writer output) throws IOException - { - long count = copyLarge(input, output); - if(count > Integer.MAX_VALUE) - { - return -1; - } - return (int) count; - } - - /** - * Copy chars from a large (over 2GB) Reader to a - * Writer. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - * - * @param input - * the Reader to read from - * @param output - * the Writer to write to - * @return the number of characters copied - * @throws NullPointerException - * if the input or output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.3 - */ - public static long copyLarge(Reader input, Writer output) throws IOException - { - char[] buffer = new char[DEFAULT_BUFFER_SIZE]; - long count = 0; - int n = 0; - while(-1 != (n = input.read(buffer))) - { - output.write(buffer, 0, n); - count += n; - } - return count; - } - - /** - * Copy chars from a Reader to bytes on an - * OutputStream using the default character encoding of the - * platform, and calling flush. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - *

- * Due to the implementation of OutputStreamWriter, this method performs a - * flush. - *

- * This method uses {@link OutputStreamWriter}. - * - * @param input - * the Reader to read from - * @param output - * the OutputStream to write to - * @throws NullPointerException - * if the input or output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void copy(Reader input, OutputStream output) throws IOException - { - OutputStreamWriter out = new OutputStreamWriter(output); - copy(input, out); - // have to flush here. - out.flush(); - } - - /** - * Copy chars from a Reader to bytes on an - * OutputStream using the specified character encoding, and calling - * flush. - *

- * This method buffers the input internally, so there is no need to use a - * BufferedReader. - *

- * Character encoding names can be found at - * IANA. - *

- * Due to the implementation of OutputStreamWriter, this method performs a - * flush. - *

- * This method uses {@link OutputStreamWriter}. - * - * @param input - * the Reader to read from - * @param output - * the OutputStream to write to - * @param encoding - * the encoding to use, null means platform default - * @throws NullPointerException - * if the input or output is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static void copy(Reader input, OutputStream output, String encoding) throws IOException - { - if(encoding == null) - { - copy(input, output); - } - else - { - OutputStreamWriter out = new OutputStreamWriter(output, encoding); - copy(input, out); - // we have to flush here. - out.flush(); - } - } - - // content equals - // ----------------------------------------------------------------------- - /** - * Compare the contents of two Streams to determine if they are equal or not. - *

- * This method buffers the input internally using - * BufferedInputStream if they are not already buffered. - * - * @param input1 - * the first stream - * @param input2 - * the second stream - * @return true if the content of the streams are equal or they both don't - * exist, false otherwise - * @throws NullPointerException - * if either input is null - * @throws IOException - * if an I/O error occurs - */ - public static boolean contentEquals(InputStream input1, InputStream input2) throws IOException - { - if(!(input1 instanceof BufferedInputStream)) - { - input1 = new BufferedInputStream(input1); - } - if(!(input2 instanceof BufferedInputStream)) - { - input2 = new BufferedInputStream(input2); - } - - int ch = input1.read(); - while(-1 != ch) - { - int ch2 = input2.read(); - if(ch != ch2) - { - return false; - } - ch = input1.read(); - } - - int ch2 = input2.read(); - return (ch2 == -1); - } - - /** - * Compare the contents of two Readers to determine if they are equal or not. - *

- * This method buffers the input internally using BufferedReader if - * they are not already buffered. - * - * @param input1 - * the first reader - * @param input2 - * the second reader - * @return true if the content of the readers are equal or they both don't - * exist, false otherwise - * @throws NullPointerException - * if either input is null - * @throws IOException - * if an I/O error occurs - * @since Commons IO 1.1 - */ - public static boolean contentEquals(Reader input1, Reader input2) throws IOException - { - if(!(input1 instanceof BufferedReader)) - { - input1 = new BufferedReader(input1); - } - if(!(input2 instanceof BufferedReader)) - { - input2 = new BufferedReader(input2); - } - - int ch = input1.read(); - while(-1 != ch) - { - int ch2 = input2.read(); - if(ch != ch2) - { - return false; - } - ch = input1.read(); - } - - int ch2 = input2.read(); - return (ch2 == -1); - } - - static - { - // avoid security issues - StringWriter buf = new StringWriter(4); - PrintWriter out = new PrintWriter(buf); - out.println(); - LINE_SEPARATOR = buf.toString(); - } +public class IO { + /** + * The Unix directory separator character. + */ + public static final char DIR_SEPARATOR_UNIX = '/'; + /** + * The Windows directory separator character. + */ + public static final char DIR_SEPARATOR_WINDOWS = '\\'; + /** + * The system directory separator character. + */ + public static final char DIR_SEPARATOR = File.separatorChar; + /** + * The Unix line separator string. + */ + public static final String LINE_SEPARATOR_UNIX = "\n"; + /** + * The Windows line separator string. + */ + public static final String LINE_SEPARATOR_WINDOWS = "\r\n"; + /** + * The system line separator string. + */ + public static final String LINE_SEPARATOR; + + /** + * The default buffer size to use. + */ + private static final int DEFAULT_BUFFER_SIZE = 1024 * 4; + private final static char[] hexArray = "0123456789ABCDEF".toCharArray(); + + public static String decompress(String gz) throws IOException { + ByteArrayInputStream bin = new ByteArrayInputStream(Base64.getUrlDecoder().decode(gz)); + GZIPInputStream gzi = new GZIPInputStream(bin); + ByteArrayOutputStream boas = new ByteArrayOutputStream(); + IO.fullTransfer(gzi, boas, 256); + gzi.close(); + + return boas.toString(StandardCharsets.UTF_8); + } + + public static byte[] sdecompress(String compressed) throws IOException { + ByteArrayInputStream bin = new ByteArrayInputStream(Base64.getUrlDecoder().decode(compressed)); + GZIPInputStream gzi = new GZIPInputStream(bin); + ByteArrayOutputStream boas = new ByteArrayOutputStream(); + IO.fullTransfer(gzi, boas, 256); + gzi.close(); + + return boas.toByteArray(); + } + + public static String encode(byte[] data) { + return Base64.getUrlEncoder().encodeToString(data); + } + + public static byte[] decode(String u) { + return Base64.getUrlDecoder().decode(u); + } + + public static String hash(String b) { + try { + MessageDigest d = MessageDigest.getInstance("SHA-256"); + return bytesToHex(d.digest(b.getBytes(StandardCharsets.UTF_8))); + } catch (NoSuchAlgorithmException e) { + e.printStackTrace(); + } + + return "¯\\_(ツ)_/¯"; + } + + public static String hash(File b) { + try { + MessageDigest d = MessageDigest.getInstance("SHA-256"); + DigestInputStream din = new DigestInputStream(new FileInputStream(b), d); + fullTransfer(din, new VoidOutputStream(), 8192); + din.close(); + return bytesToHex(din.getMessageDigest().digest()); + } catch (Throwable e) { + e.printStackTrace(); + } + + return "¯\\_(ツ)_/¯"; + } + + public static String bytesToHex(byte[] bytes) { + char[] hexChars = new char[bytes.length * 2]; + for (int j = 0; j < bytes.length; j++) { + int v = bytes[j] & 0xFF; + hexChars[j * 2] = hexArray[v >>> 4]; + hexChars[j * 2 + 1] = hexArray[v & 0x0F]; + } + + return new String(hexChars).toUpperCase(); + } + + /** + * Transfers the length of the buffer amount of data from the input stream to + * the output stream + * + * @param in the input + * @param out the output + * @param amount the buffer and size to use + * @return the actual transfered amount + * @throws IOException shit happens + */ + public static int transfer(InputStream in, OutputStream out, byte[] buffer) throws IOException { + int r = in.read(buffer); + + if (r != -1) { + out.write(buffer, 0, r); + } + + return r; + } + + /** + * Transfers the length of the buffer amount of data from the input stream to + * the output stream + * + * @param in the input + * @param out the output + * @param targetBuffer the buffer and size to use + * @param totalSize the total amount to transfer + * @return the actual transfered amount + * @throws IOException shit happens + */ + public static long transfer(InputStream in, OutputStream out, int targetBuffer, long totalSize) throws IOException { + long total = totalSize; + long wrote = 0; + byte[] buf = new byte[targetBuffer]; + int r = 0; + + while ((r = in.read(buf, 0, (int) (total < targetBuffer ? total : targetBuffer))) != -1) { + total -= r; + out.write(buf, 0, r); + wrote += r; + + if (total <= 0) { + break; + } + } + + return wrote; + } + + /** + * Fully move data from a finite inputstream to an output stream using a buffer + * size of 8192. This does NOT close streams. + * + * @param in + * @param out + * @return total size transfered + * @throws IOException + */ + public static long fillTransfer(InputStream in, OutputStream out) throws IOException { + return fullTransfer(in, out, 8192); + } + + public static void deleteUp(File f) { + if (f.exists()) { + f.delete(); + + if (f.getParentFile().list().length == 0) { + deleteUp(f.getParentFile()); + } + } + } + + /** + * Fully move data from a finite inputstream to an output stream using a given + * buffer size. This does NOT close streams. + * + * @param in the input stream to read from + * @param out the output stream to write to + * @param bufferSize the target buffer size + * @return total size transfered + * @throws IOException shit happens + */ + public static long fullTransfer(InputStream in, OutputStream out, int bufferSize) throws IOException { + long wrote = 0; + byte[] buf = new byte[bufferSize]; + int r = 0; + + while ((r = in.read(buf)) != -1) { + out.write(buf, 0, r); + wrote += r; + } + + return wrote; + } + + /** + * Recursive delete (deleting folders) + * + * @param f the file to delete (and subfiles if folder) + */ + public static void delete(File f) { + if (f == null || !f.exists()) { + return; + } + + if (f.isDirectory()) { + for (File i : f.listFiles()) { + delete(i); + } + } + + f.delete(); + } + + public static long size(File file) { + long s = 0; + + if (file.exists()) { + if (file.isDirectory()) { + for (File i : file.listFiles()) { + s += size(i); + } + } else { + s += file.length(); + } + } + + return s; + } + + public static long count(File file) { + long s = 0; + + if (file.exists()) { + if (file.isDirectory()) { + for (File i : file.listFiles()) { + s += count(i); + } + } else { + s++; + } + } + + return s; + } + + public static long transfer(InputStream in, OutputStream out, byte[] buf, int totalSize) throws IOException { + long total = totalSize; + long wrote = 0; + int r = 0; + + while ((r = in.read(buf, 0, (int) (total < buf.length ? total : buf.length))) != -1) { + total -= r; + out.write(buf, 0, r); + wrote += r; + + if (total <= 0) { + break; + } + } + + return wrote; + } + + public static void readEntry(File zipfile, String entryname, Consumer v) throws IOException { + ZipFile file = new ZipFile(zipfile); + Throwable x = null; + + try { + Enumeration entries = file.entries(); + while (entries.hasMoreElements()) { + ZipEntry entry = entries.nextElement(); + + if (entryname.equals(entry.getName())) { + InputStream in = file.getInputStream(entry); + v.accept(in); + } + } + } catch (Exception ex) { + x = ex.getCause(); + } finally { + file.close(); + } + + if (x != null) { + throw new IOException("Failed to read zip entry, however it has been closed safely.", x); + } + } + + public static void writeAll(File f, Object c) throws IOException { + f.getParentFile().mkdirs(); + PrintWriter pw = new PrintWriter(new FileWriter(f)); + pw.println(c.toString()); + pw.close(); + } + + public static String readAll(File f) throws IOException { + FileReader fr; + try { + fr = new FileReader(f); + } catch (IOException e) { + throw e; + } + BufferedReader bu = new BufferedReader(fr); + String c = ""; + String l = ""; + + while ((l = bu.readLine()) != null) { + c += l + "\n"; + } + + bu.close(); + + return c; + } + + public static String readAll(InputStream in) throws IOException { + BufferedReader bu = new BufferedReader(new InputStreamReader(in)); + String c = ""; + String l = ""; + + while ((l = bu.readLine()) != null) { + c += l + "\n"; + } + + bu.close(); + + return c; + } + + /** + * Implements the same behaviour as the "touch" utility on Unix. It creates a + * new file with size 0 or, if the file exists already, it is opened and closed + * without modifying it, but updating the file date and time. + * + * @param file the File to touch + * @throws IOException If an I/O problem occurs + */ + public static void touch(File file) throws IOException { + if (!file.exists()) { + OutputStream out = new FileOutputStream(file); + out.close(); + } + file.setLastModified(System.currentTimeMillis()); + } + + /** + * Copies a file to a new location preserving the file date. + *

+ * This method copies the contents of the specified source file to the specified + * destination file. The directory holding the destination file is created if it + * does not exist. If the destination file exists, then this method will + * overwrite it. + * + * @param srcFile an existing file to copy, must not be null + * @param destFile the new file, must not be null + * @throws NullPointerException if source or destination is null + * @throws IOException if source or destination is invalid + * @throws IOException if an IO error occurs during copying + * @see #copyFileToDirectory + */ + public static void copyFile(File srcFile, File destFile) throws IOException { + copyFile(srcFile, destFile, true); + } + + /** + * Copies a file to a new location. + *

+ * This method copies the contents of the specified source file to the specified + * destination file. The directory holding the destination file is created if it + * does not exist. If the destination file exists, then this method will + * overwrite it. + * + * @param srcFile an existing file to copy, must not be null + * @param destFile the new file, must not be null + * @param preserveFileDate true if the file date of the copy should be the same as the + * original + * @throws NullPointerException if source or destination is null + * @throws IOException if source or destination is invalid + * @throws IOException if an IO error occurs during copying + * @see #copyFileToDirectory + */ + public static void copyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { + if (srcFile == null) { + throw new NullPointerException("Source must not be null"); + } + if (destFile == null) { + throw new NullPointerException("Destination must not be null"); + } + if (srcFile.exists() == false) { + throw new FileNotFoundException("Source '" + srcFile + "' does not exist"); + } + if (srcFile.isDirectory()) { + throw new IOException("Source '" + srcFile + "' exists but is a directory"); + } + if (srcFile.getCanonicalPath().equals(destFile.getCanonicalPath())) { + throw new IOException("Source '" + srcFile + "' and destination '" + destFile + "' are the same"); + } + if (destFile.getParentFile() != null && destFile.getParentFile().exists() == false) { + if (destFile.getParentFile().mkdirs() == false) { + throw new IOException("Destination '" + destFile + "' directory cannot be created"); + } + } + if (destFile.exists() && destFile.canWrite() == false) { + throw new IOException("Destination '" + destFile + "' exists but is read-only"); + } + doCopyFile(srcFile, destFile, preserveFileDate); + } + + /** + * Internal copy file method. + * + * @param srcFile the validated source file, not null + * @param destFile the validated destination file, not null + * @param preserveFileDate whether to preserve the file date + * @throws IOException if an error occurs + */ + private static void doCopyFile(File srcFile, File destFile, boolean preserveFileDate) throws IOException { + if (destFile.exists() && destFile.isDirectory()) { + throw new IOException("Destination '" + destFile + "' exists but is a directory"); + } + + FileInputStream input = new FileInputStream(srcFile); + try { + FileOutputStream output = new FileOutputStream(destFile); + try { + IO.copy(input, output); + } finally { + output.close(); + } + } finally { + input.close(); + } + + if (srcFile.length() != destFile.length()) { + throw new IOException("Failed to copy full contents from '" + srcFile + "' to '" + destFile + "'"); + } + if (preserveFileDate) { + destFile.setLastModified(srcFile.lastModified()); + } + } + + // ----------------------------------------------------------------------- + + /** + * Unconditionally close an Reader. + *

+ * Equivalent to {@link Reader#close()}, except any exceptions will be ignored. + * This is typically used in finally blocks. + * + * @param input the Reader to close, may be null or already closed + */ + public static void closeQuietly(Reader input) { + try { + if (input != null) { + input.close(); + } + } catch (IOException ioe) { + // ignore + } + } + + /** + * Unconditionally close a Writer. + *

+ * Equivalent to {@link Writer#close()}, except any exceptions will be ignored. + * This is typically used in finally blocks. + * + * @param output the Writer to close, may be null or already closed + */ + public static void closeQuietly(Writer output) { + try { + if (output != null) { + output.close(); + } + } catch (IOException ioe) { + // ignore + } + } + + /** + * Unconditionally close an InputStream. + *

+ * Equivalent to {@link InputStream#close()}, except any exceptions will be + * ignored. This is typically used in finally blocks. + * + * @param input the InputStream to close, may be null or already closed + */ + public static void closeQuietly(InputStream input) { + try { + if (input != null) { + input.close(); + } + } catch (IOException ioe) { + // ignore + } + } + + /** + * Unconditionally close an OutputStream. + *

+ * Equivalent to {@link OutputStream#close()}, except any exceptions will be + * ignored. This is typically used in finally blocks. + * + * @param output the OutputStream to close, may be null or already closed + */ + public static void closeQuietly(OutputStream output) { + try { + if (output != null) { + output.close(); + } + } catch (IOException ioe) { + // ignore + } + } + + // read toByteArray + // ----------------------------------------------------------------------- + + /** + * Get the contents of an InputStream as a byte[]. + *

+ * This method buffers the input internally, so there is no need to use a + * BufferedInputStream. + * + * @param input the InputStream to read from + * @return the requested byte array + * @throws NullPointerException if the input is null + * @throws IOException if an I/O error occurs + */ + public static byte[] toByteArray(InputStream input) throws IOException { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + copy(input, output); + return output.toByteArray(); + } + + /** + * Get the contents of a Reader as a byte[] using the + * default character encoding of the platform. + *

+ * This method buffers the input internally, so there is no need to use a + * BufferedReader. + * + * @param input the Reader to read from + * @return the requested byte array + * @throws NullPointerException if the input is null + * @throws IOException if an I/O error occurs + */ + public static byte[] toByteArray(Reader input) throws IOException { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + copy(input, output); + return output.toByteArray(); + } + + /** + * Get the contents of a Reader as a byte[] using the + * specified character encoding. + *

+ * Character encoding names can be found at + * IANA. + *

+ * This method buffers the input internally, so there is no need to use a + * BufferedReader. + * + * @param input the Reader to read from + * @param encoding the encoding to use, null means platform default + * @return the requested byte array + * @throws NullPointerException if the input is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static byte[] toByteArray(Reader input, String encoding) throws IOException { + ByteArrayOutputStream output = new ByteArrayOutputStream(); + copy(input, output, encoding); + return output.toByteArray(); + } + + /** + * Get the contents of a String as a byte[] using the + * default character encoding of the platform. + *

+ * This is the same as {@link String#getBytes()}. + * + * @param input the String to convert + * @return the requested byte array + * @throws NullPointerException if the input is null + * @throws IOException if an I/O error occurs (never occurs) + * @deprecated Use {@link String#getBytes()} + */ + public static byte[] toByteArray(String input) throws IOException { + return input.getBytes(); + } + + // read char[] + // ----------------------------------------------------------------------- + + /** + * Get the contents of an InputStream as a character array using + * the default character encoding of the platform. + *

+ * This method buffers the input internally, so there is no need to use a + * BufferedInputStream. + * + * @param is the InputStream to read from + * @return the requested character array + * @throws NullPointerException if the input is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static char[] toCharArray(InputStream is) throws IOException { + CharArrayWriter output = new CharArrayWriter(); + copy(is, output); + return output.toCharArray(); + } + + /** + * Get the contents of an InputStream as a character array using + * the specified character encoding. + *

+ * Character encoding names can be found at + * IANA. + *

+ * This method buffers the input internally, so there is no need to use a + * BufferedInputStream. + * + * @param is the InputStream to read from + * @param encoding the encoding to use, null means platform default + * @return the requested character array + * @throws NullPointerException if the input is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static char[] toCharArray(InputStream is, String encoding) throws IOException { + CharArrayWriter output = new CharArrayWriter(); + copy(is, output, encoding); + return output.toCharArray(); + } + + /** + * Get the contents of a Reader as a character array. + *

+ * This method buffers the input internally, so there is no need to use a + * BufferedReader. + * + * @param input the Reader to read from + * @return the requested character array + * @throws NullPointerException if the input is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static char[] toCharArray(Reader input) throws IOException { + CharArrayWriter sw = new CharArrayWriter(); + copy(input, sw); + return sw.toCharArray(); + } + + // read toString + // ----------------------------------------------------------------------- + + /** + * Get the contents of an InputStream as a String using the default + * character encoding of the platform. + *

+ * This method buffers the input internally, so there is no need to use a + * BufferedInputStream. + * + * @param input the InputStream to read from + * @return the requested String + * @throws NullPointerException if the input is null + * @throws IOException if an I/O error occurs + */ + public static String toString(InputStream input) throws IOException { + StringWriter sw = new StringWriter(); + copy(input, sw); + return sw.toString(); + } + + /** + * Get the contents of an InputStream as a String using the + * specified character encoding. + *

+ * Character encoding names can be found at + * IANA. + *

+ * This method buffers the input internally, so there is no need to use a + * BufferedInputStream. + * + * @param input the InputStream to read from + * @param encoding the encoding to use, null means platform default + * @return the requested String + * @throws NullPointerException if the input is null + * @throws IOException if an I/O error occurs + */ + public static String toString(InputStream input, String encoding) throws IOException { + StringWriter sw = new StringWriter(); + copy(input, sw, encoding); + return sw.toString(); + } + + /** + * Get the contents of a Reader as a String. + *

+ * This method buffers the input internally, so there is no need to use a + * BufferedReader. + * + * @param input the Reader to read from + * @return the requested String + * @throws NullPointerException if the input is null + * @throws IOException if an I/O error occurs + */ + public static String toString(Reader input) throws IOException { + StringWriter sw = new StringWriter(); + copy(input, sw); + return sw.toString(); + } + + /** + * Get the contents of a byte[] as a String using the default + * character encoding of the platform. + * + * @param input the byte array to read from + * @return the requested String + * @throws NullPointerException if the input is null + * @throws IOException if an I/O error occurs (never occurs) + * @deprecated Use {@link String#String(byte[])} + */ + public static String toString(byte[] input) throws IOException { + return new String(input); + } + + /** + * Get the contents of a byte[] as a String using the specified + * character encoding. + *

+ * Character encoding names can be found at + * IANA. + * + * @param input the byte array to read from + * @param encoding the encoding to use, null means platform default + * @return the requested String + * @throws NullPointerException if the input is null + * @throws IOException if an I/O error occurs (never occurs) + * @deprecated Use {@link String#String(byte[], String)} + */ + public static String toString(byte[] input, String encoding) throws IOException { + if (encoding == null) { + return new String(input); + } else { + return new String(input, encoding); + } + } + + // readLines + // ----------------------------------------------------------------------- + + /** + * Get the contents of an InputStream as a list of Strings, one + * entry per line, using the default character encoding of the platform. + *

+ * This method buffers the input internally, so there is no need to use a + * BufferedInputStream. + * + * @param input the InputStream to read from, not null + * @return the list of Strings, never null + * @throws NullPointerException if the input is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static List readLines(InputStream input) throws IOException { + InputStreamReader reader = new InputStreamReader(input); + return readLines(reader); + } + + /** + * Get the contents of an InputStream as a list of Strings, one + * entry per line, using the specified character encoding. + *

+ * Character encoding names can be found at + * IANA. + *

+ * This method buffers the input internally, so there is no need to use a + * BufferedInputStream. + * + * @param input the InputStream to read from, not null + * @param encoding the encoding to use, null means platform default + * @return the list of Strings, never null + * @throws NullPointerException if the input is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static List readLines(InputStream input, String encoding) throws IOException { + if (encoding == null) { + return readLines(input); + } else { + InputStreamReader reader = new InputStreamReader(input, encoding); + return readLines(reader); + } + } + + /** + * Get the contents of a Reader as a list of Strings, one entry per + * line. + *

+ * This method buffers the input internally, so there is no need to use a + * BufferedReader. + * + * @param input the Reader to read from, not null + * @return the list of Strings, never null + * @throws NullPointerException if the input is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static List readLines(Reader input) throws IOException { + BufferedReader reader = new BufferedReader(input); + List list = new ArrayList(); + String line = reader.readLine(); + while (line != null) { + list.add(line); + line = reader.readLine(); + } + return list; + } + + // ----------------------------------------------------------------------- + + /** + * Convert the specified string to an input stream, encoded as bytes using the + * default character encoding of the platform. + * + * @param input the string to convert + * @return an input stream + * @since Commons IO 1.1 + */ + public static InputStream toInputStream(String input) { + byte[] bytes = input.getBytes(); + return new ByteArrayInputStream(bytes); + } + + /** + * Convert the specified string to an input stream, encoded as bytes using the + * specified character encoding. + *

+ * Character encoding names can be found at + * IANA. + * + * @param input the string to convert + * @param encoding the encoding to use, null means platform default + * @return an input stream + * @throws IOException if the encoding is invalid + * @since Commons IO 1.1 + */ + public static InputStream toInputStream(String input, String encoding) throws IOException { + byte[] bytes = encoding != null ? input.getBytes(encoding) : input.getBytes(); + return new ByteArrayInputStream(bytes); + } + + // write byte[] + // ----------------------------------------------------------------------- + + /** + * Writes bytes from a byte[] to an OutputStream. + * + * @param data the byte array to write, do not modify during output, null ignored + * @param output the OutputStream to write to + * @throws NullPointerException if output is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static void write(byte[] data, OutputStream output) throws IOException { + if (data != null) { + output.write(data); + } + } + + /** + * Writes bytes from a byte[] to chars on a Writer + * using the default character encoding of the platform. + *

+ * This method uses {@link String#String(byte[])}. + * + * @param data the byte array to write, do not modify during output, null ignored + * @param output the Writer to write to + * @throws NullPointerException if output is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static void write(byte[] data, Writer output) throws IOException { + if (data != null) { + output.write(new String(data)); + } + } + + /** + * Writes bytes from a byte[] to chars on a Writer + * using the specified character encoding. + *

+ * Character encoding names can be found at + * IANA. + *

+ * This method uses {@link String#String(byte[], String)}. + * + * @param data the byte array to write, do not modify during output, null ignored + * @param output the Writer to write to + * @param encoding the encoding to use, null means platform default + * @throws NullPointerException if output is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static void write(byte[] data, Writer output, String encoding) throws IOException { + if (data != null) { + if (encoding == null) { + write(data, output); + } else { + output.write(new String(data, encoding)); + } + } + } + + // write char[] + // ----------------------------------------------------------------------- + + /** + * Writes chars from a char[] to a Writer using the + * default character encoding of the platform. + * + * @param data the char array to write, do not modify during output, null ignored + * @param output the Writer to write to + * @throws NullPointerException if output is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static void write(char[] data, Writer output) throws IOException { + if (data != null) { + output.write(data); + } + } + + /** + * Writes chars from a char[] to bytes on an + * OutputStream. + *

+ * This method uses {@link String#String(char[])} and {@link String#getBytes()}. + * + * @param data the char array to write, do not modify during output, null ignored + * @param output the OutputStream to write to + * @throws NullPointerException if output is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static void write(char[] data, OutputStream output) throws IOException { + if (data != null) { + output.write(new String(data).getBytes()); + } + } + + /** + * Writes chars from a char[] to bytes on an + * OutputStream using the specified character encoding. + *

+ * Character encoding names can be found at + * IANA. + *

+ * This method uses {@link String#String(char[])} and + * {@link String#getBytes(String)}. + * + * @param data the char array to write, do not modify during output, null ignored + * @param output the OutputStream to write to + * @param encoding the encoding to use, null means platform default + * @throws NullPointerException if output is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static void write(char[] data, OutputStream output, String encoding) throws IOException { + if (data != null) { + if (encoding == null) { + write(data, output); + } else { + output.write(new String(data).getBytes(encoding)); + } + } + } + + // write String + // ----------------------------------------------------------------------- + + /** + * Writes chars from a String to a Writer. + * + * @param data the String to write, null ignored + * @param output the Writer to write to + * @throws NullPointerException if output is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static void write(String data, Writer output) throws IOException { + if (data != null) { + output.write(data); + } + } + + /** + * Writes chars from a String to bytes on an + * OutputStream using the default character encoding of the + * platform. + *

+ * This method uses {@link String#getBytes()}. + * + * @param data the String to write, null ignored + * @param output the OutputStream to write to + * @throws NullPointerException if output is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static void write(String data, OutputStream output) throws IOException { + if (data != null) { + output.write(data.getBytes()); + } + } + + /** + * Writes chars from a String to bytes on an + * OutputStream using the specified character encoding. + *

+ * Character encoding names can be found at + * IANA. + *

+ * This method uses {@link String#getBytes(String)}. + * + * @param data the String to write, null ignored + * @param output the OutputStream to write to + * @param encoding the encoding to use, null means platform default + * @throws NullPointerException if output is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static void write(String data, OutputStream output, String encoding) throws IOException { + if (data != null) { + if (encoding == null) { + write(data, output); + } else { + output.write(data.getBytes(encoding)); + } + } + } + + // write StringBuffer + // ----------------------------------------------------------------------- + + /** + * Writes chars from a StringBuffer to a Writer. + * + * @param data the StringBuffer to write, null ignored + * @param output the Writer to write to + * @throws NullPointerException if output is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static void write(StringBuffer data, Writer output) throws IOException { + if (data != null) { + output.write(data.toString()); + } + } + + /** + * Writes chars from a StringBuffer to bytes on an + * OutputStream using the default character encoding of the + * platform. + *

+ * This method uses {@link String#getBytes()}. + * + * @param data the StringBuffer to write, null ignored + * @param output the OutputStream to write to + * @throws NullPointerException if output is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static void write(StringBuffer data, OutputStream output) throws IOException { + if (data != null) { + output.write(data.toString().getBytes()); + } + } + + /** + * Writes chars from a StringBuffer to bytes on an + * OutputStream using the specified character encoding. + *

+ * Character encoding names can be found at + * IANA. + *

+ * This method uses {@link String#getBytes(String)}. + * + * @param data the StringBuffer to write, null ignored + * @param output the OutputStream to write to + * @param encoding the encoding to use, null means platform default + * @throws NullPointerException if output is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static void write(StringBuffer data, OutputStream output, String encoding) throws IOException { + if (data != null) { + if (encoding == null) { + write(data, output); + } else { + output.write(data.toString().getBytes(encoding)); + } + } + } + + // writeLines + // ----------------------------------------------------------------------- + + /** + * Writes the toString() value of each item in a collection to an + * OutputStream line by line, using the default character encoding + * of the platform and the specified line ending. + * + * @param lines the lines to write, null entries produce blank lines + * @param lineEnding the line separator to use, null is system default + * @param output the OutputStream to write to, not null, not closed + * @throws NullPointerException if the output is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static void writeLines(Collection lines, String lineEnding, OutputStream output) throws IOException { + if (lines == null) { + return; + } + if (lineEnding == null) { + lineEnding = LINE_SEPARATOR; + } + for (Iterator it = lines.iterator(); it.hasNext(); ) { + Object line = it.next(); + if (line != null) { + output.write(line.toString().getBytes()); + } + output.write(lineEnding.getBytes()); + } + } + + /** + * Writes the toString() value of each item in a collection to an + * OutputStream line by line, using the specified character + * encoding and the specified line ending. + *

+ * Character encoding names can be found at + * IANA. + * + * @param lines the lines to write, null entries produce blank lines + * @param lineEnding the line separator to use, null is system default + * @param output the OutputStream to write to, not null, not closed + * @param encoding the encoding to use, null means platform default + * @throws NullPointerException if the output is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static void writeLines(Collection lines, String lineEnding, OutputStream output, String encoding) throws IOException { + if (encoding == null) { + writeLines(lines, lineEnding, output); + } else { + if (lines == null) { + return; + } + if (lineEnding == null) { + lineEnding = LINE_SEPARATOR; + } + for (Iterator it = lines.iterator(); it.hasNext(); ) { + Object line = it.next(); + if (line != null) { + output.write(line.toString().getBytes(encoding)); + } + output.write(lineEnding.getBytes(encoding)); + } + } + } + + /** + * Writes the toString() value of each item in a collection to a + * Writer line by line, using the specified line ending. + * + * @param lines the lines to write, null entries produce blank lines + * @param lineEnding the line separator to use, null is system default + * @param writer the Writer to write to, not null, not closed + * @throws NullPointerException if the input is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static void writeLines(Collection lines, String lineEnding, Writer writer) throws IOException { + if (lines == null) { + return; + } + if (lineEnding == null) { + lineEnding = LINE_SEPARATOR; + } + for (Iterator it = lines.iterator(); it.hasNext(); ) { + Object line = it.next(); + if (line != null) { + writer.write(line.toString()); + } + writer.write(lineEnding); + } + } + + // copy from InputStream + // ----------------------------------------------------------------------- + + /** + * Copy bytes from an InputStream to an OutputStream. + *

+ * This method buffers the input internally, so there is no need to use a + * BufferedInputStream. + *

+ * Large streams (over 2GB) will return a bytes copied value of -1 + * after the copy has completed since the correct number of bytes cannot be + * returned as an int. For large streams use the + * copyLarge(InputStream, OutputStream) method. + * + * @param input the InputStream to read from + * @param output the OutputStream to write to + * @return the number of bytes copied + * @throws NullPointerException if the input or output is null + * @throws IOException if an I/O error occurs + * @throws ArithmeticException if the byte count is too large + * @since Commons IO 1.1 + */ + public static int copy(InputStream input, OutputStream output) throws IOException { + long count = copyLarge(input, output); + if (count > Integer.MAX_VALUE) { + return -1; + } + return (int) count; + } + + /** + * Copy bytes from a large (over 2GB) InputStream to an + * OutputStream. + *

+ * This method buffers the input internally, so there is no need to use a + * BufferedInputStream. + * + * @param input the InputStream to read from + * @param output the OutputStream to write to + * @return the number of bytes copied + * @throws NullPointerException if the input or output is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.3 + */ + public static long copyLarge(InputStream input, OutputStream output) throws IOException { + byte[] buffer = new byte[DEFAULT_BUFFER_SIZE]; + long count = 0; + int n = 0; + while (-1 != (n = input.read(buffer))) { + output.write(buffer, 0, n); + count += n; + } + return count; + } + + /** + * Copy bytes from an InputStream to chars on a Writer + * using the default character encoding of the platform. + *

+ * This method buffers the input internally, so there is no need to use a + * BufferedInputStream. + *

+ * This method uses {@link InputStreamReader}. + * + * @param input the InputStream to read from + * @param output the Writer to write to + * @throws NullPointerException if the input or output is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static void copy(InputStream input, Writer output) throws IOException { + InputStreamReader in = new InputStreamReader(input); + copy(in, output); + } + + /** + * Copy bytes from an InputStream to chars on a Writer + * using the specified character encoding. + *

+ * This method buffers the input internally, so there is no need to use a + * BufferedInputStream. + *

+ * Character encoding names can be found at + * IANA. + *

+ * This method uses {@link InputStreamReader}. + * + * @param input the InputStream to read from + * @param output the Writer to write to + * @param encoding the encoding to use, null means platform default + * @throws NullPointerException if the input or output is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static void copy(InputStream input, Writer output, String encoding) throws IOException { + if (encoding == null) { + copy(input, output); + } else { + InputStreamReader in = new InputStreamReader(input, encoding); + copy(in, output); + } + } + + // copy from Reader + // ----------------------------------------------------------------------- + + /** + * Copy chars from a Reader to a Writer. + *

+ * This method buffers the input internally, so there is no need to use a + * BufferedReader. + *

+ * Large streams (over 2GB) will return a chars copied value of -1 + * after the copy has completed since the correct number of chars cannot be + * returned as an int. For large streams use the + * copyLarge(Reader, Writer) method. + * + * @param input the Reader to read from + * @param output the Writer to write to + * @return the number of characters copied + * @throws NullPointerException if the input or output is null + * @throws IOException if an I/O error occurs + * @throws ArithmeticException if the character count is too large + * @since Commons IO 1.1 + */ + public static int copy(Reader input, Writer output) throws IOException { + long count = copyLarge(input, output); + if (count > Integer.MAX_VALUE) { + return -1; + } + return (int) count; + } + + /** + * Copy chars from a large (over 2GB) Reader to a + * Writer. + *

+ * This method buffers the input internally, so there is no need to use a + * BufferedReader. + * + * @param input the Reader to read from + * @param output the Writer to write to + * @return the number of characters copied + * @throws NullPointerException if the input or output is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.3 + */ + public static long copyLarge(Reader input, Writer output) throws IOException { + char[] buffer = new char[DEFAULT_BUFFER_SIZE]; + long count = 0; + int n = 0; + while (-1 != (n = input.read(buffer))) { + output.write(buffer, 0, n); + count += n; + } + return count; + } + + /** + * Copy chars from a Reader to bytes on an + * OutputStream using the default character encoding of the + * platform, and calling flush. + *

+ * This method buffers the input internally, so there is no need to use a + * BufferedReader. + *

+ * Due to the implementation of OutputStreamWriter, this method performs a + * flush. + *

+ * This method uses {@link OutputStreamWriter}. + * + * @param input the Reader to read from + * @param output the OutputStream to write to + * @throws NullPointerException if the input or output is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static void copy(Reader input, OutputStream output) throws IOException { + OutputStreamWriter out = new OutputStreamWriter(output); + copy(input, out); + // have to flush here. + out.flush(); + } + + /** + * Copy chars from a Reader to bytes on an + * OutputStream using the specified character encoding, and calling + * flush. + *

+ * This method buffers the input internally, so there is no need to use a + * BufferedReader. + *

+ * Character encoding names can be found at + * IANA. + *

+ * Due to the implementation of OutputStreamWriter, this method performs a + * flush. + *

+ * This method uses {@link OutputStreamWriter}. + * + * @param input the Reader to read from + * @param output the OutputStream to write to + * @param encoding the encoding to use, null means platform default + * @throws NullPointerException if the input or output is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static void copy(Reader input, OutputStream output, String encoding) throws IOException { + if (encoding == null) { + copy(input, output); + } else { + OutputStreamWriter out = new OutputStreamWriter(output, encoding); + copy(input, out); + // we have to flush here. + out.flush(); + } + } + + // content equals + // ----------------------------------------------------------------------- + + /** + * Compare the contents of two Streams to determine if they are equal or not. + *

+ * This method buffers the input internally using + * BufferedInputStream if they are not already buffered. + * + * @param input1 the first stream + * @param input2 the second stream + * @return true if the content of the streams are equal or they both don't + * exist, false otherwise + * @throws NullPointerException if either input is null + * @throws IOException if an I/O error occurs + */ + public static boolean contentEquals(InputStream input1, InputStream input2) throws IOException { + if (!(input1 instanceof BufferedInputStream)) { + input1 = new BufferedInputStream(input1); + } + if (!(input2 instanceof BufferedInputStream)) { + input2 = new BufferedInputStream(input2); + } + + int ch = input1.read(); + while (-1 != ch) { + int ch2 = input2.read(); + if (ch != ch2) { + return false; + } + ch = input1.read(); + } + + int ch2 = input2.read(); + return (ch2 == -1); + } + + /** + * Compare the contents of two Readers to determine if they are equal or not. + *

+ * This method buffers the input internally using BufferedReader if + * they are not already buffered. + * + * @param input1 the first reader + * @param input2 the second reader + * @return true if the content of the readers are equal or they both don't + * exist, false otherwise + * @throws NullPointerException if either input is null + * @throws IOException if an I/O error occurs + * @since Commons IO 1.1 + */ + public static boolean contentEquals(Reader input1, Reader input2) throws IOException { + if (!(input1 instanceof BufferedReader)) { + input1 = new BufferedReader(input1); + } + if (!(input2 instanceof BufferedReader)) { + input2 = new BufferedReader(input2); + } + + int ch = input1.read(); + while (-1 != ch) { + int ch2 = input2.read(); + if (ch != ch2) { + return false; + } + ch = input1.read(); + } + + int ch2 = input2.read(); + return (ch2 == -1); + } + + static { + // avoid security issues + StringWriter buf = new StringWriter(4); + PrintWriter out = new PrintWriter(buf); + out.println(); + LINE_SEPARATOR = buf.toString(); + } } diff --git a/src/main/java/com/volmit/iris/util/IORunnable.java b/src/main/java/com/volmit/iris/util/IORunnable.java index 010fd7366..e51fc8a3e 100644 --- a/src/main/java/com/volmit/iris/util/IORunnable.java +++ b/src/main/java/com/volmit/iris/util/IORunnable.java @@ -2,7 +2,6 @@ package com.volmit.iris.util; import java.io.IOException; -public interface IORunnable -{ - public void run() throws IOException; +public interface IORunnable { + void run() throws IOException; } diff --git a/src/main/java/com/volmit/iris/util/IObjectPlacer.java b/src/main/java/com/volmit/iris/util/IObjectPlacer.java index 8f96223af..f6e6cbb24 100644 --- a/src/main/java/com/volmit/iris/util/IObjectPlacer.java +++ b/src/main/java/com/volmit/iris/util/IObjectPlacer.java @@ -4,25 +4,24 @@ import com.volmit.iris.object.tile.TileData; import org.bukkit.block.TileState; import org.bukkit.block.data.BlockData; -public interface IObjectPlacer -{ - public int getHighest(int x, int z); +public interface IObjectPlacer { + int getHighest(int x, int z); - public int getHighest(int x, int z, boolean ignoreFluid); + int getHighest(int x, int z, boolean ignoreFluid); - public void set(int x, int y, int z, BlockData d); + void set(int x, int y, int z, BlockData d); - public BlockData get(int x, int y, int z); + BlockData get(int x, int y, int z); - public boolean isPreventingDecay(); + boolean isPreventingDecay(); - public boolean isSolid(int x, int y, int z); + boolean isSolid(int x, int y, int z); - public boolean isUnderwater(int x, int z); + boolean isUnderwater(int x, int z); - public int getFluidHeight(); + int getFluidHeight(); - public boolean isDebugSmartBore(); + boolean isDebugSmartBore(); void setTile(int xx, int yy, int zz, TileData tile); } diff --git a/src/main/java/com/volmit/iris/util/IPostBlockAccess.java b/src/main/java/com/volmit/iris/util/IPostBlockAccess.java index 631d341ad..04a5ac71d 100644 --- a/src/main/java/com/volmit/iris/util/IPostBlockAccess.java +++ b/src/main/java/com/volmit/iris/util/IPostBlockAccess.java @@ -3,17 +3,16 @@ package com.volmit.iris.util; import org.bukkit.block.data.BlockData; import org.bukkit.generator.ChunkGenerator.ChunkData; -public interface IPostBlockAccess -{ - public BlockData getPostBlock(int x, int y, int z, int currentPostX, int currentPostZ, ChunkData currentData); +public interface IPostBlockAccess { + BlockData getPostBlock(int x, int y, int z, int currentPostX, int currentPostZ, ChunkData currentData); - public void setPostBlock(int x, int y, int z, BlockData d, int currentPostX, int currentPostZ, ChunkData currentData); + void setPostBlock(int x, int y, int z, BlockData d, int currentPostX, int currentPostZ, ChunkData currentData); - public int highestTerrainOrFluidBlock(int x, int z); + int highestTerrainOrFluidBlock(int x, int z); - public int highestTerrainBlock(int x, int z); + int highestTerrainBlock(int x, int z); - public void updateHeight(int x, int z, int h); + void updateHeight(int x, int z, int h); - public KList caveFloors(int x, int z); + KList caveFloors(int x, int z); } diff --git a/src/main/java/com/volmit/iris/util/IRare.java b/src/main/java/com/volmit/iris/util/IRare.java index 441fa3baf..59e950e1e 100644 --- a/src/main/java/com/volmit/iris/util/IRare.java +++ b/src/main/java/com/volmit/iris/util/IRare.java @@ -1,11 +1,9 @@ package com.volmit.iris.util; -public interface IRare -{ - public int getRarity(); +public interface IRare { + int getRarity(); - public static int get(Object v) - { - return v instanceof IRare ? ((IRare) v).getRarity() : 1; - } + static int get(Object v) { + return v instanceof IRare ? ((IRare) v).getRarity() : 1; + } } diff --git a/src/main/java/com/volmit/iris/util/Info.java b/src/main/java/com/volmit/iris/util/Info.java index 5fad9857f..6012e269b 100644 --- a/src/main/java/com/volmit/iris/util/Info.java +++ b/src/main/java/com/volmit/iris/util/Info.java @@ -2,10 +2,8 @@ package com.volmit.iris.util; import org.bukkit.Bukkit; -public class Info -{ - public static String getPortIP() - { - return Bukkit.getPort() + Bukkit.getIp(); - } +public class Info { + public static String getPortIP() { + return Bukkit.getPort() + Bukkit.getIp(); + } } diff --git a/src/main/java/com/volmit/iris/util/Instance.java b/src/main/java/com/volmit/iris/util/Instance.java index dbdb027a9..cc9bb9340 100644 --- a/src/main/java/com/volmit/iris/util/Instance.java +++ b/src/main/java/com/volmit/iris/util/Instance.java @@ -1,14 +1,13 @@ package com.volmit.iris.util; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - 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 Instance -{ +public @interface Instance { } diff --git a/src/main/java/com/volmit/iris/util/IntArrayTag.java b/src/main/java/com/volmit/iris/util/IntArrayTag.java index 195d1cf20..8e17906ba 100644 --- a/src/main/java/com/volmit/iris/util/IntArrayTag.java +++ b/src/main/java/com/volmit/iris/util/IntArrayTag.java @@ -4,24 +4,24 @@ import java.util.Arrays; /* * JNBT License - * + * * Copyright (c) 2015 Neil Wightman * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. - * + * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * * Neither the name of the JNBT team nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -32,13 +32,13 @@ import java.util.Arrays; * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * POSSIBILITY OF SUCH DAMAGE. */ + /** * The TAG_Int_Array tag. * * @author Neil Wightman - * */ public final class IntArrayTag extends Tag { @@ -50,7 +50,7 @@ public final class IntArrayTag extends Tag { /** * Creates the tag. * - * @param name The name. + * @param name The name. * @param value The value. */ public IntArrayTag(String name, int[] value) { diff --git a/src/main/java/com/volmit/iris/util/IntTag.java b/src/main/java/com/volmit/iris/util/IntTag.java index 223a4d32c..88fb30452 100644 --- a/src/main/java/com/volmit/iris/util/IntTag.java +++ b/src/main/java/com/volmit/iris/util/IntTag.java @@ -2,24 +2,24 @@ package com.volmit.iris.util; /* * JNBT License - * + * * Copyright (c) 2010 Graham Edgecombe * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. - * + * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * * Neither the name of the JNBT team nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -30,13 +30,13 @@ package com.volmit.iris.util; * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * POSSIBILITY OF SUCH DAMAGE. */ + /** * The TAG_Int tag. * * @author Graham Edgecombe - * */ public final class IntTag extends Tag { @@ -48,7 +48,7 @@ public final class IntTag extends Tag { /** * Creates the tag. * - * @param name The name. + * @param name The name. * @param value The value. */ public IntTag(String name, int value) { diff --git a/src/main/java/com/volmit/iris/util/InterpolationType.java b/src/main/java/com/volmit/iris/util/InterpolationType.java index 9745f7f5e..cf4ca0aa1 100644 --- a/src/main/java/com/volmit/iris/util/InterpolationType.java +++ b/src/main/java/com/volmit/iris/util/InterpolationType.java @@ -1,9 +1,9 @@ package com.volmit.iris.util; -public enum InterpolationType -{ - LINEAR, - PARAMETRIC_2, - PARAMETRIC_4, - BEZIER, - NONE; + +public enum InterpolationType { + LINEAR, + PARAMETRIC_2, + PARAMETRIC_4, + BEZIER, + NONE } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/InvertedBiomeGrid.java b/src/main/java/com/volmit/iris/util/InvertedBiomeGrid.java index 81f5641a1..ea1fcf044 100644 --- a/src/main/java/com/volmit/iris/util/InvertedBiomeGrid.java +++ b/src/main/java/com/volmit/iris/util/InvertedBiomeGrid.java @@ -1,53 +1,44 @@ package com.volmit.iris.util; +import com.volmit.iris.Iris; import org.bukkit.block.Biome; import org.bukkit.generator.ChunkGenerator.BiomeGrid; -import com.volmit.iris.Iris; +public class InvertedBiomeGrid implements BiomeGrid { + private final BiomeGrid grid; -public class InvertedBiomeGrid implements BiomeGrid -{ - private BiomeGrid grid; + public InvertedBiomeGrid(BiomeGrid real) { + this.grid = real; + } - public InvertedBiomeGrid(BiomeGrid real) - { - this.grid = real; - } + @SuppressWarnings("deprecation") + @Override + public Biome getBiome(int arg0, int arg1) { + return grid.getBiome(arg0, arg1); + } - @SuppressWarnings("deprecation") - @Override - public Biome getBiome(int arg0, int arg1) - { - return grid.getBiome(arg0, arg1); - } + @Override + public Biome getBiome(int arg0, int arg1, int arg2) { + if (!Iris.biome3d) { + return getBiome(arg0, arg2); + } - @Override - public Biome getBiome(int arg0, int arg1, int arg2) - { - if(!Iris.biome3d) - { - return getBiome(arg0, arg2); - } + return grid.getBiome(arg0, 255 - arg1, arg2); + } - return grid.getBiome(arg0, 255 - arg1, arg2); - } + @SuppressWarnings("deprecation") + @Override + public void setBiome(int arg0, int arg1, Biome arg2) { + grid.setBiome(arg0, arg1, arg2); + } - @SuppressWarnings("deprecation") - @Override - public void setBiome(int arg0, int arg1, Biome arg2) - { - grid.setBiome(arg0, arg1, arg2); - } + @Override + public void setBiome(int arg0, int arg1, int arg2, Biome arg3) { + if (!Iris.biome3d) { + setBiome(arg0, arg2, arg3); + return; + } - @Override - public void setBiome(int arg0, int arg1, int arg2, Biome arg3) - { - if(!Iris.biome3d) - { - setBiome(arg0, arg2, arg3); - return; - } - - grid.setBiome(arg0, 255 - arg1, arg2, arg3); - } + grid.setBiome(arg0, 255 - arg1, arg2, arg3); + } } diff --git a/src/main/java/com/volmit/iris/util/IrisBiomeStorage.java b/src/main/java/com/volmit/iris/util/IrisBiomeStorage.java index 5918c2519..18cc80b1e 100644 --- a/src/main/java/com/volmit/iris/util/IrisBiomeStorage.java +++ b/src/main/java/com/volmit/iris/util/IrisBiomeStorage.java @@ -3,74 +3,62 @@ package com.volmit.iris.util; import org.bukkit.block.Biome; import org.bukkit.generator.ChunkGenerator.BiomeGrid; -public class IrisBiomeStorage -{ - private static final int e; - private static final int f; - public static final int a; - public static final int b; - public static final int c; - private final Biome[] g; +public class IrisBiomeStorage { + private static final int e; + private static final int f; + public static final int a; + public static final int b; + public static final int c; + private final Biome[] g; - static - { - e = (int) Math.round(Math.log(16.0) / Math.log(2.0)) - 2; - f = (int) Math.round(Math.log(256.0) / Math.log(2.0)) - 2; // TODO: WARNING HEIGHT - a = 1 << IrisBiomeStorage.e + IrisBiomeStorage.e + IrisBiomeStorage.f; - b = (1 << IrisBiomeStorage.e) - 1; - c = (1 << IrisBiomeStorage.f) - 1; - } + static { + e = (int) Math.round(Math.log(16.0) / Math.log(2.0)) - 2; + f = (int) Math.round(Math.log(256.0) / Math.log(2.0)) - 2; // TODO: WARNING HEIGHT + a = 1 << IrisBiomeStorage.e + IrisBiomeStorage.e + IrisBiomeStorage.f; + b = (1 << IrisBiomeStorage.e) - 1; + c = (1 << IrisBiomeStorage.f) - 1; + } - public IrisBiomeStorage(final Biome[] aBiome) - { - this.g = aBiome; - } + public IrisBiomeStorage(final Biome[] aBiome) { + this.g = aBiome; + } - public IrisBiomeStorage() - { - this(new Biome[IrisBiomeStorage.a]); - } + public IrisBiomeStorage() { + this(new Biome[IrisBiomeStorage.a]); + } - public IrisBiomeStorage b() - { - return new IrisBiomeStorage(this.g.clone()); - } + public IrisBiomeStorage b() { + return new IrisBiomeStorage(this.g.clone()); + } - public void inject(BiomeGrid grid) - { - // TODO: WARNING HEIGHT - for(int i = 0; i < 256; i++) - { - for(int j = 0; j < 16; j++) - { - for(int k = 0; k < 16; k++) - { - Biome b = getBiome(j, i, k); + public void inject(BiomeGrid grid) { + // TODO: WARNING HEIGHT + for (int i = 0; i < 256; i++) { + for (int j = 0; j < 16; j++) { + for (int k = 0; k < 16; k++) { + Biome b = getBiome(j, i, k); - if(b == null || b.equals(Biome.THE_VOID)) - { - continue; - } + if (b == null || b.equals(Biome.THE_VOID)) { + continue; + } - grid.setBiome(j, i, k, b); - } - } - } - } + grid.setBiome(j, i, k, b); + } + } + } + } - public Biome getBiome(final int x, final int y, final int z) - { - final int l = x & IrisBiomeStorage.b; - final int i2 = IrisMathHelper.clamp(y, 0, IrisBiomeStorage.c); - final int j2 = z & IrisBiomeStorage.b; - return this.g[i2 << IrisBiomeStorage.e + IrisBiomeStorage.e | j2 << IrisBiomeStorage.e | l]; - } + public Biome getBiome(final int x, final int y, final int z) { + final int l = x & IrisBiomeStorage.b; + final int i2 = IrisMathHelper.clamp(y, 0, IrisBiomeStorage.c); + final int j2 = z & IrisBiomeStorage.b; + return this.g[i2 << IrisBiomeStorage.e + IrisBiomeStorage.e | j2 << IrisBiomeStorage.e | l]; + } - public void setBiome(final int x, final int y, final int z, final Biome biome) - { - final int l = x & IrisBiomeStorage.b; - final int i2 = IrisMathHelper.clamp(y, 0, IrisBiomeStorage.c); - final int j2 = z & IrisBiomeStorage.b; - this.g[i2 << IrisBiomeStorage.e + IrisBiomeStorage.e | j2 << IrisBiomeStorage.e | l] = biome; - } + public void setBiome(final int x, final int y, final int z, final Biome biome) { + final int l = x & IrisBiomeStorage.b; + final int i2 = IrisMathHelper.clamp(y, 0, IrisBiomeStorage.c); + final int j2 = z & IrisBiomeStorage.b; + this.g[i2 << IrisBiomeStorage.e + IrisBiomeStorage.e | j2 << IrisBiomeStorage.e | l] = biome; + } } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/IrisInterpolation.java b/src/main/java/com/volmit/iris/util/IrisInterpolation.java index c0078cd3a..5da27c7f6 100644 --- a/src/main/java/com/volmit/iris/util/IrisInterpolation.java +++ b/src/main/java/com/volmit/iris/util/IrisInterpolation.java @@ -3,1005 +3,867 @@ package com.volmit.iris.util; import com.google.common.util.concurrent.AtomicDouble; import com.volmit.iris.generator.noise.CNG; import com.volmit.iris.object.InterpolationMethod; -import com.volmit.iris.object.IrisInterpolator; import com.volmit.iris.object.NoiseStyle; -public class IrisInterpolation -{ - public static double bezier(double t) - { - return t * t * (3.0d - 2.0d * t); - } - - public static double parametric(double t, double alpha) - { - double sqt = Math.pow(t, alpha); - return sqt / (alpha * (sqt - Math.pow(t, alpha - 1)) + 1.0d); - } - - public static float lerpf(float a, float b, float f) - { - return a + (f * (b - a)); - } - - public static double lerpBezier(double a, double b, double f) - { - return a + (bezier(f) * (b - a)); - } - - public static double sinCenter(double f) - { - return Math.sin(f * Math.PI); - } - - public static double lerpCenterSinBezier(double a, double b, double f) - { - return lerpBezier(a, b, sinCenter(f)); - } - - public static double lerpCenterSin(double a, double b, double f) - { - return lerpBezier(a, b, sinCenter(f)); - } - - public static double lerpParametric(double a, double b, double f, double v) - { - return a + (parametric(f, v) * (b - a)); - } - - public static double blerp(double a, double b, double c, double d, double tx, double ty, InterpolationType type) - { - if(type.equals(InterpolationType.LINEAR)) - { - return blerp(a, b, c, d, tx, ty); - } - - if(type.equals(InterpolationType.BEZIER)) - { - return blerpBezier(a, b, c, d, tx, ty); - } - - if(type.equals(InterpolationType.PARAMETRIC_2)) - { - return blerpParametric(a, b, c, d, tx, ty, 2); - } - - if(type.equals(InterpolationType.PARAMETRIC_4)) - { - return blerpParametric(a, b, c, d, tx, ty, 4); - } - - return 0; - } - - public static double blerpBezier(double a, double b, double c, double d, double tx, double ty) - { - return lerpBezier(lerpBezier(a, b, tx), lerpBezier(c, d, tx), ty); - } - - public static double blerpSinCenter(double a, double b, double c, double d, double tx, double ty) - { - return lerpCenterSin(lerpCenterSin(a, b, tx), lerpCenterSin(c, d, tx), ty); - } - - public static double blerpParametric(double a, double b, double c, double d, double tx, double ty, double v) - { - return lerpParametric(lerpParametric(a, b, tx, v), lerpParametric(c, d, tx, v), ty, v); - } - - public static double hermiteBezier(double p0, double p1, double p2, double p3, double mu, double tension, double bias) - { - return bezier(hermite(p0, p1, p2, p3, mu, tension, bias)); - } - - public static double hermiteParametric(double p0, double p1, double p2, double p3, double mu, double tension, double bias, double a) - { - return parametric(hermite(p0, p1, p2, p3, mu, tension, bias), a); - } - - public static double bihermiteBezier(double p00, double p01, double p02, double p03, double p10, double p11, double p12, double p13, double p20, double p21, double p22, double p23, double p30, double p31, double p32, double p33, double mux, double muy, double tension, double bias) - { - //@builder - return hermiteBezier( - hermiteBezier(p00, p01, p02, p03, muy, tension, bias), - hermiteBezier(p10, p11, p12, p13, muy, tension, bias), - hermiteBezier(p20, p21, p22, p23, muy, tension, bias), - hermiteBezier(p30, p31, p32, p33, muy, tension, bias), - mux, tension, bias); - //@done - } - - public static double bihermiteParametric(double p00, double p01, double p02, double p03, double p10, double p11, double p12, double p13, double p20, double p21, double p22, double p23, double p30, double p31, double p32, double p33, double mux, double muy, double tension, double bias, double a) - { - //@builder - return hermiteParametric( - hermiteParametric(p00, p01, p02, p03, muy, tension, bias, a), - hermiteParametric(p10, p11, p12, p13, muy, tension, bias, a), - hermiteParametric(p20, p21, p22, p23, muy, tension, bias, a), - hermiteParametric(p30, p31, p32, p33, muy, tension, bias, a), - mux, tension, bias, a); - //@done - } - - public static double cubicBezier(double p0, double p1, double p2, double p3, double mu) - { - return bezier(cubic(p0, p1, p2, p3, mu)); - } - - public static double cubicParametric(double p0, double p1, double p2, double p3, double mu, double a) - { - return parametric(cubic(p0, p1, p2, p3, mu), a); - } - - public static double hermite(double p0, double p1, double p2, double p3, double mu, double tension, double bias) - { - double m0, m1, mu2, mu3; - double a0, a1, a2, a3; - - mu2 = mu * mu; - mu3 = mu2 * mu; - m0 = (p1 - p0) * (1 + bias) * (1 - tension) / 2; - m0 += (p2 - p1) * (1 - bias) * (1 - tension) / 2; - m1 = (p2 - p1) * (1 + bias) * (1 - tension) / 2; - m1 += (p3 - p2) * (1 - bias) * (1 - tension) / 2; - a0 = 2 * mu3 - 3 * mu2 + 1; - a1 = mu3 - 2 * mu2 + mu; - a2 = mu3 - mu2; - a3 = -2 * mu3 + 3 * mu2; - - return (a0 * p1 + a1 * m0 + a2 * m1 + a3 * p2); - } - - public static double cubic(double p0, double p1, double p2, double p3, double mu) - { - double a0, a1, a2, a3, mu2; - - mu2 = mu * mu; - a0 = p3 - p2 - p0 + p1; - a1 = p0 - p1 - a0; - a2 = p2 - p0; - a3 = p1; - - return a0 * mu * mu2 + a1 * mu2 + a2 * mu + a3; - } - - public static double getTriStarcast(int x, int y, int z, double rad, double checks, NoiseProvider n) - { - return (getStarcast(x, z, rad, checks, n) + getStarcast(x, y, rad, checks, n) + getStarcast(y, z, rad, checks, n)) / 3D; - } - - public static double bicubic(double p00, double p01, double p02, double p03, double p10, double p11, double p12, double p13, double p20, double p21, double p22, double p23, double p30, double p31, double p32, double p33, double mux, double muy) - { - //@builder - return cubic( - cubic(p00, p01, p02, p03, muy), - cubic(p10, p11, p12, p13, muy), - cubic(p20, p21, p22, p23, muy), - cubic(p30, p31, p32, p33, muy), - mux); - //@done - } - - public static double bihermite(double p00, double p01, double p02, double p03, double p10, double p11, double p12, double p13, double p20, double p21, double p22, double p23, double p30, double p31, double p32, double p33, double mux, double muy, double tension, double bias) - { - //@builder - return hermite( - hermite(p00, p01, p02, p03, muy, tension, bias), - hermite(p10, p11, p12, p13, muy, tension, bias), - hermite(p20, p21, p22, p23, muy, tension, bias), - hermite(p30, p31, p32, p33, muy, tension, bias), - mux, tension, bias); - //@done - } - - public static double trihermite(double p000, double p001, double p002, double p003, double p010, double p011, double p012, double p013, double p020, double p021, double p022, double p023, double p030, double p031, double p032, double p033, double p100, double p101, double p102, double p103, double p110, double p111, double p112, double p113, double p120, double p121, double p122, double p123, double p130, double p131, double p132, double p133, double p200, double p201, double p202, double p203, double p210, double p211, double p212, double p213, double p220, double p221, double p222, double p223, double p230, double p231, double p232, double p233, double p300, double p301, double p302, double p303, double p310, double p311, double p312, double p313, double p320, double p321, double p322, double p323, double p330, double p331, double p332, double p333, double mux, double muy, double muz, double tension, double bias) - { - //@builder - return hermite( - bihermite(p000, p001, p002, p003, - p010, p011, p012, p013, - p020, p021, p022, p023, - p030, p031, p032, p033, - mux, muy, tension, bias), - bihermite(p100, p101, p102, p103, - p110, p111, p112, p113, - p120, p121, p122, p123, - p130, p131, p132, p133, - mux, muy, tension, bias), - bihermite(p200, p201, p202, p203, - p210, p211, p212, p213, - p220, p221, p222, p223, - p230, p231, p232, p233, - mux, muy, tension, bias), - bihermite(p300, p301, p302, p303, - p310, p311, p312, p313, - p320, p321, p322, p323, - p330, p331, p332, p333, - mux, muy, tension, bias), - muz, tension, bias); - //@done - } - - public static double tricubic(double p000, - double p001, - double p002, - double p003, - double p010, - double p011, - double p012, double p013, double p020, double p021, double p022, double p023, double p030, double p031, double p032, double p033, double p100, double p101, double p102, double p103, double p110, double p111, double p112, double p113, double p120, double p121, double p122, double p123, double p130, double p131, double p132, double p133, double p200, double p201, double p202, double p203, double p210, double p211, double p212, double p213, double p220, double p221, double p222, double p223, double p230, double p231, double p232, double p233, double p300, double p301, double p302, double p303, double p310, double p311, double p312, double p313, double p320, double p321, double p322, double p323, double p330, double p331, double p332, double p333, double mux, double muy, double muz) - { - //@builder - return cubic( - bicubic(p000, p001, p002, p003, - p010, p011, p012, p013, - p020, p021, p022, p023, - p030, p031, p032, p033, - mux, muy), - bicubic(p100, p101, p102, p103, - p110, p111, p112, p113, - p120, p121, p122, p123, - p130, p131, p132, p133, - mux, muy), - bicubic(p200, p201, p202, p203, - p210, p211, p212, p213, - p220, p221, p222, p223, - p230, p231, p232, p233, - mux, muy), - bicubic(p300, p301, p302, p303, - p310, p311, p312, p313, - p320, p321, p322, p323, - p330, p331, p332, p333, - mux, muy), - muz); - //@done - } - - public static double lerp(double a, double b, double f) - { - return a + (f * (b - a)); - } - - public static double blerp(double a, double b, double c, double d, double tx, double ty) - { - return lerp(lerp(a, b, tx), lerp(c, d, tx), ty); - } - - public static double trilerp(double v1, double v2, double v3, double v4, double v5, double v6, double v7, double v8, double x, double y, double z) - { - return lerp(blerp(v1, v2, v3, v4, x, y), blerp(v5, v6, v7, v8, x, y), z); - } - - public static double bicubicBezier(double p00, double p01, double p02, double p03, double p10, double p11, double p12, double p13, double p20, double p21, double p22, double p23, double p30, double p31, double p32, double p33, double mux, double muy) - { - //@builder - return cubicBezier( - cubicBezier(p00, p01, p02, p03, muy), - cubicBezier(p10, p11, p12, p13, muy), - cubicBezier(p20, p21, p22, p23, muy), - cubicBezier(p30, p31, p32, p33, muy), - mux); - //@done - } - - public static double bicubicParametric(double p00, double p01, double p02, double p03, double p10, double p11, double p12, double p13, double p20, double p21, double p22, double p23, double p30, double p31, double p32, double p33, double mux, double muy, double a) - { - //@builder - return cubicParametric( - cubicParametric(p00, p01, p02, p03, muy,a), - cubicParametric(p10, p11, p12, p13, muy,a), - cubicParametric(p20, p21, p22, p23, muy,a), - cubicParametric(p30, p31, p32, p33, muy,a), - mux, a); - //@done - } - - public static CNG cng = NoiseStyle.SIMPLEX.create(new RNG()); - - public static double getBilinearNoise(int x, int z, double rad, NoiseProvider n) - { - int fx = (int) Math.floor(x / rad); - int fz = (int) Math.floor(z / rad); - int x1 = (int) Math.round(fx * rad); - int z1 = (int) Math.round(fz * rad); - int x2 = (int) Math.round((fx + 1) * rad); - int z2 = (int) Math.round((fz + 1) * rad); - - double px = rangeScale(0, 1, x1, x2, x); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - return blerp( - n.noise(x1, z1), - n.noise(x2, z1), - n.noise(x1, z2), - n.noise(x2, z2), - px, pz); - //@done - } - - public static double getStarcast(int x, int z, double rad, double checks, NoiseProvider n) - { - double m = (360 / checks); - double v = 0; - - for(int i = 0; i < 360; i += m) - { - double sin = Math.sin(Math.toRadians(i)); - double cos = Math.cos(Math.toRadians(i)); - double cx = x + ((rad * cos) - (rad * sin)); - double cz = z + ((rad * sin) + (rad * cos)); - v += n.noise(cx, cz); - } - - return v / checks; - } - - public static double getBilinearBezierNoise(int x, int z, double rad, NoiseProvider n) - { - int fx = (int) Math.floor(x / rad); - int fz = (int) Math.floor(z / rad); - int x1 = (int) Math.round(fx * rad); - int z1 = (int) Math.round(fz * rad); - int x2 = (int) Math.round((fx + 1) * rad); - int z2 = (int) Math.round((fz + 1) * rad); - double px = rangeScale(0, 1, x1, x2, x); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - return blerpBezier( - n.noise(x1, z1), - n.noise(x2, z1), - n.noise(x1, z2), - n.noise(x2, z2), - px, pz); - //@done - } - - public static double getBilinearParametricNoise(int x, int z, double rad, NoiseProvider n, double a) - { - int fx = (int) Math.floor(x / rad); - int fz = (int) Math.floor(z / rad); - int x1 = (int) Math.round(fx * rad); - int z1 = (int) Math.round(fz * rad); - int x2 = (int) Math.round((fx + 1) * rad); - int z2 = (int) Math.round((fz + 1) * rad); - double px = rangeScale(0, 1, x1, x2, x); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - return blerpParametric( - n.noise(x1, z1), - n.noise(x2, z1), - n.noise(x1, z2), - n.noise(x2, z2), - px, pz, a); - //@done - } - - public static double getTrilinear(int x, int y, int z, double rad, NoiseProvider3 n) - { - int fx = (int) Math.floor(x / rad); - int fy = (int) Math.floor(y / rad); - int fz = (int) Math.floor(z / rad); - int x1 = (int) Math.round(fx * rad); - int y1 = (int) Math.round(fy * rad); - int z1 = (int) Math.round(fz * rad); - int x2 = (int) Math.round((fx + 1) * rad); - int y2 = (int) Math.round((fy + 1) * rad); - int z2 = (int) Math.round((fz + 1) * rad); - double px = rangeScale(0, 1, x1, x2, x); - double py = rangeScale(0, 1, y1, y2, y); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - return trilerp( - n.noise(x1, y1, z1), - n.noise(x2, y1, z1), - n.noise(x1, y2, z1), - n.noise(x2, y2, z1), - n.noise(x1, y1, z2), - n.noise(x2, y1, z2), - n.noise(x1, y2, z2), - n.noise(x2, y2, z2), - px, py, pz); - //@done - } - - public static double getTricubic(int x, int y, int z, double rad, NoiseProvider3 n) - { - int fx = (int) Math.floor(x / rad); - int fy = (int) Math.floor(y / rad); - int fz = (int) Math.floor(z / rad); - int x0 = (int) Math.round((fx - 1) * rad); - int y0 = (int) Math.round((fy - 1) * rad); - int z0 = (int) Math.round((fz - 1) * rad); - int x1 = (int) Math.round(fx * rad); - int y1 = (int) Math.round(fy * rad); - int z1 = (int) Math.round(fz * rad); - int x2 = (int) Math.round((fx + 1) * rad); - int y2 = (int) Math.round((fy + 1) * rad); - int z2 = (int) Math.round((fz + 1) * rad); - int x3 = (int) Math.round((fx + 2) * rad); - int y3 = (int) Math.round((fy + 2) * rad); - int z3 = (int) Math.round((fz + 2) * rad); - double px = rangeScale(0, 1, x1, x2, x); - double py = rangeScale(0, 1, y1, y2, y); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - //!!!!!!!!!!!!!!!!!! 2 1 3 - - return tricubic( - n.noise(x0, y0, z0), - n.noise(x0, y1, z0), - n.noise(x0, y2, z0), - n.noise(x0, y3, z0), - n.noise(x1, y0, z0), - n.noise(x1, y1, z0), - n.noise(x1, y2, z0), - n.noise(x1, y3, z0), - n.noise(x2, y0, z0), - n.noise(x2, y1, z0), - n.noise(x2, y2, z0), - n.noise(x2, y3, z0), - n.noise(x3, y0, z0), - n.noise(x3, y1, z0), - n.noise(x3, y2, z0), - n.noise(x3, y3, z0), - n.noise(x0, y0, z1), - n.noise(x0, y1, z1), - n.noise(x0, y2, z1), - n.noise(x0, y3, z1), - n.noise(x1, y0, z1), - n.noise(x1, y1, z1), - n.noise(x1, y2, z1), - n.noise(x1, y3, z1), - n.noise(x2, y0, z1), - n.noise(x2, y1, z1), - n.noise(x2, y2, z1), - n.noise(x2, y3, z1), - n.noise(x3, y0, z1), - n.noise(x3, y1, z1), - n.noise(x3, y2, z1), - n.noise(x3, y3, z1), - n.noise(x0, y0, z2), - n.noise(x0, y1, z2), - n.noise(x0, y2, z2), - n.noise(x0, y3, z2), - n.noise(x1, y0, z2), - n.noise(x1, y1, z2), - n.noise(x1, y2, z2), - n.noise(x1, y3, z2), - n.noise(x2, y0, z2), - n.noise(x2, y1, z2), - n.noise(x2, y2, z2), - n.noise(x2, y3, z2), - n.noise(x3, y0, z2), - n.noise(x3, y1, z2), - n.noise(x3, y2, z2), - n.noise(x3, y3, z2), - n.noise(x0, y0, z3), - n.noise(x0, y1, z3), - n.noise(x0, y2, z3), - n.noise(x0, y3, z3), - n.noise(x1, y0, z3), - n.noise(x1, y1, z3), - n.noise(x1, y2, z3), - n.noise(x1, y3, z3), - n.noise(x2, y0, z3), - n.noise(x2, y1, z3), - n.noise(x2, y2, z3), - n.noise(x2, y3, z3), - n.noise(x3, y0, z3), - n.noise(x3, y1, z3), - n.noise(x3, y2, z3), - n.noise(x3, y3, z3), - px, py, pz); - //@done - } - - public static double getTrihermite(int x, int y, int z, double rad, NoiseProvider3 n) - { - return getTrihermite(x,y,z,rad,n,0D,0D); - } - - public static double getTrihermite(int x, int y, int z, double rad, NoiseProvider3 n, double tension, double bias) - { - int fx = (int) Math.floor(x / rad); - int fy = (int) Math.floor(y / rad); - int fz = (int) Math.floor(z / rad); - int x0 = (int) Math.round((fx - 1) * rad); - int y0 = (int) Math.round((fy - 1) * rad); - int z0 = (int) Math.round((fz - 1) * rad); - int x1 = (int) Math.round(fx * rad); - int y1 = (int) Math.round(fy * rad); - int z1 = (int) Math.round(fz * rad); - int x2 = (int) Math.round((fx + 1) * rad); - int y2 = (int) Math.round((fy + 1) * rad); - int z2 = (int) Math.round((fz + 1) * rad); - int x3 = (int) Math.round((fx + 2) * rad); - int y3 = (int) Math.round((fy + 2) * rad); - int z3 = (int) Math.round((fz + 2) * rad); - double px = rangeScale(0, 1, x1, x2, x); - double py = rangeScale(0, 1, y1, y2, y); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - //!!!!!!!!!!!!!!!!!! 2 1 3 - - return trihermite( - n.noise(x0, y0, z0), - n.noise(x0, y1, z0), - n.noise(x0, y2, z0), - n.noise(x0, y3, z0), - n.noise(x1, y0, z0), - n.noise(x1, y1, z0), - n.noise(x1, y2, z0), - n.noise(x1, y3, z0), - n.noise(x2, y0, z0), - n.noise(x2, y1, z0), - n.noise(x2, y2, z0), - n.noise(x2, y3, z0), - n.noise(x3, y0, z0), - n.noise(x3, y1, z0), - n.noise(x3, y2, z0), - n.noise(x3, y3, z0), - n.noise(x0, y0, z1), - n.noise(x0, y1, z1), - n.noise(x0, y2, z1), - n.noise(x0, y3, z1), - n.noise(x1, y0, z1), - n.noise(x1, y1, z1), - n.noise(x1, y2, z1), - n.noise(x1, y3, z1), - n.noise(x2, y0, z1), - n.noise(x2, y1, z1), - n.noise(x2, y2, z1), - n.noise(x2, y3, z1), - n.noise(x3, y0, z1), - n.noise(x3, y1, z1), - n.noise(x3, y2, z1), - n.noise(x3, y3, z1), - n.noise(x0, y0, z2), - n.noise(x0, y1, z2), - n.noise(x0, y2, z2), - n.noise(x0, y3, z2), - n.noise(x1, y0, z2), - n.noise(x1, y1, z2), - n.noise(x1, y2, z2), - n.noise(x1, y3, z2), - n.noise(x2, y0, z2), - n.noise(x2, y1, z2), - n.noise(x2, y2, z2), - n.noise(x2, y3, z2), - n.noise(x3, y0, z2), - n.noise(x3, y1, z2), - n.noise(x3, y2, z2), - n.noise(x3, y3, z2), - n.noise(x0, y0, z3), - n.noise(x0, y1, z3), - n.noise(x0, y2, z3), - n.noise(x0, y3, z3), - n.noise(x1, y0, z3), - n.noise(x1, y1, z3), - n.noise(x1, y2, z3), - n.noise(x1, y3, z3), - n.noise(x2, y0, z3), - n.noise(x2, y1, z3), - n.noise(x2, y2, z3), - n.noise(x2, y3, z3), - n.noise(x3, y0, z3), - n.noise(x3, y1, z3), - n.noise(x3, y2, z3), - n.noise(x3, y3, z3), - px, py, pz, tension, bias); - //@done - } - - public static double getBilinearCenterSineNoise(int x, int z, double rad, NoiseProvider n) - { - int fx = (int) Math.floor(x / rad); - int fz = (int) Math.floor(z / rad); - int x1 = (int) Math.round(fx * rad); - int z1 = (int) Math.round(fz * rad); - int x2 = (int) Math.round((fx + 1) * rad); - int z2 = (int) Math.round((fz + 1) * rad); - double px = rangeScale(0, 1, x1, x2, x); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - return blerpSinCenter( - n.noise(x1, z1), - n.noise(x2, z1), - n.noise(x1, z2), - n.noise(x2, z2), - px, pz); - //@done - } - - public static double getBicubicNoise(int x, int z, double rad, NoiseProvider n) - { - int fx = (int) Math.floor(x / rad); - int fz = (int) Math.floor(z / rad); - int x0 = (int) Math.round((fx - 1) * rad); - int z0 = (int) Math.round((fz - 1) * rad); - int x1 = (int) Math.round(fx * rad); - int z1 = (int) Math.round(fz * rad); - int x2 = (int) Math.round((fx + 1) * rad); - int z2 = (int) Math.round((fz + 1) * rad); - int x3 = (int) Math.round((fx + 2) * rad); - int z3 = (int) Math.round((fz + 2) * rad); - double px = rangeScale(0, 1, x1, x2, x); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - return bicubic( - n.noise(x0, z0), - n.noise(x0, z1), - n.noise(x0, z2), - n.noise(x0, z3), - n.noise(x1, z0), - n.noise(x1, z1), - n.noise(x1, z2), - n.noise(x1, z3), - n.noise(x2, z0), - n.noise(x2, z1), - n.noise(x2, z2), - n.noise(x2, z3), - n.noise(x3, z0), - n.noise(x3, z1), - n.noise(x3, z2), - n.noise(x3, z3), - px, pz); - //@done - } - - public static double getBicubicBezierNoise(int x, int z, double rad, NoiseProvider n) - { - int fx = (int) Math.floor(x / rad); - int fz = (int) Math.floor(z / rad); - int x0 = (int) Math.round((fx - 1) * rad); - int z0 = (int) Math.round((fz - 1) * rad); - int x1 = (int) Math.round(fx * rad); - int z1 = (int) Math.round(fz * rad); - int x2 = (int) Math.round((fx + 1) * rad); - int z2 = (int) Math.round((fz + 1) * rad); - int x3 = (int) Math.round((fx + 2) * rad); - int z3 = (int) Math.round((fz + 2) * rad); - double px = rangeScale(0, 1, x1, x2, x); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - return bicubicBezier( - n.noise(x0, z0), - n.noise(x0, z1), - n.noise(x0, z2), - n.noise(x0, z3), - n.noise(x1, z0), - n.noise(x1, z1), - n.noise(x1, z2), - n.noise(x1, z3), - n.noise(x2, z0), - n.noise(x2, z1), - n.noise(x2, z2), - n.noise(x2, z3), - n.noise(x3, z0), - n.noise(x3, z1), - n.noise(x3, z2), - n.noise(x3, z3), - px, pz); - //@done - } - - public static double getBicubicParametricNoise(int x, int z, double rad, NoiseProvider n, double a) - { - int fx = (int) Math.floor(x / rad); - int fz = (int) Math.floor(z / rad); - int x0 = (int) Math.round((fx - 1) * rad); - int z0 = (int) Math.round((fz - 1) * rad); - int x1 = (int) Math.round(fx * rad); - int z1 = (int) Math.round(fz * rad); - int x2 = (int) Math.round((fx + 1) * rad); - int z2 = (int) Math.round((fz + 1) * rad); - int x3 = (int) Math.round((fx + 2) * rad); - int z3 = (int) Math.round((fz + 2) * rad); - double px = rangeScale(0, 1, x1, x2, x); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - return bicubicParametric( - n.noise(x0, z0), - n.noise(x0, z1), - n.noise(x0, z2), - n.noise(x0, z3), - n.noise(x1, z0), - n.noise(x1, z1), - n.noise(x1, z2), - n.noise(x1, z3), - n.noise(x2, z0), - n.noise(x2, z1), - n.noise(x2, z2), - n.noise(x2, z3), - n.noise(x3, z0), - n.noise(x3, z1), - n.noise(x3, z2), - n.noise(x3, z3), - px, pz, a); - //@done - } - - public static double getHermiteNoise(int x, int z, double rad, NoiseProvider n) - { - return getHermiteNoise(x, z, rad, n, 0.5, 0); - } - - public static double getHermiteBezierNoise(int x, int z, double rad, NoiseProvider n) - { - return getHermiteBezierNoise(x, z, rad, n, 0.5, 0); - } - - public static double getHermiteParametricNoise(int x, int z, double rad, NoiseProvider n, double a) - { - return getHermiteParametricNoise(x, z, rad, n, 0.5, 0, a); - } - - public static double getHermiteNoise(int x, int z, double rad, NoiseProvider n, double t, double b) - { - int fx = (int) Math.floor(x / rad); - int fz = (int) Math.floor(z / rad); - int x0 = (int) Math.round((fx - 1) * rad); - int z0 = (int) Math.round((fz - 1) * rad); - int x1 = (int) Math.round(fx * rad); - int z1 = (int) Math.round(fz * rad); - int x2 = (int) Math.round((fx + 1) * rad); - int z2 = (int) Math.round((fz + 1) * rad); - int x3 = (int) Math.round((fx + 2) * rad); - int z3 = (int) Math.round((fz + 2) * rad); - double px = rangeScale(0, 1, x1, x2, x); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - return bihermite( - n.noise(x0, z0), - n.noise(x0, z1), - n.noise(x0, z2), - n.noise(x0, z3), - n.noise(x1, z0), - n.noise(x1, z1), - n.noise(x1, z2), - n.noise(x1, z3), - n.noise(x2, z0), - n.noise(x2, z1), - n.noise(x2, z2), - n.noise(x2, z3), - n.noise(x3, z0), - n.noise(x3, z1), - n.noise(x3, z2), - n.noise(x3, z3), - px, pz, t, b); - //@done - } - - public static double getHermiteBezierNoise(int x, int z, double rad, NoiseProvider n, double t, double b) - { - int fx = (int) Math.floor(x / rad); - int fz = (int) Math.floor(z / rad); - int x0 = (int) Math.round((fx - 1) * rad); - int z0 = (int) Math.round((fz - 1) * rad); - int x1 = (int) Math.round(fx * rad); - int z1 = (int) Math.round(fz * rad); - int x2 = (int) Math.round((fx + 1) * rad); - int z2 = (int) Math.round((fz + 1) * rad); - int x3 = (int) Math.round((fx + 2) * rad); - int z3 = (int) Math.round((fz + 2) * rad); - double px = rangeScale(0, 1, x1, x2, x); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - return bihermiteBezier( - n.noise(x0, z0), - n.noise(x0, z1), - n.noise(x0, z2), - n.noise(x0, z3), - n.noise(x1, z0), - n.noise(x1, z1), - n.noise(x1, z2), - n.noise(x1, z3), - n.noise(x2, z0), - n.noise(x2, z1), - n.noise(x2, z2), - n.noise(x2, z3), - n.noise(x3, z0), - n.noise(x3, z1), - n.noise(x3, z2), - n.noise(x3, z3), - px, pz, t, b); - //@done - } - - public static double getHermiteParametricNoise(int x, int z, double rad, NoiseProvider n, double t, double b, double a) - { - int fx = (int) Math.floor(x / rad); - int fz = (int) Math.floor(z / rad); - int x0 = (int) Math.round((fx - 1) * rad); - int z0 = (int) Math.round((fz - 1) * rad); - int x1 = (int) Math.round(fx * rad); - int z1 = (int) Math.round(fz * rad); - int x2 = (int) Math.round((fx + 1) * rad); - int z2 = (int) Math.round((fz + 1) * rad); - int x3 = (int) Math.round((fx + 2) * rad); - int z3 = (int) Math.round((fz + 2) * rad); - double px = rangeScale(0, 1, x1, x2, x); - double pz = rangeScale(0, 1, z1, z2, z); - //@builder - return bihermiteParametric( - n.noise(x0, z0), - n.noise(x0, z1), - n.noise(x0, z2), - n.noise(x0, z3), - n.noise(x1, z0), - n.noise(x1, z1), - n.noise(x1, z2), - n.noise(x1, z3), - n.noise(x2, z0), - n.noise(x2, z1), - n.noise(x2, z2), - n.noise(x2, z3), - n.noise(x3, z0), - n.noise(x3, z1), - n.noise(x3, z2), - n.noise(x3, z3), - px, pz, t, b, a); - //@done - } - - public static double getRealRadius(InterpolationMethod method, double h) - { - AtomicDouble rad = new AtomicDouble(h); - AtomicDouble accessX = new AtomicDouble(); - AtomicDouble accessZ = new AtomicDouble(); - NoiseProvider np = (x1, z1) -> { - double d = Math.max(Math.abs(x1), Math.abs(z1)); - if(d > rad.get()) - { - rad.set(d); - } - return 0; - }; - getNoise(method, 0, 0, h, np); - return rad.get(); - } - - public static double getNoise(InterpolationMethod method, int x, int z, double h, NoiseProvider n) - { - if(method.equals(InterpolationMethod.BILINEAR)) - { - return getBilinearNoise(x, z, h, n); - } - - else if(method.equals(InterpolationMethod.STARCAST_3)) - { - return getStarcast(x, z, h, 3D, n); - } - - else if(method.equals(InterpolationMethod.STARCAST_6)) - { - return getStarcast(x, z, h, 6D, n); - } - - else if(method.equals(InterpolationMethod.STARCAST_9)) - { - return getStarcast(x, z, h, 9D, n); - } - - else if(method.equals(InterpolationMethod.STARCAST_12)) - { - return getStarcast(x, z, h, 12D, n); - } - - else if(method.equals(InterpolationMethod.BILINEAR_STARCAST_3)) - { - return getStarcast(x, z, h, 3D, (xx, zz) -> getBilinearNoise((int) xx, (int) zz, h, n)); - } - - else if(method.equals(InterpolationMethod.BILINEAR_STARCAST_6)) - { - return getStarcast(x, z, h, 6D, (xx, zz) -> getBilinearNoise((int) xx, (int) zz, h, n)); - } - - else if(method.equals(InterpolationMethod.BILINEAR_STARCAST_9)) - { - return getStarcast(x, z, h, 9D, (xx, zz) -> getBilinearNoise((int) xx, (int) zz, h, n)); - } - - else if(method.equals(InterpolationMethod.BILINEAR_STARCAST_12)) - { - return getStarcast(x, z, h, 12D, (xx, zz) -> getBilinearNoise((int) xx, (int) zz, h, n)); - } - - else if(method.equals(InterpolationMethod.HERMITE_STARCAST_3)) - { - return getStarcast(x, z, h, 3D, (xx, zz) -> getHermiteNoise((int) xx, (int) zz, h, n, 0D, 0D)); - } - - else if(method.equals(InterpolationMethod.HERMITE_STARCAST_6)) - { - return getStarcast(x, z, h, 6D, (xx, zz) -> getHermiteNoise((int) xx, (int) zz, h, n, 0D, 0D)); - } - - else if(method.equals(InterpolationMethod.HERMITE_STARCAST_9)) - { - return getStarcast(x, z, h, 9D, (xx, zz) -> getHermiteNoise((int) xx, (int) zz, h, n, 0D, 0D)); - } - - else if(method.equals(InterpolationMethod.HERMITE_STARCAST_12)) - { - return getStarcast(x, z, h, 12D, (xx, zz) -> getHermiteNoise((int) xx, (int) zz, h, n, 0D, 0D)); - } - - else if(method.equals(InterpolationMethod.BICUBIC)) - { - return getBicubicNoise(x, z, h, n); - } - - else if(method.equals(InterpolationMethod.BILINEAR_BEZIER)) - { - return getBilinearBezierNoise(x, z, h, n); - } - - else if(method.equals(InterpolationMethod.BILINEAR_PARAMETRIC_2)) - { - return getBilinearParametricNoise(x, z, h, n, 2); - } - - else if(method.equals(InterpolationMethod.BILINEAR_PARAMETRIC_4)) - { - return getBilinearParametricNoise(x, z, h, n, 4); - } - - else if(method.equals(InterpolationMethod.BILINEAR_PARAMETRIC_1_5)) - { - return getBilinearParametricNoise(x, z, h, n, 1.5); - } - - else if(method.equals(InterpolationMethod.BICUBIC)) - { - return getBilinearNoise(x, z, h, n); - } - - else if(method.equals(InterpolationMethod.HERMITE)) - { - return getHermiteNoise(x, z, h, n); - } - - else if(method.equals(InterpolationMethod.HERMITE_TENSE)) - { - return getHermiteNoise(x, z, h, n, 0.8D, 0D); - } - - else if(method.equals(InterpolationMethod.CATMULL_ROM_SPLINE)) - { - return getHermiteNoise(x, z, h, n, 1D, 0D); - } - - else if(method.equals(InterpolationMethod.HERMITE_LOOSE)) - { - return getHermiteNoise(x, z, h, n, 0D, 0D); - } - - else if(method.equals(InterpolationMethod.HERMITE_LOOSE_HALF_NEGATIVE_BIAS)) - { - return getHermiteNoise(x, z, h, n, 0D, -0.5D); - } - - else if(method.equals(InterpolationMethod.HERMITE_LOOSE_HALF_POSITIVE_BIAS)) - { - return getHermiteNoise(x, z, h, n, 0D, 0.5D); - } - - else if(method.equals(InterpolationMethod.HERMITE_LOOSE_FULL_NEGATIVE_BIAS)) - { - return getHermiteNoise(x, z, h, n, 0D, -1D); - } - - else if(method.equals(InterpolationMethod.HERMITE_LOOSE_FULL_POSITIVE_BIAS)) - { - return getHermiteNoise(x, z, h, n, 0D, 1D); - } - - return n.noise(x, z); - } - - public static double rangeScale(double amin, double amax, double bmin, double bmax, double b) - { - return amin + ((amax - amin) * ((b - bmin) / (bmax - bmin))); - } +public class IrisInterpolation { + public static double bezier(double t) { + return t * t * (3.0d - 2.0d * t); + } + + public static double parametric(double t, double alpha) { + double sqt = Math.pow(t, alpha); + return sqt / (alpha * (sqt - Math.pow(t, alpha - 1)) + 1.0d); + } + + public static float lerpf(float a, float b, float f) { + return a + (f * (b - a)); + } + + public static double lerpBezier(double a, double b, double f) { + return a + (bezier(f) * (b - a)); + } + + public static double sinCenter(double f) { + return Math.sin(f * Math.PI); + } + + public static double lerpCenterSinBezier(double a, double b, double f) { + return lerpBezier(a, b, sinCenter(f)); + } + + public static double lerpCenterSin(double a, double b, double f) { + return lerpBezier(a, b, sinCenter(f)); + } + + public static double lerpParametric(double a, double b, double f, double v) { + return a + (parametric(f, v) * (b - a)); + } + + public static double blerp(double a, double b, double c, double d, double tx, double ty, InterpolationType type) { + if (type.equals(InterpolationType.LINEAR)) { + return blerp(a, b, c, d, tx, ty); + } + + if (type.equals(InterpolationType.BEZIER)) { + return blerpBezier(a, b, c, d, tx, ty); + } + + if (type.equals(InterpolationType.PARAMETRIC_2)) { + return blerpParametric(a, b, c, d, tx, ty, 2); + } + + if (type.equals(InterpolationType.PARAMETRIC_4)) { + return blerpParametric(a, b, c, d, tx, ty, 4); + } + + return 0; + } + + public static double blerpBezier(double a, double b, double c, double d, double tx, double ty) { + return lerpBezier(lerpBezier(a, b, tx), lerpBezier(c, d, tx), ty); + } + + public static double blerpSinCenter(double a, double b, double c, double d, double tx, double ty) { + return lerpCenterSin(lerpCenterSin(a, b, tx), lerpCenterSin(c, d, tx), ty); + } + + public static double blerpParametric(double a, double b, double c, double d, double tx, double ty, double v) { + return lerpParametric(lerpParametric(a, b, tx, v), lerpParametric(c, d, tx, v), ty, v); + } + + public static double hermiteBezier(double p0, double p1, double p2, double p3, double mu, double tension, double bias) { + return bezier(hermite(p0, p1, p2, p3, mu, tension, bias)); + } + + public static double hermiteParametric(double p0, double p1, double p2, double p3, double mu, double tension, double bias, double a) { + return parametric(hermite(p0, p1, p2, p3, mu, tension, bias), a); + } + + public static double bihermiteBezier(double p00, double p01, double p02, double p03, double p10, double p11, double p12, double p13, double p20, double p21, double p22, double p23, double p30, double p31, double p32, double p33, double mux, double muy, double tension, double bias) { + //@builder + return hermiteBezier( + hermiteBezier(p00, p01, p02, p03, muy, tension, bias), + hermiteBezier(p10, p11, p12, p13, muy, tension, bias), + hermiteBezier(p20, p21, p22, p23, muy, tension, bias), + hermiteBezier(p30, p31, p32, p33, muy, tension, bias), + mux, tension, bias); + //@done + } + + public static double bihermiteParametric(double p00, double p01, double p02, double p03, double p10, double p11, double p12, double p13, double p20, double p21, double p22, double p23, double p30, double p31, double p32, double p33, double mux, double muy, double tension, double bias, double a) { + //@builder + return hermiteParametric( + hermiteParametric(p00, p01, p02, p03, muy, tension, bias, a), + hermiteParametric(p10, p11, p12, p13, muy, tension, bias, a), + hermiteParametric(p20, p21, p22, p23, muy, tension, bias, a), + hermiteParametric(p30, p31, p32, p33, muy, tension, bias, a), + mux, tension, bias, a); + //@done + } + + public static double cubicBezier(double p0, double p1, double p2, double p3, double mu) { + return bezier(cubic(p0, p1, p2, p3, mu)); + } + + public static double cubicParametric(double p0, double p1, double p2, double p3, double mu, double a) { + return parametric(cubic(p0, p1, p2, p3, mu), a); + } + + public static double hermite(double p0, double p1, double p2, double p3, double mu, double tension, double bias) { + double m0, m1, mu2, mu3; + double a0, a1, a2, a3; + + mu2 = mu * mu; + mu3 = mu2 * mu; + m0 = (p1 - p0) * (1 + bias) * (1 - tension) / 2; + m0 += (p2 - p1) * (1 - bias) * (1 - tension) / 2; + m1 = (p2 - p1) * (1 + bias) * (1 - tension) / 2; + m1 += (p3 - p2) * (1 - bias) * (1 - tension) / 2; + a0 = 2 * mu3 - 3 * mu2 + 1; + a1 = mu3 - 2 * mu2 + mu; + a2 = mu3 - mu2; + a3 = -2 * mu3 + 3 * mu2; + + return (a0 * p1 + a1 * m0 + a2 * m1 + a3 * p2); + } + + public static double cubic(double p0, double p1, double p2, double p3, double mu) { + double a0, a1, a2, a3, mu2; + + mu2 = mu * mu; + a0 = p3 - p2 - p0 + p1; + a1 = p0 - p1 - a0; + a2 = p2 - p0; + a3 = p1; + + return a0 * mu * mu2 + a1 * mu2 + a2 * mu + a3; + } + + public static double getTriStarcast(int x, int y, int z, double rad, double checks, NoiseProvider n) { + return (getStarcast(x, z, rad, checks, n) + getStarcast(x, y, rad, checks, n) + getStarcast(y, z, rad, checks, n)) / 3D; + } + + public static double bicubic(double p00, double p01, double p02, double p03, double p10, double p11, double p12, double p13, double p20, double p21, double p22, double p23, double p30, double p31, double p32, double p33, double mux, double muy) { + //@builder + return cubic( + cubic(p00, p01, p02, p03, muy), + cubic(p10, p11, p12, p13, muy), + cubic(p20, p21, p22, p23, muy), + cubic(p30, p31, p32, p33, muy), + mux); + //@done + } + + public static double bihermite(double p00, double p01, double p02, double p03, double p10, double p11, double p12, double p13, double p20, double p21, double p22, double p23, double p30, double p31, double p32, double p33, double mux, double muy, double tension, double bias) { + //@builder + return hermite( + hermite(p00, p01, p02, p03, muy, tension, bias), + hermite(p10, p11, p12, p13, muy, tension, bias), + hermite(p20, p21, p22, p23, muy, tension, bias), + hermite(p30, p31, p32, p33, muy, tension, bias), + mux, tension, bias); + //@done + } + + public static double trihermite(double p000, double p001, double p002, double p003, double p010, double p011, double p012, double p013, double p020, double p021, double p022, double p023, double p030, double p031, double p032, double p033, double p100, double p101, double p102, double p103, double p110, double p111, double p112, double p113, double p120, double p121, double p122, double p123, double p130, double p131, double p132, double p133, double p200, double p201, double p202, double p203, double p210, double p211, double p212, double p213, double p220, double p221, double p222, double p223, double p230, double p231, double p232, double p233, double p300, double p301, double p302, double p303, double p310, double p311, double p312, double p313, double p320, double p321, double p322, double p323, double p330, double p331, double p332, double p333, double mux, double muy, double muz, double tension, double bias) { + //@builder + return hermite( + bihermite(p000, p001, p002, p003, + p010, p011, p012, p013, + p020, p021, p022, p023, + p030, p031, p032, p033, + mux, muy, tension, bias), + bihermite(p100, p101, p102, p103, + p110, p111, p112, p113, + p120, p121, p122, p123, + p130, p131, p132, p133, + mux, muy, tension, bias), + bihermite(p200, p201, p202, p203, + p210, p211, p212, p213, + p220, p221, p222, p223, + p230, p231, p232, p233, + mux, muy, tension, bias), + bihermite(p300, p301, p302, p303, + p310, p311, p312, p313, + p320, p321, p322, p323, + p330, p331, p332, p333, + mux, muy, tension, bias), + muz, tension, bias); + //@done + } + + public static double tricubic(double p000, + double p001, + double p002, + double p003, + double p010, + double p011, + double p012, double p013, double p020, double p021, double p022, double p023, double p030, double p031, double p032, double p033, double p100, double p101, double p102, double p103, double p110, double p111, double p112, double p113, double p120, double p121, double p122, double p123, double p130, double p131, double p132, double p133, double p200, double p201, double p202, double p203, double p210, double p211, double p212, double p213, double p220, double p221, double p222, double p223, double p230, double p231, double p232, double p233, double p300, double p301, double p302, double p303, double p310, double p311, double p312, double p313, double p320, double p321, double p322, double p323, double p330, double p331, double p332, double p333, double mux, double muy, double muz) { + //@builder + return cubic( + bicubic(p000, p001, p002, p003, + p010, p011, p012, p013, + p020, p021, p022, p023, + p030, p031, p032, p033, + mux, muy), + bicubic(p100, p101, p102, p103, + p110, p111, p112, p113, + p120, p121, p122, p123, + p130, p131, p132, p133, + mux, muy), + bicubic(p200, p201, p202, p203, + p210, p211, p212, p213, + p220, p221, p222, p223, + p230, p231, p232, p233, + mux, muy), + bicubic(p300, p301, p302, p303, + p310, p311, p312, p313, + p320, p321, p322, p323, + p330, p331, p332, p333, + mux, muy), + muz); + //@done + } + + public static double lerp(double a, double b, double f) { + return a + (f * (b - a)); + } + + public static double blerp(double a, double b, double c, double d, double tx, double ty) { + return lerp(lerp(a, b, tx), lerp(c, d, tx), ty); + } + + public static double trilerp(double v1, double v2, double v3, double v4, double v5, double v6, double v7, double v8, double x, double y, double z) { + return lerp(blerp(v1, v2, v3, v4, x, y), blerp(v5, v6, v7, v8, x, y), z); + } + + public static double bicubicBezier(double p00, double p01, double p02, double p03, double p10, double p11, double p12, double p13, double p20, double p21, double p22, double p23, double p30, double p31, double p32, double p33, double mux, double muy) { + //@builder + return cubicBezier( + cubicBezier(p00, p01, p02, p03, muy), + cubicBezier(p10, p11, p12, p13, muy), + cubicBezier(p20, p21, p22, p23, muy), + cubicBezier(p30, p31, p32, p33, muy), + mux); + //@done + } + + public static double bicubicParametric(double p00, double p01, double p02, double p03, double p10, double p11, double p12, double p13, double p20, double p21, double p22, double p23, double p30, double p31, double p32, double p33, double mux, double muy, double a) { + //@builder + return cubicParametric( + cubicParametric(p00, p01, p02, p03, muy, a), + cubicParametric(p10, p11, p12, p13, muy, a), + cubicParametric(p20, p21, p22, p23, muy, a), + cubicParametric(p30, p31, p32, p33, muy, a), + mux, a); + //@done + } + + public static CNG cng = NoiseStyle.SIMPLEX.create(new RNG()); + + public static double getBilinearNoise(int x, int z, double rad, NoiseProvider n) { + int fx = (int) Math.floor(x / rad); + int fz = (int) Math.floor(z / rad); + int x1 = (int) Math.round(fx * rad); + int z1 = (int) Math.round(fz * rad); + int x2 = (int) Math.round((fx + 1) * rad); + int z2 = (int) Math.round((fz + 1) * rad); + + double px = rangeScale(0, 1, x1, x2, x); + double pz = rangeScale(0, 1, z1, z2, z); + //@builder + return blerp( + n.noise(x1, z1), + n.noise(x2, z1), + n.noise(x1, z2), + n.noise(x2, z2), + px, pz); + //@done + } + + public static double getStarcast(int x, int z, double rad, double checks, NoiseProvider n) { + double m = (360 / checks); + double v = 0; + + for (int i = 0; i < 360; i += m) { + double sin = Math.sin(Math.toRadians(i)); + double cos = Math.cos(Math.toRadians(i)); + double cx = x + ((rad * cos) - (rad * sin)); + double cz = z + ((rad * sin) + (rad * cos)); + v += n.noise(cx, cz); + } + + return v / checks; + } + + public static double getBilinearBezierNoise(int x, int z, double rad, NoiseProvider n) { + int fx = (int) Math.floor(x / rad); + int fz = (int) Math.floor(z / rad); + int x1 = (int) Math.round(fx * rad); + int z1 = (int) Math.round(fz * rad); + int x2 = (int) Math.round((fx + 1) * rad); + int z2 = (int) Math.round((fz + 1) * rad); + double px = rangeScale(0, 1, x1, x2, x); + double pz = rangeScale(0, 1, z1, z2, z); + //@builder + return blerpBezier( + n.noise(x1, z1), + n.noise(x2, z1), + n.noise(x1, z2), + n.noise(x2, z2), + px, pz); + //@done + } + + public static double getBilinearParametricNoise(int x, int z, double rad, NoiseProvider n, double a) { + int fx = (int) Math.floor(x / rad); + int fz = (int) Math.floor(z / rad); + int x1 = (int) Math.round(fx * rad); + int z1 = (int) Math.round(fz * rad); + int x2 = (int) Math.round((fx + 1) * rad); + int z2 = (int) Math.round((fz + 1) * rad); + double px = rangeScale(0, 1, x1, x2, x); + double pz = rangeScale(0, 1, z1, z2, z); + //@builder + return blerpParametric( + n.noise(x1, z1), + n.noise(x2, z1), + n.noise(x1, z2), + n.noise(x2, z2), + px, pz, a); + //@done + } + + public static double getTrilinear(int x, int y, int z, double rad, NoiseProvider3 n) { + int fx = (int) Math.floor(x / rad); + int fy = (int) Math.floor(y / rad); + int fz = (int) Math.floor(z / rad); + int x1 = (int) Math.round(fx * rad); + int y1 = (int) Math.round(fy * rad); + int z1 = (int) Math.round(fz * rad); + int x2 = (int) Math.round((fx + 1) * rad); + int y2 = (int) Math.round((fy + 1) * rad); + int z2 = (int) Math.round((fz + 1) * rad); + double px = rangeScale(0, 1, x1, x2, x); + double py = rangeScale(0, 1, y1, y2, y); + double pz = rangeScale(0, 1, z1, z2, z); + //@builder + return trilerp( + n.noise(x1, y1, z1), + n.noise(x2, y1, z1), + n.noise(x1, y2, z1), + n.noise(x2, y2, z1), + n.noise(x1, y1, z2), + n.noise(x2, y1, z2), + n.noise(x1, y2, z2), + n.noise(x2, y2, z2), + px, py, pz); + //@done + } + + public static double getTricubic(int x, int y, int z, double rad, NoiseProvider3 n) { + int fx = (int) Math.floor(x / rad); + int fy = (int) Math.floor(y / rad); + int fz = (int) Math.floor(z / rad); + int x0 = (int) Math.round((fx - 1) * rad); + int y0 = (int) Math.round((fy - 1) * rad); + int z0 = (int) Math.round((fz - 1) * rad); + int x1 = (int) Math.round(fx * rad); + int y1 = (int) Math.round(fy * rad); + int z1 = (int) Math.round(fz * rad); + int x2 = (int) Math.round((fx + 1) * rad); + int y2 = (int) Math.round((fy + 1) * rad); + int z2 = (int) Math.round((fz + 1) * rad); + int x3 = (int) Math.round((fx + 2) * rad); + int y3 = (int) Math.round((fy + 2) * rad); + int z3 = (int) Math.round((fz + 2) * rad); + double px = rangeScale(0, 1, x1, x2, x); + double py = rangeScale(0, 1, y1, y2, y); + double pz = rangeScale(0, 1, z1, z2, z); + //@builder + //!!!!!!!!!!!!!!!!!! 2 1 3 + + return tricubic( + n.noise(x0, y0, z0), + n.noise(x0, y1, z0), + n.noise(x0, y2, z0), + n.noise(x0, y3, z0), + n.noise(x1, y0, z0), + n.noise(x1, y1, z0), + n.noise(x1, y2, z0), + n.noise(x1, y3, z0), + n.noise(x2, y0, z0), + n.noise(x2, y1, z0), + n.noise(x2, y2, z0), + n.noise(x2, y3, z0), + n.noise(x3, y0, z0), + n.noise(x3, y1, z0), + n.noise(x3, y2, z0), + n.noise(x3, y3, z0), + n.noise(x0, y0, z1), + n.noise(x0, y1, z1), + n.noise(x0, y2, z1), + n.noise(x0, y3, z1), + n.noise(x1, y0, z1), + n.noise(x1, y1, z1), + n.noise(x1, y2, z1), + n.noise(x1, y3, z1), + n.noise(x2, y0, z1), + n.noise(x2, y1, z1), + n.noise(x2, y2, z1), + n.noise(x2, y3, z1), + n.noise(x3, y0, z1), + n.noise(x3, y1, z1), + n.noise(x3, y2, z1), + n.noise(x3, y3, z1), + n.noise(x0, y0, z2), + n.noise(x0, y1, z2), + n.noise(x0, y2, z2), + n.noise(x0, y3, z2), + n.noise(x1, y0, z2), + n.noise(x1, y1, z2), + n.noise(x1, y2, z2), + n.noise(x1, y3, z2), + n.noise(x2, y0, z2), + n.noise(x2, y1, z2), + n.noise(x2, y2, z2), + n.noise(x2, y3, z2), + n.noise(x3, y0, z2), + n.noise(x3, y1, z2), + n.noise(x3, y2, z2), + n.noise(x3, y3, z2), + n.noise(x0, y0, z3), + n.noise(x0, y1, z3), + n.noise(x0, y2, z3), + n.noise(x0, y3, z3), + n.noise(x1, y0, z3), + n.noise(x1, y1, z3), + n.noise(x1, y2, z3), + n.noise(x1, y3, z3), + n.noise(x2, y0, z3), + n.noise(x2, y1, z3), + n.noise(x2, y2, z3), + n.noise(x2, y3, z3), + n.noise(x3, y0, z3), + n.noise(x3, y1, z3), + n.noise(x3, y2, z3), + n.noise(x3, y3, z3), + px, py, pz); + //@done + } + + public static double getTrihermite(int x, int y, int z, double rad, NoiseProvider3 n) { + return getTrihermite(x, y, z, rad, n, 0D, 0D); + } + + public static double getTrihermite(int x, int y, int z, double rad, NoiseProvider3 n, double tension, double bias) { + int fx = (int) Math.floor(x / rad); + int fy = (int) Math.floor(y / rad); + int fz = (int) Math.floor(z / rad); + int x0 = (int) Math.round((fx - 1) * rad); + int y0 = (int) Math.round((fy - 1) * rad); + int z0 = (int) Math.round((fz - 1) * rad); + int x1 = (int) Math.round(fx * rad); + int y1 = (int) Math.round(fy * rad); + int z1 = (int) Math.round(fz * rad); + int x2 = (int) Math.round((fx + 1) * rad); + int y2 = (int) Math.round((fy + 1) * rad); + int z2 = (int) Math.round((fz + 1) * rad); + int x3 = (int) Math.round((fx + 2) * rad); + int y3 = (int) Math.round((fy + 2) * rad); + int z3 = (int) Math.round((fz + 2) * rad); + double px = rangeScale(0, 1, x1, x2, x); + double py = rangeScale(0, 1, y1, y2, y); + double pz = rangeScale(0, 1, z1, z2, z); + //@builder + //!!!!!!!!!!!!!!!!!! 2 1 3 + + return trihermite( + n.noise(x0, y0, z0), + n.noise(x0, y1, z0), + n.noise(x0, y2, z0), + n.noise(x0, y3, z0), + n.noise(x1, y0, z0), + n.noise(x1, y1, z0), + n.noise(x1, y2, z0), + n.noise(x1, y3, z0), + n.noise(x2, y0, z0), + n.noise(x2, y1, z0), + n.noise(x2, y2, z0), + n.noise(x2, y3, z0), + n.noise(x3, y0, z0), + n.noise(x3, y1, z0), + n.noise(x3, y2, z0), + n.noise(x3, y3, z0), + n.noise(x0, y0, z1), + n.noise(x0, y1, z1), + n.noise(x0, y2, z1), + n.noise(x0, y3, z1), + n.noise(x1, y0, z1), + n.noise(x1, y1, z1), + n.noise(x1, y2, z1), + n.noise(x1, y3, z1), + n.noise(x2, y0, z1), + n.noise(x2, y1, z1), + n.noise(x2, y2, z1), + n.noise(x2, y3, z1), + n.noise(x3, y0, z1), + n.noise(x3, y1, z1), + n.noise(x3, y2, z1), + n.noise(x3, y3, z1), + n.noise(x0, y0, z2), + n.noise(x0, y1, z2), + n.noise(x0, y2, z2), + n.noise(x0, y3, z2), + n.noise(x1, y0, z2), + n.noise(x1, y1, z2), + n.noise(x1, y2, z2), + n.noise(x1, y3, z2), + n.noise(x2, y0, z2), + n.noise(x2, y1, z2), + n.noise(x2, y2, z2), + n.noise(x2, y3, z2), + n.noise(x3, y0, z2), + n.noise(x3, y1, z2), + n.noise(x3, y2, z2), + n.noise(x3, y3, z2), + n.noise(x0, y0, z3), + n.noise(x0, y1, z3), + n.noise(x0, y2, z3), + n.noise(x0, y3, z3), + n.noise(x1, y0, z3), + n.noise(x1, y1, z3), + n.noise(x1, y2, z3), + n.noise(x1, y3, z3), + n.noise(x2, y0, z3), + n.noise(x2, y1, z3), + n.noise(x2, y2, z3), + n.noise(x2, y3, z3), + n.noise(x3, y0, z3), + n.noise(x3, y1, z3), + n.noise(x3, y2, z3), + n.noise(x3, y3, z3), + px, py, pz, tension, bias); + //@done + } + + public static double getBilinearCenterSineNoise(int x, int z, double rad, NoiseProvider n) { + int fx = (int) Math.floor(x / rad); + int fz = (int) Math.floor(z / rad); + int x1 = (int) Math.round(fx * rad); + int z1 = (int) Math.round(fz * rad); + int x2 = (int) Math.round((fx + 1) * rad); + int z2 = (int) Math.round((fz + 1) * rad); + double px = rangeScale(0, 1, x1, x2, x); + double pz = rangeScale(0, 1, z1, z2, z); + //@builder + return blerpSinCenter( + n.noise(x1, z1), + n.noise(x2, z1), + n.noise(x1, z2), + n.noise(x2, z2), + px, pz); + //@done + } + + public static double getBicubicNoise(int x, int z, double rad, NoiseProvider n) { + int fx = (int) Math.floor(x / rad); + int fz = (int) Math.floor(z / rad); + int x0 = (int) Math.round((fx - 1) * rad); + int z0 = (int) Math.round((fz - 1) * rad); + int x1 = (int) Math.round(fx * rad); + int z1 = (int) Math.round(fz * rad); + int x2 = (int) Math.round((fx + 1) * rad); + int z2 = (int) Math.round((fz + 1) * rad); + int x3 = (int) Math.round((fx + 2) * rad); + int z3 = (int) Math.round((fz + 2) * rad); + double px = rangeScale(0, 1, x1, x2, x); + double pz = rangeScale(0, 1, z1, z2, z); + //@builder + return bicubic( + n.noise(x0, z0), + n.noise(x0, z1), + n.noise(x0, z2), + n.noise(x0, z3), + n.noise(x1, z0), + n.noise(x1, z1), + n.noise(x1, z2), + n.noise(x1, z3), + n.noise(x2, z0), + n.noise(x2, z1), + n.noise(x2, z2), + n.noise(x2, z3), + n.noise(x3, z0), + n.noise(x3, z1), + n.noise(x3, z2), + n.noise(x3, z3), + px, pz); + //@done + } + + public static double getBicubicBezierNoise(int x, int z, double rad, NoiseProvider n) { + int fx = (int) Math.floor(x / rad); + int fz = (int) Math.floor(z / rad); + int x0 = (int) Math.round((fx - 1) * rad); + int z0 = (int) Math.round((fz - 1) * rad); + int x1 = (int) Math.round(fx * rad); + int z1 = (int) Math.round(fz * rad); + int x2 = (int) Math.round((fx + 1) * rad); + int z2 = (int) Math.round((fz + 1) * rad); + int x3 = (int) Math.round((fx + 2) * rad); + int z3 = (int) Math.round((fz + 2) * rad); + double px = rangeScale(0, 1, x1, x2, x); + double pz = rangeScale(0, 1, z1, z2, z); + //@builder + return bicubicBezier( + n.noise(x0, z0), + n.noise(x0, z1), + n.noise(x0, z2), + n.noise(x0, z3), + n.noise(x1, z0), + n.noise(x1, z1), + n.noise(x1, z2), + n.noise(x1, z3), + n.noise(x2, z0), + n.noise(x2, z1), + n.noise(x2, z2), + n.noise(x2, z3), + n.noise(x3, z0), + n.noise(x3, z1), + n.noise(x3, z2), + n.noise(x3, z3), + px, pz); + //@done + } + + public static double getBicubicParametricNoise(int x, int z, double rad, NoiseProvider n, double a) { + int fx = (int) Math.floor(x / rad); + int fz = (int) Math.floor(z / rad); + int x0 = (int) Math.round((fx - 1) * rad); + int z0 = (int) Math.round((fz - 1) * rad); + int x1 = (int) Math.round(fx * rad); + int z1 = (int) Math.round(fz * rad); + int x2 = (int) Math.round((fx + 1) * rad); + int z2 = (int) Math.round((fz + 1) * rad); + int x3 = (int) Math.round((fx + 2) * rad); + int z3 = (int) Math.round((fz + 2) * rad); + double px = rangeScale(0, 1, x1, x2, x); + double pz = rangeScale(0, 1, z1, z2, z); + //@builder + return bicubicParametric( + n.noise(x0, z0), + n.noise(x0, z1), + n.noise(x0, z2), + n.noise(x0, z3), + n.noise(x1, z0), + n.noise(x1, z1), + n.noise(x1, z2), + n.noise(x1, z3), + n.noise(x2, z0), + n.noise(x2, z1), + n.noise(x2, z2), + n.noise(x2, z3), + n.noise(x3, z0), + n.noise(x3, z1), + n.noise(x3, z2), + n.noise(x3, z3), + px, pz, a); + //@done + } + + public static double getHermiteNoise(int x, int z, double rad, NoiseProvider n) { + return getHermiteNoise(x, z, rad, n, 0.5, 0); + } + + public static double getHermiteBezierNoise(int x, int z, double rad, NoiseProvider n) { + return getHermiteBezierNoise(x, z, rad, n, 0.5, 0); + } + + public static double getHermiteParametricNoise(int x, int z, double rad, NoiseProvider n, double a) { + return getHermiteParametricNoise(x, z, rad, n, 0.5, 0, a); + } + + public static double getHermiteNoise(int x, int z, double rad, NoiseProvider n, double t, double b) { + int fx = (int) Math.floor(x / rad); + int fz = (int) Math.floor(z / rad); + int x0 = (int) Math.round((fx - 1) * rad); + int z0 = (int) Math.round((fz - 1) * rad); + int x1 = (int) Math.round(fx * rad); + int z1 = (int) Math.round(fz * rad); + int x2 = (int) Math.round((fx + 1) * rad); + int z2 = (int) Math.round((fz + 1) * rad); + int x3 = (int) Math.round((fx + 2) * rad); + int z3 = (int) Math.round((fz + 2) * rad); + double px = rangeScale(0, 1, x1, x2, x); + double pz = rangeScale(0, 1, z1, z2, z); + //@builder + return bihermite( + n.noise(x0, z0), + n.noise(x0, z1), + n.noise(x0, z2), + n.noise(x0, z3), + n.noise(x1, z0), + n.noise(x1, z1), + n.noise(x1, z2), + n.noise(x1, z3), + n.noise(x2, z0), + n.noise(x2, z1), + n.noise(x2, z2), + n.noise(x2, z3), + n.noise(x3, z0), + n.noise(x3, z1), + n.noise(x3, z2), + n.noise(x3, z3), + px, pz, t, b); + //@done + } + + public static double getHermiteBezierNoise(int x, int z, double rad, NoiseProvider n, double t, double b) { + int fx = (int) Math.floor(x / rad); + int fz = (int) Math.floor(z / rad); + int x0 = (int) Math.round((fx - 1) * rad); + int z0 = (int) Math.round((fz - 1) * rad); + int x1 = (int) Math.round(fx * rad); + int z1 = (int) Math.round(fz * rad); + int x2 = (int) Math.round((fx + 1) * rad); + int z2 = (int) Math.round((fz + 1) * rad); + int x3 = (int) Math.round((fx + 2) * rad); + int z3 = (int) Math.round((fz + 2) * rad); + double px = rangeScale(0, 1, x1, x2, x); + double pz = rangeScale(0, 1, z1, z2, z); + //@builder + return bihermiteBezier( + n.noise(x0, z0), + n.noise(x0, z1), + n.noise(x0, z2), + n.noise(x0, z3), + n.noise(x1, z0), + n.noise(x1, z1), + n.noise(x1, z2), + n.noise(x1, z3), + n.noise(x2, z0), + n.noise(x2, z1), + n.noise(x2, z2), + n.noise(x2, z3), + n.noise(x3, z0), + n.noise(x3, z1), + n.noise(x3, z2), + n.noise(x3, z3), + px, pz, t, b); + //@done + } + + public static double getHermiteParametricNoise(int x, int z, double rad, NoiseProvider n, double t, double b, double a) { + int fx = (int) Math.floor(x / rad); + int fz = (int) Math.floor(z / rad); + int x0 = (int) Math.round((fx - 1) * rad); + int z0 = (int) Math.round((fz - 1) * rad); + int x1 = (int) Math.round(fx * rad); + int z1 = (int) Math.round(fz * rad); + int x2 = (int) Math.round((fx + 1) * rad); + int z2 = (int) Math.round((fz + 1) * rad); + int x3 = (int) Math.round((fx + 2) * rad); + int z3 = (int) Math.round((fz + 2) * rad); + double px = rangeScale(0, 1, x1, x2, x); + double pz = rangeScale(0, 1, z1, z2, z); + //@builder + return bihermiteParametric( + n.noise(x0, z0), + n.noise(x0, z1), + n.noise(x0, z2), + n.noise(x0, z3), + n.noise(x1, z0), + n.noise(x1, z1), + n.noise(x1, z2), + n.noise(x1, z3), + n.noise(x2, z0), + n.noise(x2, z1), + n.noise(x2, z2), + n.noise(x2, z3), + n.noise(x3, z0), + n.noise(x3, z1), + n.noise(x3, z2), + n.noise(x3, z3), + px, pz, t, b, a); + //@done + } + + public static double getRealRadius(InterpolationMethod method, double h) { + AtomicDouble rad = new AtomicDouble(h); + AtomicDouble accessX = new AtomicDouble(); + AtomicDouble accessZ = new AtomicDouble(); + NoiseProvider np = (x1, z1) -> { + double d = Math.max(Math.abs(x1), Math.abs(z1)); + if (d > rad.get()) { + rad.set(d); + } + return 0; + }; + getNoise(method, 0, 0, h, np); + return rad.get(); + } + + public static double getNoise(InterpolationMethod method, int x, int z, double h, NoiseProvider n) { + if (method.equals(InterpolationMethod.BILINEAR)) { + return getBilinearNoise(x, z, h, n); + } else if (method.equals(InterpolationMethod.STARCAST_3)) { + return getStarcast(x, z, h, 3D, n); + } else if (method.equals(InterpolationMethod.STARCAST_6)) { + return getStarcast(x, z, h, 6D, n); + } else if (method.equals(InterpolationMethod.STARCAST_9)) { + return getStarcast(x, z, h, 9D, n); + } else if (method.equals(InterpolationMethod.STARCAST_12)) { + return getStarcast(x, z, h, 12D, n); + } else if (method.equals(InterpolationMethod.BILINEAR_STARCAST_3)) { + return getStarcast(x, z, h, 3D, (xx, zz) -> getBilinearNoise((int) xx, (int) zz, h, n)); + } else if (method.equals(InterpolationMethod.BILINEAR_STARCAST_6)) { + return getStarcast(x, z, h, 6D, (xx, zz) -> getBilinearNoise((int) xx, (int) zz, h, n)); + } else if (method.equals(InterpolationMethod.BILINEAR_STARCAST_9)) { + return getStarcast(x, z, h, 9D, (xx, zz) -> getBilinearNoise((int) xx, (int) zz, h, n)); + } else if (method.equals(InterpolationMethod.BILINEAR_STARCAST_12)) { + return getStarcast(x, z, h, 12D, (xx, zz) -> getBilinearNoise((int) xx, (int) zz, h, n)); + } else if (method.equals(InterpolationMethod.HERMITE_STARCAST_3)) { + return getStarcast(x, z, h, 3D, (xx, zz) -> getHermiteNoise((int) xx, (int) zz, h, n, 0D, 0D)); + } else if (method.equals(InterpolationMethod.HERMITE_STARCAST_6)) { + return getStarcast(x, z, h, 6D, (xx, zz) -> getHermiteNoise((int) xx, (int) zz, h, n, 0D, 0D)); + } else if (method.equals(InterpolationMethod.HERMITE_STARCAST_9)) { + return getStarcast(x, z, h, 9D, (xx, zz) -> getHermiteNoise((int) xx, (int) zz, h, n, 0D, 0D)); + } else if (method.equals(InterpolationMethod.HERMITE_STARCAST_12)) { + return getStarcast(x, z, h, 12D, (xx, zz) -> getHermiteNoise((int) xx, (int) zz, h, n, 0D, 0D)); + } else if (method.equals(InterpolationMethod.BICUBIC)) { + return getBicubicNoise(x, z, h, n); + } else if (method.equals(InterpolationMethod.BILINEAR_BEZIER)) { + return getBilinearBezierNoise(x, z, h, n); + } else if (method.equals(InterpolationMethod.BILINEAR_PARAMETRIC_2)) { + return getBilinearParametricNoise(x, z, h, n, 2); + } else if (method.equals(InterpolationMethod.BILINEAR_PARAMETRIC_4)) { + return getBilinearParametricNoise(x, z, h, n, 4); + } else if (method.equals(InterpolationMethod.BILINEAR_PARAMETRIC_1_5)) { + return getBilinearParametricNoise(x, z, h, n, 1.5); + } else if (method.equals(InterpolationMethod.BICUBIC)) { + return getBilinearNoise(x, z, h, n); + } else if (method.equals(InterpolationMethod.HERMITE)) { + return getHermiteNoise(x, z, h, n); + } else if (method.equals(InterpolationMethod.HERMITE_TENSE)) { + return getHermiteNoise(x, z, h, n, 0.8D, 0D); + } else if (method.equals(InterpolationMethod.CATMULL_ROM_SPLINE)) { + return getHermiteNoise(x, z, h, n, 1D, 0D); + } else if (method.equals(InterpolationMethod.HERMITE_LOOSE)) { + return getHermiteNoise(x, z, h, n, 0D, 0D); + } else if (method.equals(InterpolationMethod.HERMITE_LOOSE_HALF_NEGATIVE_BIAS)) { + return getHermiteNoise(x, z, h, n, 0D, -0.5D); + } else if (method.equals(InterpolationMethod.HERMITE_LOOSE_HALF_POSITIVE_BIAS)) { + return getHermiteNoise(x, z, h, n, 0D, 0.5D); + } else if (method.equals(InterpolationMethod.HERMITE_LOOSE_FULL_NEGATIVE_BIAS)) { + return getHermiteNoise(x, z, h, n, 0D, -1D); + } else if (method.equals(InterpolationMethod.HERMITE_LOOSE_FULL_POSITIVE_BIAS)) { + return getHermiteNoise(x, z, h, n, 0D, 1D); + } + + return n.noise(x, z); + } + + public static double rangeScale(double amin, double amax, double bmin, double bmax, double b) { + return amin + ((amax - amin) * ((b - bmin) / (bmax - bmin))); + } } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/IrisLock.java b/src/main/java/com/volmit/iris/util/IrisLock.java index 63bc8420f..58777d935 100644 --- a/src/main/java/com/volmit/iris/util/IrisLock.java +++ b/src/main/java/com/volmit/iris/util/IrisLock.java @@ -1,46 +1,36 @@ package com.volmit.iris.util; -import java.util.concurrent.locks.ReentrantLock; - import lombok.Data; +import java.util.concurrent.locks.ReentrantLock; + @Data -public class IrisLock -{ - private transient final ReentrantLock lock; - private transient final String name; - private transient boolean disabled = false; +public class IrisLock { + private transient final ReentrantLock lock; + private transient final String name; + private transient boolean disabled = false; - public IrisLock(String name) - { - this.name = name; - lock = new ReentrantLock(false); - } + public IrisLock(String name) { + this.name = name; + lock = new ReentrantLock(false); + } - public void lock() - { - if(disabled) - { - return; - } + public void lock() { + if (disabled) { + return; + } - lock.lock(); - } + lock.lock(); + } - public void unlock() - { - if(disabled) - { - return; - } - try - { - lock.unlock(); - } + public void unlock() { + if (disabled) { + return; + } + try { + lock.unlock(); + } catch (Throwable e) { - catch(Throwable e) - { - - } - } + } + } } diff --git a/src/main/java/com/volmit/iris/util/IrisMathHelper.java b/src/main/java/com/volmit/iris/util/IrisMathHelper.java index 8f775c5c7..554767bb4 100644 --- a/src/main/java/com/volmit/iris/util/IrisMathHelper.java +++ b/src/main/java/com/volmit/iris/util/IrisMathHelper.java @@ -4,548 +4,448 @@ import java.util.Random; import java.util.UUID; import java.util.function.IntPredicate; -public class IrisMathHelper -{ - public static final float a; - private static final Random c; - private static final int[] d; - private static final double e; - private static final double[] f; - private static final double[] g; +public class IrisMathHelper { + public static final float a; + private static final Random c; + private static final int[] d; + private static final double e; + private static final double[] f; + private static final double[] g; - public static float c(final float var0) - { - return (float) Math.sqrt(var0); - } + public static float c(final float var0) { + return (float) Math.sqrt(var0); + } - public static float sqrt(final double var0) - { - return (float) Math.sqrt(var0); - } + public static float sqrt(final double var0) { + return (float) Math.sqrt(var0); + } - public static int d(final float var0) - { - final int var = (int) var0; - return (var0 < var) ? (var - 1) : var; - } + public static int d(final float var0) { + final int var = (int) var0; + return (var0 < var) ? (var - 1) : var; + } - public static int floor(final double var0) - { - final int var = (int) var0; - return (var0 < var) ? (var - 1) : var; - } + public static int floor(final double var0) { + final int var = (int) var0; + return (var0 < var) ? (var - 1) : var; + } - public static long d(final double var0) - { - final long var = (long) var0; - return (var0 < var) ? (var - 1L) : var; - } + public static long d(final double var0) { + final long var = (long) var0; + return (var0 < var) ? (var - 1L) : var; + } - public static float e(final float var0) - { - return Math.abs(var0); - } + public static float e(final float var0) { + return Math.abs(var0); + } - public static int a(final int var0) - { - return Math.abs(var0); - } + public static int a(final int var0) { + return Math.abs(var0); + } - public static int f(final float var0) - { - final int var = (int) var0; - return (var0 > var) ? (var + 1) : var; - } + public static int f(final float var0) { + final int var = (int) var0; + return (var0 > var) ? (var + 1) : var; + } - public static int f(final double var0) - { - final int var = (int) var0; - return (var0 > var) ? (var + 1) : var; - } + public static int f(final double var0) { + final int var = (int) var0; + return (var0 > var) ? (var + 1) : var; + } - public static int clamp(final int var0, final int var1, final int var2) - { - if(var0 < var1) - { - return var1; - } - if(var0 > var2) - { - return var2; - } - return var0; - } + public static int clamp(final int var0, final int var1, final int var2) { + if (var0 < var1) { + return var1; + } + if (var0 > var2) { + return var2; + } + return var0; + } - public static float a(final float var0, final float var1, final float var2) - { - if(var0 < var1) - { - return var1; - } - if(var0 > var2) - { - return var2; - } - return var0; - } + public static float a(final float var0, final float var1, final float var2) { + if (var0 < var1) { + return var1; + } + if (var0 > var2) { + return var2; + } + return var0; + } - public static double a(final double var0, final double var2, final double var4) - { - if(var0 < var2) - { - return var2; - } - if(var0 > var4) - { - return var4; - } - return var0; - } + public static double a(final double var0, final double var2, final double var4) { + if (var0 < var2) { + return var2; + } + if (var0 > var4) { + return var4; + } + return var0; + } - public static double b(final double var0, final double var2, final double var4) - { - if(var4 < 0.0) - { - return var0; - } - if(var4 > 1.0) - { - return var2; - } - return d(var4, var0, var2); - } + public static double b(final double var0, final double var2, final double var4) { + if (var4 < 0.0) { + return var0; + } + if (var4 > 1.0) { + return var2; + } + return d(var4, var0, var2); + } - public static double a(double var0, double var2) - { - if(var0 < 0.0) - { - var0 = -var0; - } - if(var2 < 0.0) - { - var2 = -var2; - } - return (var0 > var2) ? var0 : var2; - } + public static double a(double var0, double var2) { + if (var0 < 0.0) { + var0 = -var0; + } + if (var2 < 0.0) { + var2 = -var2; + } + return (var0 > var2) ? var0 : var2; + } - public static int a(final int var0, final int var1) - { - return Math.floorDiv(var0, var1); - } + public static int a(final int var0, final int var1) { + return Math.floorDiv(var0, var1); + } - public static int nextInt(final Random var0, final int var1, final int var2) - { - if(var1 >= var2) - { - return var1; - } - return var0.nextInt(var2 - var1 + 1) + var1; - } + public static int nextInt(final Random var0, final int var1, final int var2) { + if (var1 >= var2) { + return var1; + } + return var0.nextInt(var2 - var1 + 1) + var1; + } - public static float a(final Random var0, final float var1, final float var2) - { - if(var1 >= var2) - { - return var1; - } - return var0.nextFloat() * (var2 - var1) + var1; - } + public static float a(final Random var0, final float var1, final float var2) { + if (var1 >= var2) { + return var1; + } + return var0.nextFloat() * (var2 - var1) + var1; + } - public static double a(final Random var0, final double var1, final double var3) - { - if(var1 >= var3) - { - return var1; - } - return var0.nextDouble() * (var3 - var1) + var1; - } + public static double a(final Random var0, final double var1, final double var3) { + if (var1 >= var3) { + return var1; + } + return var0.nextDouble() * (var3 - var1) + var1; + } - public static double a(final long[] var0) - { - long var = 0L; - for(final long var2 : var0) - { - var += var2; - } - return var / (double) var0.length; - } + public static double a(final long[] var0) { + long var = 0L; + for (final long var2 : var0) { + var += var2; + } + return var / (double) var0.length; + } - public static boolean b(final double var0, final double var2) - { - return Math.abs(var2 - var0) < 9.999999747378752E-6; - } + public static boolean b(final double var0, final double var2) { + return Math.abs(var2 - var0) < 9.999999747378752E-6; + } - public static int b(final int var0, final int var1) - { - return Math.floorMod(var0, var1); - } + public static int b(final int var0, final int var1) { + return Math.floorMod(var0, var1); + } - public static float g(final float var0) - { - float var = var0 % 360.0f; - if(var >= 180.0f) - { - var -= 360.0f; - } - if(var < -180.0f) - { - var += 360.0f; - } - return var; - } + public static float g(final float var0) { + float var = var0 % 360.0f; + if (var >= 180.0f) { + var -= 360.0f; + } + if (var < -180.0f) { + var += 360.0f; + } + return var; + } - public static double g(final double var0) - { - double var = var0 % 360.0; - if(var >= 180.0) - { - var -= 360.0; - } - if(var < -180.0) - { - var += 360.0; - } - return var; - } + public static double g(final double var0) { + double var = var0 % 360.0; + if (var >= 180.0) { + var -= 360.0; + } + if (var < -180.0) { + var += 360.0; + } + return var; + } - public static float c(final float var0, final float var1) - { - return g(var1 - var0); - } + public static float c(final float var0, final float var1) { + return g(var1 - var0); + } - public static float d(final float var0, final float var1) - { - return e(c(var0, var1)); - } + public static float d(final float var0, final float var1) { + return e(c(var0, var1)); + } - public static float b(final float var0, final float var1, final float var2) - { - final float var3 = c(var0, var1); - final float var4 = a(var3, -var2, var2); - return var1 - var4; - } + public static float b(final float var0, final float var1, final float var2) { + final float var3 = c(var0, var1); + final float var4 = a(var3, -var2, var2); + return var1 - var4; + } - public static float c(final float var0, final float var1, float var2) - { - var2 = e(var2); - if(var0 < var1) - { - return a(var0 + var2, var0, var1); - } - return a(var0 - var2, var1, var0); - } + public static float c(final float var0, final float var1, float var2) { + var2 = e(var2); + if (var0 < var1) { + return a(var0 + var2, var0, var1); + } + return a(var0 - var2, var1, var0); + } - public static float d(final float var0, final float var1, final float var2) - { - final float var3 = c(var0, var1); - return c(var0, var0 + var3, var2); - } + public static float d(final float var0, final float var1, final float var2) { + final float var3 = c(var0, var1); + return c(var0, var0 + var3, var2); + } - public static int c(final int var0) - { - int var = var0 - 1; - var |= var >> 1; - var |= var >> 2; - var |= var >> 4; - var |= var >> 8; - var |= var >> 16; - return var + 1; - } + public static int c(final int var0) { + int var = var0 - 1; + var |= var >> 1; + var |= var >> 2; + var |= var >> 4; + var |= var >> 8; + var |= var >> 16; + return var + 1; + } - public static boolean d(final int var0) - { - return var0 != 0 && (var0 & var0 - 1) == 0x0; - } + public static boolean d(final int var0) { + return var0 != 0 && (var0 & var0 - 1) == 0x0; + } - public static int e(int var0) - { - var0 = (d(var0) ? var0 : c(var0)); - return IrisMathHelper.d[(int) (var0 * 125613361L >> 27) & 0x1F]; - } + public static int e(int var0) { + var0 = (d(var0) ? var0 : c(var0)); + return IrisMathHelper.d[(int) (var0 * 125613361L >> 27) & 0x1F]; + } - public static int f(final int var0) - { - return e(var0) - (d(var0) ? 0 : 1); - } + public static int f(final int var0) { + return e(var0) - (d(var0) ? 0 : 1); + } - public static int c(final int var0, int var1) - { - if(var1 == 0) - { - return 0; - } - if(var0 == 0) - { - return var1; - } - if(var0 < 0) - { - var1 *= -1; - } - final int var2 = var0 % var1; - if(var2 == 0) - { - return var0; - } - return var0 + var1 - var2; - } + public static int c(final int var0, int var1) { + if (var1 == 0) { + return 0; + } + if (var0 == 0) { + return var1; + } + if (var0 < 0) { + var1 *= -1; + } + final int var2 = var0 % var1; + if (var2 == 0) { + return var0; + } + return var0 + var1 - var2; + } - public static float h(final float var0) - { - return var0 - d(var0); - } + public static float h(final float var0) { + return var0 - d(var0); + } - public static double h(final double var0) - { - return var0 - d(var0); - } + public static double h(final double var0) { + return var0 - d(var0); + } - public static long c(final int var0, final int var1, final int var2) - { - long var3 = (long) (var0 * 3129871) ^ var2 * 116129781L ^ (long) var1; - var3 = var3 * var3 * 42317861L + var3 * 11L; - return var3 >> 16; - } + public static long c(final int var0, final int var1, final int var2) { + long var3 = (long) (var0 * 3129871) ^ var2 * 116129781L ^ (long) var1; + var3 = var3 * var3 * 42317861L + var3 * 11L; + return var3 >> 16; + } - public static UUID a(final Random var0) - { - final long var = (var0.nextLong() & 0xFFFFFFFFFFFF0FFFL) | 0x4000L; - final long var2 = (var0.nextLong() & 0x3FFFFFFFFFFFFFFFL) | Long.MIN_VALUE; - return new UUID(var, var2); - } + public static UUID a(final Random var0) { + final long var = (var0.nextLong() & 0xFFFFFFFFFFFF0FFFL) | 0x4000L; + final long var2 = (var0.nextLong() & 0x3FFFFFFFFFFFFFFFL) | Long.MIN_VALUE; + return new UUID(var, var2); + } - public static UUID a() - { - return a(IrisMathHelper.c); - } + public static UUID a() { + return a(IrisMathHelper.c); + } - public static double c(final double var0, final double var2, final double var4) - { - return (var0 - var2) / (var4 - var2); - } + public static double c(final double var0, final double var2, final double var4) { + return (var0 - var2) / (var4 - var2); + } - public static double d(double var0, double var2) - { - final double var3 = var2 * var2 + var0 * var0; - if(Double.isNaN(var3)) - { - return Double.NaN; - } - final boolean var4 = var0 < 0.0; - if(var4) - { - var0 = -var0; - } - final boolean var5 = var2 < 0.0; - if(var5) - { - var2 = -var2; - } - final boolean var6 = var0 > var2; - if(var6) - { - final double var7 = var2; - var2 = var0; - var0 = var7; - } - final double var7 = i(var3); - var2 *= var7; - var0 *= var7; - final double var8 = IrisMathHelper.e + var0; - final int var9 = (int) Double.doubleToRawLongBits(var8); - final double var10 = IrisMathHelper.f[var9]; - final double var11 = IrisMathHelper.g[var9]; - final double var12 = var8 - IrisMathHelper.e; - final double var13 = var0 * var11 - var2 * var12; - final double var14 = (6.0 + var13 * var13) * var13 * 0.16666666666666666; - double var15 = var10 + var14; - if(var6) - { - var15 = 1.5707963267948966 - var15; - } - if(var5) - { - var15 = 3.141592653589793 - var15; - } - if(var4) - { - var15 = -var15; - } - return var15; - } + public static double d(double var0, double var2) { + final double var3 = var2 * var2 + var0 * var0; + if (Double.isNaN(var3)) { + return Double.NaN; + } + final boolean var4 = var0 < 0.0; + if (var4) { + var0 = -var0; + } + final boolean var5 = var2 < 0.0; + if (var5) { + var2 = -var2; + } + final boolean var6 = var0 > var2; + if (var6) { + final double var7 = var2; + var2 = var0; + var0 = var7; + } + final double var7 = i(var3); + var2 *= var7; + var0 *= var7; + final double var8 = IrisMathHelper.e + var0; + final int var9 = (int) Double.doubleToRawLongBits(var8); + final double var10 = IrisMathHelper.f[var9]; + final double var11 = IrisMathHelper.g[var9]; + final double var12 = var8 - IrisMathHelper.e; + final double var13 = var0 * var11 - var2 * var12; + final double var14 = (6.0 + var13 * var13) * var13 * 0.16666666666666666; + double var15 = var10 + var14; + if (var6) { + var15 = 1.5707963267948966 - var15; + } + if (var5) { + var15 = 3.141592653589793 - var15; + } + if (var4) { + var15 = -var15; + } + return var15; + } - public static double i(double var0) - { - final double var = 0.5 * var0; - long var2 = Double.doubleToRawLongBits(var0); - var2 = 6910469410427058090L - (var2 >> 1); - var0 = Double.longBitsToDouble(var2); - var0 *= 1.5 - var * var0 * var0; - return var0; - } + public static double i(double var0) { + final double var = 0.5 * var0; + long var2 = Double.doubleToRawLongBits(var0); + var2 = 6910469410427058090L - (var2 >> 1); + var0 = Double.longBitsToDouble(var2); + var0 *= 1.5 - var * var0 * var0; + return var0; + } - public static int f(final float var0, final float var1, final float var2) - { - final int var3 = (int) (var0 * 6.0f) % 6; - final float var4 = var0 * 6.0f - var3; - final float var5 = var2 * (1.0f - var1); - final float var6 = var2 * (1.0f - var4 * var1); - final float var7 = var2 * (1.0f - (1.0f - var4) * var1); - float var8 = 0.0f; - float var9 = 0.0f; - float var10 = 0.0f; - switch(var3) - { - case 0: - { - var8 = var2; - var9 = var7; - var10 = var5; - break; - } - case 1: - { - var8 = var6; - var9 = var2; - var10 = var5; - break; - } - case 2: - { - var8 = var5; - var9 = var2; - var10 = var7; - break; - } - case 3: - { - var8 = var5; - var9 = var6; - var10 = var2; - break; - } - case 4: - { - var8 = var7; - var9 = var5; - var10 = var2; - break; - } - case 5: - { - var8 = var2; - var9 = var5; - var10 = var6; - break; - } - default: - { - throw new RuntimeException("Something went wrong when converting from HSV to RGB. Input was " + var0 + ", " + var1 + ", " + var2); - } - } - final int var11 = clamp((int) (var8 * 255.0f), 0, 255); - final int var12 = clamp((int) (var9 * 255.0f), 0, 255); - final int var13 = clamp((int) (var10 * 255.0f), 0, 255); - return var11 << 16 | var12 << 8 | var13; - } + public static int f(final float var0, final float var1, final float var2) { + final int var3 = (int) (var0 * 6.0f) % 6; + final float var4 = var0 * 6.0f - var3; + final float var5 = var2 * (1.0f - var1); + final float var6 = var2 * (1.0f - var4 * var1); + final float var7 = var2 * (1.0f - (1.0f - var4) * var1); + float var8 = 0.0f; + float var9 = 0.0f; + float var10 = 0.0f; + switch (var3) { + case 0: { + var8 = var2; + var9 = var7; + var10 = var5; + break; + } + case 1: { + var8 = var6; + var9 = var2; + var10 = var5; + break; + } + case 2: { + var8 = var5; + var9 = var2; + var10 = var7; + break; + } + case 3: { + var8 = var5; + var9 = var6; + var10 = var2; + break; + } + case 4: { + var8 = var7; + var9 = var5; + var10 = var2; + break; + } + case 5: { + var8 = var2; + var9 = var5; + var10 = var6; + break; + } + default: { + throw new RuntimeException("Something went wrong when converting from HSV to RGB. Input was " + var0 + ", " + var1 + ", " + var2); + } + } + final int var11 = clamp((int) (var8 * 255.0f), 0, 255); + final int var12 = clamp((int) (var9 * 255.0f), 0, 255); + final int var13 = clamp((int) (var10 * 255.0f), 0, 255); + return var11 << 16 | var12 << 8 | var13; + } - public static int g(int var0) - { - var0 ^= var0 >>> 16; - var0 *= -2048144789; - var0 ^= var0 >>> 13; - var0 *= -1028477387; - var0 ^= var0 >>> 16; - return var0; - } + public static int g(int var0) { + var0 ^= var0 >>> 16; + var0 *= -2048144789; + var0 ^= var0 >>> 13; + var0 *= -1028477387; + var0 ^= var0 >>> 16; + return var0; + } - public static int a(int var0, final int var1, final IntPredicate var2) - { - int var3 = var1 - var0; - while(var3 > 0) - { - final int var4 = var3 / 2; - final int var5 = var0 + var4; - if(var2.test(var5)) - { - var3 = var4; - } - else - { - var0 = var5 + 1; - var3 -= var4 + 1; - } - } - return var0; - } + public static int a(int var0, final int var1, final IntPredicate var2) { + int var3 = var1 - var0; + while (var3 > 0) { + final int var4 = var3 / 2; + final int var5 = var0 + var4; + if (var2.test(var5)) { + var3 = var4; + } else { + var0 = var5 + 1; + var3 -= var4 + 1; + } + } + return var0; + } - public static float g(final float var0, final float var1, final float var2) - { - return var1 + var0 * (var2 - var1); - } + public static float g(final float var0, final float var1, final float var2) { + return var1 + var0 * (var2 - var1); + } - public static double d(final double var0, final double var2, final double var4) - { - return var2 + var0 * (var4 - var2); - } + public static double d(final double var0, final double var2, final double var4) { + return var2 + var0 * (var4 - var2); + } - public static double a(final double var0, final double var2, final double var4, final double var6, final double var8, final double var10) - { - return d(var2, d(var0, var4, var6), d(var0, var8, var10)); - } + public static double a(final double var0, final double var2, final double var4, final double var6, final double var8, final double var10) { + return d(var2, d(var0, var4, var6), d(var0, var8, var10)); + } - public static double a(final double var0, final double var2, final double var4, final double var6, final double var8, final double var10, final double var12, final double var14, final double var16, final double var18, final double var20) - { - return d(var4, a(var0, var2, var6, var8, var10, var12), a(var0, var2, var14, var16, var18, var20)); - } + public static double a(final double var0, final double var2, final double var4, final double var6, final double var8, final double var10, final double var12, final double var14, final double var16, final double var18, final double var20) { + return d(var4, a(var0, var2, var6, var8, var10, var12), a(var0, var2, var14, var16, var18, var20)); + } - public static double j(final double var0) - { - return var0 * var0 * var0 * (var0 * (var0 * 6.0 - 15.0) + 10.0); - } + public static double j(final double var0) { + return var0 * var0 * var0 * (var0 * (var0 * 6.0 - 15.0) + 10.0); + } - public static int k(final double var0) - { - if(var0 == 0.0) - { - return 0; - } - return (var0 > 0.0) ? 1 : -1; - } + public static int k(final double var0) { + if (var0 == 0.0) { + return 0; + } + return (var0 > 0.0) ? 1 : -1; + } - @Deprecated - public static float j(final float var0, final float var1, final float var2) - { - float var3; - for(var3 = var1 - var0; var3 < -180.0f; var3 += 360.0f) - { - } - while(var3 >= 180.0f) - { - var3 -= 360.0f; - } - return var0 + var2 * var3; - } + @Deprecated + public static float j(final float var0, final float var1, final float var2) { + float var3; + for (var3 = var1 - var0; var3 < -180.0f; var3 += 360.0f) { + } + while (var3 >= 180.0f) { + var3 -= 360.0f; + } + return var0 + var2 * var3; + } - public static float k(final float var0) - { - return var0 * var0; - } + public static float k(final float var0) { + return var0 * var0; + } - static - { - a = c(2.0f); - c = new Random(); - d = new int[] {0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9}; - e = Double.longBitsToDouble(4805340802404319232L); - f = new double[257]; - g = new double[257]; - for(int var2 = 0; var2 < 257; ++var2) - { - final double var3 = var2 / 256.0; - final double var4 = Math.asin(var3); - IrisMathHelper.g[var2] = Math.cos(var4); - IrisMathHelper.f[var2] = var4; - } - } + static { + a = c(2.0f); + c = new Random(); + d = new int[]{0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9}; + e = Double.longBitsToDouble(4805340802404319232L); + f = new double[257]; + g = new double[257]; + for (int var2 = 0; var2 < 257; ++var2) { + final double var3 = var2 / 256.0; + final double var4 = Math.asin(var3); + IrisMathHelper.g[var2] = Math.cos(var4); + IrisMathHelper.f[var2] = var4; + } + } } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/J.java b/src/main/java/com/volmit/iris/util/J.java index cf1f43c2a..e7648c3e2 100644 --- a/src/main/java/com/volmit/iris/util/J.java +++ b/src/main/java/com/volmit/iris/util/J.java @@ -8,384 +8,295 @@ import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; -public class J -{ - private static int tid = 0; - private static final ExecutorService e = Executors.newCachedThreadPool(new ThreadFactory() - { - @Override - public Thread newThread(Runnable r) - { - tid++; - Thread t = new Thread(r); - t.setName("Iris Actuator " + tid); - t.setPriority(8); - t.setUncaughtExceptionHandler((et, e) -> - { - Iris.info("Exception encountered in " + et.getName()); - e.printStackTrace(); - }); +public class J { + private static int tid = 0; + private static final ExecutorService e = Executors.newCachedThreadPool(new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + tid++; + Thread t = new Thread(r); + t.setName("Iris Actuator " + tid); + t.setPriority(8); + t.setUncaughtExceptionHandler((et, e) -> + { + Iris.info("Exception encountered in " + et.getName()); + e.printStackTrace(); + }); - return t; - } - }); + return t; + } + }); - public static void dofor(int a, Function c, int ch, Consumer d) - { - for(int i = a; c.apply(i); i += ch) - { - c.apply(i); - } - } + public static void dofor(int a, Function c, int ch, Consumer d) { + for (int i = a; c.apply(i); i += ch) { + c.apply(i); + } + } - public static boolean doif(Supplier c, Runnable g) - { - try { - if (c.get()) { - g.run(); - return true; - } - } - catch (NullPointerException e) { - // TODO: Fix this because this is just a suppression for an NPE on g - return false; - } + public static boolean doif(Supplier c, Runnable g) { + try { + if (c.get()) { + g.run(); + return true; + } + } catch (NullPointerException e) { + // TODO: Fix this because this is just a suppression for an NPE on g + return false; + } - return false; - } + return false; + } - public static void arun(Runnable a) - { - e.submit(() -> { - try - { - a.run(); - } + public static void arun(Runnable a) { + e.submit(() -> { + try { + a.run(); + } catch (Throwable e) { + System.out.println("Failed to run async task"); + e.printStackTrace(); + } + }); + } - catch(Throwable e) - { - System.out.println("Failed to run async task"); - e.printStackTrace(); - } - }); - } + public static void a(Runnable a) { + e.submit(() -> { + try { + a.run(); + } catch (Throwable e) { + System.out.println("Failed to run async task"); + e.printStackTrace(); + } + }); + } - public static void a(Runnable a) - { - e.submit(() -> { - try - { - a.run(); - } + public static Future a(Callable a) { + return e.submit(a); + } - catch(Throwable e) - { - System.out.println("Failed to run async task"); - e.printStackTrace(); - } - }); - } + public static void attemptAsync(NastyRunnable r) { + J.a(() -> J.attempt(r)); + } - public static Future a(Callable a) - { - return e.submit(a); - } + public static R attemptResult(NastyFuture r, R onError) { + try { + return r.run(); + } catch (Throwable e) { - public static void attemptAsync(NastyRunnable r) - { - J.a(() -> J.attempt(r)); - } + } - public static R attemptResult(NastyFuture r, R onError) - { - try - { - return r.run(); - } + return onError; + } - catch(Throwable e) - { + public static R attemptFunction(NastyFunction r, T param, R onError) { + try { + return r.run(param); + } catch (Throwable e) { - } + } - return onError; - } + return onError; + } - public static R attemptFunction(NastyFunction r, T param, R onError) - { - try - { - return r.run(param); - } + public static boolean sleep(long ms) { + return J.attempt(() -> Thread.sleep(ms)); + } - catch(Throwable e) - { + public static boolean attempt(NastyRunnable r) { + return attemptCatch(r) == null; + } - } + public static Throwable attemptCatch(NastyRunnable r) { + try { + r.run(); + } catch (Throwable e) { + return e; + } - return onError; - } + return null; + } - public static boolean sleep(long ms) - { - return J.attempt(() -> Thread.sleep(ms)); - } + public static T attempt(Supplier t, T i) { + try { + return t.get(); + } catch (Throwable e) { + return i; + } + } - public static boolean attempt(NastyRunnable r) - { - return attemptCatch(r) == null; - } + private static KList afterStartup = new KList<>(); + private static KList afterStartupAsync = new KList<>(); + private static boolean started = false; - public static Throwable attemptCatch(NastyRunnable r) - { - try - { - r.run(); - } + /** + * Dont call this unless you know what you are doing! + */ + public static void executeAfterStartupQueue() { + if (started) { + return; + } - catch(Throwable e) - { - return e; - } + started = true; - return null; - } + for (Runnable r : afterStartup) { + s(r); + } - public static T attempt(Supplier t, T i) - { - try - { - return t.get(); - } + for (Runnable r : afterStartupAsync) { + a(r); + } - catch(Throwable e) - { - return i; - } - } + afterStartup = null; + afterStartupAsync = null; + } - private static KList afterStartup = new KList<>(); - private static KList afterStartupAsync = new KList<>(); - private static boolean started = false; + /** + * Schedule a sync task to be run right after startup. If the server has already + * started ticking, it will simply run it in a sync task. + *

+ * If you dont know if you should queue this or not, do so, it's pretty + * forgiving. + * + * @param r the runnable + */ + public static void ass(Runnable r) { + if (started) { + s(r); + } else { + afterStartup.add(r); + } + } - /** - * Dont call this unless you know what you are doing! - */ - public static void executeAfterStartupQueue() - { - if(started) - { - return; - } + /** + * Schedule an async task to be run right after startup. If the server has + * already started ticking, it will simply run it in an async task. + *

+ * If you dont know if you should queue this or not, do so, it's pretty + * forgiving. + * + * @param r the runnable + */ + public static void asa(Runnable r) { + if (started) { + a(r); + } else { + afterStartupAsync.add(r); + } + } - started = true; + /** + * Queue a sync task + * + * @param r the runnable + */ + public static void s(Runnable r) { + Bukkit.getScheduler().scheduleSyncDelayedTask(Iris.instance, r); + } - for(Runnable r : afterStartup) - { - s(r); - } + /** + * Queue a sync task + * + * @param r the runnable + * @param delay the delay to wait in ticks before running + */ + public static void s(Runnable r, int delay) { + Bukkit.getScheduler().scheduleSyncDelayedTask(Iris.instance, r, delay); + } - for(Runnable r : afterStartupAsync) - { - a(r); - } + /** + * Cancel a sync repeating task + * + * @param id the task id + */ + public static void csr(int id) { + Bukkit.getScheduler().cancelTask(id); + } - afterStartup = null; - afterStartupAsync = null; - } + /** + * Start a sync repeating task + * + * @param r the runnable + * @param interval the interval + * @return the task id + */ + public static int sr(Runnable r, int interval) { + return Bukkit.getScheduler().scheduleSyncRepeatingTask(Iris.instance, r, 0, interval); + } - /** - * Schedule a sync task to be run right after startup. If the server has already - * started ticking, it will simply run it in a sync task. - * - * If you dont know if you should queue this or not, do so, it's pretty - * forgiving. - * - * @param r - * the runnable - */ - public static void ass(Runnable r) - { - if(started) - { - s(r); - } + /** + * Start a sync repeating task for a limited amount of ticks + * + * @param r the runnable + * @param interval the interval in ticks + * @param intervals the maximum amount of intervals to run + */ + public static void sr(Runnable r, int interval, int intervals) { + FinalInteger fi = new FinalInteger(0); - else - { - afterStartup.add(r); - } - } + new SR() { + @Override + public void run() { + fi.add(1); + r.run(); - /** - * Schedule an async task to be run right after startup. If the server has - * already started ticking, it will simply run it in an async task. - * - * If you dont know if you should queue this or not, do so, it's pretty - * forgiving. - * - * @param r - * the runnable - */ - public static void asa(Runnable r) - { - if(started) - { - a(r); - } + if (fi.get() >= intervals) { + cancel(); + } + } + }; + } - else - { - afterStartupAsync.add(r); - } - } + /** + * Call an async task dealyed + * + * @param r the runnable + * @param delay the delay to wait before running + */ + @SuppressWarnings("deprecation") + public static void a(Runnable r, int delay) { + Bukkit.getScheduler().scheduleAsyncDelayedTask(Iris.instance, r, delay); + } - /** - * Queue a sync task - * - * @param r - * the runnable - */ - public static void s(Runnable r) - { - Bukkit.getScheduler().scheduleSyncDelayedTask(Iris.instance, r); - } + /** + * Cancel an async repeat task + * + * @param id the id + */ + public static void car(int id) { + Bukkit.getScheduler().cancelTask(id); + } - /** - * Queue a sync task - * - * @param r - * the runnable - * @param delay - * the delay to wait in ticks before running - */ - public static void s(Runnable r, int delay) - { - Bukkit.getScheduler().scheduleSyncDelayedTask(Iris.instance, r, delay); - } + /** + * Start an async repeat task + * + * @param r the runnable + * @param interval the interval in ticks + * @return the task id + */ + @SuppressWarnings("deprecation") + public static int ar(Runnable r, int interval) { + return Bukkit.getScheduler().scheduleAsyncRepeatingTask(Iris.instance, r, 0, interval); + } - /** - * Cancel a sync repeating task - * - * @param id - * the task id - */ - public static void csr(int id) - { - Bukkit.getScheduler().cancelTask(id); - } + /** + * Start an async repeating task for a limited time + * + * @param r the runnable + * @param interval the interval + * @param intervals the intervals to run + */ + public static void ar(Runnable r, int interval, int intervals) { + FinalInteger fi = new FinalInteger(0); - /** - * Start a sync repeating task - * - * @param r - * the runnable - * @param interval - * the interval - * @return the task id - */ - public static int sr(Runnable r, int interval) - { - return Bukkit.getScheduler().scheduleSyncRepeatingTask(Iris.instance, r, 0, interval); - } + new AR() { + @Override + public void run() { + fi.add(1); + r.run(); - /** - * Start a sync repeating task for a limited amount of ticks - * - * @param r - * the runnable - * @param interval - * the interval in ticks - * @param intervals - * the maximum amount of intervals to run - */ - public static void sr(Runnable r, int interval, int intervals) - { - FinalInteger fi = new FinalInteger(0); - - new SR() - { - @Override - public void run() - { - fi.add(1); - r.run(); - - if(fi.get() >= intervals) - { - cancel(); - } - } - }; - } - - /** - * Call an async task dealyed - * - * @param r - * the runnable - * @param delay - * the delay to wait before running - */ - @SuppressWarnings("deprecation") - public static void a(Runnable r, int delay) - { - Bukkit.getScheduler().scheduleAsyncDelayedTask(Iris.instance, r, delay); - } - - /** - * Cancel an async repeat task - * - * @param id - * the id - */ - public static void car(int id) - { - Bukkit.getScheduler().cancelTask(id); - } - - /** - * Start an async repeat task - * - * @param r - * the runnable - * @param interval - * the interval in ticks - * @return the task id - */ - @SuppressWarnings("deprecation") - public static int ar(Runnable r, int interval) - { - return Bukkit.getScheduler().scheduleAsyncRepeatingTask(Iris.instance, r, 0, interval); - } - - /** - * Start an async repeating task for a limited time - * - * @param r - * the runnable - * @param interval - * the interval - * @param intervals - * the intervals to run - */ - public static void ar(Runnable r, int interval, int intervals) - { - FinalInteger fi = new FinalInteger(0); - - new AR() - { - @Override - public void run() - { - fi.add(1); - r.run(); - - if(fi.get() >= intervals) - { - cancel(); - } - } - }; - } + if (fi.get() >= intervals) { + cancel(); + } + } + }; + } } diff --git a/src/main/java/com/volmit/iris/util/JSONArray.java b/src/main/java/com/volmit/iris/util/JSONArray.java index ed935bcc3..78a8038eb 100644 --- a/src/main/java/com/volmit/iris/util/JSONArray.java +++ b/src/main/java/com/volmit/iris/util/JSONArray.java @@ -80,1173 +80,942 @@ import java.util.Map; * @author JSON.org * @version 2015-07-22 */ -public class JSONArray implements Iterable -{ +public class JSONArray implements Iterable { - /** - * The arrayList where the JSONArray's properties are kept. - */ - private final ArrayList myArrayList; + /** + * The arrayList where the JSONArray's properties are kept. + */ + private final ArrayList myArrayList; - /** - * Construct an empty JSONArray. - */ - public JSONArray() - { - this.myArrayList = new ArrayList(); - } + /** + * Construct an empty JSONArray. + */ + public JSONArray() { + this.myArrayList = new ArrayList(); + } - /** - * Construct a JSONArray from a JSONTokener. - * - * @param x - * A JSONTokener - * @throws JSONException - * If there is a syntax error. - */ - public JSONArray(JSONTokener x) throws JSONException - { - this(); - if(x.nextClean() != '[') - { - throw x.syntaxError("A JSONArray text must start with '['"); - } - if(x.nextClean() != ']') - { - x.back(); - for(;;) - { - if(x.nextClean() == ',') - { - x.back(); - this.myArrayList.add(JSONObject.NULL); - } else - { - x.back(); - this.myArrayList.add(x.nextValue()); - } - switch(x.nextClean()) - { - case ',': - if(x.nextClean() == ']') - { - return; - } - x.back(); - break; - case ']': - return; - default: - throw x.syntaxError("Expected a ',' or ']'"); - } - } - } - } + /** + * Construct a JSONArray from a JSONTokener. + * + * @param x A JSONTokener + * @throws JSONException If there is a syntax error. + */ + public JSONArray(JSONTokener x) throws JSONException { + this(); + if (x.nextClean() != '[') { + throw x.syntaxError("A JSONArray text must start with '['"); + } + if (x.nextClean() != ']') { + x.back(); + for (; ; ) { + if (x.nextClean() == ',') { + x.back(); + this.myArrayList.add(JSONObject.NULL); + } else { + x.back(); + this.myArrayList.add(x.nextValue()); + } + switch (x.nextClean()) { + case ',': + if (x.nextClean() == ']') { + return; + } + x.back(); + break; + case ']': + return; + default: + throw x.syntaxError("Expected a ',' or ']'"); + } + } + } + } - /** - * Construct a JSONArray from a source JSON text. - * - * @param source - * A string that begins with [ (left - * bracket) and ends with ]   - * (right bracket). - * @throws JSONException - * If there is a syntax error. - */ - public JSONArray(String source) throws JSONException - { - this(new JSONTokener(source)); - } + /** + * Construct a JSONArray from a source JSON text. + * + * @param source A string that begins with [ (left + * bracket) and ends with ]   + * (right bracket). + * @throws JSONException If there is a syntax error. + */ + public JSONArray(String source) throws JSONException { + this(new JSONTokener(source)); + } - /** - * Construct a JSONArray from a Collection. - * - * @param collection - * A Collection. - */ - public JSONArray(Collection collection) - { - this.myArrayList = new ArrayList(); - if(collection != null) - { - Iterator iter = collection.iterator(); - while(iter.hasNext()) - { - this.myArrayList.add(JSONObject.wrap(iter.next())); - } - } - } + /** + * Construct a JSONArray from a Collection. + * + * @param collection A Collection. + */ + public JSONArray(Collection collection) { + this.myArrayList = new ArrayList(); + if (collection != null) { + Iterator iter = collection.iterator(); + while (iter.hasNext()) { + this.myArrayList.add(JSONObject.wrap(iter.next())); + } + } + } - /** - * Construct a JSONArray from an array - * - * @throws JSONException - * If not an array. - */ - public JSONArray(Object array) throws JSONException - { - this(); - if(array.getClass().isArray()) - { - int length = Array.getLength(array); - for(int i = 0; i < length; i += 1) - { - this.put(JSONObject.wrap(Array.get(array, i))); - } - } else - { - throw new JSONException("JSONArray initial value should be a string or collection or array."); - } - } + /** + * Construct a JSONArray from an array + * + * @throws JSONException If not an array. + */ + public JSONArray(Object array) throws JSONException { + this(); + if (array.getClass().isArray()) { + int length = Array.getLength(array); + for (int i = 0; i < length; i += 1) { + this.put(JSONObject.wrap(Array.get(array, i))); + } + } else { + throw new JSONException("JSONArray initial value should be a string or collection or array."); + } + } - @Override - public Iterator iterator() - { - return myArrayList.iterator(); - } + @Override + public Iterator iterator() { + return myArrayList.iterator(); + } - /** - * Get the object value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return An object value. - * @throws JSONException - * If there is no value for the index. - */ - public Object get(int index) throws JSONException - { - Object object = this.opt(index); - if(object == null) - { - throw new JSONException("JSONArray[" + index + "] not found."); - } - return object; - } + /** + * Get the object value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return An object value. + * @throws JSONException If there is no value for the index. + */ + public Object get(int index) throws JSONException { + Object object = this.opt(index); + if (object == null) { + throw new JSONException("JSONArray[" + index + "] not found."); + } + return object; + } - /** - * Get the boolean value associated with an index. The string values "true" - * and "false" are converted to boolean. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The truth. - * @throws JSONException - * If there is no value for the index or if the value is not - * convertible to boolean. - */ - public boolean getBoolean(int index) throws JSONException - { - Object object = this.get(index); - if(object.equals(Boolean.FALSE) || (object instanceof String && ((String) object).equalsIgnoreCase("false"))) - { - return false; - } else if(object.equals(Boolean.TRUE) || (object instanceof String && ((String) object).equalsIgnoreCase("true"))) - { - return true; - } - throw new JSONException("JSONArray[" + index + "] is not a boolean."); - } + /** + * Get the boolean value associated with an index. The string values "true" + * and "false" are converted to boolean. + * + * @param index The index must be between 0 and length() - 1. + * @return The truth. + * @throws JSONException If there is no value for the index or if the value is not + * convertible to boolean. + */ + public boolean getBoolean(int index) throws JSONException { + Object object = this.get(index); + if (object.equals(Boolean.FALSE) || (object instanceof String && ((String) object).equalsIgnoreCase("false"))) { + return false; + } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String) object).equalsIgnoreCase("true"))) { + return true; + } + throw new JSONException("JSONArray[" + index + "] is not a boolean."); + } - /** - * Get the double value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException - * If the key is not found or if the value cannot be converted - * to a number. - */ - public double getDouble(int index) throws JSONException - { - Object object = this.get(index); - try - { - return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); - } catch(Exception e) - { - throw new JSONException("JSONArray[" + index + "] is not a number."); - } - } + /** + * Get the double value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + * @throws JSONException If the key is not found or if the value cannot be converted + * to a number. + */ + public double getDouble(int index) throws JSONException { + Object object = this.get(index); + try { + return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); + } catch (Exception e) { + throw new JSONException("JSONArray[" + index + "] is not a number."); + } + } - /** - * Get the enum value associated with an index. - * - * @param clazz - * The type of enum to retrieve. - * @param index - * The index must be between 0 and length() - 1. - * @return The enum value at the index location - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to an enum. - */ - public > E getEnum(Class clazz, int index) throws JSONException - { - E val = optEnum(clazz, index); - if(val == null) - { - // JSONException should really take a throwable argument. - // If it did, I would re-implement this with the Enum.valueOf - // method and place any thrown exception in the JSONException - throw new JSONException("JSONObject[" + JSONObject.quote(Integer.toString(index)) + "] is not an enum of type " + JSONObject.quote(clazz.getSimpleName()) + "."); - } - return val; - } + /** + * Get the enum value associated with an index. + * + * @param clazz The type of enum to retrieve. + * @param index The index must be between 0 and length() - 1. + * @return The enum value at the index location + * @throws JSONException if the key is not found or if the value cannot be converted + * to an enum. + */ + public > E getEnum(Class clazz, int index) throws JSONException { + E val = optEnum(clazz, index); + if (val == null) { + // JSONException should really take a throwable argument. + // If it did, I would re-implement this with the Enum.valueOf + // method and place any thrown exception in the JSONException + throw new JSONException("JSONObject[" + JSONObject.quote(Integer.toString(index)) + "] is not an enum of type " + JSONObject.quote(clazz.getSimpleName()) + "."); + } + return val; + } - /** - * Get the BigDecimal value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException - * If the key is not found or if the value cannot be converted - * to a BigDecimal. - */ - public BigDecimal getBigDecimal(int index) throws JSONException - { - Object object = this.get(index); - try - { - return new BigDecimal(object.toString()); - } catch(Exception e) - { - throw new JSONException("JSONArray[" + index + "] could not convert to BigDecimal."); - } - } + /** + * Get the BigDecimal value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + * @throws JSONException If the key is not found or if the value cannot be converted + * to a BigDecimal. + */ + public BigDecimal getBigDecimal(int index) throws JSONException { + Object object = this.get(index); + try { + return new BigDecimal(object.toString()); + } catch (Exception e) { + throw new JSONException("JSONArray[" + index + "] could not convert to BigDecimal."); + } + } - /** - * Get the BigInteger value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException - * If the key is not found or if the value cannot be converted - * to a BigInteger. - */ - public BigInteger getBigInteger(int index) throws JSONException - { - Object object = this.get(index); - try - { - return new BigInteger(object.toString()); - } catch(Exception e) - { - throw new JSONException("JSONArray[" + index + "] could not convert to BigInteger."); - } - } + /** + * Get the BigInteger value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + * @throws JSONException If the key is not found or if the value cannot be converted + * to a BigInteger. + */ + public BigInteger getBigInteger(int index) throws JSONException { + Object object = this.get(index); + try { + return new BigInteger(object.toString()); + } catch (Exception e) { + throw new JSONException("JSONArray[" + index + "] could not convert to BigInteger."); + } + } - /** - * Get the int value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException - * If the key is not found or if the value is not a number. - */ - public int getInt(int index) throws JSONException - { - Object object = this.get(index); - try - { - return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); - } catch(Exception e) - { - throw new JSONException("JSONArray[" + index + "] is not a number."); - } - } + /** + * Get the int value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + * @throws JSONException If the key is not found or if the value is not a number. + */ + public int getInt(int index) throws JSONException { + Object object = this.get(index); + try { + return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); + } catch (Exception e) { + throw new JSONException("JSONArray[" + index + "] is not a number."); + } + } - /** - * Get the JSONArray associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return A JSONArray value. - * @throws JSONException - * If there is no value for the index. or if the value is not a - * JSONArray - */ - public JSONArray getJSONArray(int index) throws JSONException - { - Object object = this.get(index); - if(object instanceof JSONArray) - { - return (JSONArray) object; - } - throw new JSONException("JSONArray[" + index + "] is not a JSONArray."); - } + /** + * Get the JSONArray associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return A JSONArray value. + * @throws JSONException If there is no value for the index. or if the value is not a + * JSONArray + */ + public JSONArray getJSONArray(int index) throws JSONException { + Object object = this.get(index); + if (object instanceof JSONArray) { + return (JSONArray) object; + } + throw new JSONException("JSONArray[" + index + "] is not a JSONArray."); + } - /** - * Get the JSONObject associated with an index. - * - * @param index - * subscript - * @return A JSONObject value. - * @throws JSONException - * If there is no value for the index or if the value is not a - * JSONObject - */ - public JSONObject getJSONObject(int index) throws JSONException - { - Object object = this.get(index); - if(object instanceof JSONObject) - { - return (JSONObject) object; - } - throw new JSONException("JSONArray[" + index + "] is not a JSONObject."); - } + /** + * Get the JSONObject associated with an index. + * + * @param index subscript + * @return A JSONObject value. + * @throws JSONException If there is no value for the index or if the value is not a + * JSONObject + */ + public JSONObject getJSONObject(int index) throws JSONException { + Object object = this.get(index); + if (object instanceof JSONObject) { + return (JSONObject) object; + } + throw new JSONException("JSONArray[" + index + "] is not a JSONObject."); + } - /** - * Get the long value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - * @throws JSONException - * If the key is not found or if the value cannot be converted - * to a number. - */ - public long getLong(int index) throws JSONException - { - Object object = this.get(index); - try - { - return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); - } catch(Exception e) - { - throw new JSONException("JSONArray[" + index + "] is not a number."); - } - } + /** + * Get the long value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + * @throws JSONException If the key is not found or if the value cannot be converted + * to a number. + */ + public long getLong(int index) throws JSONException { + Object object = this.get(index); + try { + return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); + } catch (Exception e) { + throw new JSONException("JSONArray[" + index + "] is not a number."); + } + } - /** - * Get the string associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return A string value. - * @throws JSONException - * If there is no string value for the index. - */ - public String getString(int index) throws JSONException - { - Object object = this.get(index); - if(object instanceof String) - { - return (String) object; - } - throw new JSONException("JSONArray[" + index + "] not a string."); - } + /** + * Get the string associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return A string value. + * @throws JSONException If there is no string value for the index. + */ + public String getString(int index) throws JSONException { + Object object = this.get(index); + if (object instanceof String) { + return (String) object; + } + throw new JSONException("JSONArray[" + index + "] not a string."); + } - /** - * Determine if the value is null. - * - * @param index - * The index must be between 0 and length() - 1. - * @return true if the value at the index is null, or if there is no value. - */ - public boolean isNull(int index) - { - return JSONObject.NULL.equals(this.opt(index)); - } + /** + * Determine if the value is null. + * + * @param index The index must be between 0 and length() - 1. + * @return true if the value at the index is null, or if there is no value. + */ + public boolean isNull(int index) { + return JSONObject.NULL.equals(this.opt(index)); + } - /** - * Make a string from the contents of this JSONArray. The - * separator string is inserted between each element. Warning: - * This method assumes that the data structure is acyclical. - * - * @param separator - * A string that will be inserted between the elements. - * @return a string. - * @throws JSONException - * If the array contains an invalid number. - */ - public String join(String separator) throws JSONException - { - int len = this.length(); - StringBuilder sb = new StringBuilder(); + /** + * Make a string from the contents of this JSONArray. The + * separator string is inserted between each element. Warning: + * This method assumes that the data structure is acyclical. + * + * @param separator A string that will be inserted between the elements. + * @return a string. + * @throws JSONException If the array contains an invalid number. + */ + public String join(String separator) throws JSONException { + int len = this.length(); + StringBuilder sb = new StringBuilder(); - for(int i = 0; i < len; i += 1) - { - if(i > 0) - { - sb.append(separator); - } - sb.append(JSONObject.valueToString(this.myArrayList.get(i))); - } - return sb.toString(); - } + for (int i = 0; i < len; i += 1) { + if (i > 0) { + sb.append(separator); + } + sb.append(JSONObject.valueToString(this.myArrayList.get(i))); + } + return sb.toString(); + } - /** - * Get the number of elements in the JSONArray, included nulls. - * - * @return The length (or size). - */ - public int length() - { - return this.myArrayList.size(); - } + /** + * Get the number of elements in the JSONArray, included nulls. + * + * @return The length (or size). + */ + public int length() { + return this.myArrayList.size(); + } - /** - * Get the optional object value associated with an index. - * - * @param index - * The index must be between 0 and length() - 1. - * @return An object value, or null if there is no object at that index. - */ - public Object opt(int index) - { - return (index < 0 || index >= this.length()) ? null : this.myArrayList.get(index); - } + /** + * Get the optional object value associated with an index. + * + * @param index The index must be between 0 and length() - 1. + * @return An object value, or null if there is no object at that index. + */ + public Object opt(int index) { + return (index < 0 || index >= this.length()) ? null : this.myArrayList.get(index); + } - /** - * Get the optional boolean value associated with an index. It returns false - * if there is no value at that index, or if the value is not Boolean.TRUE - * or the String "true". - * - * @param index - * The index must be between 0 and length() - 1. - * @return The truth. - */ - public boolean optBoolean(int index) - { - return this.optBoolean(index, false); - } + /** + * Get the optional boolean value associated with an index. It returns false + * if there is no value at that index, or if the value is not Boolean.TRUE + * or the String "true". + * + * @param index The index must be between 0 and length() - 1. + * @return The truth. + */ + public boolean optBoolean(int index) { + return this.optBoolean(index, false); + } - /** - * Get the optional boolean value associated with an index. It returns the - * defaultValue if there is no value at that index or if it is not a Boolean - * or the String "true" or "false" (case insensitive). - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * A boolean default. - * @return The truth. - */ - public boolean optBoolean(int index, boolean defaultValue) - { - try - { - return this.getBoolean(index); - } catch(Exception e) - { - return defaultValue; - } - } + /** + * Get the optional boolean value associated with an index. It returns the + * defaultValue if there is no value at that index or if it is not a Boolean + * or the String "true" or "false" (case insensitive). + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue A boolean default. + * @return The truth. + */ + public boolean optBoolean(int index, boolean defaultValue) { + try { + return this.getBoolean(index); + } catch (Exception e) { + return defaultValue; + } + } - /** - * Get the optional double value associated with an index. NaN is returned - * if there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - */ - public double optDouble(int index) - { - return this.optDouble(index, Double.NaN); - } + /** + * Get the optional double value associated with an index. NaN is returned + * if there is no value for the index, or if the value is not a number and + * cannot be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + */ + public double optDouble(int index) { + return this.optDouble(index, Double.NaN); + } - /** - * Get the optional double value associated with an index. The defaultValue - * is returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @param index - * subscript - * @param defaultValue - * The default value. - * @return The value. - */ - public double optDouble(int index, double defaultValue) - { - try - { - return this.getDouble(index); - } catch(Exception e) - { - return defaultValue; - } - } + /** + * Get the optional double value associated with an index. The defaultValue + * is returned if there is no value for the index, or if the value is not a + * number and cannot be converted to a number. + * + * @param index subscript + * @param defaultValue The default value. + * @return The value. + */ + public double optDouble(int index, double defaultValue) { + try { + return this.getDouble(index); + } catch (Exception e) { + return defaultValue; + } + } - /** - * Get the optional int value associated with an index. Zero is returned if - * there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - */ - public int optInt(int index) - { - return this.optInt(index, 0); - } + /** + * Get the optional int value associated with an index. Zero is returned if + * there is no value for the index, or if the value is not a number and + * cannot be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + */ + public int optInt(int index) { + return this.optInt(index, 0); + } - /** - * Get the optional int value associated with an index. The defaultValue is - * returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. - * @return The value. - */ - public int optInt(int index, int defaultValue) - { - try - { - return this.getInt(index); - } catch(Exception e) - { - return defaultValue; - } - } + /** + * Get the optional int value associated with an index. The defaultValue is + * returned if there is no value for the index, or if the value is not a + * number and cannot be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. + * @return The value. + */ + public int optInt(int index, int defaultValue) { + try { + return this.getInt(index); + } catch (Exception e) { + return defaultValue; + } + } - /** - * Get the enum value associated with a key. - * - * @param clazz - * The type of enum to retrieve. - * @param index - * The index must be between 0 and length() - 1. - * @return The enum value at the index location or null if not found - */ - public > E optEnum(Class clazz, int index) - { - return this.optEnum(clazz, index, null); - } + /** + * Get the enum value associated with a key. + * + * @param clazz The type of enum to retrieve. + * @param index The index must be between 0 and length() - 1. + * @return The enum value at the index location or null if not found + */ + public > E optEnum(Class clazz, int index) { + return this.optEnum(clazz, index, null); + } - /** - * Get the enum value associated with a key. - * - * @param clazz - * The type of enum to retrieve. - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default in case the value is not found - * @return The enum value at the index location or defaultValue if the value - * is not found or cannot be assigned to clazz - */ - public > E optEnum(Class clazz, int index, E defaultValue) - { - try - { - Object val = this.opt(index); - if(JSONObject.NULL.equals(val)) - { - return defaultValue; - } - if(clazz.isAssignableFrom(val.getClass())) - { - // we just checked it! - @SuppressWarnings("unchecked") - E myE = (E) val; - return myE; - } - return Enum.valueOf(clazz, val.toString()); - } + /** + * Get the enum value associated with a key. + * + * @param clazz The type of enum to retrieve. + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default in case the value is not found + * @return The enum value at the index location or defaultValue if the value + * is not found or cannot be assigned to clazz + */ + public > E optEnum(Class clazz, int index, E defaultValue) { + try { + Object val = this.opt(index); + if (JSONObject.NULL.equals(val)) { + return defaultValue; + } + if (clazz.isAssignableFrom(val.getClass())) { + // we just checked it! + @SuppressWarnings("unchecked") + E myE = (E) val; + return myE; + } + return Enum.valueOf(clazz, val.toString()); + } catch (IllegalArgumentException e) { + return defaultValue; + } catch (NullPointerException e) { + return defaultValue; + } + } - catch(IllegalArgumentException e) - { - return defaultValue; - } + /** + * Get the optional BigInteger value associated with an index. The + * defaultValue is returned if there is no value for the index, or if the + * value is not a number and cannot be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. + * @return The value. + */ + public BigInteger optBigInteger(int index, BigInteger defaultValue) { + try { + return this.getBigInteger(index); + } catch (Exception e) { + return defaultValue; + } + } - catch(NullPointerException e) - { - return defaultValue; - } - } + /** + * Get the optional BigDecimal value associated with an index. The + * defaultValue is returned if there is no value for the index, or if the + * value is not a number and cannot be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. + * @return The value. + */ + public BigDecimal optBigDecimal(int index, BigDecimal defaultValue) { + try { + return this.getBigDecimal(index); + } catch (Exception e) { + return defaultValue; + } + } - /** - * Get the optional BigInteger value associated with an index. The - * defaultValue is returned if there is no value for the index, or if the - * value is not a number and cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. - * @return The value. - */ - public BigInteger optBigInteger(int index, BigInteger defaultValue) - { - try - { - return this.getBigInteger(index); - } catch(Exception e) - { - return defaultValue; - } - } + /** + * Get the optional JSONArray associated with an index. + * + * @param index subscript + * @return A JSONArray value, or null if the index has no value, or if the + * value is not a JSONArray. + */ + public JSONArray optJSONArray(int index) { + Object o = this.opt(index); + return o instanceof JSONArray ? (JSONArray) o : null; + } - /** - * Get the optional BigDecimal value associated with an index. The - * defaultValue is returned if there is no value for the index, or if the - * value is not a number and cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. - * @return The value. - */ - public BigDecimal optBigDecimal(int index, BigDecimal defaultValue) - { - try - { - return this.getBigDecimal(index); - } catch(Exception e) - { - return defaultValue; - } - } + /** + * Get the optional JSONObject associated with an index. Null is returned if + * the key is not found, or null if the index has no value, or if the value + * is not a JSONObject. + * + * @param index The index must be between 0 and length() - 1. + * @return A JSONObject value. + */ + public JSONObject optJSONObject(int index) { + Object o = this.opt(index); + return o instanceof JSONObject ? (JSONObject) o : null; + } - /** - * Get the optional JSONArray associated with an index. - * - * @param index - * subscript - * @return A JSONArray value, or null if the index has no value, or if the - * value is not a JSONArray. - */ - public JSONArray optJSONArray(int index) - { - Object o = this.opt(index); - return o instanceof JSONArray ? (JSONArray) o : null; - } + /** + * Get the optional long value associated with an index. Zero is returned if + * there is no value for the index, or if the value is not a number and + * cannot be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @return The value. + */ + public long optLong(int index) { + return this.optLong(index, 0); + } - /** - * Get the optional JSONObject associated with an index. Null is returned if - * the key is not found, or null if the index has no value, or if the value - * is not a JSONObject. - * - * @param index - * The index must be between 0 and length() - 1. - * @return A JSONObject value. - */ - public JSONObject optJSONObject(int index) - { - Object o = this.opt(index); - return o instanceof JSONObject ? (JSONObject) o : null; - } + /** + * Get the optional long value associated with an index. The defaultValue is + * returned if there is no value for the index, or if the value is not a + * number and cannot be converted to a number. + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. + * @return The value. + */ + public long optLong(int index, long defaultValue) { + try { + return this.getLong(index); + } catch (Exception e) { + return defaultValue; + } + } - /** - * Get the optional long value associated with an index. Zero is returned if - * there is no value for the index, or if the value is not a number and - * cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @return The value. - */ - public long optLong(int index) - { - return this.optLong(index, 0); - } + /** + * Get the optional string value associated with an index. It returns an + * empty string if there is no value at that index. If the value is not a + * string and is not null, then it is coverted to a string. + * + * @param index The index must be between 0 and length() - 1. + * @return A String value. + */ + public String optString(int index) { + return this.optString(index, ""); + } - /** - * Get the optional long value associated with an index. The defaultValue is - * returned if there is no value for the index, or if the value is not a - * number and cannot be converted to a number. - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. - * @return The value. - */ - public long optLong(int index, long defaultValue) - { - try - { - return this.getLong(index); - } catch(Exception e) - { - return defaultValue; - } - } + /** + * Get the optional string associated with an index. The defaultValue is + * returned if the key is not found. + * + * @param index The index must be between 0 and length() - 1. + * @param defaultValue The default value. + * @return A String value. + */ + public String optString(int index, String defaultValue) { + Object object = this.opt(index); + return JSONObject.NULL.equals(object) ? defaultValue : object.toString(); + } - /** - * Get the optional string value associated with an index. It returns an - * empty string if there is no value at that index. If the value is not a - * string and is not null, then it is coverted to a string. - * - * @param index - * The index must be between 0 and length() - 1. - * @return A String value. - */ - public String optString(int index) - { - return this.optString(index, ""); - } + /** + * Append a boolean value. This increases the array's length by one. + * + * @param value A boolean value. + * @return this. + */ + public JSONArray put(boolean value) { + this.put(value ? Boolean.TRUE : Boolean.FALSE); + return this; + } - /** - * Get the optional string associated with an index. The defaultValue is - * returned if the key is not found. - * - * @param index - * The index must be between 0 and length() - 1. - * @param defaultValue - * The default value. - * @return A String value. - */ - public String optString(int index, String defaultValue) - { - Object object = this.opt(index); - return JSONObject.NULL.equals(object) ? defaultValue : object.toString(); - } + /** + * Put a value in the JSONArray, where the value will be a JSONArray which + * is produced from a Collection. + * + * @param value A Collection value. + * @return this. + */ + public JSONArray put(Collection value) { + this.put(new JSONArray(value)); + return this; + } - /** - * Append a boolean value. This increases the array's length by one. - * - * @param value - * A boolean value. - * @return this. - */ - public JSONArray put(boolean value) - { - this.put(value ? Boolean.TRUE : Boolean.FALSE); - return this; - } + /** + * Append a double value. This increases the array's length by one. + * + * @param value A double value. + * @return this. + * @throws JSONException if the value is not finite. + */ + public JSONArray put(double value) throws JSONException { + Double d = new Double(value); + JSONObject.testValidity(d); + this.put(d); + return this; + } - /** - * Put a value in the JSONArray, where the value will be a JSONArray which - * is produced from a Collection. - * - * @param value - * A Collection value. - * @return this. - */ - public JSONArray put(Collection value) - { - this.put(new JSONArray(value)); - return this; - } + /** + * Append an int value. This increases the array's length by one. + * + * @param value An int value. + * @return this. + */ + public JSONArray put(int value) { + this.put(new Integer(value)); + return this; + } - /** - * Append a double value. This increases the array's length by one. - * - * @param value - * A double value. - * @throws JSONException - * if the value is not finite. - * @return this. - */ - public JSONArray put(double value) throws JSONException - { - Double d = new Double(value); - JSONObject.testValidity(d); - this.put(d); - return this; - } + /** + * Append an long value. This increases the array's length by one. + * + * @param value A long value. + * @return this. + */ + public JSONArray put(long value) { + this.put(new Long(value)); + return this; + } - /** - * Append an int value. This increases the array's length by one. - * - * @param value - * An int value. - * @return this. - */ - public JSONArray put(int value) - { - this.put(new Integer(value)); - return this; - } + /** + * Put a value in the JSONArray, where the value will be a JSONObject which + * is produced from a Map. + * + * @param value A Map value. + * @return this. + */ + public JSONArray put(Map value) { + this.put(new JSONObject(value)); + return this; + } - /** - * Append an long value. This increases the array's length by one. - * - * @param value - * A long value. - * @return this. - */ - public JSONArray put(long value) - { - this.put(new Long(value)); - return this; - } + /** + * Append an object value. This increases the array's length by one. + * + * @param value An object value. The value should be a Boolean, Double, + * Integer, JSONArray, JSONObject, Long, or String, or the + * JSONObject.NULL object. + * @return this. + */ + public JSONArray put(Object value) { + this.myArrayList.add(value); + return this; + } - /** - * Put a value in the JSONArray, where the value will be a JSONObject which - * is produced from a Map. - * - * @param value - * A Map value. - * @return this. - */ - public JSONArray put(Map value) - { - this.put(new JSONObject(value)); - return this; - } + /** + * Put or replace a boolean value in the JSONArray. If the index is greater + * than the length of the JSONArray, then null elements will be added as + * necessary to pad it out. + * + * @param index The subscript. + * @param value A boolean value. + * @return this. + * @throws JSONException If the index is negative. + */ + public JSONArray put(int index, boolean value) throws JSONException { + this.put(index, value ? Boolean.TRUE : Boolean.FALSE); + return this; + } - /** - * Append an object value. This increases the array's length by one. - * - * @param value - * An object value. The value should be a Boolean, Double, - * Integer, JSONArray, JSONObject, Long, or String, or the - * JSONObject.NULL object. - * @return this. - */ - public JSONArray put(Object value) - { - this.myArrayList.add(value); - return this; - } + /** + * Put a value in the JSONArray, where the value will be a JSONArray which + * is produced from a Collection. + * + * @param index The subscript. + * @param value A Collection value. + * @return this. + * @throws JSONException If the index is negative or if the value is not finite. + */ + public JSONArray put(int index, Collection value) throws JSONException { + this.put(index, new JSONArray(value)); + return this; + } - /** - * Put or replace a boolean value in the JSONArray. If the index is greater - * than the length of the JSONArray, then null elements will be added as - * necessary to pad it out. - * - * @param index - * The subscript. - * @param value - * A boolean value. - * @return this. - * @throws JSONException - * If the index is negative. - */ - public JSONArray put(int index, boolean value) throws JSONException - { - this.put(index, value ? Boolean.TRUE : Boolean.FALSE); - return this; - } + /** + * Put or replace a double value. If the index is greater than the length of + * the JSONArray, then null elements will be added as necessary to pad it + * out. + * + * @param index The subscript. + * @param value A double value. + * @return this. + * @throws JSONException If the index is negative or if the value is not finite. + */ + public JSONArray put(int index, double value) throws JSONException { + this.put(index, new Double(value)); + return this; + } - /** - * Put a value in the JSONArray, where the value will be a JSONArray which - * is produced from a Collection. - * - * @param index - * The subscript. - * @param value - * A Collection value. - * @return this. - * @throws JSONException - * If the index is negative or if the value is not finite. - */ - public JSONArray put(int index, Collection value) throws JSONException - { - this.put(index, new JSONArray(value)); - return this; - } + /** + * Put or replace an int value. If the index is greater than the length of + * the JSONArray, then null elements will be added as necessary to pad it + * out. + * + * @param index The subscript. + * @param value An int value. + * @return this. + * @throws JSONException If the index is negative. + */ + public JSONArray put(int index, int value) throws JSONException { + this.put(index, new Integer(value)); + return this; + } - /** - * Put or replace a double value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad it - * out. - * - * @param index - * The subscript. - * @param value - * A double value. - * @return this. - * @throws JSONException - * If the index is negative or if the value is not finite. - */ - public JSONArray put(int index, double value) throws JSONException - { - this.put(index, new Double(value)); - return this; - } + /** + * Put or replace a long value. If the index is greater than the length of + * the JSONArray, then null elements will be added as necessary to pad it + * out. + * + * @param index The subscript. + * @param value A long value. + * @return this. + * @throws JSONException If the index is negative. + */ + public JSONArray put(int index, long value) throws JSONException { + this.put(index, new Long(value)); + return this; + } - /** - * Put or replace an int value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad it - * out. - * - * @param index - * The subscript. - * @param value - * An int value. - * @return this. - * @throws JSONException - * If the index is negative. - */ - public JSONArray put(int index, int value) throws JSONException - { - this.put(index, new Integer(value)); - return this; - } + /** + * Put a value in the JSONArray, where the value will be a JSONObject that + * is produced from a Map. + * + * @param index The subscript. + * @param value The Map value. + * @return this. + * @throws JSONException If the index is negative or if the the value is an invalid + * number. + */ + public JSONArray put(int index, Map value) throws JSONException { + this.put(index, new JSONObject(value)); + return this; + } - /** - * Put or replace a long value. If the index is greater than the length of - * the JSONArray, then null elements will be added as necessary to pad it - * out. - * - * @param index - * The subscript. - * @param value - * A long value. - * @return this. - * @throws JSONException - * If the index is negative. - */ - public JSONArray put(int index, long value) throws JSONException - { - this.put(index, new Long(value)); - return this; - } + /** + * Put or replace an object value in the JSONArray. If the index is greater + * than the length of the JSONArray, then null elements will be added as + * necessary to pad it out. + * + * @param index The subscript. + * @param value The value to put into the array. The value should be a + * Boolean, Double, Integer, JSONArray, JSONObject, Long, or + * String, or the JSONObject.NULL object. + * @return this. + * @throws JSONException If the index is negative or if the the value is an invalid + * number. + */ + public JSONArray put(int index, Object value) throws JSONException { + JSONObject.testValidity(value); + if (index < 0) { + throw new JSONException("JSONArray[" + index + "] not found."); + } + if (index < this.length()) { + this.myArrayList.set(index, value); + } else { + while (index != this.length()) { + this.put(JSONObject.NULL); + } + this.put(value); + } + return this; + } - /** - * Put a value in the JSONArray, where the value will be a JSONObject that - * is produced from a Map. - * - * @param index - * The subscript. - * @param value - * The Map value. - * @return this. - * @throws JSONException - * If the index is negative or if the the value is an invalid - * number. - */ - public JSONArray put(int index, Map value) throws JSONException - { - this.put(index, new JSONObject(value)); - return this; - } + /** + * Remove an index and close the hole. + * + * @param index The index of the element to be removed. + * @return The value that was associated with the index, or null if there + * was no value. + */ + public Object remove(int index) { + return index >= 0 && index < this.length() ? this.myArrayList.remove(index) : null; + } - /** - * Put or replace an object value in the JSONArray. If the index is greater - * than the length of the JSONArray, then null elements will be added as - * necessary to pad it out. - * - * @param index - * The subscript. - * @param value - * The value to put into the array. The value should be a - * Boolean, Double, Integer, JSONArray, JSONObject, Long, or - * String, or the JSONObject.NULL object. - * @return this. - * @throws JSONException - * If the index is negative or if the the value is an invalid - * number. - */ - public JSONArray put(int index, Object value) throws JSONException - { - JSONObject.testValidity(value); - if(index < 0) - { - throw new JSONException("JSONArray[" + index + "] not found."); - } - if(index < this.length()) - { - this.myArrayList.set(index, value); - } else - { - while(index != this.length()) - { - this.put(JSONObject.NULL); - } - this.put(value); - } - return this; - } + /** + * Determine if two JSONArrays are similar. They must contain similar + * sequences. + * + * @param other The other JSONArray + * @return true if they are equal + */ + public boolean similar(Object other) { + if (!(other instanceof JSONArray)) { + return false; + } + int len = this.length(); + if (len != ((JSONArray) other).length()) { + return false; + } + for (int i = 0; i < len; i += 1) { + Object valueThis = this.get(i); + Object valueOther = ((JSONArray) other).get(i); + if (valueThis instanceof JSONObject) { + if (!((JSONObject) valueThis).similar(valueOther)) { + return false; + } + } else if (valueThis instanceof JSONArray) { + if (!((JSONArray) valueThis).similar(valueOther)) { + return false; + } + } else if (!valueThis.equals(valueOther)) { + return false; + } + } + return true; + } - /** - * Remove an index and close the hole. - * - * @param index - * The index of the element to be removed. - * @return The value that was associated with the index, or null if there - * was no value. - */ - public Object remove(int index) - { - return index >= 0 && index < this.length() ? this.myArrayList.remove(index) : null; - } + /** + * Produce a JSONObject by combining a JSONArray of names with the values of + * this JSONArray. + * + * @param names A JSONArray containing a list of key strings. These will be + * paired with the values. + * @return A JSONObject, or null if there are no names or if this JSONArray + * has no values. + * @throws JSONException If any of the names are null. + */ + public JSONObject toJSONObject(JSONArray names) throws JSONException { + if (names == null || names.length() == 0 || this.length() == 0) { + return null; + } + JSONObject jo = new JSONObject(); + for (int i = 0; i < names.length(); i += 1) { + jo.put(names.getString(i), this.opt(i)); + } + return jo; + } - /** - * Determine if two JSONArrays are similar. They must contain similar - * sequences. - * - * @param other - * The other JSONArray - * @return true if they are equal - */ - public boolean similar(Object other) - { - if(!(other instanceof JSONArray)) - { - return false; - } - int len = this.length(); - if(len != ((JSONArray) other).length()) - { - return false; - } - for(int i = 0; i < len; i += 1) - { - Object valueThis = this.get(i); - Object valueOther = ((JSONArray) other).get(i); - if(valueThis instanceof JSONObject) - { - if(!((JSONObject) valueThis).similar(valueOther)) - { - return false; - } - } else if(valueThis instanceof JSONArray) - { - if(!((JSONArray) valueThis).similar(valueOther)) - { - return false; - } - } else if(!valueThis.equals(valueOther)) - { - return false; - } - } - return true; - } + /** + * Make a JSON text of this JSONArray. For compactness, no unnecessary + * whitespace is added. If it is not possible to produce a syntactically + * correct JSON text then null will be returned instead. This could occur if + * the array contains an invalid number. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @return a printable, displayable, transmittable representation of the + * array. + */ + @Override + public String toString() { + try { + return this.toString(0); + } catch (Exception e) { + return null; + } + } - /** - * Produce a JSONObject by combining a JSONArray of names with the values of - * this JSONArray. - * - * @param names - * A JSONArray containing a list of key strings. These will be - * paired with the values. - * @return A JSONObject, or null if there are no names or if this JSONArray - * has no values. - * @throws JSONException - * If any of the names are null. - */ - public JSONObject toJSONObject(JSONArray names) throws JSONException - { - if(names == null || names.length() == 0 || this.length() == 0) - { - return null; - } - JSONObject jo = new JSONObject(); - for(int i = 0; i < names.length(); i += 1) - { - jo.put(names.getString(i), this.opt(i)); - } - return jo; - } + /** + * Make a prettyprinted JSON text of this JSONArray. Warning: This method + * assumes that the data structure is acyclical. + * + * @param indentFactor The number of spaces to add to each level of indentation. + * @return a printable, displayable, transmittable representation of the + * object, beginning with [ (left + * bracket) and ending with ]   + * (right bracket). + * @throws JSONException + */ + public String toString(int indentFactor) throws JSONException { + StringWriter sw = new StringWriter(); + synchronized (sw.getBuffer()) { + return this.write(sw, indentFactor, 0).toString(); + } + } - /** - * Make a JSON text of this JSONArray. For compactness, no unnecessary - * whitespace is added. If it is not possible to produce a syntactically - * correct JSON text then null will be returned instead. This could occur if - * the array contains an invalid number. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return a printable, displayable, transmittable representation of the - * array. - */ - @Override - public String toString() - { - try - { - return this.toString(0); - } catch(Exception e) - { - return null; - } - } + /** + * Write the contents of the JSONArray as JSON text to a writer. For + * compactness, no whitespace is added. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @return The writer. + * @throws JSONException + */ + public Writer write(Writer writer) throws JSONException { + return this.write(writer, 0, 0); + } - /** - * Make a prettyprinted JSON text of this JSONArray. Warning: This method - * assumes that the data structure is acyclical. - * - * @param indentFactor - * The number of spaces to add to each level of indentation. - * @return a printable, displayable, transmittable representation of the - * object, beginning with [ (left - * bracket) and ending with ]   - * (right bracket). - * @throws JSONException - */ - public String toString(int indentFactor) throws JSONException - { - StringWriter sw = new StringWriter(); - synchronized(sw.getBuffer()) - { - return this.write(sw, indentFactor, 0).toString(); - } - } + /** + * Write the contents of the JSONArray as JSON text to a writer. For + * compactness, no whitespace is added. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @param indentFactor The number of spaces to add to each level of indentation. + * @param indent The indention of the top level. + * @return The writer. + * @throws JSONException + */ + Writer write(Writer writer, int indentFactor, int indent) throws JSONException { + try { + boolean commanate = false; + int length = this.length(); + writer.write('['); - /** - * Write the contents of the JSONArray as JSON text to a writer. For - * compactness, no whitespace is added. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return The writer. - * @throws JSONException - */ - public Writer write(Writer writer) throws JSONException - { - return this.write(writer, 0, 0); - } + if (length == 1) { + JSONObject.writeValue(writer, this.myArrayList.get(0), indentFactor, indent); + } else if (length != 0) { + final int newindent = indent + indentFactor; - /** - * Write the contents of the JSONArray as JSON text to a writer. For - * compactness, no whitespace is added. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @param indentFactor - * The number of spaces to add to each level of indentation. - * @param indent - * The indention of the top level. - * @return The writer. - * @throws JSONException - */ - Writer write(Writer writer, int indentFactor, int indent) throws JSONException - { - try - { - boolean commanate = false; - int length = this.length(); - writer.write('['); - - if(length == 1) - { - JSONObject.writeValue(writer, this.myArrayList.get(0), indentFactor, indent); - } else if(length != 0) - { - final int newindent = indent + indentFactor; - - for(int i = 0; i < length; i += 1) - { - if(commanate) - { - writer.write(','); - } - if(indentFactor > 0) - { - writer.write('\n'); - } - JSONObject.indent(writer, newindent); - JSONObject.writeValue(writer, this.myArrayList.get(i), indentFactor, newindent); - commanate = true; - } - if(indentFactor > 0) - { - writer.write('\n'); - } - JSONObject.indent(writer, indent); - } - writer.write(']'); - return writer; - } catch(IOException e) - { - throw new JSONException(e); - } - } + for (int i = 0; i < length; i += 1) { + if (commanate) { + writer.write(','); + } + if (indentFactor > 0) { + writer.write('\n'); + } + JSONObject.indent(writer, newindent); + JSONObject.writeValue(writer, this.myArrayList.get(i), indentFactor, newindent); + commanate = true; + } + if (indentFactor > 0) { + writer.write('\n'); + } + JSONObject.indent(writer, indent); + } + writer.write(']'); + return writer; + } catch (IOException e) { + throw new JSONException(e); + } + } } diff --git a/src/main/java/com/volmit/iris/util/JSONException.java b/src/main/java/com/volmit/iris/util/JSONException.java index 4d6430452..5d5ec5f5e 100644 --- a/src/main/java/com/volmit/iris/util/JSONException.java +++ b/src/main/java/com/volmit/iris/util/JSONException.java @@ -7,44 +7,38 @@ package com.volmit.iris.util; * @author JSON.org * @version 2014-05-03 */ -public class JSONException extends RuntimeException -{ - private static final long serialVersionUID = 0; - private Throwable cause; - - /** - * Constructs a JSONException with an explanatory message. - * - * @param message - * Detail about the reason for the exception. - */ - public JSONException(String message) - { - super(message); - } - - /** - * Constructs a new JSONException with the specified cause. - * - * @param cause - * The cause. - */ - public JSONException(Throwable cause) - { - super(cause.getMessage()); - this.cause = cause; - } - - /** - * Returns the cause of this exception or null if the cause is nonexistent - * or unknown. - * - * @return the cause of this exception or null if the cause is nonexistent - * or unknown. - */ - @Override - public Throwable getCause() - { - return this.cause; - } +public class JSONException extends RuntimeException { + private static final long serialVersionUID = 0; + private Throwable cause; + + /** + * Constructs a JSONException with an explanatory message. + * + * @param message Detail about the reason for the exception. + */ + public JSONException(String message) { + super(message); + } + + /** + * Constructs a new JSONException with the specified cause. + * + * @param cause The cause. + */ + public JSONException(Throwable cause) { + super(cause.getMessage()); + this.cause = cause; + } + + /** + * Returns the cause of this exception or null if the cause is nonexistent + * or unknown. + * + * @return the cause of this exception or null if the cause is nonexistent + * or unknown. + */ + @Override + public Throwable getCause() { + return this.cause; + } } diff --git a/src/main/java/com/volmit/iris/util/JSONML.java b/src/main/java/com/volmit/iris/util/JSONML.java index a90f38ed1..6520980cf 100644 --- a/src/main/java/com/volmit/iris/util/JSONML.java +++ b/src/main/java/com/volmit/iris/util/JSONML.java @@ -35,521 +35,428 @@ import java.util.Iterator; * @author JSON.org * @version 2014-05-03 */ -public class JSONML -{ - - /** - * Parse XML values and store them in a JSONArray. - * - * @param x - * The XMLTokener containing the source string. - * @param arrayForm - * true if array form, false if object form. - * @param ja - * The JSONArray that is containing the current tag or null if we - * are at the outermost level. - * @return A JSONArray if the value is the outermost tag, otherwise null. - * @throws JSONException - */ - private static Object parse(XMLTokener x, boolean arrayForm, JSONArray ja) throws JSONException - { - String attribute; - char c; - String closeTag = null; - int i; - JSONArray newja = null; - JSONObject newjo = null; - Object token; - String tagName = null; - - // Test for and skip past these forms: - // - // - // - // - - while(true) - { - if(!x.more()) - { - throw x.syntaxError("Bad XML"); - } - token = x.nextContent(); - if(token == XML.LT) - { - token = x.nextToken(); - if(token instanceof Character) - { - if(token == XML.SLASH) - { - - // Close tag "); - } else - { - x.back(); - } - } else if(c == '[') - { - token = x.nextToken(); - if(token.equals("CDATA") && x.next() == '[') - { - if(ja != null) - { - ja.put(x.nextCDATA()); - } - } else - { - throw x.syntaxError("Expected 'CDATA['"); - } - } else - { - i = 1; - do - { - token = x.nextMeta(); - if(token == null) - { - throw x.syntaxError("Missing '>' after ' 0); - } - } else if(token == XML.QUEST) - { - - // "); - } else - { - throw x.syntaxError("Misshaped tag"); - } - - // Open tag < - - } else - { - if(!(token instanceof String)) - { - throw x.syntaxError("Bad tagName '" + token + "'."); - } - tagName = (String) token; - newja = new JSONArray(); - newjo = new JSONObject(); - if(arrayForm) - { - newja.put(tagName); - if(ja != null) - { - ja.put(newja); - } - } else - { - newjo.put("tagName", tagName); - if(ja != null) - { - ja.put(newjo); - } - } - token = null; - for(;;) - { - if(token == null) - { - token = x.nextToken(); - } - if(token == null) - { - throw x.syntaxError("Misshaped tag"); - } - if(!(token instanceof String)) - { - break; - } - - // attribute = value - - attribute = (String) token; - if(!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) - { - throw x.syntaxError("Reserved attribute."); - } - token = x.nextToken(); - if(token == XML.EQ) - { - token = x.nextToken(); - if(!(token instanceof String)) - { - throw x.syntaxError("Missing value"); - } - newjo.accumulate(attribute, XML.stringToValue((String) token)); - token = null; - } else - { - newjo.accumulate(attribute, ""); - } - } - if(arrayForm && newjo.length() > 0) - { - newja.put(newjo); - } - - // Empty tag <.../> - - if(token == XML.SLASH) - { - if(x.nextToken() != XML.GT) - { - throw x.syntaxError("Misshaped tag"); - } - if(ja == null) - { - if(arrayForm) - { - return newja; - } else - { - return newjo; - } - } - - // Content, between <...> and - - } else - { - if(token != XML.GT) - { - throw x.syntaxError("Misshaped tag"); - } - closeTag = (String) parse(x, arrayForm, newja); - if(closeTag != null) - { - if(!closeTag.equals(tagName)) - { - throw x.syntaxError("Mismatched '" + tagName + "' and '" + closeTag + "'"); - } - tagName = null; - if(!arrayForm && newja.length() > 0) - { - newjo.put("childNodes", newja); - } - if(ja == null) - { - if(arrayForm) - { - return newja; - } else - { - return newjo; - } - } - } - } - } - } else - { - if(ja != null) - { - ja.put(token instanceof String ? XML.stringToValue((String) token) : token); - } - } - } - } - - /** - * Convert a well-formed (but not necessarily valid) XML string into a - * JSONArray using the JsonML transform. Each XML tag is represented as a - * JSONArray in which the first element is the tag name. If the tag has - * attributes, then the second element will be JSONObject containing the - * name/value pairs. If the tag contains children, then strings and - * JSONArrays will represent the child tags. Comments, prologs, DTDs, and - * <[ [ ]]> are ignored. - * - * @param string - * The source string. - * @return A JSONArray containing the structured data from the XML string. - * @throws JSONException - */ - public static JSONArray toJSONArray(String string) throws JSONException - { - return toJSONArray(new XMLTokener(string)); - } - - /** - * Convert a well-formed (but not necessarily valid) XML string into a - * JSONArray using the JsonML transform. Each XML tag is represented as a - * JSONArray in which the first element is the tag name. If the tag has - * attributes, then the second element will be JSONObject containing the - * name/value pairs. If the tag contains children, then strings and - * JSONArrays will represent the child content and tags. Comments, prologs, - * DTDs, and <[ [ ]]> are ignored. - * - * @param x - * An XMLTokener. - * @return A JSONArray containing the structured data from the XML string. - * @throws JSONException - */ - public static JSONArray toJSONArray(XMLTokener x) throws JSONException - { - return (JSONArray) parse(x, true, null); - } - - /** - * Convert a well-formed (but not necessarily valid) XML string into a - * JSONObject using the JsonML transform. Each XML tag is represented as a - * JSONObject with a "tagName" property. If the tag has attributes, then the - * attributes will be in the JSONObject as properties. If the tag contains - * children, the object will have a "childNodes" property which will be an - * array of strings and JsonML JSONObjects. - * - * Comments, prologs, DTDs, and <[ [ ]]> are ignored. - * - * @param x - * An XMLTokener of the XML source text. - * @return A JSONObject containing the structured data from the XML string. - * @throws JSONException - */ - public static JSONObject toJSONObject(XMLTokener x) throws JSONException - { - return (JSONObject) parse(x, false, null); - } - - /** - * Convert a well-formed (but not necessarily valid) XML string into a - * JSONObject using the JsonML transform. Each XML tag is represented as a - * JSONObject with a "tagName" property. If the tag has attributes, then the - * attributes will be in the JSONObject as properties. If the tag contains - * children, the object will have a "childNodes" property which will be an - * array of strings and JsonML JSONObjects. - * - * Comments, prologs, DTDs, and <[ [ ]]> are ignored. - * - * @param string - * The XML source text. - * @return A JSONObject containing the structured data from the XML string. - * @throws JSONException - */ - public static JSONObject toJSONObject(String string) throws JSONException - { - return toJSONObject(new XMLTokener(string)); - } - - /** - * Reverse the JSONML transformation, making an XML text from a JSONArray. - * - * @param ja - * A JSONArray. - * @return An XML string. - * @throws JSONException - */ - public static String toString(JSONArray ja) throws JSONException - { - int i; - JSONObject jo; - String key; - Iterator keys; - int length; - Object object; - StringBuilder sb = new StringBuilder(); - String tagName; - String value; - - // Emit = length) - { - sb.append('/'); - sb.append('>'); - } else - { - sb.append('>'); - do - { - object = ja.get(i); - i += 1; - if(object != null) - { - if(object instanceof String) - { - sb.append(XML.escape(object.toString())); - } else if(object instanceof JSONObject) - { - sb.append(toString((JSONObject) object)); - } else if(object instanceof JSONArray) - { - sb.append(toString((JSONArray) object)); - } else - { - sb.append(object.toString()); - } - } - } while(i < length); - sb.append('<'); - sb.append('/'); - sb.append(tagName); - sb.append('>'); - } - return sb.toString(); - } - - /** - * Reverse the JSONML transformation, making an XML text from a JSONObject. - * The JSONObject must contain a "tagName" property. If it has children, - * then it must have a "childNodes" property containing an array of objects. - * The other properties are attributes with string values. - * - * @param jo - * A JSONObject. - * @return An XML string. - * @throws JSONException - */ - public static String toString(JSONObject jo) throws JSONException - { - StringBuilder sb = new StringBuilder(); - int i; - JSONArray ja; - String key; - Iterator keys; - int length; - Object object; - String tagName; - String value; - - // Emit '); - } else - { - sb.append('>'); - length = ja.length(); - for(i = 0; i < length; i += 1) - { - object = ja.get(i); - if(object != null) - { - if(object instanceof String) - { - sb.append(XML.escape(object.toString())); - } else if(object instanceof JSONObject) - { - sb.append(toString((JSONObject) object)); - } else if(object instanceof JSONArray) - { - sb.append(toString((JSONArray) object)); - } else - { - sb.append(object.toString()); - } - } - } - sb.append('<'); - sb.append('/'); - sb.append(tagName); - sb.append('>'); - } - return sb.toString(); - } +public class JSONML { + + /** + * Parse XML values and store them in a JSONArray. + * + * @param x The XMLTokener containing the source string. + * @param arrayForm true if array form, false if object form. + * @param ja The JSONArray that is containing the current tag or null if we + * are at the outermost level. + * @return A JSONArray if the value is the outermost tag, otherwise null. + * @throws JSONException + */ + private static Object parse(XMLTokener x, boolean arrayForm, JSONArray ja) throws JSONException { + String attribute; + char c; + String closeTag = null; + int i; + JSONArray newja = null; + JSONObject newjo = null; + Object token; + String tagName = null; + + // Test for and skip past these forms: + // + // + // + // + + while (true) { + if (!x.more()) { + throw x.syntaxError("Bad XML"); + } + token = x.nextContent(); + if (token == XML.LT) { + token = x.nextToken(); + if (token instanceof Character) { + if (token == XML.SLASH) { + + // Close tag "); + } else { + x.back(); + } + } else if (c == '[') { + token = x.nextToken(); + if (token.equals("CDATA") && x.next() == '[') { + if (ja != null) { + ja.put(x.nextCDATA()); + } + } else { + throw x.syntaxError("Expected 'CDATA['"); + } + } else { + i = 1; + do { + token = x.nextMeta(); + if (token == null) { + throw x.syntaxError("Missing '>' after ' 0); + } + } else if (token == XML.QUEST) { + + // "); + } else { + throw x.syntaxError("Misshaped tag"); + } + + // Open tag < + + } else { + if (!(token instanceof String)) { + throw x.syntaxError("Bad tagName '" + token + "'."); + } + tagName = (String) token; + newja = new JSONArray(); + newjo = new JSONObject(); + if (arrayForm) { + newja.put(tagName); + if (ja != null) { + ja.put(newja); + } + } else { + newjo.put("tagName", tagName); + if (ja != null) { + ja.put(newjo); + } + } + token = null; + for (; ; ) { + if (token == null) { + token = x.nextToken(); + } + if (token == null) { + throw x.syntaxError("Misshaped tag"); + } + if (!(token instanceof String)) { + break; + } + + // attribute = value + + attribute = (String) token; + if (!arrayForm && ("tagName".equals(attribute) || "childNode".equals(attribute))) { + throw x.syntaxError("Reserved attribute."); + } + token = x.nextToken(); + if (token == XML.EQ) { + token = x.nextToken(); + if (!(token instanceof String)) { + throw x.syntaxError("Missing value"); + } + newjo.accumulate(attribute, XML.stringToValue((String) token)); + token = null; + } else { + newjo.accumulate(attribute, ""); + } + } + if (arrayForm && newjo.length() > 0) { + newja.put(newjo); + } + + // Empty tag <.../> + + if (token == XML.SLASH) { + if (x.nextToken() != XML.GT) { + throw x.syntaxError("Misshaped tag"); + } + if (ja == null) { + if (arrayForm) { + return newja; + } else { + return newjo; + } + } + + // Content, between <...> and + + } else { + if (token != XML.GT) { + throw x.syntaxError("Misshaped tag"); + } + closeTag = (String) parse(x, arrayForm, newja); + if (closeTag != null) { + if (!closeTag.equals(tagName)) { + throw x.syntaxError("Mismatched '" + tagName + "' and '" + closeTag + "'"); + } + tagName = null; + if (!arrayForm && newja.length() > 0) { + newjo.put("childNodes", newja); + } + if (ja == null) { + if (arrayForm) { + return newja; + } else { + return newjo; + } + } + } + } + } + } else { + if (ja != null) { + ja.put(token instanceof String ? XML.stringToValue((String) token) : token); + } + } + } + } + + /** + * Convert a well-formed (but not necessarily valid) XML string into a + * JSONArray using the JsonML transform. Each XML tag is represented as a + * JSONArray in which the first element is the tag name. If the tag has + * attributes, then the second element will be JSONObject containing the + * name/value pairs. If the tag contains children, then strings and + * JSONArrays will represent the child tags. Comments, prologs, DTDs, and + * <[ [ ]]> are ignored. + * + * @param string The source string. + * @return A JSONArray containing the structured data from the XML string. + * @throws JSONException + */ + public static JSONArray toJSONArray(String string) throws JSONException { + return toJSONArray(new XMLTokener(string)); + } + + /** + * Convert a well-formed (but not necessarily valid) XML string into a + * JSONArray using the JsonML transform. Each XML tag is represented as a + * JSONArray in which the first element is the tag name. If the tag has + * attributes, then the second element will be JSONObject containing the + * name/value pairs. If the tag contains children, then strings and + * JSONArrays will represent the child content and tags. Comments, prologs, + * DTDs, and <[ [ ]]> are ignored. + * + * @param x An XMLTokener. + * @return A JSONArray containing the structured data from the XML string. + * @throws JSONException + */ + public static JSONArray toJSONArray(XMLTokener x) throws JSONException { + return (JSONArray) parse(x, true, null); + } + + /** + * Convert a well-formed (but not necessarily valid) XML string into a + * JSONObject using the JsonML transform. Each XML tag is represented as a + * JSONObject with a "tagName" property. If the tag has attributes, then the + * attributes will be in the JSONObject as properties. If the tag contains + * children, the object will have a "childNodes" property which will be an + * array of strings and JsonML JSONObjects. + *

+ * Comments, prologs, DTDs, and <[ [ ]]> are ignored. + * + * @param x An XMLTokener of the XML source text. + * @return A JSONObject containing the structured data from the XML string. + * @throws JSONException + */ + public static JSONObject toJSONObject(XMLTokener x) throws JSONException { + return (JSONObject) parse(x, false, null); + } + + /** + * Convert a well-formed (but not necessarily valid) XML string into a + * JSONObject using the JsonML transform. Each XML tag is represented as a + * JSONObject with a "tagName" property. If the tag has attributes, then the + * attributes will be in the JSONObject as properties. If the tag contains + * children, the object will have a "childNodes" property which will be an + * array of strings and JsonML JSONObjects. + *

+ * Comments, prologs, DTDs, and <[ [ ]]> are ignored. + * + * @param string The XML source text. + * @return A JSONObject containing the structured data from the XML string. + * @throws JSONException + */ + public static JSONObject toJSONObject(String string) throws JSONException { + return toJSONObject(new XMLTokener(string)); + } + + /** + * Reverse the JSONML transformation, making an XML text from a JSONArray. + * + * @param ja A JSONArray. + * @return An XML string. + * @throws JSONException + */ + public static String toString(JSONArray ja) throws JSONException { + int i; + JSONObject jo; + String key; + Iterator keys; + int length; + Object object; + StringBuilder sb = new StringBuilder(); + String tagName; + String value; + + // Emit = length) { + sb.append('/'); + sb.append('>'); + } else { + sb.append('>'); + do { + object = ja.get(i); + i += 1; + if (object != null) { + if (object instanceof String) { + sb.append(XML.escape(object.toString())); + } else if (object instanceof JSONObject) { + sb.append(toString((JSONObject) object)); + } else if (object instanceof JSONArray) { + sb.append(toString((JSONArray) object)); + } else { + sb.append(object); + } + } + } while (i < length); + sb.append('<'); + sb.append('/'); + sb.append(tagName); + sb.append('>'); + } + return sb.toString(); + } + + /** + * Reverse the JSONML transformation, making an XML text from a JSONObject. + * The JSONObject must contain a "tagName" property. If it has children, + * then it must have a "childNodes" property containing an array of objects. + * The other properties are attributes with string values. + * + * @param jo A JSONObject. + * @return An XML string. + * @throws JSONException + */ + public static String toString(JSONObject jo) throws JSONException { + StringBuilder sb = new StringBuilder(); + int i; + JSONArray ja; + String key; + Iterator keys; + int length; + Object object; + String tagName; + String value; + + // Emit '); + } else { + sb.append('>'); + length = ja.length(); + for (i = 0; i < length; i += 1) { + object = ja.get(i); + if (object != null) { + if (object instanceof String) { + sb.append(XML.escape(object.toString())); + } else if (object instanceof JSONObject) { + sb.append(toString((JSONObject) object)); + } else if (object instanceof JSONArray) { + sb.append(toString((JSONArray) object)); + } else { + sb.append(object); + } + } + } + sb.append('<'); + sb.append('/'); + sb.append(tagName); + sb.append('>'); + } + return sb.toString(); + } } diff --git a/src/main/java/com/volmit/iris/util/JSONObject.java b/src/main/java/com/volmit/iris/util/JSONObject.java index 0ff4c6111..ec9ef642c 100644 --- a/src/main/java/com/volmit/iris/util/JSONObject.java +++ b/src/main/java/com/volmit/iris/util/JSONObject.java @@ -63,7 +63,7 @@ import java.util.Map.Entry; *

  * myString = new JSONObject().put("JSON", "Hello, World!").toString();
  * 
- * + *

* produces the string {"JSON": "Hello, World"}. *

* The texts produced by the toString methods strictly conform to @@ -85,1980 +85,1598 @@ import java.util.Map.Entry; * @author JSON.org * @version 2015-07-22 */ -public class JSONObject -{ - /** - * JSONObject.NULL is equivalent to the value that JavaScript calls null, - * whilst Java's null is equivalent to the value that JavaScript calls - * undefined. - */ - private static final class Null - { - - /** - * There is only intended to be a single instance of the NULL object, so - * the clone method returns itself. - * - * @return NULL. - */ - @Override - protected final Object clone() - { - return this; - } - - /** - * A Null object is equal to the null value and to itself. - * - * @param object - * An object to test for nullness. - * @return true if the object parameter is the JSONObject.NULL object or - * null. - */ - @Override - public boolean equals(Object object) - { - return object == null || object == this; - } - - /** - * Get the "null" string value. - * - * @return The string "null". - */ - public String toString() - { - return "null"; - } - } - - /** - * The map where the JSONObject's properties are kept. - */ - private final LinkedHashMap map; - - /** - * It is sometimes more convenient and less ambiguous to have a - * NULL object than to use Java's null value. - * JSONObject.NULL.equals(null) returns true. - * JSONObject.NULL.toString() returns "null". - */ - public static final Object NULL = new Null(); - - /** - * Construct an empty JSONObject. - */ - public JSONObject() - { - this.map = new LinkedHashMap<>(); - } - - /** - * Construct a JSONObject from a subset of another JSONObject. An array of - * strings is used to identify the keys that should be copied. Missing keys - * are ignored. - * - * @param jo - * A JSONObject. - * @param names - * An array of strings. - * @throws JSONException - * @exception JSONException - * If a value is a non-finite number or if a name is - * duplicated. - */ - public JSONObject(JSONObject jo, String[] names) - { - this(); - for(int i = 0; i < names.length; i += 1) - { - try - { - this.putOnce(names[i], jo.opt(names[i])); - } catch(Exception ignore) - { - } - } - } - - /** - * Construct a JSONObject from a JSONTokener. - * - * @param x - * A JSONTokener object containing the source string. - * @throws JSONException - * If there is a syntax error in the source string or a - * duplicated key. - */ - public JSONObject(JSONTokener x) throws JSONException - { - this(); - char c; - String key; - - if(x.nextClean() != '{') - { - throw x.syntaxError("A JSONObject text must begin with '{'"); - } - for(;;) - { - c = x.nextClean(); - switch(c) - { - case 0: - throw x.syntaxError("A JSONObject text must end with '}'"); - case '}': - return; - default: - x.back(); - key = x.nextValue().toString(); - } - - // The key is followed by ':'. - - c = x.nextClean(); - if(c != ':') - { - throw x.syntaxError("Expected a ':' after a key"); - } - this.putOnce(key, x.nextValue()); - - // Pairs are separated by ','. - - switch(x.nextClean()) - { - case ';': - case ',': - if(x.nextClean() == '}') - { - return; - } - x.back(); - break; - case '}': - return; - default: - throw x.syntaxError("Expected a ',' or '}'"); - } - } - } - - /** - * Construct a JSONObject from a Map. - * - * @param map - * A map object that can be used to initialize the contents of - * the JSONObject. - * @throws JSONException - */ - public JSONObject(Map map) - { - this.map = new LinkedHashMap<>(); - if(map != null) - { - Iterator> i = map.entrySet().iterator(); - while(i.hasNext()) - { - Entry entry = i.next(); - Object value = entry.getValue(); - if(value != null) - { - this.map.put(entry.getKey(), wrap(value)); - } - } - } - } - - /** - * Construct a JSONObject from an Object using bean getters. It reflects on - * all of the public methods of the object. For each of the methods with no - * parameters and a name starting with "get" or - * "is" followed by an uppercase letter, the method is invoked, - * and a key and the value returned from the getter method are put into the - * new JSONObject. - * - * The key is formed by removing the "get" or "is" - * prefix. If the second remaining character is not upper case, then the - * first character is converted to lower case. - * - * For example, if an object has a method named "getName", and - * if the result of calling object.getName() is - * "Larry Fine", then the JSONObject will contain - * "name": "Larry Fine". - * - * @param bean - * An object that has getter methods that should be used to make - * a JSONObject. - */ - public JSONObject(Object bean) - { - this(); - this.populateMap(bean); - } - - /** - * Construct a JSONObject from an Object, using reflection to find the - * public members. The resulting JSONObject's keys will be the strings from - * the names array, and the values will be the field values associated with - * those keys in the object. If a key is not found or not visible, then it - * will not be copied into the new JSONObject. - * - * @param object - * An object that has fields that should be used to make a - * JSONObject. - * @param names - * An array of strings, the names of the fields to be obtained - * from the object. - */ - public JSONObject(Object object, String names[]) - { - this(); - Class c = object.getClass(); - for(int i = 0; i < names.length; i += 1) - { - String name = names[i]; - try - { - this.putOpt(name, c.getField(name).get(object)); - } catch(Exception ignore) - { - } - } - } - - /** - * Construct a JSONObject from a source JSON text string. This is the most - * commonly used JSONObject constructor. - * - * @param source - * A string beginning with { (left - * brace) and ending with }   - * (right brace). - * @exception JSONException - * If there is a syntax error in the source string or a - * duplicated key. - */ - public JSONObject(String source) throws JSONException - { - this(new JSONTokener(source)); - } - - /** - * Construct a JSONObject from a ResourceBundle. - * - * @param baseName - * The ResourceBundle base name. - * @param locale - * The Locale to load the ResourceBundle for. - * @throws JSONException - * If any JSONExceptions are detected. - */ - public JSONObject(String baseName, Locale locale) throws JSONException - { - this(); - ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, Thread.currentThread().getContextClassLoader()); - - // Iterate through the keys in the bundle. - - Enumeration keys = bundle.getKeys(); - while(keys.hasMoreElements()) - { - Object key = keys.nextElement(); - if(key != null) - { - - // Go through the path, ensuring that there is a nested - // JSONObject for each - // segment except the last. Add the value using the last - // segment's name into - // the deepest nested JSONObject. - - String[] path = ((String) key).split("\\."); - int last = path.length - 1; - JSONObject target = this; - for(int i = 0; i < last; i += 1) - { - String segment = path[i]; - JSONObject nextTarget = target.optJSONObject(segment); - if(nextTarget == null) - { - nextTarget = new JSONObject(); - target.put(segment, nextTarget); - } - target = nextTarget; - } - target.put(path[last], bundle.getString((String) key)); - } - } - } - - /** - * Accumulate values under a key. It is similar to the put method except - * that if there is already an object stored under the key then a JSONArray - * is stored under the key to hold all of the accumulated values. If there - * is already a JSONArray, then the new value is appended to it. In - * contrast, the put method replaces the previous value. - * - * If only one value is accumulated that is not a JSONArray, then the result - * will be the same as using put. But if multiple values are accumulated, - * then the result will be like append. - * - * @param key - * A key string. - * @param value - * An object to be accumulated under the key. - * @return this. - * @throws JSONException - * If the value is an invalid number or if the key is null. - */ - public JSONObject accumulate(String key, Object value) throws JSONException - { - testValidity(value); - Object object = this.opt(key); - if(object == null) - { - this.put(key, value instanceof JSONArray ? new JSONArray().put(value) : value); - } else if(object instanceof JSONArray) - { - ((JSONArray) object).put(value); - } else - { - this.put(key, new JSONArray().put(object).put(value)); - } - return this; - } - - /** - * Append values to the array under a key. If the key does not exist in the - * JSONObject, then the key is put in the JSONObject with its value being a - * JSONArray containing the value parameter. If the key was already - * associated with a JSONArray, then the value parameter is appended to it. - * - * @param key - * A key string. - * @param value - * An object to be accumulated under the key. - * @return this. - * @throws JSONException - * If the key is null or if the current value associated with - * the key is not a JSONArray. - */ - public JSONObject append(String key, Object value) throws JSONException - { - testValidity(value); - Object object = this.opt(key); - if(object == null) - { - this.put(key, new JSONArray().put(value)); - } else if(object instanceof JSONArray) - { - this.put(key, ((JSONArray) object).put(value)); - } else - { - throw new JSONException("JSONObject[" + key + "] is not a JSONArray."); - } - return this; - } - - /** - * Produce a string from a double. The string "null" will be returned if the - * number is not finite. - * - * @param d - * A double. - * @return A String. - */ - public static String doubleToString(double d) - { - if(Double.isInfinite(d) || Double.isNaN(d)) - { - return "null"; - } - - // Shave off trailing zeros and decimal point, if possible. - - String string = Double.toString(d); - if(string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) - { - while(string.endsWith("0")) - { - string = string.substring(0, string.length() - 1); - } - if(string.endsWith(".")) - { - string = string.substring(0, string.length() - 1); - } - } - return string; - } - - /** - * Get the value object associated with a key. - * - * @param key - * A key string. - * @return The object associated with the key. - * @throws JSONException - * if the key is not found. - */ - public Object get(String key) throws JSONException - { - if(key == null) - { - throw new JSONException("Null key."); - } - Object object = this.opt(key); - if(object == null) - { - throw new JSONException("JSONObject[" + quote(key) + "] not found."); - } - return object; - } - - /** - * Get the enum value associated with a key. - * - * @param clazz - * The type of enum to retrieve. - * @param key - * A key string. - * @return The enum value associated with the key - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to an enum. - */ - public > E getEnum(Class clazz, String key) throws JSONException - { - E val = optEnum(clazz, key); - if(val == null) - { - // JSONException should really take a throwable argument. - // If it did, I would re-implement this with the Enum.valueOf - // method and place any thrown exception in the JSONException - throw new JSONException("JSONObject[" + quote(key) + "] is not an enum of type " + quote(clazz.getSimpleName()) + "."); - } - return val; - } - - /** - * Get the boolean value associated with a key. - * - * @param key - * A key string. - * @return The truth. - * @throws JSONException - * if the value is not a Boolean or the String "true" or - * "false". - */ - public boolean getBoolean(String key) throws JSONException - { - Object object = this.get(key); - if(object.equals(Boolean.FALSE) || (object instanceof String && ((String) object).equalsIgnoreCase("false"))) - { - return false; - } else if(object.equals(Boolean.TRUE) || (object instanceof String && ((String) object).equalsIgnoreCase("true"))) - { - return true; - } - throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean."); - } - - /** - * Get the BigInteger value associated with a key. - * - * @param key - * A key string. - * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to BigInteger. - */ - public BigInteger getBigInteger(String key) throws JSONException - { - Object object = this.get(key); - try - { - return new BigInteger(object.toString()); - } catch(Exception e) - { - throw new JSONException("JSONObject[" + quote(key) + "] could not be converted to BigInteger."); - } - } - - /** - * Get the BigDecimal value associated with a key. - * - * @param key - * A key string. - * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to BigDecimal. - */ - public BigDecimal getBigDecimal(String key) throws JSONException - { - Object object = this.get(key); - try - { - return new BigDecimal(object.toString()); - } catch(Exception e) - { - throw new JSONException("JSONObject[" + quote(key) + "] could not be converted to BigDecimal."); - } - } - - /** - * Get the double value associated with a key. - * - * @param key - * A key string. - * @return The numeric value. - * @throws JSONException - * if the key is not found or if the value is not a Number - * object and cannot be converted to a number. - */ - public double getDouble(String key) throws JSONException - { - Object object = this.get(key); - try - { - return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); - } catch(Exception e) - { - throw new JSONException("JSONObject[" + quote(key) + "] is not a number."); - } - } - - /** - * Get the int value associated with a key. - * - * @param key - * A key string. - * @return The integer value. - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to an integer. - */ - public int getInt(String key) throws JSONException - { - Object object = this.get(key); - try - { - return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); - } catch(Exception e) - { - throw new JSONException("JSONObject[" + quote(key) + "] is not an int."); - } - } - - /** - * Get the JSONArray value associated with a key. - * - * @param key - * A key string. - * @return A JSONArray which is the value. - * @throws JSONException - * if the key is not found or if the value is not a JSONArray. - */ - public JSONArray getJSONArray(String key) throws JSONException - { - Object object = this.get(key); - if(object instanceof JSONArray) - { - return (JSONArray) object; - } - throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray."); - } - - /** - * Get the JSONObject value associated with a key. - * - * @param key - * A key string. - * @return A JSONObject which is the value. - * @throws JSONException - * if the key is not found or if the value is not a JSONObject. - */ - public JSONObject getJSONObject(String key) throws JSONException - { - Object object = this.get(key); - if(object instanceof JSONObject) - { - return (JSONObject) object; - } - throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject."); - } - - /** - * Get the long value associated with a key. - * - * @param key - * A key string. - * @return The long value. - * @throws JSONException - * if the key is not found or if the value cannot be converted - * to a long. - */ - public long getLong(String key) throws JSONException - { - Object object = this.get(key); - try - { - return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); - } catch(Exception e) - { - throw new JSONException("JSONObject[" + quote(key) + "] is not a long."); - } - } - - /** - * Get an array of field names from a JSONObject. - * - * @return An array of field names, or null if there are no names. - */ - public static String[] getNames(JSONObject jo) - { - int length = jo.length(); - if(length == 0) - { - return null; - } - Iterator iterator = jo.keys(); - String[] names = new String[length]; - int i = 0; - while(iterator.hasNext()) - { - names[i] = iterator.next(); - i += 1; - } - return names; - } - - /** - * Get an array of field names from an Object. - * - * @return An array of field names, or null if there are no names. - */ - public static String[] getNames(Object object) - { - if(object == null) - { - return null; - } - Class klass = object.getClass(); - Field[] fields = klass.getFields(); - int length = fields.length; - if(length == 0) - { - return null; - } - String[] names = new String[length]; - for(int i = 0; i < length; i += 1) - { - names[i] = fields[i].getName(); - } - return names; - } - - /** - * Get the string associated with a key. - * - * @param key - * A key string. - * @return A string which is the value. - * @throws JSONException - * if there is no string value for the key. - */ - public String getString(String key) throws JSONException - { - Object object = this.get(key); - if(object instanceof String) - { - return (String) object; - } - throw new JSONException("JSONObject[" + quote(key) + "] not a string."); - } - - /** - * Determine if the JSONObject contains a specific key. - * - * @param key - * A key string. - * @return true if the key exists in the JSONObject. - */ - public boolean has(String key) - { - return this.map.containsKey(key); - } - - /** - * Increment a property of a JSONObject. If there is no such property, - * create one with a value of 1. If there is such a property, and if it is - * an Integer, Long, Double, or Float, then add one to it. - * - * @param key - * A key string. - * @return this. - * @throws JSONException - * If there is already a property with this name that is not an - * Integer, Long, Double, or Float. - */ - public JSONObject increment(String key) throws JSONException - { - Object value = this.opt(key); - if(value == null) - { - this.put(key, 1); - } else if(value instanceof BigInteger) - { - this.put(key, ((BigInteger) value).add(BigInteger.ONE)); - } else if(value instanceof BigDecimal) - { - this.put(key, ((BigDecimal) value).add(BigDecimal.ONE)); - } else if(value instanceof Integer) - { - this.put(key, (Integer) value + 1); - } else if(value instanceof Long) - { - this.put(key, (Long) value + 1); - } else if(value instanceof Double) - { - this.put(key, (Double) value + 1); - } else if(value instanceof Float) - { - this.put(key, (Float) value + 1); - } else - { - throw new JSONException("Unable to increment [" + quote(key) + "]."); - } - return this; - } - - /** - * Determine if the value associated with the key is null or if there is no - * value. - * - * @param key - * A key string. - * @return true if there is no value associated with the key or if the value - * is the JSONObject.NULL object. - */ - public boolean isNull(String key) - { - return JSONObject.NULL.equals(this.opt(key)); - } - - /** - * Get an enumeration of the keys of the JSONObject. - * - * @return An iterator of the keys. - */ - public Iterator keys() - { - return this.keySet().iterator(); - } - - /** - * Get a set of keys of the JSONObject. - * - * @return A keySet. - */ - public Set keySet() - { - return this.map.keySet(); - } - - /** - * Get the number of keys stored in the JSONObject. - * - * @return The number of keys in the JSONObject. - */ - public int length() - { - return this.map.size(); - } - - /** - * Produce a JSONArray containing the names of the elements of this - * JSONObject. - * - * @return A JSONArray containing the key strings, or null if the JSONObject - * is empty. - */ - public JSONArray names() - { - JSONArray ja = new JSONArray(); - Iterator keys = this.keys(); - while(keys.hasNext()) - { - ja.put(keys.next()); - } - return ja.length() == 0 ? null : ja; - } - - /** - * Produce a string from a Number. - * - * @param number - * A Number - * @return A String. - * @throws JSONException - * If n is a non-finite number. - */ - public static String numberToString(Number number) throws JSONException - { - if(number == null) - { - throw new JSONException("Null pointer"); - } - testValidity(number); - - // Shave off trailing zeros and decimal point, if possible. - - String string = number.toString(); - if(string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) - { - while(string.endsWith("0")) - { - string = string.substring(0, string.length() - 1); - } - if(string.endsWith(".")) - { - string = string.substring(0, string.length() - 1); - } - } - return string; - } - - /** - * Get an optional value associated with a key. - * - * @param key - * A key string. - * @return An object which is the value, or null if there is no value. - */ - public Object opt(String key) - { - return key == null ? null : this.map.get(key); - } - - /** - * Get the enum value associated with a key. - * - * @param clazz - * The type of enum to retrieve. - * @param key - * A key string. - * @return The enum value associated with the key or null if not found - */ - public > E optEnum(Class clazz, String key) - { - return this.optEnum(clazz, key, null); - } - - /** - * Get the enum value associated with a key. - * - * @param clazz - * The type of enum to retrieve. - * @param key - * A key string. - * @param defaultValue - * The default in case the value is not found - * @return The enum value associated with the key or defaultValue if the - * value is not found or cannot be assigned to clazz - */ - public > E optEnum(Class clazz, String key, E defaultValue) - { - try - { - Object val = this.opt(key); - if(NULL.equals(val)) - { - return defaultValue; - } - if(clazz.isAssignableFrom(val.getClass())) - { - // we just checked it! - @SuppressWarnings("unchecked") - E myE = (E) val; - return myE; - } - return Enum.valueOf(clazz, val.toString()); - } - - catch(IllegalArgumentException e) - { - return defaultValue; - } - - catch(NullPointerException e) - { - return defaultValue; - } - } - - /** - * Get an optional boolean associated with a key. It returns false if there - * is no such key, or if the value is not Boolean.TRUE or the String "true". - * - * @param key - * A key string. - * @return The truth. - */ - public boolean optBoolean(String key) - { - return this.optBoolean(key, false); - } - - /** - * Get an optional boolean associated with a key. It returns the - * defaultValue if there is no such key, or if it is not a Boolean or the - * String "true" or "false" (case insensitive). - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return The truth. - */ - public boolean optBoolean(String key, boolean defaultValue) - { - try - { - return this.getBoolean(key); - } catch(Exception e) - { - return defaultValue; - } - } - - /** - * Get an optional double associated with a key, or NaN if there is no such - * key or if its value is not a number. If the value is a string, an attempt - * will be made to evaluate it as a number. - * - * @param key - * A string which is the key. - * @return An object which is the value. - */ - public double optDouble(String key) - { - return this.optDouble(key, Double.NaN); - } - - /** - * Get an optional BigInteger associated with a key, or the defaultValue if - * there is no such key or if its value is not a number. If the value is a - * string, an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public BigInteger optBigInteger(String key, BigInteger defaultValue) - { - try - { - return this.getBigInteger(key); - } catch(Exception e) - { - return defaultValue; - } - } - - /** - * Get an optional BigDecimal associated with a key, or the defaultValue if - * there is no such key or if its value is not a number. If the value is a - * string, an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public BigDecimal optBigDecimal(String key, BigDecimal defaultValue) - { - try - { - return this.getBigDecimal(key); - } catch(Exception e) - { - return defaultValue; - } - } - - /** - * Get an optional double associated with a key, or the defaultValue if - * there is no such key or if its value is not a number. If the value is a - * string, an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public double optDouble(String key, double defaultValue) - { - try - { - return this.getDouble(key); - } catch(Exception e) - { - return defaultValue; - } - } - - /** - * Get an optional int value associated with a key, or zero if there is no - * such key or if the value is not a number. If the value is a string, an - * attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @return An object which is the value. - */ - public int optInt(String key) - { - return this.optInt(key, 0); - } - - /** - * Get an optional int value associated with a key, or the default if there - * is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public int optInt(String key, int defaultValue) - { - try - { - return this.getInt(key); - } catch(Exception e) - { - return defaultValue; - } - } - - /** - * Get an optional JSONArray associated with a key. It returns null if there - * is no such key, or if its value is not a JSONArray. - * - * @param key - * A key string. - * @return A JSONArray which is the value. - */ - public JSONArray optJSONArray(String key) - { - Object o = this.opt(key); - return o instanceof JSONArray ? (JSONArray) o : null; - } - - /** - * Get an optional JSONObject associated with a key. It returns null if - * there is no such key, or if its value is not a JSONObject. - * - * @param key - * A key string. - * @return A JSONObject which is the value. - */ - public JSONObject optJSONObject(String key) - { - Object object = this.opt(key); - return object instanceof JSONObject ? (JSONObject) object : null; - } - - /** - * Get an optional long value associated with a key, or zero if there is no - * such key or if the value is not a number. If the value is a string, an - * attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @return An object which is the value. - */ - public long optLong(String key) - { - return this.optLong(key, 0); - } - - /** - * Get an optional long value associated with a key, or the default if there - * is no such key or if the value is not a number. If the value is a string, - * an attempt will be made to evaluate it as a number. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return An object which is the value. - */ - public long optLong(String key, long defaultValue) - { - try - { - return this.getLong(key); - } catch(Exception e) - { - return defaultValue; - } - } - - /** - * Get an optional string associated with a key. It returns an empty string - * if there is no such key. If the value is not a string and is not null, - * then it is converted to a string. - * - * @param key - * A key string. - * @return A string which is the value. - */ - public String optString(String key) - { - return this.optString(key, ""); - } - - /** - * Get an optional string associated with a key. It returns the defaultValue - * if there is no such key. - * - * @param key - * A key string. - * @param defaultValue - * The default. - * @return A string which is the value. - */ - public String optString(String key, String defaultValue) - { - Object object = this.opt(key); - return NULL.equals(object) ? defaultValue : object.toString(); - } - - private void populateMap(Object bean) - { - Class klass = bean.getClass(); - - // If klass is a System class then set includeSuperClass to false. - - boolean includeSuperClass = klass.getClassLoader() != null; - - Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods(); - for(int i = 0; i < methods.length; i += 1) - { - try - { - Method method = methods[i]; - if(Modifier.isPublic(method.getModifiers())) - { - String name = method.getName(); - String key = ""; - if(name.startsWith("get")) - { - if("getClass".equals(name) || "getDeclaringClass".equals(name)) - { - key = ""; - } else - { - key = name.substring(3); - } - } else if(name.startsWith("is")) - { - key = name.substring(2); - } - if(key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) - { - if(key.length() == 1) - { - key = key.toLowerCase(); - } else if(!Character.isUpperCase(key.charAt(1))) - { - key = key.substring(0, 1).toLowerCase() + key.substring(1); - } - - Object result = method.invoke(bean, (Object[]) null); - if(result != null) - { - this.map.put(key, wrap(result)); - } - } - } - } catch(Exception ignore) - { - } - } - } - - /** - * Put a key/boolean pair in the JSONObject. - * - * @param key - * A key string. - * @param value - * A boolean which is the value. - * @return this. - * @throws JSONException - * If the key is null. - */ - public JSONObject put(String key, boolean value) throws JSONException - { - this.put(key, value ? Boolean.TRUE : Boolean.FALSE); - return this; - } - - /** - * Put a key/value pair in the JSONObject, where the value will be a - * JSONArray which is produced from a Collection. - * - * @param key - * A key string. - * @param value - * A Collection value. - * @return this. - * @throws JSONException - */ - public JSONObject put(String key, Collection value) throws JSONException - { - this.put(key, new JSONArray(value)); - return this; - } - - /** - * Put a key/double pair in the JSONObject. - * - * @param key - * A key string. - * @param value - * A double which is the value. - * @return this. - * @throws JSONException - * If the key is null or if the number is invalid. - */ - public JSONObject put(String key, double value) throws JSONException - { - this.put(key, new Double(value)); - return this; - } - - /** - * Put a key/int pair in the JSONObject. - * - * @param key - * A key string. - * @param value - * An int which is the value. - * @return this. - * @throws JSONException - * If the key is null. - */ - public JSONObject put(String key, int value) throws JSONException - { - this.put(key, new Integer(value)); - return this; - } - - /** - * Put a key/long pair in the JSONObject. - * - * @param key - * A key string. - * @param value - * A long which is the value. - * @return this. - * @throws JSONException - * If the key is null. - */ - public JSONObject put(String key, long value) throws JSONException - { - this.put(key, new Long(value)); - return this; - } - - /** - * Put a key/value pair in the JSONObject, where the value will be a - * JSONObject which is produced from a Map. - * - * @param key - * A key string. - * @param value - * A Map value. - * @return this. - * @throws JSONException - */ - public JSONObject put(String key, Map value) throws JSONException - { - this.put(key, new JSONObject(value)); - return this; - } - - /** - * Put a key/value pair in the JSONObject. If the value is null, then the - * key will be removed from the JSONObject if it is present. - * - * @param key - * A key string. - * @param value - * An object which is the value. It should be of one of these - * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, - * String, or the JSONObject.NULL object. - * @return this. - * @throws JSONException - * If the value is non-finite number or if the key is null. - */ - public JSONObject put(String key, Object value) throws JSONException - { - if(key == null) - { - throw new NullPointerException("Null key."); - } - if(value != null) - { - testValidity(value); - this.map.put(key, value); - } else - { - this.remove(key); - } - return this; - } - - /** - * Put a key/value pair in the JSONObject, but only if the key and the value - * are both non-null, and only if there is not already a member with that - * name. - * - * @param key - * string - * @param value - * object - * @return this. - * @throws JSONException - * if the key is a duplicate - */ - public JSONObject putOnce(String key, Object value) throws JSONException - { - if(key != null && value != null) - { - if(this.opt(key) != null) - { - throw new JSONException("Duplicate key \"" + key + "\""); - } - this.put(key, value); - } - return this; - } - - /** - * Put a key/value pair in the JSONObject, but only if the key and the value - * are both non-null. - * - * @param key - * A key string. - * @param value - * An object which is the value. It should be of one of these - * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, - * String, or the JSONObject.NULL object. - * @return this. - * @throws JSONException - * If the value is a non-finite number. - */ - public JSONObject putOpt(String key, Object value) throws JSONException - { - if(key != null && value != null) - { - this.put(key, value); - } - return this; - } - - /** - * Produce a string in double quotes with backslash sequences in all the - * right places. A backslash will be inserted within = '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100')) - { - w.write("\\u"); - hhhh = Integer.toHexString(c); - w.write("0000", 0, 4 - hhhh.length()); - w.write(hhhh); - } else - { - w.write(c); - } - } - } - w.write('"'); - return w; - } - - /** - * Remove a name and its value, if present. - * - * @param key - * The name to be removed. - * @return The value that was associated with the name, or null if there was - * no value. - */ - public Object remove(String key) - { - return this.map.remove(key); - } - - /** - * Determine if two JSONObjects are similar. They must contain the same set - * of names which must be associated with similar values. - * - * @param other - * The other JSONObject - * @return true if they are equal - */ - public boolean similar(Object other) - { - try - { - if(!(other instanceof JSONObject)) - { - return false; - } - Set set = this.keySet(); - if(!set.equals(((JSONObject) other).keySet())) - { - return false; - } - Iterator iterator = set.iterator(); - while(iterator.hasNext()) - { - String name = iterator.next(); - Object valueThis = this.get(name); - Object valueOther = ((JSONObject) other).get(name); - if(valueThis instanceof JSONObject) - { - if(!((JSONObject) valueThis).similar(valueOther)) - { - return false; - } - } else if(valueThis instanceof JSONArray) - { - if(!((JSONArray) valueThis).similar(valueOther)) - { - return false; - } - } else if(!valueThis.equals(valueOther)) - { - return false; - } - } - return true; - } catch(Throwable exception) - { - return false; - } - } - - /** - * Try to convert a string into a number, boolean, or null. If the string - * can't be converted, return the string. - * - * @param string - * A String. - * @return A simple JSON value. - */ - public static Object stringToValue(String string) - { - Double d; - if(string.equals("")) - { - return string; - } - if(string.equalsIgnoreCase("true")) - { - return Boolean.TRUE; - } - if(string.equalsIgnoreCase("false")) - { - return Boolean.FALSE; - } - if(string.equalsIgnoreCase("null")) - { - return JSONObject.NULL; - } - - /* - * If it might be a number, try converting it. If a number cannot be - * produced, then the value will just be a string. - */ - - char b = string.charAt(0); - if((b >= '0' && b <= '9') || b == '-') - { - try - { - if(string.indexOf('.') > -1 || string.indexOf('e') > -1 || string.indexOf('E') > -1) - { - d = Double.valueOf(string); - if(!d.isInfinite() && !d.isNaN()) - { - return d; - } - } else - { - Long myLong = new Long(string); - if(string.equals(myLong.toString())) - { - if(myLong == myLong.intValue()) - { - return myLong.intValue(); - } else - { - return myLong; - } - } - } - } catch(Exception ignore) - { - } - } - return string; - } - - /** - * Throw an exception if the object is a NaN or infinite number. - * - * @param o - * The object to test. - * @throws JSONException - * If o is a non-finite number. - */ - public static void testValidity(Object o) throws JSONException - { - if(o != null) - { - if(o instanceof Double) - { - if(((Double) o).isInfinite() || ((Double) o).isNaN()) - { - throw new JSONException("JSON does not allow non-finite numbers."); - } - } else if(o instanceof Float) - { - if(((Float) o).isInfinite() || ((Float) o).isNaN()) - { - throw new JSONException("JSON does not allow non-finite numbers."); - } - } - } - } - - /** - * Produce a JSONArray containing the values of the members of this - * JSONObject. - * - * @param names - * A JSONArray containing a list of key strings. This determines - * the sequence of the values in the result. - * @return A JSONArray of values. - * @throws JSONException - * If any of the values are non-finite numbers. - */ - public JSONArray toJSONArray(JSONArray names) throws JSONException - { - if(names == null || names.length() == 0) - { - return null; - } - JSONArray ja = new JSONArray(); - for(int i = 0; i < names.length(); i += 1) - { - ja.put(this.opt(names.getString(i))); - } - return ja; - } - - /** - * Make a JSON text of this JSONObject. For compactness, no whitespace is - * added. If this would not result in a syntactically correct JSON text, - * then null will be returned instead. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return a printable, displayable, portable, transmittable representation - * of the object, beginning with { (left - * brace) and ending with } (right - * brace). - */ - public String toString() - { - try - { - return this.toString(0); - } catch(Exception e) - { - return null; - } - } - - /** - * Make a prettyprinted JSON text of this JSONObject. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @param indentFactor - * The number of spaces to add to each level of indentation. - * @return a printable, displayable, portable, transmittable representation - * of the object, beginning with { (left - * brace) and ending with } (right - * brace). - * @throws JSONException - * If the object contains an invalid number. - */ - public String toString(int indentFactor) throws JSONException - { - StringWriter w = new StringWriter(); - synchronized(w.getBuffer()) - { - return this.write(w, indentFactor, 0).toString(); - } - } - - /** - * Make a JSON text of an Object value. If the object has an - * value.toJSONString() method, then that method will be used to produce the - * JSON text. The method is required to produce a strictly conforming text. - * If the object does not contain a toJSONString method (which is the most - * common case), then a text will be produced by other means. If the value - * is an array or Collection, then a JSONArray will be made from it and its - * toJSONString method will be called. If the value is a MAP, then a - * JSONObject will be made from it and its toJSONString method will be - * called. Otherwise, the value's toString method will be called, and the - * result will be quoted. - * - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @param value - * The value to be serialized. - * @return a printable, displayable, transmittable representation of the - * object, beginning with { (left - * brace) and ending with } (right - * brace). - * @throws JSONException - * If the value is or contains an invalid number. - */ - public static String valueToString(Object value) throws JSONException - { - if(value == null || value.equals(null)) - { - return "null"; - } - if(value instanceof JSONString) - { - Object object; - try - { - object = ((JSONString) value).toJSONString(); - } catch(Exception e) - { - throw new JSONException(e); - } - if(object instanceof String) - { - return (String) object; - } - throw new JSONException("Bad value from toJSONString: " + object); - } - if(value instanceof Number) - { - return numberToString((Number) value); - } - if(value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) - { - return value.toString(); - } - if(value instanceof Map) - { - @SuppressWarnings("unchecked") - Map map = (Map) value; - return new JSONObject(map).toString(); - } - if(value instanceof Collection) - { - @SuppressWarnings("unchecked") - Collection coll = (Collection) value; - return new JSONArray(coll).toString(); - } - if(value.getClass().isArray()) - { - return new JSONArray(value).toString(); - } - return quote(value.toString()); - } - - /** - * Wrap an object, if necessary. If the object is null, return the NULL - * object. If it is an array or collection, wrap it in a JSONArray. If it is - * a map, wrap it in a JSONObject. If it is a standard property (Double, - * String, et al) then it is already wrapped. Otherwise, if it comes from - * one of the java packages, turn it into a string. And if it doesn't, try - * to wrap it in a JSONObject. If the wrapping fails, then null is returned. - * - * @param object - * The object to wrap - * @return The wrapped value - */ - public static Object wrap(Object object) - { - try - { - if(object == null) - { - return NULL; - } - if(object instanceof JSONObject || object instanceof JSONArray || NULL.equals(object) || object instanceof JSONString || object instanceof Byte || object instanceof Character || object instanceof Short || object instanceof Integer || object instanceof Long || object instanceof Boolean || object instanceof Float || object instanceof Double || object instanceof String || object instanceof BigInteger || object instanceof BigDecimal) - { - return object; - } - - if(object instanceof Collection) - { - @SuppressWarnings("unchecked") - Collection coll = (Collection) object; - return new JSONArray(coll); - } - if(object.getClass().isArray()) - { - return new JSONArray(object); - } - if(object instanceof Map) - { - @SuppressWarnings("unchecked") - Map map = (Map) object; - return new JSONObject(map); - } - Package objectPackage = object.getClass().getPackage(); - String objectPackageName = objectPackage != null ? objectPackage.getName() : ""; - if(objectPackageName.startsWith("java.") || objectPackageName.startsWith("javax.") || object.getClass().getClassLoader() == null) - { - return object.toString(); - } - return new JSONObject(object); - } catch(Exception exception) - { - return null; - } - } - - /** - * Write the contents of the JSONObject as JSON text to a writer. For - * compactness, no whitespace is added. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return The writer. - * @throws JSONException - */ - public Writer write(Writer writer) throws JSONException - { - return this.write(writer, 0, 0); - } - - static final Writer writeValue(Writer writer, Object value, int indentFactor, int indent) throws JSONException, IOException - { - if(value == null || value.equals(null)) - { - writer.write("null"); - } else if(value instanceof JSONObject) - { - ((JSONObject) value).write(writer, indentFactor, indent); - } else if(value instanceof JSONArray) - { - ((JSONArray) value).write(writer, indentFactor, indent); - } else if(value instanceof Map) - { - @SuppressWarnings("unchecked") - Map map = (Map) value; - new JSONObject(map).write(writer, indentFactor, indent); - } else if(value instanceof Collection) - { - @SuppressWarnings("unchecked") - Collection coll = (Collection) value; - new JSONArray(coll).write(writer, indentFactor, indent); - } else if(value.getClass().isArray()) - { - new JSONArray(value).write(writer, indentFactor, indent); - } else if(value instanceof Number) - { - writer.write(numberToString((Number) value)); - } else if(value instanceof Boolean) - { - writer.write(value.toString()); - } else if(value instanceof JSONString) - { - Object o; - try - { - o = ((JSONString) value).toJSONString(); - } catch(Exception e) - { - throw new JSONException(e); - } - writer.write(o != null ? o.toString() : quote(value.toString())); - } else - { - quote(value.toString(), writer); - } - return writer; - } - - static final void indent(Writer writer, int indent) throws IOException - { - for(int i = 0; i < indent; i += 1) - { - writer.write(' '); - } - } - - /** - * Write the contents of the JSONObject as JSON text to a writer. For - * compactness, no whitespace is added. - *

- * Warning: This method assumes that the data structure is acyclical. - * - * @return The writer. - * @throws JSONException - */ - Writer write(Writer writer, int indentFactor, int indent) throws JSONException - { - try - { - boolean commanate = false; - final int length = this.length(); - Iterator keys = this.keys(); - writer.write('{'); - - if(length == 1) - { - Object key = keys.next(); - writer.write(quote(key.toString())); - writer.write(':'); - if(indentFactor > 0) - { - writer.write(' '); - } - writeValue(writer, this.map.get(key), indentFactor, indent); - } else if(length != 0) - { - final int newindent = indent + indentFactor; - while(keys.hasNext()) - { - Object key = keys.next(); - if(commanate) - { - writer.write(','); - } - if(indentFactor > 0) - { - writer.write('\n'); - } - indent(writer, newindent); - writer.write(quote(key.toString())); - writer.write(':'); - if(indentFactor > 0) - { - writer.write(' '); - } - writeValue(writer, this.map.get(key), indentFactor, newindent); - commanate = true; - } - if(indentFactor > 0) - { - writer.write('\n'); - } - indent(writer, indent); - } - writer.write('}'); - return writer; - } catch(IOException exception) - { - throw new JSONException(exception); - } - } +public class JSONObject { + /** + * JSONObject.NULL is equivalent to the value that JavaScript calls null, + * whilst Java's null is equivalent to the value that JavaScript calls + * undefined. + */ + private static final class Null { + + /** + * There is only intended to be a single instance of the NULL object, so + * the clone method returns itself. + * + * @return NULL. + */ + @Override + protected final Object clone() { + return this; + } + + /** + * A Null object is equal to the null value and to itself. + * + * @param object An object to test for nullness. + * @return true if the object parameter is the JSONObject.NULL object or + * null. + */ + @Override + public boolean equals(Object object) { + return object == null || object == this; + } + + /** + * Get the "null" string value. + * + * @return The string "null". + */ + public String toString() { + return "null"; + } + } + + /** + * The map where the JSONObject's properties are kept. + */ + private final LinkedHashMap map; + + /** + * It is sometimes more convenient and less ambiguous to have a + * NULL object than to use Java's null value. + * JSONObject.NULL.equals(null) returns true. + * JSONObject.NULL.toString() returns "null". + */ + public static final Object NULL = new Null(); + + /** + * Construct an empty JSONObject. + */ + public JSONObject() { + this.map = new LinkedHashMap<>(); + } + + /** + * Construct a JSONObject from a subset of another JSONObject. An array of + * strings is used to identify the keys that should be copied. Missing keys + * are ignored. + * + * @param jo A JSONObject. + * @param names An array of strings. + * @throws JSONException + * @throws JSONException If a value is a non-finite number or if a name is + * duplicated. + */ + public JSONObject(JSONObject jo, String[] names) { + this(); + for (int i = 0; i < names.length; i += 1) { + try { + this.putOnce(names[i], jo.opt(names[i])); + } catch (Exception ignore) { + } + } + } + + /** + * Construct a JSONObject from a JSONTokener. + * + * @param x A JSONTokener object containing the source string. + * @throws JSONException If there is a syntax error in the source string or a + * duplicated key. + */ + public JSONObject(JSONTokener x) throws JSONException { + this(); + char c; + String key; + + if (x.nextClean() != '{') { + throw x.syntaxError("A JSONObject text must begin with '{'"); + } + for (; ; ) { + c = x.nextClean(); + switch (c) { + case 0: + throw x.syntaxError("A JSONObject text must end with '}'"); + case '}': + return; + default: + x.back(); + key = x.nextValue().toString(); + } + + // The key is followed by ':'. + + c = x.nextClean(); + if (c != ':') { + throw x.syntaxError("Expected a ':' after a key"); + } + this.putOnce(key, x.nextValue()); + + // Pairs are separated by ','. + + switch (x.nextClean()) { + case ';': + case ',': + if (x.nextClean() == '}') { + return; + } + x.back(); + break; + case '}': + return; + default: + throw x.syntaxError("Expected a ',' or '}'"); + } + } + } + + /** + * Construct a JSONObject from a Map. + * + * @param map A map object that can be used to initialize the contents of + * the JSONObject. + * @throws JSONException + */ + public JSONObject(Map map) { + this.map = new LinkedHashMap<>(); + if (map != null) { + Iterator> i = map.entrySet().iterator(); + while (i.hasNext()) { + Entry entry = i.next(); + Object value = entry.getValue(); + if (value != null) { + this.map.put(entry.getKey(), wrap(value)); + } + } + } + } + + /** + * Construct a JSONObject from an Object using bean getters. It reflects on + * all of the public methods of the object. For each of the methods with no + * parameters and a name starting with "get" or + * "is" followed by an uppercase letter, the method is invoked, + * and a key and the value returned from the getter method are put into the + * new JSONObject. + *

+ * The key is formed by removing the "get" or "is" + * prefix. If the second remaining character is not upper case, then the + * first character is converted to lower case. + *

+ * For example, if an object has a method named "getName", and + * if the result of calling object.getName() is + * "Larry Fine", then the JSONObject will contain + * "name": "Larry Fine". + * + * @param bean An object that has getter methods that should be used to make + * a JSONObject. + */ + public JSONObject(Object bean) { + this(); + this.populateMap(bean); + } + + /** + * Construct a JSONObject from an Object, using reflection to find the + * public members. The resulting JSONObject's keys will be the strings from + * the names array, and the values will be the field values associated with + * those keys in the object. If a key is not found or not visible, then it + * will not be copied into the new JSONObject. + * + * @param object An object that has fields that should be used to make a + * JSONObject. + * @param names An array of strings, the names of the fields to be obtained + * from the object. + */ + public JSONObject(Object object, String[] names) { + this(); + Class c = object.getClass(); + for (int i = 0; i < names.length; i += 1) { + String name = names[i]; + try { + this.putOpt(name, c.getField(name).get(object)); + } catch (Exception ignore) { + } + } + } + + /** + * Construct a JSONObject from a source JSON text string. This is the most + * commonly used JSONObject constructor. + * + * @param source A string beginning with { (left + * brace) and ending with }   + * (right brace). + * @throws JSONException If there is a syntax error in the source string or a + * duplicated key. + */ + public JSONObject(String source) throws JSONException { + this(new JSONTokener(source)); + } + + /** + * Construct a JSONObject from a ResourceBundle. + * + * @param baseName The ResourceBundle base name. + * @param locale The Locale to load the ResourceBundle for. + * @throws JSONException If any JSONExceptions are detected. + */ + public JSONObject(String baseName, Locale locale) throws JSONException { + this(); + ResourceBundle bundle = ResourceBundle.getBundle(baseName, locale, Thread.currentThread().getContextClassLoader()); + + // Iterate through the keys in the bundle. + + Enumeration keys = bundle.getKeys(); + while (keys.hasMoreElements()) { + Object key = keys.nextElement(); + if (key != null) { + + // Go through the path, ensuring that there is a nested + // JSONObject for each + // segment except the last. Add the value using the last + // segment's name into + // the deepest nested JSONObject. + + String[] path = ((String) key).split("\\."); + int last = path.length - 1; + JSONObject target = this; + for (int i = 0; i < last; i += 1) { + String segment = path[i]; + JSONObject nextTarget = target.optJSONObject(segment); + if (nextTarget == null) { + nextTarget = new JSONObject(); + target.put(segment, nextTarget); + } + target = nextTarget; + } + target.put(path[last], bundle.getString((String) key)); + } + } + } + + /** + * Accumulate values under a key. It is similar to the put method except + * that if there is already an object stored under the key then a JSONArray + * is stored under the key to hold all of the accumulated values. If there + * is already a JSONArray, then the new value is appended to it. In + * contrast, the put method replaces the previous value. + *

+ * If only one value is accumulated that is not a JSONArray, then the result + * will be the same as using put. But if multiple values are accumulated, + * then the result will be like append. + * + * @param key A key string. + * @param value An object to be accumulated under the key. + * @return this. + * @throws JSONException If the value is an invalid number or if the key is null. + */ + public JSONObject accumulate(String key, Object value) throws JSONException { + testValidity(value); + Object object = this.opt(key); + if (object == null) { + this.put(key, value instanceof JSONArray ? new JSONArray().put(value) : value); + } else if (object instanceof JSONArray) { + ((JSONArray) object).put(value); + } else { + this.put(key, new JSONArray().put(object).put(value)); + } + return this; + } + + /** + * Append values to the array under a key. If the key does not exist in the + * JSONObject, then the key is put in the JSONObject with its value being a + * JSONArray containing the value parameter. If the key was already + * associated with a JSONArray, then the value parameter is appended to it. + * + * @param key A key string. + * @param value An object to be accumulated under the key. + * @return this. + * @throws JSONException If the key is null or if the current value associated with + * the key is not a JSONArray. + */ + public JSONObject append(String key, Object value) throws JSONException { + testValidity(value); + Object object = this.opt(key); + if (object == null) { + this.put(key, new JSONArray().put(value)); + } else if (object instanceof JSONArray) { + this.put(key, ((JSONArray) object).put(value)); + } else { + throw new JSONException("JSONObject[" + key + "] is not a JSONArray."); + } + return this; + } + + /** + * Produce a string from a double. The string "null" will be returned if the + * number is not finite. + * + * @param d A double. + * @return A String. + */ + public static String doubleToString(double d) { + if (Double.isInfinite(d) || Double.isNaN(d)) { + return "null"; + } + + // Shave off trailing zeros and decimal point, if possible. + + String string = Double.toString(d); + if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { + while (string.endsWith("0")) { + string = string.substring(0, string.length() - 1); + } + if (string.endsWith(".")) { + string = string.substring(0, string.length() - 1); + } + } + return string; + } + + /** + * Get the value object associated with a key. + * + * @param key A key string. + * @return The object associated with the key. + * @throws JSONException if the key is not found. + */ + public Object get(String key) throws JSONException { + if (key == null) { + throw new JSONException("Null key."); + } + Object object = this.opt(key); + if (object == null) { + throw new JSONException("JSONObject[" + quote(key) + "] not found."); + } + return object; + } + + /** + * Get the enum value associated with a key. + * + * @param clazz The type of enum to retrieve. + * @param key A key string. + * @return The enum value associated with the key + * @throws JSONException if the key is not found or if the value cannot be converted + * to an enum. + */ + public > E getEnum(Class clazz, String key) throws JSONException { + E val = optEnum(clazz, key); + if (val == null) { + // JSONException should really take a throwable argument. + // If it did, I would re-implement this with the Enum.valueOf + // method and place any thrown exception in the JSONException + throw new JSONException("JSONObject[" + quote(key) + "] is not an enum of type " + quote(clazz.getSimpleName()) + "."); + } + return val; + } + + /** + * Get the boolean value associated with a key. + * + * @param key A key string. + * @return The truth. + * @throws JSONException if the value is not a Boolean or the String "true" or + * "false". + */ + public boolean getBoolean(String key) throws JSONException { + Object object = this.get(key); + if (object.equals(Boolean.FALSE) || (object instanceof String && ((String) object).equalsIgnoreCase("false"))) { + return false; + } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String) object).equalsIgnoreCase("true"))) { + return true; + } + throw new JSONException("JSONObject[" + quote(key) + "] is not a Boolean."); + } + + /** + * Get the BigInteger value associated with a key. + * + * @param key A key string. + * @return The numeric value. + * @throws JSONException if the key is not found or if the value cannot be converted + * to BigInteger. + */ + public BigInteger getBigInteger(String key) throws JSONException { + Object object = this.get(key); + try { + return new BigInteger(object.toString()); + } catch (Exception e) { + throw new JSONException("JSONObject[" + quote(key) + "] could not be converted to BigInteger."); + } + } + + /** + * Get the BigDecimal value associated with a key. + * + * @param key A key string. + * @return The numeric value. + * @throws JSONException if the key is not found or if the value cannot be converted + * to BigDecimal. + */ + public BigDecimal getBigDecimal(String key) throws JSONException { + Object object = this.get(key); + try { + return new BigDecimal(object.toString()); + } catch (Exception e) { + throw new JSONException("JSONObject[" + quote(key) + "] could not be converted to BigDecimal."); + } + } + + /** + * Get the double value associated with a key. + * + * @param key A key string. + * @return The numeric value. + * @throws JSONException if the key is not found or if the value is not a Number + * object and cannot be converted to a number. + */ + public double getDouble(String key) throws JSONException { + Object object = this.get(key); + try { + return object instanceof Number ? ((Number) object).doubleValue() : Double.parseDouble((String) object); + } catch (Exception e) { + throw new JSONException("JSONObject[" + quote(key) + "] is not a number."); + } + } + + /** + * Get the int value associated with a key. + * + * @param key A key string. + * @return The integer value. + * @throws JSONException if the key is not found or if the value cannot be converted + * to an integer. + */ + public int getInt(String key) throws JSONException { + Object object = this.get(key); + try { + return object instanceof Number ? ((Number) object).intValue() : Integer.parseInt((String) object); + } catch (Exception e) { + throw new JSONException("JSONObject[" + quote(key) + "] is not an int."); + } + } + + /** + * Get the JSONArray value associated with a key. + * + * @param key A key string. + * @return A JSONArray which is the value. + * @throws JSONException if the key is not found or if the value is not a JSONArray. + */ + public JSONArray getJSONArray(String key) throws JSONException { + Object object = this.get(key); + if (object instanceof JSONArray) { + return (JSONArray) object; + } + throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONArray."); + } + + /** + * Get the JSONObject value associated with a key. + * + * @param key A key string. + * @return A JSONObject which is the value. + * @throws JSONException if the key is not found or if the value is not a JSONObject. + */ + public JSONObject getJSONObject(String key) throws JSONException { + Object object = this.get(key); + if (object instanceof JSONObject) { + return (JSONObject) object; + } + throw new JSONException("JSONObject[" + quote(key) + "] is not a JSONObject."); + } + + /** + * Get the long value associated with a key. + * + * @param key A key string. + * @return The long value. + * @throws JSONException if the key is not found or if the value cannot be converted + * to a long. + */ + public long getLong(String key) throws JSONException { + Object object = this.get(key); + try { + return object instanceof Number ? ((Number) object).longValue() : Long.parseLong((String) object); + } catch (Exception e) { + throw new JSONException("JSONObject[" + quote(key) + "] is not a long."); + } + } + + /** + * Get an array of field names from a JSONObject. + * + * @return An array of field names, or null if there are no names. + */ + public static String[] getNames(JSONObject jo) { + int length = jo.length(); + if (length == 0) { + return null; + } + Iterator iterator = jo.keys(); + String[] names = new String[length]; + int i = 0; + while (iterator.hasNext()) { + names[i] = iterator.next(); + i += 1; + } + return names; + } + + /** + * Get an array of field names from an Object. + * + * @return An array of field names, or null if there are no names. + */ + public static String[] getNames(Object object) { + if (object == null) { + return null; + } + Class klass = object.getClass(); + Field[] fields = klass.getFields(); + int length = fields.length; + if (length == 0) { + return null; + } + String[] names = new String[length]; + for (int i = 0; i < length; i += 1) { + names[i] = fields[i].getName(); + } + return names; + } + + /** + * Get the string associated with a key. + * + * @param key A key string. + * @return A string which is the value. + * @throws JSONException if there is no string value for the key. + */ + public String getString(String key) throws JSONException { + Object object = this.get(key); + if (object instanceof String) { + return (String) object; + } + throw new JSONException("JSONObject[" + quote(key) + "] not a string."); + } + + /** + * Determine if the JSONObject contains a specific key. + * + * @param key A key string. + * @return true if the key exists in the JSONObject. + */ + public boolean has(String key) { + return this.map.containsKey(key); + } + + /** + * Increment a property of a JSONObject. If there is no such property, + * create one with a value of 1. If there is such a property, and if it is + * an Integer, Long, Double, or Float, then add one to it. + * + * @param key A key string. + * @return this. + * @throws JSONException If there is already a property with this name that is not an + * Integer, Long, Double, or Float. + */ + public JSONObject increment(String key) throws JSONException { + Object value = this.opt(key); + if (value == null) { + this.put(key, 1); + } else if (value instanceof BigInteger) { + this.put(key, ((BigInteger) value).add(BigInteger.ONE)); + } else if (value instanceof BigDecimal) { + this.put(key, ((BigDecimal) value).add(BigDecimal.ONE)); + } else if (value instanceof Integer) { + this.put(key, (Integer) value + 1); + } else if (value instanceof Long) { + this.put(key, (Long) value + 1); + } else if (value instanceof Double) { + this.put(key, (Double) value + 1); + } else if (value instanceof Float) { + this.put(key, (Float) value + 1); + } else { + throw new JSONException("Unable to increment [" + quote(key) + "]."); + } + return this; + } + + /** + * Determine if the value associated with the key is null or if there is no + * value. + * + * @param key A key string. + * @return true if there is no value associated with the key or if the value + * is the JSONObject.NULL object. + */ + public boolean isNull(String key) { + return JSONObject.NULL.equals(this.opt(key)); + } + + /** + * Get an enumeration of the keys of the JSONObject. + * + * @return An iterator of the keys. + */ + public Iterator keys() { + return this.keySet().iterator(); + } + + /** + * Get a set of keys of the JSONObject. + * + * @return A keySet. + */ + public Set keySet() { + return this.map.keySet(); + } + + /** + * Get the number of keys stored in the JSONObject. + * + * @return The number of keys in the JSONObject. + */ + public int length() { + return this.map.size(); + } + + /** + * Produce a JSONArray containing the names of the elements of this + * JSONObject. + * + * @return A JSONArray containing the key strings, or null if the JSONObject + * is empty. + */ + public JSONArray names() { + JSONArray ja = new JSONArray(); + Iterator keys = this.keys(); + while (keys.hasNext()) { + ja.put(keys.next()); + } + return ja.length() == 0 ? null : ja; + } + + /** + * Produce a string from a Number. + * + * @param number A Number + * @return A String. + * @throws JSONException If n is a non-finite number. + */ + public static String numberToString(Number number) throws JSONException { + if (number == null) { + throw new JSONException("Null pointer"); + } + testValidity(number); + + // Shave off trailing zeros and decimal point, if possible. + + String string = number.toString(); + if (string.indexOf('.') > 0 && string.indexOf('e') < 0 && string.indexOf('E') < 0) { + while (string.endsWith("0")) { + string = string.substring(0, string.length() - 1); + } + if (string.endsWith(".")) { + string = string.substring(0, string.length() - 1); + } + } + return string; + } + + /** + * Get an optional value associated with a key. + * + * @param key A key string. + * @return An object which is the value, or null if there is no value. + */ + public Object opt(String key) { + return key == null ? null : this.map.get(key); + } + + /** + * Get the enum value associated with a key. + * + * @param clazz The type of enum to retrieve. + * @param key A key string. + * @return The enum value associated with the key or null if not found + */ + public > E optEnum(Class clazz, String key) { + return this.optEnum(clazz, key, null); + } + + /** + * Get the enum value associated with a key. + * + * @param clazz The type of enum to retrieve. + * @param key A key string. + * @param defaultValue The default in case the value is not found + * @return The enum value associated with the key or defaultValue if the + * value is not found or cannot be assigned to clazz + */ + public > E optEnum(Class clazz, String key, E defaultValue) { + try { + Object val = this.opt(key); + if (NULL.equals(val)) { + return defaultValue; + } + if (clazz.isAssignableFrom(val.getClass())) { + // we just checked it! + @SuppressWarnings("unchecked") + E myE = (E) val; + return myE; + } + return Enum.valueOf(clazz, val.toString()); + } catch (IllegalArgumentException e) { + return defaultValue; + } catch (NullPointerException e) { + return defaultValue; + } + } + + /** + * Get an optional boolean associated with a key. It returns false if there + * is no such key, or if the value is not Boolean.TRUE or the String "true". + * + * @param key A key string. + * @return The truth. + */ + public boolean optBoolean(String key) { + return this.optBoolean(key, false); + } + + /** + * Get an optional boolean associated with a key. It returns the + * defaultValue if there is no such key, or if it is not a Boolean or the + * String "true" or "false" (case insensitive). + * + * @param key A key string. + * @param defaultValue The default. + * @return The truth. + */ + public boolean optBoolean(String key, boolean defaultValue) { + try { + return this.getBoolean(key); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get an optional double associated with a key, or NaN if there is no such + * key or if its value is not a number. If the value is a string, an attempt + * will be made to evaluate it as a number. + * + * @param key A string which is the key. + * @return An object which is the value. + */ + public double optDouble(String key) { + return this.optDouble(key, Double.NaN); + } + + /** + * Get an optional BigInteger associated with a key, or the defaultValue if + * there is no such key or if its value is not a number. If the value is a + * string, an attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public BigInteger optBigInteger(String key, BigInteger defaultValue) { + try { + return this.getBigInteger(key); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get an optional BigDecimal associated with a key, or the defaultValue if + * there is no such key or if its value is not a number. If the value is a + * string, an attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public BigDecimal optBigDecimal(String key, BigDecimal defaultValue) { + try { + return this.getBigDecimal(key); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get an optional double associated with a key, or the defaultValue if + * there is no such key or if its value is not a number. If the value is a + * string, an attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public double optDouble(String key, double defaultValue) { + try { + return this.getDouble(key); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get an optional int value associated with a key, or zero if there is no + * such key or if the value is not a number. If the value is a string, an + * attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @return An object which is the value. + */ + public int optInt(String key) { + return this.optInt(key, 0); + } + + /** + * Get an optional int value associated with a key, or the default if there + * is no such key or if the value is not a number. If the value is a string, + * an attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public int optInt(String key, int defaultValue) { + try { + return this.getInt(key); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get an optional JSONArray associated with a key. It returns null if there + * is no such key, or if its value is not a JSONArray. + * + * @param key A key string. + * @return A JSONArray which is the value. + */ + public JSONArray optJSONArray(String key) { + Object o = this.opt(key); + return o instanceof JSONArray ? (JSONArray) o : null; + } + + /** + * Get an optional JSONObject associated with a key. It returns null if + * there is no such key, or if its value is not a JSONObject. + * + * @param key A key string. + * @return A JSONObject which is the value. + */ + public JSONObject optJSONObject(String key) { + Object object = this.opt(key); + return object instanceof JSONObject ? (JSONObject) object : null; + } + + /** + * Get an optional long value associated with a key, or zero if there is no + * such key or if the value is not a number. If the value is a string, an + * attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @return An object which is the value. + */ + public long optLong(String key) { + return this.optLong(key, 0); + } + + /** + * Get an optional long value associated with a key, or the default if there + * is no such key or if the value is not a number. If the value is a string, + * an attempt will be made to evaluate it as a number. + * + * @param key A key string. + * @param defaultValue The default. + * @return An object which is the value. + */ + public long optLong(String key, long defaultValue) { + try { + return this.getLong(key); + } catch (Exception e) { + return defaultValue; + } + } + + /** + * Get an optional string associated with a key. It returns an empty string + * if there is no such key. If the value is not a string and is not null, + * then it is converted to a string. + * + * @param key A key string. + * @return A string which is the value. + */ + public String optString(String key) { + return this.optString(key, ""); + } + + /** + * Get an optional string associated with a key. It returns the defaultValue + * if there is no such key. + * + * @param key A key string. + * @param defaultValue The default. + * @return A string which is the value. + */ + public String optString(String key, String defaultValue) { + Object object = this.opt(key); + return NULL.equals(object) ? defaultValue : object.toString(); + } + + private void populateMap(Object bean) { + Class klass = bean.getClass(); + + // If klass is a System class then set includeSuperClass to false. + + boolean includeSuperClass = klass.getClassLoader() != null; + + Method[] methods = includeSuperClass ? klass.getMethods() : klass.getDeclaredMethods(); + for (int i = 0; i < methods.length; i += 1) { + try { + Method method = methods[i]; + if (Modifier.isPublic(method.getModifiers())) { + String name = method.getName(); + String key = ""; + if (name.startsWith("get")) { + if ("getClass".equals(name) || "getDeclaringClass".equals(name)) { + key = ""; + } else { + key = name.substring(3); + } + } else if (name.startsWith("is")) { + key = name.substring(2); + } + if (key.length() > 0 && Character.isUpperCase(key.charAt(0)) && method.getParameterTypes().length == 0) { + if (key.length() == 1) { + key = key.toLowerCase(); + } else if (!Character.isUpperCase(key.charAt(1))) { + key = key.substring(0, 1).toLowerCase() + key.substring(1); + } + + Object result = method.invoke(bean, (Object[]) null); + if (result != null) { + this.map.put(key, wrap(result)); + } + } + } + } catch (Exception ignore) { + } + } + } + + /** + * Put a key/boolean pair in the JSONObject. + * + * @param key A key string. + * @param value A boolean which is the value. + * @return this. + * @throws JSONException If the key is null. + */ + public JSONObject put(String key, boolean value) throws JSONException { + this.put(key, value ? Boolean.TRUE : Boolean.FALSE); + return this; + } + + /** + * Put a key/value pair in the JSONObject, where the value will be a + * JSONArray which is produced from a Collection. + * + * @param key A key string. + * @param value A Collection value. + * @return this. + * @throws JSONException + */ + public JSONObject put(String key, Collection value) throws JSONException { + this.put(key, new JSONArray(value)); + return this; + } + + /** + * Put a key/double pair in the JSONObject. + * + * @param key A key string. + * @param value A double which is the value. + * @return this. + * @throws JSONException If the key is null or if the number is invalid. + */ + public JSONObject put(String key, double value) throws JSONException { + this.put(key, new Double(value)); + return this; + } + + /** + * Put a key/int pair in the JSONObject. + * + * @param key A key string. + * @param value An int which is the value. + * @return this. + * @throws JSONException If the key is null. + */ + public JSONObject put(String key, int value) throws JSONException { + this.put(key, new Integer(value)); + return this; + } + + /** + * Put a key/long pair in the JSONObject. + * + * @param key A key string. + * @param value A long which is the value. + * @return this. + * @throws JSONException If the key is null. + */ + public JSONObject put(String key, long value) throws JSONException { + this.put(key, new Long(value)); + return this; + } + + /** + * Put a key/value pair in the JSONObject, where the value will be a + * JSONObject which is produced from a Map. + * + * @param key A key string. + * @param value A Map value. + * @return this. + * @throws JSONException + */ + public JSONObject put(String key, Map value) throws JSONException { + this.put(key, new JSONObject(value)); + return this; + } + + /** + * Put a key/value pair in the JSONObject. If the value is null, then the + * key will be removed from the JSONObject if it is present. + * + * @param key A key string. + * @param value An object which is the value. It should be of one of these + * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, + * String, or the JSONObject.NULL object. + * @return this. + * @throws JSONException If the value is non-finite number or if the key is null. + */ + public JSONObject put(String key, Object value) throws JSONException { + if (key == null) { + throw new NullPointerException("Null key."); + } + if (value != null) { + testValidity(value); + this.map.put(key, value); + } else { + this.remove(key); + } + return this; + } + + /** + * Put a key/value pair in the JSONObject, but only if the key and the value + * are both non-null, and only if there is not already a member with that + * name. + * + * @param key string + * @param value object + * @return this. + * @throws JSONException if the key is a duplicate + */ + public JSONObject putOnce(String key, Object value) throws JSONException { + if (key != null && value != null) { + if (this.opt(key) != null) { + throw new JSONException("Duplicate key \"" + key + "\""); + } + this.put(key, value); + } + return this; + } + + /** + * Put a key/value pair in the JSONObject, but only if the key and the value + * are both non-null. + * + * @param key A key string. + * @param value An object which is the value. It should be of one of these + * types: Boolean, Double, Integer, JSONArray, JSONObject, Long, + * String, or the JSONObject.NULL object. + * @return this. + * @throws JSONException If the value is a non-finite number. + */ + public JSONObject putOpt(String key, Object value) throws JSONException { + if (key != null && value != null) { + this.put(key, value); + } + return this; + } + + /** + * Produce a string in double quotes with backslash sequences in all the + * right places. A backslash will be inserted within = '\u0080' && c < '\u00a0') || (c >= '\u2000' && c < '\u2100')) { + w.write("\\u"); + hhhh = Integer.toHexString(c); + w.write("0000", 0, 4 - hhhh.length()); + w.write(hhhh); + } else { + w.write(c); + } + } + } + w.write('"'); + return w; + } + + /** + * Remove a name and its value, if present. + * + * @param key The name to be removed. + * @return The value that was associated with the name, or null if there was + * no value. + */ + public Object remove(String key) { + return this.map.remove(key); + } + + /** + * Determine if two JSONObjects are similar. They must contain the same set + * of names which must be associated with similar values. + * + * @param other The other JSONObject + * @return true if they are equal + */ + public boolean similar(Object other) { + try { + if (!(other instanceof JSONObject)) { + return false; + } + Set set = this.keySet(); + if (!set.equals(((JSONObject) other).keySet())) { + return false; + } + Iterator iterator = set.iterator(); + while (iterator.hasNext()) { + String name = iterator.next(); + Object valueThis = this.get(name); + Object valueOther = ((JSONObject) other).get(name); + if (valueThis instanceof JSONObject) { + if (!((JSONObject) valueThis).similar(valueOther)) { + return false; + } + } else if (valueThis instanceof JSONArray) { + if (!((JSONArray) valueThis).similar(valueOther)) { + return false; + } + } else if (!valueThis.equals(valueOther)) { + return false; + } + } + return true; + } catch (Throwable exception) { + return false; + } + } + + /** + * Try to convert a string into a number, boolean, or null. If the string + * can't be converted, return the string. + * + * @param string A String. + * @return A simple JSON value. + */ + public static Object stringToValue(String string) { + Double d; + if (string.equals("")) { + return string; + } + if (string.equalsIgnoreCase("true")) { + return Boolean.TRUE; + } + if (string.equalsIgnoreCase("false")) { + return Boolean.FALSE; + } + if (string.equalsIgnoreCase("null")) { + return JSONObject.NULL; + } + + /* + * If it might be a number, try converting it. If a number cannot be + * produced, then the value will just be a string. + */ + + char b = string.charAt(0); + if ((b >= '0' && b <= '9') || b == '-') { + try { + if (string.indexOf('.') > -1 || string.indexOf('e') > -1 || string.indexOf('E') > -1) { + d = Double.valueOf(string); + if (!d.isInfinite() && !d.isNaN()) { + return d; + } + } else { + Long myLong = new Long(string); + if (string.equals(myLong.toString())) { + if (myLong == myLong.intValue()) { + return myLong.intValue(); + } else { + return myLong; + } + } + } + } catch (Exception ignore) { + } + } + return string; + } + + /** + * Throw an exception if the object is a NaN or infinite number. + * + * @param o The object to test. + * @throws JSONException If o is a non-finite number. + */ + public static void testValidity(Object o) throws JSONException { + if (o != null) { + if (o instanceof Double) { + if (((Double) o).isInfinite() || ((Double) o).isNaN()) { + throw new JSONException("JSON does not allow non-finite numbers."); + } + } else if (o instanceof Float) { + if (((Float) o).isInfinite() || ((Float) o).isNaN()) { + throw new JSONException("JSON does not allow non-finite numbers."); + } + } + } + } + + /** + * Produce a JSONArray containing the values of the members of this + * JSONObject. + * + * @param names A JSONArray containing a list of key strings. This determines + * the sequence of the values in the result. + * @return A JSONArray of values. + * @throws JSONException If any of the values are non-finite numbers. + */ + public JSONArray toJSONArray(JSONArray names) throws JSONException { + if (names == null || names.length() == 0) { + return null; + } + JSONArray ja = new JSONArray(); + for (int i = 0; i < names.length(); i += 1) { + ja.put(this.opt(names.getString(i))); + } + return ja; + } + + /** + * Make a JSON text of this JSONObject. For compactness, no whitespace is + * added. If this would not result in a syntactically correct JSON text, + * then null will be returned instead. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @return a printable, displayable, portable, transmittable representation + * of the object, beginning with { (left + * brace) and ending with } (right + * brace). + */ + public String toString() { + try { + return this.toString(0); + } catch (Exception e) { + return null; + } + } + + /** + * Make a prettyprinted JSON text of this JSONObject. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @param indentFactor The number of spaces to add to each level of indentation. + * @return a printable, displayable, portable, transmittable representation + * of the object, beginning with { (left + * brace) and ending with } (right + * brace). + * @throws JSONException If the object contains an invalid number. + */ + public String toString(int indentFactor) throws JSONException { + StringWriter w = new StringWriter(); + synchronized (w.getBuffer()) { + return this.write(w, indentFactor, 0).toString(); + } + } + + /** + * Make a JSON text of an Object value. If the object has an + * value.toJSONString() method, then that method will be used to produce the + * JSON text. The method is required to produce a strictly conforming text. + * If the object does not contain a toJSONString method (which is the most + * common case), then a text will be produced by other means. If the value + * is an array or Collection, then a JSONArray will be made from it and its + * toJSONString method will be called. If the value is a MAP, then a + * JSONObject will be made from it and its toJSONString method will be + * called. Otherwise, the value's toString method will be called, and the + * result will be quoted. + * + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @param value The value to be serialized. + * @return a printable, displayable, transmittable representation of the + * object, beginning with { (left + * brace) and ending with } (right + * brace). + * @throws JSONException If the value is or contains an invalid number. + */ + public static String valueToString(Object value) throws JSONException { + if (value == null || value.equals(null)) { + return "null"; + } + if (value instanceof JSONString) { + Object object; + try { + object = ((JSONString) value).toJSONString(); + } catch (Exception e) { + throw new JSONException(e); + } + if (object instanceof String) { + return (String) object; + } + throw new JSONException("Bad value from toJSONString: " + object); + } + if (value instanceof Number) { + return numberToString((Number) value); + } + if (value instanceof Boolean || value instanceof JSONObject || value instanceof JSONArray) { + return value.toString(); + } + if (value instanceof Map) { + @SuppressWarnings("unchecked") + Map map = (Map) value; + return new JSONObject(map).toString(); + } + if (value instanceof Collection) { + @SuppressWarnings("unchecked") + Collection coll = (Collection) value; + return new JSONArray(coll).toString(); + } + if (value.getClass().isArray()) { + return new JSONArray(value).toString(); + } + return quote(value.toString()); + } + + /** + * Wrap an object, if necessary. If the object is null, return the NULL + * object. If it is an array or collection, wrap it in a JSONArray. If it is + * a map, wrap it in a JSONObject. If it is a standard property (Double, + * String, et al) then it is already wrapped. Otherwise, if it comes from + * one of the java packages, turn it into a string. And if it doesn't, try + * to wrap it in a JSONObject. If the wrapping fails, then null is returned. + * + * @param object The object to wrap + * @return The wrapped value + */ + public static Object wrap(Object object) { + try { + if (object == null) { + return NULL; + } + if (object instanceof JSONObject || object instanceof JSONArray || NULL.equals(object) || object instanceof JSONString || object instanceof Byte || object instanceof Character || object instanceof Short || object instanceof Integer || object instanceof Long || object instanceof Boolean || object instanceof Float || object instanceof Double || object instanceof String || object instanceof BigInteger || object instanceof BigDecimal) { + return object; + } + + if (object instanceof Collection) { + @SuppressWarnings("unchecked") + Collection coll = (Collection) object; + return new JSONArray(coll); + } + if (object.getClass().isArray()) { + return new JSONArray(object); + } + if (object instanceof Map) { + @SuppressWarnings("unchecked") + Map map = (Map) object; + return new JSONObject(map); + } + Package objectPackage = object.getClass().getPackage(); + String objectPackageName = objectPackage != null ? objectPackage.getName() : ""; + if (objectPackageName.startsWith("java.") || objectPackageName.startsWith("javax.") || object.getClass().getClassLoader() == null) { + return object.toString(); + } + return new JSONObject(object); + } catch (Exception exception) { + return null; + } + } + + /** + * Write the contents of the JSONObject as JSON text to a writer. For + * compactness, no whitespace is added. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @return The writer. + * @throws JSONException + */ + public Writer write(Writer writer) throws JSONException { + return this.write(writer, 0, 0); + } + + static final Writer writeValue(Writer writer, Object value, int indentFactor, int indent) throws JSONException, IOException { + if (value == null || value.equals(null)) { + writer.write("null"); + } else if (value instanceof JSONObject) { + ((JSONObject) value).write(writer, indentFactor, indent); + } else if (value instanceof JSONArray) { + ((JSONArray) value).write(writer, indentFactor, indent); + } else if (value instanceof Map) { + @SuppressWarnings("unchecked") + Map map = (Map) value; + new JSONObject(map).write(writer, indentFactor, indent); + } else if (value instanceof Collection) { + @SuppressWarnings("unchecked") + Collection coll = (Collection) value; + new JSONArray(coll).write(writer, indentFactor, indent); + } else if (value.getClass().isArray()) { + new JSONArray(value).write(writer, indentFactor, indent); + } else if (value instanceof Number) { + writer.write(numberToString((Number) value)); + } else if (value instanceof Boolean) { + writer.write(value.toString()); + } else if (value instanceof JSONString) { + Object o; + try { + o = ((JSONString) value).toJSONString(); + } catch (Exception e) { + throw new JSONException(e); + } + writer.write(o != null ? o.toString() : quote(value.toString())); + } else { + quote(value.toString(), writer); + } + return writer; + } + + static final void indent(Writer writer, int indent) throws IOException { + for (int i = 0; i < indent; i += 1) { + writer.write(' '); + } + } + + /** + * Write the contents of the JSONObject as JSON text to a writer. For + * compactness, no whitespace is added. + *

+ * Warning: This method assumes that the data structure is acyclical. + * + * @return The writer. + * @throws JSONException + */ + Writer write(Writer writer, int indentFactor, int indent) throws JSONException { + try { + boolean commanate = false; + final int length = this.length(); + Iterator keys = this.keys(); + writer.write('{'); + + if (length == 1) { + Object key = keys.next(); + writer.write(quote(key.toString())); + writer.write(':'); + if (indentFactor > 0) { + writer.write(' '); + } + writeValue(writer, this.map.get(key), indentFactor, indent); + } else if (length != 0) { + final int newindent = indent + indentFactor; + while (keys.hasNext()) { + Object key = keys.next(); + if (commanate) { + writer.write(','); + } + if (indentFactor > 0) { + writer.write('\n'); + } + indent(writer, newindent); + writer.write(quote(key.toString())); + writer.write(':'); + if (indentFactor > 0) { + writer.write(' '); + } + writeValue(writer, this.map.get(key), indentFactor, newindent); + commanate = true; + } + if (indentFactor > 0) { + writer.write('\n'); + } + indent(writer, indent); + } + writer.write('}'); + return writer; + } catch (IOException exception) { + throw new JSONException(exception); + } + } } diff --git a/src/main/java/com/volmit/iris/util/JSONString.java b/src/main/java/com/volmit/iris/util/JSONString.java index 7fdaaf662..7017e441c 100644 --- a/src/main/java/com/volmit/iris/util/JSONString.java +++ b/src/main/java/com/volmit/iris/util/JSONString.java @@ -9,13 +9,12 @@ package com.volmit.iris.util; * toJSONString method will be used instead of the default behavior * of using the Object's toString() method and quoting the result. */ -public interface JSONString -{ - /** - * The toJSONString method allows a class to produce its own - * JSON serialization. - * - * @return A strictly syntactically correct JSON text. - */ - public String toJSONString(); +public interface JSONString { + /** + * The toJSONString method allows a class to produce its own + * JSON serialization. + * + * @return A strictly syntactically correct JSON text. + */ + String toJSONString(); } diff --git a/src/main/java/com/volmit/iris/util/JSONStringer.java b/src/main/java/com/volmit/iris/util/JSONStringer.java index 4e19d6f5f..7a6ef3556 100644 --- a/src/main/java/com/volmit/iris/util/JSONStringer.java +++ b/src/main/java/com/volmit/iris/util/JSONStringer.java @@ -40,13 +40,13 @@ import java.io.StringWriter; * endObject methods which make and bound object values. All of * these methods return the JSONWriter instance, permitting cascade style. For * example, - * + * *

  * myString = new JSONStringer().object().key("JSON").value("Hello, World!").endObject().toString();
  * 
- * + *

* which produces the string - * + * *

  * {"JSON":"Hello, World!"}
  * 
@@ -56,31 +56,28 @@ import java.io.StringWriter; * you. Objects and arrays can be nested up to 20 levels deep. *

* This can sometimes be easier than using a JSONObject to build a string. - * + * * @author JSON.org * @version 2008-09-18 */ -public class JSONStringer extends JSONWriter -{ - /** - * Make a fresh JSONStringer. It can be used to build one JSON text. - */ - public JSONStringer() - { - super(new StringWriter()); - } - - /** - * Return the JSON text. This method is used to obtain the product of the - * JSONStringer instance. It will return null if there was a - * problem in the construction of the JSON text (such as the calls to - * array were not properly balanced with calls to - * endArray). - * - * @return The JSON text. - */ - public String toString() - { - return this.mode == 'd' ? this.writer.toString() : null; - } +public class JSONStringer extends JSONWriter { + /** + * Make a fresh JSONStringer. It can be used to build one JSON text. + */ + public JSONStringer() { + super(new StringWriter()); + } + + /** + * Return the JSON text. This method is used to obtain the product of the + * JSONStringer instance. It will return null if there was a + * problem in the construction of the JSON text (such as the calls to + * array were not properly balanced with calls to + * endArray). + * + * @return The JSON text. + */ + public String toString() { + return this.mode == 'd' ? this.writer.toString() : null; + } } diff --git a/src/main/java/com/volmit/iris/util/JSONTokener.java b/src/main/java/com/volmit/iris/util/JSONTokener.java index 4b09e6830..01f3e4482 100644 --- a/src/main/java/com/volmit/iris/util/JSONTokener.java +++ b/src/main/java/com/volmit/iris/util/JSONTokener.java @@ -1,12 +1,7 @@ package com.volmit.iris.util; -import java.io.BufferedReader; -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.io.Reader; -import java.io.StringReader; +import java.io.*; /* Copyright (c) 2002 JSON.org @@ -36,469 +31,398 @@ SOFTWARE. * A JSONTokener takes a source string and extracts characters and tokens from * it. It is used by the JSONObject and JSONArray constructors to parse JSON * source strings. - * + * * @author JSON.org * @version 2014-05-03 */ -public class JSONTokener -{ - - private long character; - private boolean eof; - private long index; - private long line; - private char previous; - private Reader reader; - private boolean usePrevious; - - /** - * Construct a JSONTokener from a Reader. - * - * @param reader - * A reader. - */ - public JSONTokener(Reader reader) - { - this.reader = reader.markSupported() ? reader : new BufferedReader(reader); - this.eof = false; - this.usePrevious = false; - this.previous = 0; - this.index = 0; - this.character = 1; - this.line = 1; - } - - /** - * Construct a JSONTokener from an InputStream. - * - * @param inputStream - * The source. - */ - public JSONTokener(InputStream inputStream) throws JSONException - { - this(new InputStreamReader(inputStream)); - } - - /** - * Construct a JSONTokener from a string. - * - * @param s - * A source string. - */ - public JSONTokener(String s) - { - this(new StringReader(s)); - } - - /** - * Back up one character. This provides a sort of lookahead capability, so - * that you can test for a digit or letter before attempting to parse the - * next number or identifier. - */ - public void back() throws JSONException - { - if(this.usePrevious || this.index <= 0) - { - throw new JSONException("Stepping back two steps is not supported"); - } - this.index -= 1; - this.character -= 1; - this.usePrevious = true; - this.eof = false; - } - - /** - * Get the hex value of a character (base16). - * - * @param c - * A character between '0' and '9' or between 'A' and 'F' or - * between 'a' and 'f'. - * @return An int between 0 and 15, or -1 if c was not a hex digit. - */ - public static int dehexchar(char c) - { - if(c >= '0' && c <= '9') - { - return c - '0'; - } - if(c >= 'A' && c <= 'F') - { - return c - ('A' - 10); - } - if(c >= 'a' && c <= 'f') - { - return c - ('a' - 10); - } - return -1; - } - - public boolean end() - { - return this.eof && !this.usePrevious; - } - - /** - * Determine if the source string still contains characters that next() can - * consume. - * - * @return true if not yet at the end of the source. - */ - public boolean more() throws JSONException - { - this.next(); - if(this.end()) - { - return false; - } - this.back(); - return true; - } - - /** - * Get the next character in the source string. - * - * @return The next character, or 0 if past the end of the source string. - */ - public char next() throws JSONException - { - int c; - if(this.usePrevious) - { - this.usePrevious = false; - c = this.previous; - } else - { - try - { - c = this.reader.read(); - } catch(IOException exception) - { - throw new JSONException(exception); - } - - if(c <= 0) - { // End of stream - this.eof = true; - c = 0; - } - } - this.index += 1; - if(this.previous == '\r') - { - this.line += 1; - this.character = c == '\n' ? 0 : 1; - } else if(c == '\n') - { - this.line += 1; - this.character = 0; - } else - { - this.character += 1; - } - this.previous = (char) c; - return this.previous; - } - - /** - * Consume the next character, and check that it matches a specified - * character. - * - * @param c - * The character to match. - * @return The character. - * @throws JSONException - * if the character does not match. - */ - public char next(char c) throws JSONException - { - char n = this.next(); - if(n != c) - { - throw this.syntaxError("Expected '" + c + "' and instead saw '" + n + "'"); - } - return n; - } - - /** - * Get the next n characters. - * - * @param n - * The number of characters to take. - * @return A string of n characters. - * @throws JSONException - * Substring bounds error if there are not n characters - * remaining in the source string. - */ - public String next(int n) throws JSONException - { - if(n == 0) - { - return ""; - } - - char[] chars = new char[n]; - int pos = 0; - - while(pos < n) - { - chars[pos] = this.next(); - if(this.end()) - { - throw this.syntaxError("Substring bounds error"); - } - pos += 1; - } - return new String(chars); - } - - /** - * Get the next char in the string, skipping whitespace. - * - * @throws JSONException - * @return A character, or 0 if there are no more characters. - */ - public char nextClean() throws JSONException - { - for(;;) - { - char c = this.next(); - if(c == 0 || c > ' ') - { - return c; - } - } - } - - /** - * Return the characters up to the next close quote character. Backslash - * processing is done. The formal JSON format does not allow strings in - * single quotes, but an implementation is allowed to accept them. - * - * @param quote - * The quoting character, either "  - * (double quote) or '  - * (single quote). - * @return A String. - * @throws JSONException - * Unterminated string. - */ - public String nextString(char quote) throws JSONException - { - char c; - StringBuilder sb = new StringBuilder(); - for(;;) - { - c = this.next(); - switch(c) - { - case 0: - case '\n': - case '\r': - throw this.syntaxError("Unterminated string"); - case '\\': - c = this.next(); - switch(c) - { - case 'b': - sb.append('\b'); - break; - case 't': - sb.append('\t'); - break; - case 'n': - sb.append('\n'); - break; - case 'f': - sb.append('\f'); - break; - case 'r': - sb.append('\r'); - break; - case 'u': - sb.append((char) Integer.parseInt(this.next(4), 16)); - break; - case '"': - case '\'': - case '\\': - case '/': - sb.append(c); - break; - default: - throw this.syntaxError("Illegal escape."); - } - break; - default: - if(c == quote) - { - return sb.toString(); - } - sb.append(c); - } - } - } - - /** - * Get the text up but not including the specified character or the end of - * line, whichever comes first. - * - * @param delimiter - * A delimiter character. - * @return A string. - */ - public String nextTo(char delimiter) throws JSONException - { - StringBuilder sb = new StringBuilder(); - for(;;) - { - char c = this.next(); - if(c == delimiter || c == 0 || c == '\n' || c == '\r') - { - if(c != 0) - { - this.back(); - } - return sb.toString().trim(); - } - sb.append(c); - } - } - - /** - * Get the text up but not including one of the specified delimiter - * characters or the end of line, whichever comes first. - * - * @param delimiters - * A set of delimiter characters. - * @return A string, trimmed. - */ - public String nextTo(String delimiters) throws JSONException - { - char c; - StringBuilder sb = new StringBuilder(); - for(;;) - { - c = this.next(); - if(delimiters.indexOf(c) >= 0 || c == 0 || c == '\n' || c == '\r') - { - if(c != 0) - { - this.back(); - } - return sb.toString().trim(); - } - sb.append(c); - } - } - - /** - * Get the next value. The value can be a Boolean, Double, Integer, - * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. - * - * @throws JSONException - * If syntax error. - * - * @return An object. - */ - public Object nextValue() throws JSONException - { - char c = this.nextClean(); - String string; - - switch(c) - { - case '"': - case '\'': - return this.nextString(c); - case '{': - this.back(); - return new JSONObject(this); - case '[': - this.back(); - return new JSONArray(this); - } - - /* - * Handle unquoted text. This could be the values true, false, or null, - * or it can be a number. An implementation (such as this one) is - * allowed to also accept non-standard forms. - * - * Accumulate characters until we reach the end of the text or a - * formatting character. - */ - - StringBuilder sb = new StringBuilder(); - while(c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) - { - sb.append(c); - c = this.next(); - } - this.back(); - - string = sb.toString().trim(); - if("".equals(string)) - { - throw this.syntaxError("Missing value"); - } - return JSONObject.stringToValue(string); - } - - /** - * Skip characters until the next character is the requested character. If - * the requested character is not found, no characters are skipped. - * - * @param to - * A character to skip to. - * @return The requested character, or zero if the requested character is - * not found. - */ - public char skipTo(char to) throws JSONException - { - char c; - try - { - long startIndex = this.index; - long startCharacter = this.character; - long startLine = this.line; - this.reader.mark(1000000); - do - { - c = this.next(); - if(c == 0) - { - this.reader.reset(); - this.index = startIndex; - this.character = startCharacter; - this.line = startLine; - return c; - } - } while(c != to); - } catch(IOException exception) - { - throw new JSONException(exception); - } - this.back(); - return c; - } - - /** - * Make a JSONException to signal a syntax error. - * - * @param message - * The error message. - * @return A JSONException object, suitable for throwing - */ - public JSONException syntaxError(String message) - { - return new JSONException(message + this.toString()); - } - - /** - * Make a printable string of this JSONTokener. - * - * @return " at {index} [character {character} line {line}]" - */ - public String toString() - { - return " at " + this.index + " [character " + this.character + " line " + this.line + "]"; - } +public class JSONTokener { + + private long character; + private boolean eof; + private long index; + private long line; + private char previous; + private final Reader reader; + private boolean usePrevious; + + /** + * Construct a JSONTokener from a Reader. + * + * @param reader A reader. + */ + public JSONTokener(Reader reader) { + this.reader = reader.markSupported() ? reader : new BufferedReader(reader); + this.eof = false; + this.usePrevious = false; + this.previous = 0; + this.index = 0; + this.character = 1; + this.line = 1; + } + + /** + * Construct a JSONTokener from an InputStream. + * + * @param inputStream The source. + */ + public JSONTokener(InputStream inputStream) throws JSONException { + this(new InputStreamReader(inputStream)); + } + + /** + * Construct a JSONTokener from a string. + * + * @param s A source string. + */ + public JSONTokener(String s) { + this(new StringReader(s)); + } + + /** + * Back up one character. This provides a sort of lookahead capability, so + * that you can test for a digit or letter before attempting to parse the + * next number or identifier. + */ + public void back() throws JSONException { + if (this.usePrevious || this.index <= 0) { + throw new JSONException("Stepping back two steps is not supported"); + } + this.index -= 1; + this.character -= 1; + this.usePrevious = true; + this.eof = false; + } + + /** + * Get the hex value of a character (base16). + * + * @param c A character between '0' and '9' or between 'A' and 'F' or + * between 'a' and 'f'. + * @return An int between 0 and 15, or -1 if c was not a hex digit. + */ + public static int dehexchar(char c) { + if (c >= '0' && c <= '9') { + return c - '0'; + } + if (c >= 'A' && c <= 'F') { + return c - ('A' - 10); + } + if (c >= 'a' && c <= 'f') { + return c - ('a' - 10); + } + return -1; + } + + public boolean end() { + return this.eof && !this.usePrevious; + } + + /** + * Determine if the source string still contains characters that next() can + * consume. + * + * @return true if not yet at the end of the source. + */ + public boolean more() throws JSONException { + this.next(); + if (this.end()) { + return false; + } + this.back(); + return true; + } + + /** + * Get the next character in the source string. + * + * @return The next character, or 0 if past the end of the source string. + */ + public char next() throws JSONException { + int c; + if (this.usePrevious) { + this.usePrevious = false; + c = this.previous; + } else { + try { + c = this.reader.read(); + } catch (IOException exception) { + throw new JSONException(exception); + } + + if (c <= 0) { // End of stream + this.eof = true; + c = 0; + } + } + this.index += 1; + if (this.previous == '\r') { + this.line += 1; + this.character = c == '\n' ? 0 : 1; + } else if (c == '\n') { + this.line += 1; + this.character = 0; + } else { + this.character += 1; + } + this.previous = (char) c; + return this.previous; + } + + /** + * Consume the next character, and check that it matches a specified + * character. + * + * @param c The character to match. + * @return The character. + * @throws JSONException if the character does not match. + */ + public char next(char c) throws JSONException { + char n = this.next(); + if (n != c) { + throw this.syntaxError("Expected '" + c + "' and instead saw '" + n + "'"); + } + return n; + } + + /** + * Get the next n characters. + * + * @param n The number of characters to take. + * @return A string of n characters. + * @throws JSONException Substring bounds error if there are not n characters + * remaining in the source string. + */ + public String next(int n) throws JSONException { + if (n == 0) { + return ""; + } + + char[] chars = new char[n]; + int pos = 0; + + while (pos < n) { + chars[pos] = this.next(); + if (this.end()) { + throw this.syntaxError("Substring bounds error"); + } + pos += 1; + } + return new String(chars); + } + + /** + * Get the next char in the string, skipping whitespace. + * + * @return A character, or 0 if there are no more characters. + * @throws JSONException + */ + public char nextClean() throws JSONException { + for (; ; ) { + char c = this.next(); + if (c == 0 || c > ' ') { + return c; + } + } + } + + /** + * Return the characters up to the next close quote character. Backslash + * processing is done. The formal JSON format does not allow strings in + * single quotes, but an implementation is allowed to accept them. + * + * @param quote The quoting character, either "  + * (double quote) or '  + * (single quote). + * @return A String. + * @throws JSONException Unterminated string. + */ + public String nextString(char quote) throws JSONException { + char c; + StringBuilder sb = new StringBuilder(); + for (; ; ) { + c = this.next(); + switch (c) { + case 0: + case '\n': + case '\r': + throw this.syntaxError("Unterminated string"); + case '\\': + c = this.next(); + switch (c) { + case 'b': + sb.append('\b'); + break; + case 't': + sb.append('\t'); + break; + case 'n': + sb.append('\n'); + break; + case 'f': + sb.append('\f'); + break; + case 'r': + sb.append('\r'); + break; + case 'u': + sb.append((char) Integer.parseInt(this.next(4), 16)); + break; + case '"': + case '\'': + case '\\': + case '/': + sb.append(c); + break; + default: + throw this.syntaxError("Illegal escape."); + } + break; + default: + if (c == quote) { + return sb.toString(); + } + sb.append(c); + } + } + } + + /** + * Get the text up but not including the specified character or the end of + * line, whichever comes first. + * + * @param delimiter A delimiter character. + * @return A string. + */ + public String nextTo(char delimiter) throws JSONException { + StringBuilder sb = new StringBuilder(); + for (; ; ) { + char c = this.next(); + if (c == delimiter || c == 0 || c == '\n' || c == '\r') { + if (c != 0) { + this.back(); + } + return sb.toString().trim(); + } + sb.append(c); + } + } + + /** + * Get the text up but not including one of the specified delimiter + * characters or the end of line, whichever comes first. + * + * @param delimiters A set of delimiter characters. + * @return A string, trimmed. + */ + public String nextTo(String delimiters) throws JSONException { + char c; + StringBuilder sb = new StringBuilder(); + for (; ; ) { + c = this.next(); + if (delimiters.indexOf(c) >= 0 || c == 0 || c == '\n' || c == '\r') { + if (c != 0) { + this.back(); + } + return sb.toString().trim(); + } + sb.append(c); + } + } + + /** + * Get the next value. The value can be a Boolean, Double, Integer, + * JSONArray, JSONObject, Long, or String, or the JSONObject.NULL object. + * + * @return An object. + * @throws JSONException If syntax error. + */ + public Object nextValue() throws JSONException { + char c = this.nextClean(); + String string; + + switch (c) { + case '"': + case '\'': + return this.nextString(c); + case '{': + this.back(); + return new JSONObject(this); + case '[': + this.back(); + return new JSONArray(this); + } + + /* + * Handle unquoted text. This could be the values true, false, or null, + * or it can be a number. An implementation (such as this one) is + * allowed to also accept non-standard forms. + * + * Accumulate characters until we reach the end of the text or a + * formatting character. + */ + + StringBuilder sb = new StringBuilder(); + while (c >= ' ' && ",:]}/\\\"[{;=#".indexOf(c) < 0) { + sb.append(c); + c = this.next(); + } + this.back(); + + string = sb.toString().trim(); + if ("".equals(string)) { + throw this.syntaxError("Missing value"); + } + return JSONObject.stringToValue(string); + } + + /** + * Skip characters until the next character is the requested character. If + * the requested character is not found, no characters are skipped. + * + * @param to A character to skip to. + * @return The requested character, or zero if the requested character is + * not found. + */ + public char skipTo(char to) throws JSONException { + char c; + try { + long startIndex = this.index; + long startCharacter = this.character; + long startLine = this.line; + this.reader.mark(1000000); + do { + c = this.next(); + if (c == 0) { + this.reader.reset(); + this.index = startIndex; + this.character = startCharacter; + this.line = startLine; + return c; + } + } while (c != to); + } catch (IOException exception) { + throw new JSONException(exception); + } + this.back(); + return c; + } + + /** + * Make a JSONException to signal a syntax error. + * + * @param message The error message. + * @return A JSONException object, suitable for throwing + */ + public JSONException syntaxError(String message) { + return new JSONException(message + this); + } + + /** + * Make a printable string of this JSONTokener. + * + * @return " at {index} [character {character} line {line}]" + */ + public String toString() { + return " at " + this.index + " [character " + this.character + " line " + this.line + "]"; + } } diff --git a/src/main/java/com/volmit/iris/util/JSONWriter.java b/src/main/java/com/volmit/iris/util/JSONWriter.java index 2b662635b..5b372dd34 100644 --- a/src/main/java/com/volmit/iris/util/JSONWriter.java +++ b/src/main/java/com/volmit/iris/util/JSONWriter.java @@ -41,13 +41,13 @@ SOFTWARE. * endObject methods which make and bound object values. All of * these methods return the JSONWriter instance, permitting a cascade style. For * example, - * + * *

  * new JSONWriter(myWriter).object().key("JSON").value("Hello, World!").endObject();
  * 
- * + *

* which writes - * + * *

  * {"JSON":"Hello, World!"}
  * 
@@ -57,332 +57,276 @@ SOFTWARE. * you. Objects and arrays can be nested up to 20 levels deep. *

* This can sometimes be easier than using a JSONObject to build a string. - * + * * @author JSON.org * @version 2011-11-24 */ -public class JSONWriter -{ - private static final int maxdepth = 200; - - /** - * The comma flag determines if a comma should be output before the next - * value. - */ - private boolean comma; - - /** - * The current mode. Values: 'a' (array), 'd' (done), 'i' (initial), 'k' - * (key), 'o' (object). - */ - protected char mode; - - /** - * The object/array stack. - */ - private final JSONObject stack[]; - - /** - * The stack top index. A value of 0 indicates that the stack is empty. - */ - private int top; - - /** - * The writer that will receive the output. - */ - protected Writer writer; - - /** - * Make a fresh JSONWriter. It can be used to build one JSON text. - */ - public JSONWriter(Writer w) - { - this.comma = false; - this.mode = 'i'; - this.stack = new JSONObject[maxdepth]; - this.top = 0; - this.writer = w; - } - - /** - * Append a value. - * - * @param string - * A string value. - * @return this - * @throws JSONException - * If the value is out of sequence. - */ - private JSONWriter append(String string) throws JSONException - { - if(string == null) - { - throw new JSONException("Null pointer"); - } - if(this.mode == 'o' || this.mode == 'a') - { - try - { - if(this.comma && this.mode == 'a') - { - this.writer.write(','); - } - this.writer.write(string); - } catch(IOException e) - { - throw new JSONException(e); - } - if(this.mode == 'o') - { - this.mode = 'k'; - } - this.comma = true; - return this; - } - throw new JSONException("Value out of sequence."); - } - - /** - * Begin appending a new array. All values until the balancing - * endArray will be appended to this array. The - * endArray method must be called to mark the array's end. - * - * @return this - * @throws JSONException - * If the nesting is too deep, or if the object is started in - * the wrong place (for example as a key or after the end of the - * outermost array or object). - */ - public JSONWriter array() throws JSONException - { - if(this.mode == 'i' || this.mode == 'o' || this.mode == 'a') - { - this.push(null); - this.append("["); - this.comma = false; - return this; - } - throw new JSONException("Misplaced array."); - } - - /** - * End something. - * - * @param mode - * Mode - * @param c - * Closing character - * @return this - * @throws JSONException - * If unbalanced. - */ - private JSONWriter end(char mode, char c) throws JSONException - { - if(this.mode != mode) - { - throw new JSONException(mode == 'a' ? "Misplaced endArray." : "Misplaced endObject."); - } - this.pop(mode); - try - { - this.writer.write(c); - } catch(IOException e) - { - throw new JSONException(e); - } - this.comma = true; - return this; - } - - /** - * End an array. This method most be called to balance calls to - * array. - * - * @return this - * @throws JSONException - * If incorrectly nested. - */ - public JSONWriter endArray() throws JSONException - { - return this.end('a', ']'); - } - - /** - * End an object. This method most be called to balance calls to - * object. - * - * @return this - * @throws JSONException - * If incorrectly nested. - */ - public JSONWriter endObject() throws JSONException - { - return this.end('k', '}'); - } - - /** - * Append a key. The key will be associated with the next value. In an - * object, every value must be preceded by a key. - * - * @param string - * A key string. - * @return this - * @throws JSONException - * If the key is out of place. For example, keys do not belong - * in arrays or if the key is null. - */ - public JSONWriter key(String string) throws JSONException - { - if(string == null) - { - throw new JSONException("Null key."); - } - if(this.mode == 'k') - { - try - { - this.stack[this.top - 1].putOnce(string, Boolean.TRUE); - if(this.comma) - { - this.writer.write(','); - } - this.writer.write(JSONObject.quote(string)); - this.writer.write(':'); - this.comma = false; - this.mode = 'o'; - return this; - } catch(IOException e) - { - throw new JSONException(e); - } - } - throw new JSONException("Misplaced key."); - } - - /** - * Begin appending a new object. All keys and values until the balancing - * endObject will be appended to this object. The - * endObject method must be called to mark the object's end. - * - * @return this - * @throws JSONException - * If the nesting is too deep, or if the object is started in - * the wrong place (for example as a key or after the end of the - * outermost array or object). - */ - public JSONWriter object() throws JSONException - { - if(this.mode == 'i') - { - this.mode = 'o'; - } - if(this.mode == 'o' || this.mode == 'a') - { - this.append("{"); - this.push(new JSONObject()); - this.comma = false; - return this; - } - throw new JSONException("Misplaced object."); - - } - - /** - * Pop an array or object scope. - * - * @param c - * The scope to close. - * @throws JSONException - * If nesting is wrong. - */ - private void pop(char c) throws JSONException - { - if(this.top <= 0) - { - throw new JSONException("Nesting error."); - } - char m = this.stack[this.top - 1] == null ? 'a' : 'k'; - if(m != c) - { - throw new JSONException("Nesting error."); - } - this.top -= 1; - this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k'; - } - - /** - * Push an array or object scope. - * - * @param jo - * The scope to open. - * @throws JSONException - * If nesting is too deep. - */ - private void push(JSONObject jo) throws JSONException - { - if(this.top >= maxdepth) - { - throw new JSONException("Nesting too deep."); - } - this.stack[this.top] = jo; - this.mode = jo == null ? 'a' : 'k'; - this.top += 1; - } - - /** - * Append either the value true or the value false - * . - * - * @param b - * A boolean. - * @return this - * @throws JSONException - */ - public JSONWriter value(boolean b) throws JSONException - { - return this.append(b ? "true" : "false"); - } - - /** - * Append a double value. - * - * @param d - * A double. - * @return this - * @throws JSONException - * If the number is not finite. - */ - public JSONWriter value(double d) throws JSONException - { - return this.value(new Double(d)); - } - - /** - * Append a long value. - * - * @param l - * A long. - * @return this - * @throws JSONException - */ - public JSONWriter value(long l) throws JSONException - { - return this.append(Long.toString(l)); - } - - /** - * Append an object value. - * - * @param object - * The object to append. It can be null, or a Boolean, Number, - * String, JSONObject, or JSONArray, or an object that implements - * JSONString. - * @return this - * @throws JSONException - * If the value is out of sequence. - */ - public JSONWriter value(Object object) throws JSONException - { - return this.append(JSONObject.valueToString(object)); - } +public class JSONWriter { + private static final int maxdepth = 200; + + /** + * The comma flag determines if a comma should be output before the next + * value. + */ + private boolean comma; + + /** + * The current mode. Values: 'a' (array), 'd' (done), 'i' (initial), 'k' + * (key), 'o' (object). + */ + protected char mode; + + /** + * The object/array stack. + */ + private final JSONObject[] stack; + + /** + * The stack top index. A value of 0 indicates that the stack is empty. + */ + private int top; + + /** + * The writer that will receive the output. + */ + protected Writer writer; + + /** + * Make a fresh JSONWriter. It can be used to build one JSON text. + */ + public JSONWriter(Writer w) { + this.comma = false; + this.mode = 'i'; + this.stack = new JSONObject[maxdepth]; + this.top = 0; + this.writer = w; + } + + /** + * Append a value. + * + * @param string A string value. + * @return this + * @throws JSONException If the value is out of sequence. + */ + private JSONWriter append(String string) throws JSONException { + if (string == null) { + throw new JSONException("Null pointer"); + } + if (this.mode == 'o' || this.mode == 'a') { + try { + if (this.comma && this.mode == 'a') { + this.writer.write(','); + } + this.writer.write(string); + } catch (IOException e) { + throw new JSONException(e); + } + if (this.mode == 'o') { + this.mode = 'k'; + } + this.comma = true; + return this; + } + throw new JSONException("Value out of sequence."); + } + + /** + * Begin appending a new array. All values until the balancing + * endArray will be appended to this array. The + * endArray method must be called to mark the array's end. + * + * @return this + * @throws JSONException If the nesting is too deep, or if the object is started in + * the wrong place (for example as a key or after the end of the + * outermost array or object). + */ + public JSONWriter array() throws JSONException { + if (this.mode == 'i' || this.mode == 'o' || this.mode == 'a') { + this.push(null); + this.append("["); + this.comma = false; + return this; + } + throw new JSONException("Misplaced array."); + } + + /** + * End something. + * + * @param mode Mode + * @param c Closing character + * @return this + * @throws JSONException If unbalanced. + */ + private JSONWriter end(char mode, char c) throws JSONException { + if (this.mode != mode) { + throw new JSONException(mode == 'a' ? "Misplaced endArray." : "Misplaced endObject."); + } + this.pop(mode); + try { + this.writer.write(c); + } catch (IOException e) { + throw new JSONException(e); + } + this.comma = true; + return this; + } + + /** + * End an array. This method most be called to balance calls to + * array. + * + * @return this + * @throws JSONException If incorrectly nested. + */ + public JSONWriter endArray() throws JSONException { + return this.end('a', ']'); + } + + /** + * End an object. This method most be called to balance calls to + * object. + * + * @return this + * @throws JSONException If incorrectly nested. + */ + public JSONWriter endObject() throws JSONException { + return this.end('k', '}'); + } + + /** + * Append a key. The key will be associated with the next value. In an + * object, every value must be preceded by a key. + * + * @param string A key string. + * @return this + * @throws JSONException If the key is out of place. For example, keys do not belong + * in arrays or if the key is null. + */ + public JSONWriter key(String string) throws JSONException { + if (string == null) { + throw new JSONException("Null key."); + } + if (this.mode == 'k') { + try { + this.stack[this.top - 1].putOnce(string, Boolean.TRUE); + if (this.comma) { + this.writer.write(','); + } + this.writer.write(JSONObject.quote(string)); + this.writer.write(':'); + this.comma = false; + this.mode = 'o'; + return this; + } catch (IOException e) { + throw new JSONException(e); + } + } + throw new JSONException("Misplaced key."); + } + + /** + * Begin appending a new object. All keys and values until the balancing + * endObject will be appended to this object. The + * endObject method must be called to mark the object's end. + * + * @return this + * @throws JSONException If the nesting is too deep, or if the object is started in + * the wrong place (for example as a key or after the end of the + * outermost array or object). + */ + public JSONWriter object() throws JSONException { + if (this.mode == 'i') { + this.mode = 'o'; + } + if (this.mode == 'o' || this.mode == 'a') { + this.append("{"); + this.push(new JSONObject()); + this.comma = false; + return this; + } + throw new JSONException("Misplaced object."); + + } + + /** + * Pop an array or object scope. + * + * @param c The scope to close. + * @throws JSONException If nesting is wrong. + */ + private void pop(char c) throws JSONException { + if (this.top <= 0) { + throw new JSONException("Nesting error."); + } + char m = this.stack[this.top - 1] == null ? 'a' : 'k'; + if (m != c) { + throw new JSONException("Nesting error."); + } + this.top -= 1; + this.mode = this.top == 0 ? 'd' : this.stack[this.top - 1] == null ? 'a' : 'k'; + } + + /** + * Push an array or object scope. + * + * @param jo The scope to open. + * @throws JSONException If nesting is too deep. + */ + private void push(JSONObject jo) throws JSONException { + if (this.top >= maxdepth) { + throw new JSONException("Nesting too deep."); + } + this.stack[this.top] = jo; + this.mode = jo == null ? 'a' : 'k'; + this.top += 1; + } + + /** + * Append either the value true or the value false + * . + * + * @param b A boolean. + * @return this + * @throws JSONException + */ + public JSONWriter value(boolean b) throws JSONException { + return this.append(b ? "true" : "false"); + } + + /** + * Append a double value. + * + * @param d A double. + * @return this + * @throws JSONException If the number is not finite. + */ + public JSONWriter value(double d) throws JSONException { + return this.value(new Double(d)); + } + + /** + * Append a long value. + * + * @param l A long. + * @return this + * @throws JSONException + */ + public JSONWriter value(long l) throws JSONException { + return this.append(Long.toString(l)); + } + + /** + * Append an object value. + * + * @param object The object to append. It can be null, or a Boolean, Number, + * String, JSONObject, or JSONArray, or an object that implements + * JSONString. + * @return this + * @throws JSONException If the value is out of sequence. + */ + public JSONWriter value(Object object) throws JSONException { + return this.append(JSONObject.valueToString(object)); + } } diff --git a/src/main/java/com/volmit/iris/util/JarScanner.java b/src/main/java/com/volmit/iris/util/JarScanner.java index cb53f513f..7579a3493 100644 --- a/src/main/java/com/volmit/iris/util/JarScanner.java +++ b/src/main/java/com/volmit/iris/util/JarScanner.java @@ -6,84 +6,69 @@ import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; -public class JarScanner -{ - private final KSet> classes; - private final File jar; - private final String superPackage; +public class JarScanner { + private final KSet> classes; + private final File jar; + private final String superPackage; - /** - * Create a scanner - * - * @param jar - * the path to the jar - */ - public JarScanner(File jar, String superPackage) - { - this.jar = jar; - this.classes = new KSet>(); - this.superPackage = superPackage; - } + /** + * Create a scanner + * + * @param jar the path to the jar + */ + public JarScanner(File jar, String superPackage) { + this.jar = jar; + this.classes = new KSet>(); + this.superPackage = superPackage; + } - /** - * Scan the jar - * - * @throws IOException - * bad things happen - */ - public void scan() throws IOException - { - classes.clear(); - FileInputStream fin = new FileInputStream(jar); - ZipInputStream zip = new ZipInputStream(fin); + /** + * Scan the jar + * + * @throws IOException bad things happen + */ + public void scan() throws IOException { + classes.clear(); + FileInputStream fin = new FileInputStream(jar); + ZipInputStream zip = new ZipInputStream(fin); - for(ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) - { - if(!entry.isDirectory() && entry.getName().endsWith(".class")) - { - if(entry.getName().contains("$")) - { - continue; - } + for (ZipEntry entry = zip.getNextEntry(); entry != null; entry = zip.getNextEntry()) { + if (!entry.isDirectory() && entry.getName().endsWith(".class")) { + if (entry.getName().contains("$")) { + continue; + } - String c = entry.getName().replaceAll("/", ".").replace(".class", ""); + String c = entry.getName().replaceAll("/", ".").replace(".class", ""); - if(c.startsWith(superPackage)) - { - try - { - Class clazz = Class.forName(c); - classes.add(clazz); - } + if (c.startsWith(superPackage)) { + try { + Class clazz = Class.forName(c); + classes.add(clazz); + } catch (ClassNotFoundException e) { + e.printStackTrace(); + } + } + } + } - catch(ClassNotFoundException e) - { - e.printStackTrace(); - } - } - } - } + zip.close(); + } - zip.close(); - } + /** + * Get the scanned clases + * + * @return a gset of classes + */ + public KSet> getClasses() { + return classes; + } - /** - * Get the scanned clases - * - * @return a gset of classes - */ - public KSet> getClasses() - { - return classes; - } - - /** - * Get the file object for the jar - * - * @return a file object representing the jar - */ - public File getJar() - { - return jar; - } + /** + * Get the file object for the jar + * + * @return a file object representing the jar + */ + public File getJar() { + return jar; + } } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/KList.java b/src/main/java/com/volmit/iris/util/KList.java index 612c1f946..b3e78b136 100644 --- a/src/main/java/com/volmit/iris/util/KList.java +++ b/src/main/java/com/volmit/iris/util/KList.java @@ -6,770 +6,649 @@ import java.util.*; import java.util.function.Function; import java.util.function.Predicate; -public class KList extends ArrayList implements List -{ - private static final long serialVersionUID = -2892550695744823337L; - - @SafeVarargs - public KList(T... ts) - { - super(); - add(ts); - } - - public KList() - { - super(); - } - - public KList(int cap) - { - super(cap); - } - - public KList(Collection values) - { - super(); - add(values); - } - - public KList(Enumeration e) - { - super(); - add(e); - } - - public int indexOfAddIfNeeded(T v) - { - addIfMissing(v); - return indexOf(v); - } - - /** - * Remove the last element - */ - public KList removeLast() - { - remove(last()); - - return this; - } - - public void addMultiple(T t, int c) - { - for(int i = 0; i < c; i++) - { - add(t); - } - } - - private KList add(Enumeration e) - { - while(e.hasMoreElements()) - { - add(e.nextElement()); - } - - return this; - } - - public KList add(Collection values) - { - addAll(values); - return this; - } - - /** - * Create a Map out of this list where this list becomes the values of the - * returned map. You must specify each key for each value in this list. In the - * function, returning null will not add the keyval pair. - * - * @param - * the inferred key type - * @param f - * the function - * @return the new map - */ - public KMap asValues(Function f) - { - KMap m = new KMap(); - forEach((i) -> m.putNonNull(f.apply(i), i)); - return m; - } - - /** - * Create a Map out of this list where this list becomes the keys of the - * returned map. You must specify each value for each key in this list. In the - * function, returning null will not add the keyval pair. - * - * @param - * the inferred value type - * @param f - * the function - * @return the new map - */ - @SuppressWarnings("hiding") - public KMap asKeys(Function f) - { - KMap m = new KMap(); - forEach((i) -> m.putNonNull(i, f.apply(i))); - return m; - } - - /** - * Cut this list into targetCount sublists - * - * @param targetCount - * the target count of sublists - * @return the list of sublists - */ - public KList> divide(int targetCount) - { - return split(size() / targetCount); - } - - /** - * Split this list into a list of sublists with roughly targetSize elements of T - * per sublist - * - * @param targetSize - * the target size - * @return the list of sublists - */ - public KList> split(int targetSize) - { - targetSize = targetSize < 1 ? 1 : targetSize; - KList> gg = new KList<>(); - KList b = new KList<>(); - - for(T i : this) - { - if(b.size() >= targetSize) - { - gg.add(b.copy()); - b.clear(); - } - - b.add(i); - } - - if(!b.isEmpty()) - { - gg.add(b); - } - - return gg; - } - - /** - * Rewrite this list by checking each value and changing the value (or not). - * Return null to remove the element in the function - * - * @param t - * the function - * @return the same list (not a copy) - */ - public KList rewrite(Function t) - { - KList m = copy(); - clear(); - - for(T i : m) - { - addNonNull(t.apply(i)); - } - - return this; - } - - /** - * To array - * - * @return the array - */ - @SuppressWarnings("unchecked") - public T[] array() - { - return (T[]) toArray(); - } - - /** - * Return a copy of this list - * - * @return the copy - */ - public KList copy() - { - return new KList().add(this); - } - - /** - * Shuffle the list - * - * @return the same list - */ - public KList shuffle() - { - Collections.shuffle(this); - return this; - } - - - public KList shuffle(Random rng) - { - Collections.shuffle(this, rng); - return this; - } - - /** - * Sort the list (based on toString comparison) - * - * @return the same list - */ - public KList sort() - { - Collections.sort(this, (a, b) -> a.toString().compareTo(b.toString())); - return this; - } - - /** - * Reverse this list - * - * @return the same list - */ - public KList reverse() - { - Collections.reverse(this); - return this; - } - - @Override - public String toString() - { - return "[" + toString(", ") + "]"; - } - - /** - * Tostring with a seperator for each item in the list - * - * @param split - * the seperator - * @return the string representing this object - */ - public String toString(String split) - { - if(isEmpty()) - { - return ""; - } - - if(size() == 1) - { - return get(0).toString(); - } - - StringBuilder b = new StringBuilder(); - - for(String i : toStringList()) - { - b.append(split + i); - } - - return b.toString().substring(split.length()); - } - - /** - * Invoke tostring on each value in the list into a string list - * - * @return the string list - */ - public KList toStringList() - { - return convert((t) -> t.toString()); - } - - /** - * Add the contents of the given list (v) into this list using a converter - * - * @param - * the type of the forign list - * @param v - * the forign (given) list - * @param converter - * the converter that converts the forign type into this list type - * @return this list (builder) - */ - @SuppressWarnings("hiding") - public KList addFrom(List v, Function converter) - { - v.forEach((g) -> add(converter.apply(g))); - return this; - } - - /** - * Convert this list into another list type. Such as GList to - * GList. list.convert((i) -> "" + i); - * - * @param - * @param converter - * @return - */ - @SuppressWarnings("hiding") - public KList convert(Function converter) - { - KList v = new KList(); - forEach((t) -> v.addNonNull(converter.apply(t))); - return v; - } - - public KList removeWhere(Predicate t) - { - for(T i : copy()) - { - if(t.test(i)) - { - remove(i); - } - } - - return this; - } - - /** - * Adds T to the list, ignores if null - * - * @param t - * the value to add - * @return the same list - */ - public KList addNonNull(T t) - { - if(t != null) - { - super.add(t); - } - - return this; - } - - /** - * Swaps the values of index a and b. For example "hello", "world", "!" swap(1, - * 2) would change the list to "hello", "!", "world" - * - * @param a - * the first index - * @param b - * the second index - * @return the same list (builder), not a copy - */ - public KList swapIndexes(int a, int b) - { - T aa = remove(a); - T bb = get(b); - add(a, bb); - remove(b); - add(b, aa); - - return this; - } - - /** - * Remove a number of elements from the list - * - * @param t - * the elements - * @return this list - */ - @SuppressWarnings("unchecked") - public KList remove(T... t) - { - for(T i : t) - { - super.remove(i); - } - - return this; - } - - /** - * Add another glist's contents to this one (addall builder) - * - * @param t - * the list - * @return the same list - */ - public KList add(KList t) - { - super.addAll(t); - return this; - } - - /** - * Add a number of values to this list - * - * @param t - * the list - * @return this list - */ - @SuppressWarnings("unchecked") - public KList add(T... t) - { - for(T i : t) - { - super.add(i); - } - - return this; - } - - /** - * Check if this list has an index at the given index - * - * @param index - * the given index - * @return true if size > index - */ - public boolean hasIndex(int index) - { - return size() > index && index >= 0; - } - - /** - * Get the last index of this list (size - 1) - * - * @return the last index of this list - */ - public int last() - { - return size() - 1; - } - - /** - * Deduplicate this list by converting to linked hash set and back - * - * @return the deduplicated list - */ - public KList dedupe() - { - LinkedHashSet lhs = new LinkedHashSet(this); - return qclear().add(lhs); - } - - /** - * Clear this list (and return it) - * - * @return the same list - */ - public KList qclear() - { - super.clear(); - return this; - } - - /** - * Simply !isEmpty() - * - * @return true if this list has 1 or more element(s) - */ - public boolean hasElements() - { - return !isEmpty(); - } - - /** - * Simply !isEmpty() - * - * @return true if this list has 1 or more element(s) - */ - public boolean isNotEmpty() - { - return !isEmpty(); - } - - /** - * Pop the first item off this list and return it - * - * @return the popped off item or null if the list is empty - */ - public T pop() - { - if(isEmpty()) - { - return null; - } - - return remove(0); - } - - /** - * Pop the last item off this list and return it - * - * @return the popped off item or null if the list is empty - */ - public T popLast() - { - if(isEmpty()) - { - return null; - } - - return remove(last()); - } - - public T popRandom() - { - if(isEmpty()) - { - return null; - } - - if(size() == 1) - { - return pop(); - } - - return remove(M.irand(0, last())); - } - - public static KList fromJSONAny(JSONArray oo) - { - KList s = new KList(); - - for(int i = 0; i < oo.length(); i++) - { - s.add(oo.get(i).toString()); - } - - return s; - } - - public KList sub(int f, int t) - { - KList g = new KList<>(); - - for(int i = f; i < M.min(size(), t); i++) - { - g.add(get(i)); - } - - return g; - } - - public JSONArray toJSONStringArray() - { - JSONArray j = new JSONArray(); - - for(Object i : this) - { - j.put(i.toString()); - } - - return j; - } - - public static KList asStringList(List oo) - { - KList s = new KList(); - - for(Object i : oo) - { - s.add(i.toString()); - } - - return s; - } - - @SuppressWarnings("unchecked") - public KList forceAdd(Object[] values) - { - for(Object i : values) - { - add((T) i); - } - - return this; - } - - @SuppressWarnings("unchecked") - public KList forceAdd(int[] values) - { - for(Object i : values) - { - add((T) i); - } - - return this; - } - - @SuppressWarnings("unchecked") - public KList forceAdd(double[] values) - { - for(Object i : values) - { - add((T) i); - } - - return this; - } - - @SuppressWarnings("unchecked") - public KList forceAdd(AtomicDoubleArray values) - { - for(int i = 0; i < values.length(); i++) - { - add((T) ((Object)values.get(i))); - } - - return this; - } - - @SuppressWarnings("unchecked") - public KList forceAdd(float[] values) - { - for(Object i : values) - { - add((T) i); - } - - return this; - } - - @SuppressWarnings("unchecked") - public KList forceAdd(byte[] values) - { - for(Object i : values) - { - add((T) i); - } - - return this; - } - - @SuppressWarnings("unchecked") - public KList forceAdd(short[] values) - { - for(Object i : values) - { - add((T) i); - } - - return this; - } - - @SuppressWarnings("unchecked") - public KList forceAdd(long[] values) - { - for(Object i : values) - { - add((T) i); - } - - return this; - } - - @SuppressWarnings("unchecked") - public KList forceAdd(boolean[] values) - { - for(Object i : values) - { - add((T) i); - } - - return this; - } - - public T middleValue() - { - return get(middleIndex()); - } - - private int middleIndex() - { - return size() % 2 == 0 ? (size() / 2) : ((size() / 2) + 1); - } - - public T getRandom() - { - if(isEmpty()) - { - return null; - } - - if(size() == 1) - { - return get(0); - } - - return get(M.irand(0, last())); - } - - public T getRandom(RNG rng) - { - if(isEmpty()) - { - return null; - } - - if(size() == 1) - { - return get(0); - } - - return get(rng.i(0, last())); - } - - public KList qdel(T t) - { - remove(t); - return this; - } - - public KList qadd(T t) - { - add(t); - return this; - } - - public KList qaddIfMissing(T t) - { - addIfMissing(t); - return this; - } - - public KList removeDuplicates() - { - KSet v = new KSet<>(); - v.addAll(this); - KList m = new KList<>(); - m.addAll(v); - return m; - } - - public boolean addIfMissing(T t) - { - if(!contains(t)) - { - add(t); - return true; - } - - return false; - } - - public void addAllIfMissing(KList t) - { - for(T i : t) - { - if(!contains(i)) - { - add(i); - } - } - } - - public KList shuffleCopy(Random rng) { - KList t = copy(); - t.shuffle(rng); - return t; - } +public class KList extends ArrayList implements List { + private static final long serialVersionUID = -2892550695744823337L; + + @SafeVarargs + public KList(T... ts) { + super(); + add(ts); + } + + public KList() { + super(); + } + + public KList(int cap) { + super(cap); + } + + public KList(Collection values) { + super(); + add(values); + } + + public KList(Enumeration e) { + super(); + add(e); + } + + public int indexOfAddIfNeeded(T v) { + addIfMissing(v); + return indexOf(v); + } + + /** + * Remove the last element + */ + public KList removeLast() { + remove(last()); + + return this; + } + + public void addMultiple(T t, int c) { + for (int i = 0; i < c; i++) { + add(t); + } + } + + private KList add(Enumeration e) { + while (e.hasMoreElements()) { + add(e.nextElement()); + } + + return this; + } + + public KList add(Collection values) { + addAll(values); + return this; + } + + /** + * Create a Map out of this list where this list becomes the values of the + * returned map. You must specify each key for each value in this list. In the + * function, returning null will not add the keyval pair. + * + * @param the inferred key type + * @param f the function + * @return the new map + */ + public KMap asValues(Function f) { + KMap m = new KMap(); + forEach((i) -> m.putNonNull(f.apply(i), i)); + return m; + } + + /** + * Create a Map out of this list where this list becomes the keys of the + * returned map. You must specify each value for each key in this list. In the + * function, returning null will not add the keyval pair. + * + * @param the inferred value type + * @param f the function + * @return the new map + */ + @SuppressWarnings("hiding") + public KMap asKeys(Function f) { + KMap m = new KMap(); + forEach((i) -> m.putNonNull(i, f.apply(i))); + return m; + } + + /** + * Cut this list into targetCount sublists + * + * @param targetCount the target count of sublists + * @return the list of sublists + */ + public KList> divide(int targetCount) { + return split(size() / targetCount); + } + + /** + * Split this list into a list of sublists with roughly targetSize elements of T + * per sublist + * + * @param targetSize the target size + * @return the list of sublists + */ + public KList> split(int targetSize) { + targetSize = targetSize < 1 ? 1 : targetSize; + KList> gg = new KList<>(); + KList b = new KList<>(); + + for (T i : this) { + if (b.size() >= targetSize) { + gg.add(b.copy()); + b.clear(); + } + + b.add(i); + } + + if (!b.isEmpty()) { + gg.add(b); + } + + return gg; + } + + /** + * Rewrite this list by checking each value and changing the value (or not). + * Return null to remove the element in the function + * + * @param t the function + * @return the same list (not a copy) + */ + public KList rewrite(Function t) { + KList m = copy(); + clear(); + + for (T i : m) { + addNonNull(t.apply(i)); + } + + return this; + } + + /** + * To array + * + * @return the array + */ + @SuppressWarnings("unchecked") + public T[] array() { + return (T[]) toArray(); + } + + /** + * Return a copy of this list + * + * @return the copy + */ + public KList copy() { + return new KList().add(this); + } + + /** + * Shuffle the list + * + * @return the same list + */ + public KList shuffle() { + Collections.shuffle(this); + return this; + } + + + public KList shuffle(Random rng) { + Collections.shuffle(this, rng); + return this; + } + + /** + * Sort the list (based on toString comparison) + * + * @return the same list + */ + public KList sort() { + Collections.sort(this, (a, b) -> a.toString().compareTo(b.toString())); + return this; + } + + /** + * Reverse this list + * + * @return the same list + */ + public KList reverse() { + Collections.reverse(this); + return this; + } + + @Override + public String toString() { + return "[" + toString(", ") + "]"; + } + + /** + * Tostring with a seperator for each item in the list + * + * @param split the seperator + * @return the string representing this object + */ + public String toString(String split) { + if (isEmpty()) { + return ""; + } + + if (size() == 1) { + return get(0).toString(); + } + + StringBuilder b = new StringBuilder(); + + for (String i : toStringList()) { + b.append(split + i); + } + + return b.substring(split.length()); + } + + /** + * Invoke tostring on each value in the list into a string list + * + * @return the string list + */ + public KList toStringList() { + return convert((t) -> t.toString()); + } + + /** + * Add the contents of the given list (v) into this list using a converter + * + * @param the type of the forign list + * @param v the forign (given) list + * @param converter the converter that converts the forign type into this list type + * @return this list (builder) + */ + @SuppressWarnings("hiding") + public KList addFrom(List v, Function converter) { + v.forEach((g) -> add(converter.apply(g))); + return this; + } + + /** + * Convert this list into another list type. Such as GList to + * GList. list.convert((i) -> "" + i); + * + * @param + * @param converter + * @return + */ + @SuppressWarnings("hiding") + public KList convert(Function converter) { + KList v = new KList(); + forEach((t) -> v.addNonNull(converter.apply(t))); + return v; + } + + public KList removeWhere(Predicate t) { + for (T i : copy()) { + if (t.test(i)) { + remove(i); + } + } + + return this; + } + + /** + * Adds T to the list, ignores if null + * + * @param t the value to add + * @return the same list + */ + public KList addNonNull(T t) { + if (t != null) { + super.add(t); + } + + return this; + } + + /** + * Swaps the values of index a and b. For example "hello", "world", "!" swap(1, + * 2) would change the list to "hello", "!", "world" + * + * @param a the first index + * @param b the second index + * @return the same list (builder), not a copy + */ + public KList swapIndexes(int a, int b) { + T aa = remove(a); + T bb = get(b); + add(a, bb); + remove(b); + add(b, aa); + + return this; + } + + /** + * Remove a number of elements from the list + * + * @param t the elements + * @return this list + */ + @SuppressWarnings("unchecked") + public KList remove(T... t) { + for (T i : t) { + super.remove(i); + } + + return this; + } + + /** + * Add another glist's contents to this one (addall builder) + * + * @param t the list + * @return the same list + */ + public KList add(KList t) { + super.addAll(t); + return this; + } + + /** + * Add a number of values to this list + * + * @param t the list + * @return this list + */ + @SuppressWarnings("unchecked") + public KList add(T... t) { + for (T i : t) { + super.add(i); + } + + return this; + } + + /** + * Check if this list has an index at the given index + * + * @param index the given index + * @return true if size > index + */ + public boolean hasIndex(int index) { + return size() > index && index >= 0; + } + + /** + * Get the last index of this list (size - 1) + * + * @return the last index of this list + */ + public int last() { + return size() - 1; + } + + /** + * Deduplicate this list by converting to linked hash set and back + * + * @return the deduplicated list + */ + public KList dedupe() { + LinkedHashSet lhs = new LinkedHashSet(this); + return qclear().add(lhs); + } + + /** + * Clear this list (and return it) + * + * @return the same list + */ + public KList qclear() { + super.clear(); + return this; + } + + /** + * Simply !isEmpty() + * + * @return true if this list has 1 or more element(s) + */ + public boolean hasElements() { + return !isEmpty(); + } + + /** + * Simply !isEmpty() + * + * @return true if this list has 1 or more element(s) + */ + public boolean isNotEmpty() { + return !isEmpty(); + } + + /** + * Pop the first item off this list and return it + * + * @return the popped off item or null if the list is empty + */ + public T pop() { + if (isEmpty()) { + return null; + } + + return remove(0); + } + + /** + * Pop the last item off this list and return it + * + * @return the popped off item or null if the list is empty + */ + public T popLast() { + if (isEmpty()) { + return null; + } + + return remove(last()); + } + + public T popRandom() { + if (isEmpty()) { + return null; + } + + if (size() == 1) { + return pop(); + } + + return remove(M.irand(0, last())); + } + + public static KList fromJSONAny(JSONArray oo) { + KList s = new KList(); + + for (int i = 0; i < oo.length(); i++) { + s.add(oo.get(i).toString()); + } + + return s; + } + + public KList sub(int f, int t) { + KList g = new KList<>(); + + for (int i = f; i < M.min(size(), t); i++) { + g.add(get(i)); + } + + return g; + } + + public JSONArray toJSONStringArray() { + JSONArray j = new JSONArray(); + + for (Object i : this) { + j.put(i.toString()); + } + + return j; + } + + public static KList asStringList(List oo) { + KList s = new KList(); + + for (Object i : oo) { + s.add(i.toString()); + } + + return s; + } + + @SuppressWarnings("unchecked") + public KList forceAdd(Object[] values) { + for (Object i : values) { + add((T) i); + } + + return this; + } + + @SuppressWarnings("unchecked") + public KList forceAdd(int[] values) { + for (Object i : values) { + add((T) i); + } + + return this; + } + + @SuppressWarnings("unchecked") + public KList forceAdd(double[] values) { + for (Object i : values) { + add((T) i); + } + + return this; + } + + @SuppressWarnings("unchecked") + public KList forceAdd(AtomicDoubleArray values) { + for (int i = 0; i < values.length(); i++) { + add((T) ((Object) values.get(i))); + } + + return this; + } + + @SuppressWarnings("unchecked") + public KList forceAdd(float[] values) { + for (Object i : values) { + add((T) i); + } + + return this; + } + + @SuppressWarnings("unchecked") + public KList forceAdd(byte[] values) { + for (Object i : values) { + add((T) i); + } + + return this; + } + + @SuppressWarnings("unchecked") + public KList forceAdd(short[] values) { + for (Object i : values) { + add((T) i); + } + + return this; + } + + @SuppressWarnings("unchecked") + public KList forceAdd(long[] values) { + for (Object i : values) { + add((T) i); + } + + return this; + } + + @SuppressWarnings("unchecked") + public KList forceAdd(boolean[] values) { + for (Object i : values) { + add((T) i); + } + + return this; + } + + public T middleValue() { + return get(middleIndex()); + } + + private int middleIndex() { + return size() % 2 == 0 ? (size() / 2) : ((size() / 2) + 1); + } + + public T getRandom() { + if (isEmpty()) { + return null; + } + + if (size() == 1) { + return get(0); + } + + return get(M.irand(0, last())); + } + + public T getRandom(RNG rng) { + if (isEmpty()) { + return null; + } + + if (size() == 1) { + return get(0); + } + + return get(rng.i(0, last())); + } + + public KList qdel(T t) { + remove(t); + return this; + } + + public KList qadd(T t) { + add(t); + return this; + } + + public KList qaddIfMissing(T t) { + addIfMissing(t); + return this; + } + + public KList removeDuplicates() { + KSet v = new KSet<>(); + v.addAll(this); + KList m = new KList<>(); + m.addAll(v); + return m; + } + + public boolean addIfMissing(T t) { + if (!contains(t)) { + add(t); + return true; + } + + return false; + } + + public void addAllIfMissing(KList t) { + for (T i : t) { + if (!contains(i)) { + add(i); + } + } + } + + public KList shuffleCopy(Random rng) { + KList t = copy(); + t.shuffle(rng); + return t; + } } diff --git a/src/main/java/com/volmit/iris/util/KMap.java b/src/main/java/com/volmit/iris/util/KMap.java index 87aff4295..e313d2121 100644 --- a/src/main/java/com/volmit/iris/util/KMap.java +++ b/src/main/java/com/volmit/iris/util/KMap.java @@ -7,419 +7,351 @@ import java.util.Map; import java.util.concurrent.ConcurrentHashMap; @SuppressWarnings("hiding") -public class KMap extends ConcurrentHashMap -{ - private static final long serialVersionUID = 7288942695300448163L; +public class KMap extends ConcurrentHashMap { + private static final long serialVersionUID = 7288942695300448163L; - public KMap() - { - super(); - } + public KMap() { + super(); + } - public KMap(Map gMap) - { - this(); - put(gMap); - } + public KMap(Map gMap) { + this(); + put(gMap); + } - /** - * Puts a value into a map-value-list based on the key such that if GMap> where V is GList - * - * @param - * the list type in the value type - * @param k - * the key to look for - * @param vs - * the values to put into the list of the given key - * @return the same list (builder) - */ - @SuppressWarnings("unchecked") - public KMap putValueList(K k, S... vs) - { - try - { - KMap> s = (KMap>) this; + /** + * Puts a value into a map-value-list based on the key such that if GMap> where V is GList + * + * @param the list type in the value type + * @param k the key to look for + * @param vs the values to put into the list of the given key + * @return the same list (builder) + */ + @SuppressWarnings("unchecked") + public KMap putValueList(K k, S... vs) { + try { + KMap> s = (KMap>) this; - if(!s.containsKey(k)) - { - s.put(k, new KList()); - } + if (!s.containsKey(k)) { + s.put(k, new KList()); + } - s.get(k).add(vs); - } + s.get(k).add(vs); + } catch (Throwable e) { - catch(Throwable e) - { + } - } + return this; + } - return this; - } + /** + * Returns a sorted list of keys from this map, based on the sorting order of + * the values. + * + * @return the value-sorted key list + */ + public KList sortK() { + KList k = new KList(); + KList v = v(); - /** - * Returns a sorted list of keys from this map, based on the sorting order of - * the values. - * - * @return the value-sorted key list - */ - public KList sortK() - { - KList k = new KList(); - KList v = v(); + Collections.sort(v, new Comparator() { + @Override + public int compare(V v, V t1) { + return v.toString().compareTo(t1.toString()); + } + }); - Collections.sort(v, new Comparator() - { - @Override - public int compare(V v, V t1) - { - return v.toString().compareTo(t1.toString()); - } - }); + for (V i : v) { + for (K j : k()) { + if (get(j).equals(i)) { + k.add(j); + } + } + } - for(V i : v) - { - for(K j : k()) - { - if(get(j).equals(i)) - { - k.add(j); - } - } - } + k.dedupe(); + return k; + } - k.dedupe(); - return k; - } + /** + * Returns a sorted list of keys from this map, based on the sorting order of + * the values. Sorting is based on numerical values + * + * @return the value-sorted key list + */ + public KList sortKNumber() { + KList k = new KList(); + KList v = v(); - /** - * Returns a sorted list of keys from this map, based on the sorting order of - * the values. Sorting is based on numerical values - * - * @return the value-sorted key list - */ - public KList sortKNumber() - { - KList k = new KList(); - KList v = v(); + Collections.sort(v, new Comparator() { + @Override + public int compare(V v, V t1) { + Number n1 = (Number) v; + Number n2 = (Number) t1; - Collections.sort(v, new Comparator() - { - @Override - public int compare(V v, V t1) - { - Number n1 = (Number) v; - Number n2 = (Number) t1; + return (int) ((n1.doubleValue() - n2.doubleValue()) * 1000); + } + }); - return (int) ((n1.doubleValue() - n2.doubleValue()) * 1000); - } - }); + for (V i : v) { + for (K j : k()) { + if (get(j).equals(i)) { + k.add(j); + } + } + } - for(V i : v) - { - for(K j : k()) - { - if(get(j).equals(i)) - { - k.add(j); - } - } - } + k.dedupe(); + return k; + } - k.dedupe(); - return k; - } + /** + * Put another map's values into this map + * + * @param m the map to insert + * @return this map (builder) + */ + public KMap put(Map m) { + putAll(m); + return this; + } - /** - * Put another map's values into this map - * - * @param m - * the map to insert - * @return this map (builder) - */ - public KMap put(Map m) - { - putAll(m); - return this; - } + /** + * Return a copy of this map + * + * @return the copied map + */ + public KMap copy() { + return new KMap(this); + } - /** - * Return a copy of this map - * - * @return the copied map - */ - public KMap copy() - { - return new KMap(this); - } + /** + * Loop through each keyvalue set (copy of it) with the map parameter + * + * @param f the function + * @return the same gmap + */ + public KMap rewrite(Consumer3> f) { + KMap m = copy(); - /** - * Loop through each keyvalue set (copy of it) with the map parameter - * - * @param f - * the function - * @return the same gmap - */ - public KMap rewrite(Consumer3> f) - { - KMap m = copy(); + for (K i : m.k()) { + f.accept(i, get(i), this); + } - for(K i : m.k()) - { - f.accept(i, get(i), this); - } + return this; + } - return this; - } + /** + * Loop through each keyvalue set (copy of it) + * + * @param f the function + * @return the same gmap + */ + public KMap each(Consumer2 f) { + for (K i : k()) { + f.accept(i, get(i)); + } - /** - * Loop through each keyvalue set (copy of it) - * - * @param f - * the function - * @return the same gmap - */ - public KMap each(Consumer2 f) - { - for(K i : k()) - { - f.accept(i, get(i)); - } + return this; + } - return this; - } + /** + * Flip the hashmap and flatten the value list even if there are multiple keys + * + * @return the flipped and flattened hashmap + */ + public KMap flipFlatten() { + KMap> f = flip(); + KMap m = new KMap<>(); - /** - * Flip the hashmap and flatten the value list even if there are multiple keys - * - * @return the flipped and flattened hashmap - */ - public KMap flipFlatten() - { - KMap> f = flip(); - KMap m = new KMap<>(); + for (V i : f.k()) { + m.putNonNull(i, m.isEmpty() ? null : m.get(0)); + } - for(V i : f.k()) - { - m.putNonNull(i, m.isEmpty() ? null : m.get(0)); - } + return m; + } - return m; - } + /** + * Flip the hashmap so keys are now list-keys in the value position + * + * @return the flipped hashmap + */ + public KMap> flip() { + KMap> flipped = new KMap>(); - /** - * Flip the hashmap so keys are now list-keys in the value position - * - * @return the flipped hashmap - */ - public KMap> flip() - { - KMap> flipped = new KMap>(); + for (K i : keySet()) { + if (i == null) { + continue; + } - for(K i : keySet()) - { - if(i == null) - { - continue; - } + if (!flipped.containsKey(get(i))) { + flipped.put(get(i), new KList()); + } - if(!flipped.containsKey(get(i))) - { - flipped.put(get(i), new KList()); - } + flipped.get(get(i)).add(i); + } - flipped.get(get(i)).add(i); - } + return flipped; + } - return flipped; - } + /** + * Sort values based on the keys sorting order + * + * @return the values (sorted) + */ + public KList sortV() { + KList v = new KList(); + KList k = k(); - /** - * Sort values based on the keys sorting order - * - * @return the values (sorted) - */ - public KList sortV() - { - KList v = new KList(); - KList k = k(); + Collections.sort(k, new Comparator() { + @Override + public int compare(K v, K t1) { + return v.toString().compareTo(t1.toString()); + } + }); - Collections.sort(k, new Comparator() - { - @Override - public int compare(K v, K t1) - { - return v.toString().compareTo(t1.toString()); - } - }); + for (K i : k) { + for (V j : v()) { + if (get(i).equals(j)) { + v.add(j); + } + } + } - for(K i : k) - { - for(V j : v()) - { - if(get(i).equals(j)) - { - v.add(j); - } - } - } + v.dedupe(); + return v; + } - v.dedupe(); - return v; - } + public KList sortVNoDedupe() { + KList v = new KList(); + KList k = k(); - public KList sortVNoDedupe() - { - KList v = new KList(); - KList k = k(); + Collections.sort(k, new Comparator() { + @Override + public int compare(K v, K t1) { + return v.toString().compareTo(t1.toString()); + } + }); - Collections.sort(k, new Comparator() - { - @Override - public int compare(K v, K t1) - { - return v.toString().compareTo(t1.toString()); - } - }); + for (K i : k) { + for (V j : v()) { + if (get(i).equals(j)) { + v.add(j); + } + } + } - for(K i : k) - { - for(V j : v()) - { - if(get(i).equals(j)) - { - v.add(j); - } - } - } + return v; + } - return v; - } + /** + * Get a copy of this maps keys + * + * @return the keys + */ + public KList k() { + KList k = new KList(); + Enumeration kk = keys(); - /** - * Get a copy of this maps keys - * - * @return the keys - */ - public KList k() - { - KList k = new KList(); - Enumeration kk = keys(); + while (kk.hasMoreElements()) { + K kkk = kk.nextElement(); + k.add(kkk); + } - while(kk.hasMoreElements()) - { - K kkk = kk.nextElement(); - k.add(kkk); - } + return k; + } - return k; - } + /** + * Get a copy of this maps values + * + * @return the values + */ + public KList v() { + return new KList(values()); + } - /** - * Get a copy of this maps values - * - * @return the values - */ - public KList v() - { - return new KList(values()); - } + /** + * Still works as it normally should except it returns itself (builder) + * + * @param key the key + * @param value the value (single only supported) + * @return + */ + public KMap qput(K key, V value) { + super.put(key, value); + return this; + } - /** - * Still works as it normally should except it returns itself (builder) - * - * @param key - * the key - * @param value - * the value (single only supported) - * @return - */ - public KMap qput(K key, V value) - { - super.put(key, value); - return this; - } + /** + * Works just like put, except it wont put anything unless the key and value are + * nonnull + * + * @param key the nonnull key + * @param value the nonnull value + * @return the same map + */ + public KMap putNonNull(K key, V value) { + if (key != null || value != null) { + put(key, value); + } - /** - * Works just like put, except it wont put anything unless the key and value are - * nonnull - * - * @param key - * the nonnull key - * @param value - * the nonnull value - * @return the same map - */ - public KMap putNonNull(K key, V value) - { - if(key != null || value != null) - { - put(key, value); - } + return this; + } - return this; - } + public V putThen(K key, V valueIfKeyNotPresent) { + if (!containsKey(key)) { + put(key, valueIfKeyNotPresent); + } - public V putThen(K key, V valueIfKeyNotPresent) - { - if(!containsKey(key)) - { - put(key, valueIfKeyNotPresent); - } + return get(key); + } - return get(key); - } + /** + * Clear this map and return it + * + * @return the cleared map + */ + public KMap qclear() { + super.clear(); + return this; + } - /** - * Clear this map and return it - * - * @return the cleared map - */ - public KMap qclear() - { - super.clear(); - return this; - } + /** + * Convert this map to keypairs + * + * @return the keypair list + */ + public KList> keypair() { + KList> g = new KList<>(); + each((k, v) -> g.add(new KeyPair(k, v))); + return g; + } - /** - * Convert this map to keypairs - * - * @return the keypair list - */ - public KList> keypair() - { - KList> g = new KList<>(); - each((k, v) -> g.add(new KeyPair(k, v))); - return g; - } + /** + * Create a keypair queue + * + * @return the queue + */ + public Queue> enqueue() { + return Queue.create(keypair()); + } - /** - * Create a keypair queue - * - * @return the queue - */ - public Queue> enqueue() - { - return Queue.create(keypair()); - } + /** + * Create a key queue + * + * @return the queue + */ + public Queue enqueueKeys() { + return Queue.create(k()); + } - /** - * Create a key queue - * - * @return the queue - */ - public Queue enqueueKeys() - { - return Queue.create(k()); - } - - /** - * Create a value queue - * - * @return the queue - */ - public Queue enqueueValues() - { - return Queue.create(v()); - } + /** + * Create a value queue + * + * @return the queue + */ + public Queue enqueueValues() { + return Queue.create(v()); + } } diff --git a/src/main/java/com/volmit/iris/util/KSet.java b/src/main/java/com/volmit/iris/util/KSet.java index 95284fa98..aa2acf9f1 100644 --- a/src/main/java/com/volmit/iris/util/KSet.java +++ b/src/main/java/com/volmit/iris/util/KSet.java @@ -3,27 +3,22 @@ package com.volmit.iris.util; import java.util.Collection; import java.util.HashSet; -public class KSet extends HashSet -{ - private static final long serialVersionUID = 1L; +public class KSet extends HashSet { + private static final long serialVersionUID = 1L; - public KSet() - { - super(); - } + public KSet() { + super(); + } - public KSet(Collection c) - { - super(c); - } + public KSet(Collection c) { + super(c); + } - public KSet(int initialCapacity, float loadFactor) - { - super(initialCapacity, loadFactor); - } + public KSet(int initialCapacity, float loadFactor) { + super(initialCapacity, loadFactor); + } - public KSet(int initialCapacity) - { - super(initialCapacity); - } + public KSet(int initialCapacity) { + super(initialCapacity); + } } diff --git a/src/main/java/com/volmit/iris/util/KeyPair.java b/src/main/java/com/volmit/iris/util/KeyPair.java index c972ec733..73b6fee99 100644 --- a/src/main/java/com/volmit/iris/util/KeyPair.java +++ b/src/main/java/com/volmit/iris/util/KeyPair.java @@ -2,45 +2,40 @@ package com.volmit.iris.util; /** * Represents a keypair - * @author cyberpwn * * @param the key type * @param the value type + * @author cyberpwn */ @SuppressWarnings("hiding") -public class KeyPair -{ - private K k; - private V v; +public class KeyPair { + private K k; + private V v; - /** - * Create a keypair - * @param k the key - * @param v the value - */ - public KeyPair(K k, V v) - { - this.k = k; - this.v = v; - } + /** + * Create a keypair + * + * @param k the key + * @param v the value + */ + public KeyPair(K k, V v) { + this.k = k; + this.v = v; + } - public K getK() - { - return k; - } + public K getK() { + return k; + } - public void setK(K k) - { - this.k = k; - } + public void setK(K k) { + this.k = k; + } - public V getV() - { - return v; - } + public V getV() { + return v; + } - public void setV(V v) - { - this.v = v; - } + public void setV(V v) { + this.v = v; + } } diff --git a/src/main/java/com/volmit/iris/util/LinkedTerrainChunk.java b/src/main/java/com/volmit/iris/util/LinkedTerrainChunk.java index 1d270088e..ddb5a032f 100644 --- a/src/main/java/com/volmit/iris/util/LinkedTerrainChunk.java +++ b/src/main/java/com/volmit/iris/util/LinkedTerrainChunk.java @@ -1,5 +1,6 @@ package com.volmit.iris.util; +import com.volmit.iris.Iris; import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.Biome; @@ -8,227 +9,184 @@ import org.bukkit.generator.ChunkGenerator.BiomeGrid; import org.bukkit.generator.ChunkGenerator.ChunkData; import org.bukkit.material.MaterialData; -import com.volmit.iris.Iris; - @SuppressWarnings("deprecation") -public class LinkedTerrainChunk implements TerrainChunk -{ - private final Biome[] biome2D; - private final IrisBiomeStorage biome3D; - private ChunkData rawChunkData; - private final BiomeGrid storage; +public class LinkedTerrainChunk implements TerrainChunk { + private final Biome[] biome2D; + private final IrisBiomeStorage biome3D; + private ChunkData rawChunkData; + private final BiomeGrid storage; - public LinkedTerrainChunk(int maxHeight) - { - this(null, maxHeight); - } + public LinkedTerrainChunk(int maxHeight) { + this(null, maxHeight); + } - public LinkedTerrainChunk(BiomeGrid storage, ChunkData data) - { - this.storage = storage; - rawChunkData = data; - biome2D = storage != null ? null : Iris.biome3d ? null : new Biome[256]; - biome3D = storage != null ? null : Iris.biome3d ? new IrisBiomeStorage() : null; - } + public LinkedTerrainChunk(BiomeGrid storage, ChunkData data) { + this.storage = storage; + rawChunkData = data; + biome2D = storage != null ? null : Iris.biome3d ? null : new Biome[256]; + biome3D = storage != null ? null : Iris.biome3d ? new IrisBiomeStorage() : null; + } - public LinkedTerrainChunk(BiomeGrid storage, int maxHeight) - { - this.storage = storage; - rawChunkData = createChunkData(maxHeight); - biome2D = storage != null ? null : Iris.biome3d ? null : new Biome[256]; - biome3D = storage != null ? null : Iris.biome3d ? new IrisBiomeStorage() : null; - } + public LinkedTerrainChunk(BiomeGrid storage, int maxHeight) { + this.storage = storage; + rawChunkData = createChunkData(maxHeight); + biome2D = storage != null ? null : Iris.biome3d ? null : new Biome[256]; + biome3D = storage != null ? null : Iris.biome3d ? new IrisBiomeStorage() : null; + } - private ChunkData createChunkData(int maxHeight) - { - try - { - return Bukkit.createChunkData(new HeightedFakeWorld(maxHeight)); - } + private ChunkData createChunkData(int maxHeight) { + try { + return Bukkit.createChunkData(new HeightedFakeWorld(maxHeight)); + } catch (Throwable e) { + e.printStackTrace(); + } - catch(Throwable e) - { - e.printStackTrace(); - } + return null; + } - return null; - } + @Override + public Biome getBiome(int x, int z) { + if (storage != null) { + return storage.getBiome(x, z); + } - @Override - public Biome getBiome(int x, int z) - { - if(storage != null) - { - return storage.getBiome(x, z); - } + if (biome2D != null) { + return biome2D[(z << 4) | x]; + } - if(biome2D != null) - { - return biome2D[(z << 4) | x]; - } + return biome3D.getBiome(x, 0, z); + } - return biome3D.getBiome(x, 0, z); - } + @Override + public Biome getBiome(int x, int y, int z) { + if (storage != null) { + return storage.getBiome(x, y, z); + } - @Override - public Biome getBiome(int x, int y, int z) - { - if(storage != null) - { - return storage.getBiome(x, y, z); - } + if (biome2D != null) { + return biome2D[(z << 4) | x]; + } - if(biome2D != null) - { - return biome2D[(z << 4) | x]; - } + return biome3D.getBiome(x, y, z); + } - return biome3D.getBiome(x, y, z); - } + @Override + public void setBiome(int x, int z, Biome bio) { + if (storage != null) { + storage.setBiome(x, z, bio); + return; + } - @Override - public void setBiome(int x, int z, Biome bio) - { - if(storage != null) - { - storage.setBiome(x, z, bio); - return; - } + if (biome2D != null) { + biome2D[(z << 4) | x] = bio; + return; + } - if(biome2D != null) - { - biome2D[(z << 4) | x] = bio; - return; - } + biome3D.setBiome(x, 0, z, bio); + } - biome3D.setBiome(x, 0, z, bio); - } + @Override + public void setBiome(int x, int y, int z, Biome bio) { + if (storage != null) { + storage.setBiome(x, y, z, bio); + return; + } - @Override - public void setBiome(int x, int y, int z, Biome bio) - { - if(storage != null) - { - storage.setBiome(x, y, z, bio); - return; - } + if (biome2D != null) { + biome2D[(z << 4) | x] = bio; + return; + } - if(biome2D != null) - { - biome2D[(z << 4) | x] = bio; - return; - } + biome3D.setBiome(x, y, z, bio); + } - biome3D.setBiome(x, y, z, bio); - } + @Override + public int getMinHeight() { + return rawChunkData.getMinHeight(); + } - @Override - public int getMinHeight() { - return rawChunkData.getMinHeight(); - } + @Override + public int getMaxHeight() { + return rawChunkData.getMaxHeight(); + } - @Override - public int getMaxHeight() - { - return rawChunkData.getMaxHeight(); - } + @Override + public void setBlock(int x, int y, int z, BlockData blockData) { + rawChunkData.setBlock(x, y, z, blockData); + } - @Override - public void setBlock(int x, int y, int z, BlockData blockData) - { - rawChunkData.setBlock(x, y, z, blockData); - } + @Override + public BlockData getBlockData(int x, int y, int z) { + return rawChunkData.getBlockData(x, y, z); + } - @Override - public BlockData getBlockData(int x, int y, int z) - { - return rawChunkData.getBlockData(x, y, z); - } + @Deprecated + @Override + public void setBlock(int x, int y, int z, Material material) { + rawChunkData.setBlock(x, y, z, material); + } - @Deprecated - @Override - public void setBlock(int x, int y, int z, Material material) - { - rawChunkData.setBlock(x, y, z, material); - } + @Deprecated + @Override + public void setBlock(int x, int y, int z, MaterialData material) { + rawChunkData.setBlock(x, y, z, material); + } - @Deprecated - @Override - public void setBlock(int x, int y, int z, MaterialData material) - { - rawChunkData.setBlock(x, y, z, material); - } + @Deprecated + @Override + public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, Material material) { + rawChunkData.setRegion(xMin, yMin, zMin, xMax, yMax, zMax, material); + } - @Deprecated - @Override - public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, Material material) - { - rawChunkData.setRegion(xMin, yMin, zMin, xMax, yMax, zMax, material); - } + @Deprecated + @Override + public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, MaterialData material) { + rawChunkData.setRegion(xMin, yMin, zMin, xMax, yMax, zMax, material); + } - @Deprecated - @Override - public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, MaterialData material) - { - rawChunkData.setRegion(xMin, yMin, zMin, xMax, yMax, zMax, material); - } + @Override + public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, BlockData blockData) { + rawChunkData.setRegion(xMin, yMin, zMin, xMax, yMax, zMax, blockData); + } - @Override - public void setRegion(int xMin, int yMin, int zMin, int xMax, int yMax, int zMax, BlockData blockData) - { - rawChunkData.setRegion(xMin, yMin, zMin, xMax, yMax, zMax, blockData); - } + @Deprecated + @Override + public Material getType(int x, int y, int z) { + return rawChunkData.getType(x, y, z); + } - @Deprecated - @Override - public Material getType(int x, int y, int z) - { - return rawChunkData.getType(x, y, z); - } + @Deprecated + @Override + public MaterialData getTypeAndData(int x, int y, int z) { + return rawChunkData.getTypeAndData(x, y, z); + } - @Deprecated - @Override - public MaterialData getTypeAndData(int x, int y, int z) - { - return rawChunkData.getTypeAndData(x, y, z); - } + @Deprecated + @Override + public byte getData(int x, int y, int z) { + return rawChunkData.getData(x, y, z); + } - @Deprecated - @Override - public byte getData(int x, int y, int z) - { - return rawChunkData.getData(x, y, z); - } + @Override + public ChunkData getRaw() { + return rawChunkData; + } - @Override - public ChunkData getRaw() - { - return rawChunkData; - } + @Override + public void setRaw(ChunkData data) { + rawChunkData = data; + } - @Override - public void setRaw(ChunkData data) - { - rawChunkData = data; - } - - @Override - public void inject(BiomeGrid biome) - { - if(biome2D != null) - { - for(int i = 0; i < 16; i++) - { - for(int j = 0; j < 16; j++) - { - biome.setBiome(i, j, getBiome(i, j)); - } - } - } - - else if(biome3D != null) - { - biome3D.inject(biome); - } - } + @Override + public void inject(BiomeGrid biome) { + if (biome2D != null) { + for (int i = 0; i < 16; i++) { + for (int j = 0; j < 16; j++) { + biome.setBiome(i, j, getBiome(i, j)); + } + } + } else if (biome3D != null) { + biome3D.inject(biome); + } + } } diff --git a/src/main/java/com/volmit/iris/util/ListTag.java b/src/main/java/com/volmit/iris/util/ListTag.java index 357335145..a0d917798 100644 --- a/src/main/java/com/volmit/iris/util/ListTag.java +++ b/src/main/java/com/volmit/iris/util/ListTag.java @@ -2,24 +2,24 @@ package com.volmit.iris.util; /* * JNBT License - * + * * Copyright (c) 2010 Graham Edgecombe * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. - * + * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * * Neither the name of the JNBT team nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -30,8 +30,9 @@ package com.volmit.iris.util; * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * POSSIBILITY OF SUCH DAMAGE. */ + import java.util.Collections; import java.util.List; @@ -39,7 +40,6 @@ import java.util.List; * The TAG_List tag. * * @author Graham Edgecombe - * */ public final class ListTag extends Tag { @@ -56,8 +56,8 @@ public final class ListTag extends Tag { /** * Creates the tag. * - * @param name The name. - * @param type The type of item in the list. + * @param name The name. + * @param type The type of item in the list. * @param value The value. */ public ListTag(String name, Class type, List value) { diff --git a/src/main/java/com/volmit/iris/util/LongTag.java b/src/main/java/com/volmit/iris/util/LongTag.java index 6a835b6b9..19d1dc54e 100644 --- a/src/main/java/com/volmit/iris/util/LongTag.java +++ b/src/main/java/com/volmit/iris/util/LongTag.java @@ -2,24 +2,24 @@ package com.volmit.iris.util; /* * JNBT License - * + * * Copyright (c) 2010 Graham Edgecombe * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. - * + * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * * Neither the name of the JNBT team nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -30,13 +30,13 @@ package com.volmit.iris.util; * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * POSSIBILITY OF SUCH DAMAGE. */ + /** * The TAG_Long tag. * * @author Graham Edgecombe - * */ public final class LongTag extends Tag { @@ -48,7 +48,7 @@ public final class LongTag extends Tag { /** * Creates the tag. * - * @param name The name. + * @param name The name. * @param value The value. */ public LongTag(String name, long value) { diff --git a/src/main/java/com/volmit/iris/util/Looper.java b/src/main/java/com/volmit/iris/util/Looper.java index 9204306d5..84abbd74e 100644 --- a/src/main/java/com/volmit/iris/util/Looper.java +++ b/src/main/java/com/volmit/iris/util/Looper.java @@ -2,37 +2,26 @@ package com.volmit.iris.util; import com.volmit.iris.Iris; -public abstract class Looper extends Thread -{ - public void run() - { - while(!interrupted()) - { - try - { - long m = loop(); +public abstract class Looper extends Thread { + public void run() { + while (!interrupted()) { + try { + long m = loop(); - if(m < 0) - { - break; - } + if (m < 0) { + break; + } - Thread.sleep(m); - } + Thread.sleep(m); + } catch (InterruptedException e) { + break; + } catch (Throwable e) { + e.printStackTrace(); + } + } - catch(InterruptedException e) - { - break; - } + Iris.info("Thread " + getName() + " Shutdown."); + } - catch(Throwable e) - { - e.printStackTrace(); - } - } - - Iris.info("Thread " + getName() + " Shutdown."); - } - - protected abstract long loop(); + protected abstract long loop(); } diff --git a/src/main/java/com/volmit/iris/util/M.java b/src/main/java/com/volmit/iris/util/M.java index 27f38ad85..c245d869c 100644 --- a/src/main/java/com/volmit/iris/util/M.java +++ b/src/main/java/com/volmit/iris/util/M.java @@ -1,449 +1,356 @@ package com.volmit.iris.util; -import java.util.regex.Matcher; - import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; +import java.util.regex.Matcher; /** * Math * * @author cyberpwn */ -public class M -{ - private static final int precision = 128; - private static final int modulus = 360 * precision; - private static final float[] sin = new float[modulus]; - public static int tick = 0; +public class M { + private static final int precision = 128; + private static final int modulus = 360 * precision; + private static final float[] sin = new float[modulus]; + public static int tick = 0; - /** - * Scales B by an external range change so that
- *
- * BMIN < B < BMAX
- * AMIN < RESULT < AMAX
- *
- * So Given rangeScale(0, 20, 0, 10, 5) -> 10
- * 0 < 5 < 10
- * 0 < ? < 20
- *
- * would return 10 - * - * @param amin - * the resulting minimum - * @param amax - * the resulting maximum - * @param bmin - * the initial minimum - * @param bmax - * the initial maximum - * @param b - * the initial value - * @return the resulting value - */ - public static double rangeScale(double amin, double amax, double bmin, double bmax, double b) - { - return amin + ((amax - amin) * ((b - bmin) / (bmax - bmin))); - } + /** + * Scales B by an external range change so that
+ *
+ * BMIN < B < BMAX
+ * AMIN < RESULT < AMAX
+ *
+ * So Given rangeScale(0, 20, 0, 10, 5) -> 10
+ * 0 < 5 < 10
+ * 0 < ? < 20
+ *
+ * would return 10 + * + * @param amin the resulting minimum + * @param amax the resulting maximum + * @param bmin the initial minimum + * @param bmax the initial maximum + * @param b the initial value + * @return the resulting value + */ + public static double rangeScale(double amin, double amax, double bmin, double bmax, double b) { + return amin + ((amax - amin) * ((b - bmin) / (bmax - bmin))); + } - /** - * Get the percent (inverse lerp) from "from" to "to" where "at". - * - * If from = 0 and to = 100 and at = 25 then it would return 0.25 - * - * @param from - * the from - * @param to - * the to - * @param at - * the at - * @return the percent - */ - public static double lerpInverse(double from, double to, double at) - { - return M.rangeScale(0, 1, from, to, at); - } + /** + * Get the percent (inverse lerp) from "from" to "to" where "at". + *

+ * If from = 0 and to = 100 and at = 25 then it would return 0.25 + * + * @param from the from + * @param to the to + * @param at the at + * @return the percent + */ + public static double lerpInverse(double from, double to, double at) { + return M.rangeScale(0, 1, from, to, at); + } - /** - * Linear interpolation from a to b where f is the percent across - * - * @param a - * the first pos (0) - * @param b - * the second pos (1) - * @param f - * the percent - * @return the value - */ - public static double lerp(double a, double b, double f) - { - return a + (f * (b - a)); - } + /** + * Linear interpolation from a to b where f is the percent across + * + * @param a the first pos (0) + * @param b the second pos (1) + * @param f the percent + * @return the value + */ + public static double lerp(double a, double b, double f) { + return a + (f * (b - a)); + } - /** - * Bilinear interpolation - * - * @param a - * the first point (0, 0) - * @param b - * the second point (1, 0) - * @param c - * the third point (0, 1) - * @param d - * the fourth point (1, 1) - * @param tx - * the x - * @param ty - * the y - * @return the bilerped value - */ - public static double bilerp(double a, double b, double c, double d, double x, double y) - { - return lerp(lerp(a, b, x), lerp(c, d, x), y); - } + /** + * Bilinear interpolation + * + * @param a the first point (0, 0) + * @param b the second point (1, 0) + * @param c the third point (0, 1) + * @param d the fourth point (1, 1) + * @param tx the x + * @param ty the y + * @return the bilerped value + */ + public static double bilerp(double a, double b, double c, double d, double x, double y) { + return lerp(lerp(a, b, x), lerp(c, d, x), y); + } - /** - * Trilinear interpolation - * - * @param a - * the first point (0, 0, 0) - * @param b - * the second point (1, 0, 0) - * @param c - * the third point (0, 0, 1) - * @param d - * the fourth point (1, 0, 1) - * @param e - * the fifth point (0, 1, 0) - * @param f - * the sixth point (1, 1, 0) - * @param g - * the seventh point (0, 1, 1) - * @param h - * the eighth point (1, 1, 1) - * @param x - * the x - * @param y - * the y - * @param z - * the z - * @return the trilerped value - */ - public static double trilerp(double a, double b, double c, double d, double e, double f, double g, double h, double x, double y, double z) - { - return lerp(bilerp(a, b, c, d, x, y), bilerp(e, f, g, h, x, y), z); - } + /** + * Trilinear interpolation + * + * @param a the first point (0, 0, 0) + * @param b the second point (1, 0, 0) + * @param c the third point (0, 0, 1) + * @param d the fourth point (1, 0, 1) + * @param e the fifth point (0, 1, 0) + * @param f the sixth point (1, 1, 0) + * @param g the seventh point (0, 1, 1) + * @param h the eighth point (1, 1, 1) + * @param x the x + * @param y the y + * @param z the z + * @return the trilerped value + */ + public static double trilerp(double a, double b, double c, double d, double e, double f, double g, double h, double x, double y, double z) { + return lerp(bilerp(a, b, c, d, x, y), bilerp(e, f, g, h, x, y), z); + } - /** - * Clip a value - * - * @param value - * the value - * @param min - * the min - * @param max - * the max - * @return the clipped value - */ - @SuppressWarnings("unchecked") - public static T clip(T value, T min, T max) - { - return (T) Double.valueOf(Math.min(max.doubleValue(), Math.max(min.doubleValue(), value.doubleValue()))); - } + /** + * Clip a value + * + * @param value the value + * @param min the min + * @param max the max + * @return the clipped value + */ + @SuppressWarnings("unchecked") + public static T clip(T value, T min, T max) { + return (T) Double.valueOf(Math.min(max.doubleValue(), Math.max(min.doubleValue(), value.doubleValue()))); + } - /** - * Get true or false based on random percent - * - * @param d - * between 0 and 1 - * @return true if true - */ - public static boolean r(Double d) - { - if(d == null) - { - return Math.random() < 0.5; - } + /** + * Get true or false based on random percent + * + * @param d between 0 and 1 + * @return true if true + */ + public static boolean r(Double d) { + if (d == null) { + return Math.random() < 0.5; + } - return Math.random() < d; - } + return Math.random() < d; + } - /** - * Get the ticks per second from a time in nanoseconds, the rad can be used for - * multiple ticks - * - * @param ns - * the time in nanoseconds - * @param rad - * the radius of the time - * @return the ticks per second in double form - */ - public static double tps(long ns, int rad) - { - return (20.0 * (ns / 50000000.0)) / rad; - } + /** + * Get the ticks per second from a time in nanoseconds, the rad can be used for + * multiple ticks + * + * @param ns the time in nanoseconds + * @param rad the radius of the time + * @return the ticks per second in double form + */ + public static double tps(long ns, int rad) { + return (20.0 * (ns / 50000000.0)) / rad; + } - /** - * Get the number of ticks from a time in nanoseconds - * - * @param ns - * the nanoseconds - * @return the amount of ticks - */ - public static double ticksFromNS(long ns) - { - return (ns / 50000000.0); - } + /** + * Get the number of ticks from a time in nanoseconds + * + * @param ns the nanoseconds + * @return the amount of ticks + */ + public static double ticksFromNS(long ns) { + return (ns / 50000000.0); + } - /** - * Get a random int from to (inclusive) - * - * @param f - * the from - * @param t - * the to - * @return the value - */ - public static int irand(int f, int t) - { - return f + (int) (Math.random() * ((t - f) + 1)); - } + /** + * Get a random int from to (inclusive) + * + * @param f the from + * @param t the to + * @return the value + */ + public static int irand(int f, int t) { + return f + (int) (Math.random() * ((t - f) + 1)); + } - /** - * Get a random float from to (inclusive) - * - * @param f - * the from - * @param t - * the to - * @return the value - */ - public static float frand(float f, float t) - { - return f + (float) (Math.random() * ((t - f) + 1)); - } + /** + * Get a random float from to (inclusive) + * + * @param f the from + * @param t the to + * @return the value + */ + public static float frand(float f, float t) { + return f + (float) (Math.random() * ((t - f) + 1)); + } - /** - * Get a random double from to (inclusive) - * - * @param f - * the from - * @param t - * the to - * @return the value - */ - public static double drand(double f, double t) - { - return f + (Math.random() * ((t - f) + 1)); - } + /** + * Get a random double from to (inclusive) + * + * @param f the from + * @param t the to + * @return the value + */ + public static double drand(double f, double t) { + return f + (Math.random() * ((t - f) + 1)); + } - /** - * Get system Nanoseconds - * - * @return nanoseconds (current) - */ - public static long ns() - { - return System.nanoTime(); - } + /** + * Get system Nanoseconds + * + * @return nanoseconds (current) + */ + public static long ns() { + return System.nanoTime(); + } - /** - * Get the current millisecond time - * - * @return milliseconds - */ - public static long ms() - { - return System.currentTimeMillis(); - } + /** + * Get the current millisecond time + * + * @return milliseconds + */ + public static long ms() { + return System.currentTimeMillis(); + } - /** - * Fast sin function - * - * @param a - * the number - * @return the sin - */ - public static float sin(float a) - { - return sinLookup((int) (a * precision + 0.5f)); - } + /** + * Fast sin function + * + * @param a the number + * @return the sin + */ + public static float sin(float a) { + return sinLookup((int) (a * precision + 0.5f)); + } - /** - * Fast cos function - * - * @param a - * the number - * @return the cos - */ - public static float cos(float a) - { - return sinLookup((int) ((a + 90f) * precision + 0.5f)); - } + /** + * Fast cos function + * + * @param a the number + * @return the cos + */ + public static float cos(float a) { + return sinLookup((int) ((a + 90f) * precision + 0.5f)); + } - /** - * Fast tan function - * - * @param a - * the number - * @return the tan - */ - public static float tan(float a) - { - float c = cos(a); - return sin(a) / (c == 0 ? 0.0000001f : c); - } + /** + * Fast tan function + * + * @param a the number + * @return the tan + */ + public static float tan(float a) { + float c = cos(a); + return sin(a) / (c == 0 ? 0.0000001f : c); + } - /** - * Biggest number - * - * @param numbers - * the numbers - * @return the biggest one - */ - @SuppressWarnings("unchecked") - public static T max(T... doubles) - { - double max = Double.MIN_VALUE; + /** + * Biggest number + * + * @param numbers the numbers + * @return the biggest one + */ + @SuppressWarnings("unchecked") + public static T max(T... doubles) { + double max = Double.MIN_VALUE; - for(T i : doubles) - { - if(i.doubleValue() > max) - { - max = i.doubleValue(); - } - } + for (T i : doubles) { + if (i.doubleValue() > max) { + max = i.doubleValue(); + } + } - return (T) Double.valueOf(max); - } + return (T) Double.valueOf(max); + } - /** - * Smallest number - * - * @param doubles - * the numbers - * @return the smallest one - */ - @SuppressWarnings("unchecked") - public static T min(T... doubles) - { - double min = Double.MAX_VALUE; + /** + * Smallest number + * + * @param doubles the numbers + * @return the smallest one + */ + @SuppressWarnings("unchecked") + public static T min(T... doubles) { + double min = Double.MAX_VALUE; - for(T i : doubles) - { - if(i.doubleValue() < min) - { - min = i.doubleValue(); - } - } + for (T i : doubles) { + if (i.doubleValue() < min) { + min = i.doubleValue(); + } + } - return (T) Double.valueOf(min); - } + return (T) Double.valueOf(min); + } - /** - * Evaluates an expression using javascript engine and returns the double - * result. This can take variable parameters, so you need to define them. - * Parameters are defined as $[0-9]. For example evaluate("4$0/$1", 1, 2); This - * makes the expression (4x1)/2 == 2. Keep note that you must use 0-9, you - * cannot skip, or start at a number other than 0. - * - * @param expression - * the expression with variables - * @param args - * the arguments/variables - * @return the resulting double value - * @throws ScriptException - * ... gg - * @throws IndexOutOfBoundsException - * learn to count - */ - public static double evaluate(String expression, Double... args) throws ScriptException, IndexOutOfBoundsException - { - for(int i = 0; i < args.length; i++) - { - String current = "$" + i; + /** + * Evaluates an expression using javascript engine and returns the double + * result. This can take variable parameters, so you need to define them. + * Parameters are defined as $[0-9]. For example evaluate("4$0/$1", 1, 2); This + * makes the expression (4x1)/2 == 2. Keep note that you must use 0-9, you + * cannot skip, or start at a number other than 0. + * + * @param expression the expression with variables + * @param args the arguments/variables + * @return the resulting double value + * @throws ScriptException ... gg + * @throws IndexOutOfBoundsException learn to count + */ + public static double evaluate(String expression, Double... args) throws ScriptException, IndexOutOfBoundsException { + for (int i = 0; i < args.length; i++) { + String current = "$" + i; - if(expression.contains(current)) - { - expression = expression.replaceAll(Matcher.quoteReplacement(current), args[i] + ""); - } - } + if (expression.contains(current)) { + expression = expression.replaceAll(Matcher.quoteReplacement(current), args[i] + ""); + } + } - return evaluate(expression); - } + return evaluate(expression); + } - /** - * Evaluates an expression using javascript engine and returns the double - * - * @param expression - * the mathimatical expression - * @return the double result - * @throws ScriptException - * ... gg - */ - public static double evaluate(String expression) throws ScriptException - { - ScriptEngineManager mgr = new ScriptEngineManager(); - ScriptEngine scriptEngine = mgr.getEngineByName("JavaScript"); + /** + * Evaluates an expression using javascript engine and returns the double + * + * @param expression the mathimatical expression + * @return the double result + * @throws ScriptException ... gg + */ + public static double evaluate(String expression) throws ScriptException { + ScriptEngineManager mgr = new ScriptEngineManager(); + ScriptEngine scriptEngine = mgr.getEngineByName("JavaScript"); - return Double.valueOf(scriptEngine.eval(expression).toString()); - } + return Double.valueOf(scriptEngine.eval(expression).toString()); + } - /** - * is the number "is" within from-to - * - * @param from - * the lower end - * @param to - * the upper end - * @param is - * the check - * @return true if its within - */ - public static boolean within(int from, int to, int is) - { - return is >= from && is <= to; - } + /** + * is the number "is" within from-to + * + * @param from the lower end + * @param to the upper end + * @param is the check + * @return true if its within + */ + public static boolean within(int from, int to, int is) { + return is >= from && is <= to; + } - /** - * Get the amount of days past since the epoch time (1970 jan 1 utc) - * - * @return the epoch days - */ - public static long epochDays() - { - return epochDays(M.ms()); - } + /** + * Get the amount of days past since the epoch time (1970 jan 1 utc) + * + * @return the epoch days + */ + public static long epochDays() { + return epochDays(M.ms()); + } - /** - * Get the amount of days past since the epoch time (1970 jan 1 utc) - * - * @param ms - * the time in milliseconds - * @return the epoch days - */ - private static long epochDays(long ms) - { - return ms / 1000 / 60 / 60 / 24; - } + /** + * Get the amount of days past since the epoch time (1970 jan 1 utc) + * + * @param ms the time in milliseconds + * @return the epoch days + */ + private static long epochDays(long ms) { + return ms / 1000 / 60 / 60 / 24; + } - static - { - for(int i = 0; i < sin.length; i++) - { - sin[i] = (float) Math.sin((i * Math.PI) / (precision * 180)); - } - } + static { + for (int i = 0; i < sin.length; i++) { + sin[i] = (float) Math.sin((i * Math.PI) / (precision * 180)); + } + } - private static float sinLookup(int a) - { - return a >= 0 ? sin[a % (modulus)] : -sin[-a % (modulus)]; - } + private static float sinLookup(int a) { + return a >= 0 ? sin[a % (modulus)] : -sin[-a % (modulus)]; + } - public static boolean interval(int tickInterval) - { - return tick % (tickInterval <= 0 ? 1 : tickInterval) == 0; - } + public static boolean interval(int tickInterval) { + return tick % (tickInterval <= 0 ? 1 : tickInterval) == 0; + } } diff --git a/src/main/java/com/volmit/iris/util/MaterialBlock.java b/src/main/java/com/volmit/iris/util/MaterialBlock.java index 8073ee868..f9712cec1 100644 --- a/src/main/java/com/volmit/iris/util/MaterialBlock.java +++ b/src/main/java/com/volmit/iris/util/MaterialBlock.java @@ -11,126 +11,98 @@ import org.bukkit.block.BlockState; * @author cyberpwn */ @SuppressWarnings("deprecation") -public class MaterialBlock -{ - private Material material; - private Byte data; +public class MaterialBlock { + private Material material; + private Byte data; - /** - * Create a materialblock - * - * @param material - * the material - * @param data - * the data - */ - public MaterialBlock(Material material, Byte data) - { - this.material = material; - this.data = data; - } + /** + * Create a materialblock + * + * @param material the material + * @param data the data + */ + public MaterialBlock(Material material, Byte data) { + this.material = material; + this.data = data; + } - public MaterialBlock(Material material) - { - this.material = material; - data = 0; - } + public MaterialBlock(Material material) { + this.material = material; + data = 0; + } - public MaterialBlock(Location location) - { - this(location.getBlock()); - } + public MaterialBlock(Location location) { + this(location.getBlock()); + } - public MaterialBlock(BlockState state) - { - material = state.getType(); - data = state.getData().getData(); - } + public MaterialBlock(BlockState state) { + material = state.getType(); + data = state.getData().getData(); + } - public MaterialBlock(Block block) - { - material = block.getType(); - data = block.getData(); - } + public MaterialBlock(Block block) { + material = block.getType(); + data = block.getData(); + } - public MaterialBlock() - { - material = Material.AIR; - data = 0; - } + public MaterialBlock() { + material = Material.AIR; + data = 0; + } - public Material getMaterial() - { - return material; - } + public Material getMaterial() { + return material; + } - public void setMaterial(Material material) - { - this.material = material; - } + public void setMaterial(Material material) { + this.material = material; + } - public Byte getData() - { - return data; - } + public Byte getData() { + return data; + } - public void setData(Byte data) - { - this.data = data; - } + public void setData(Byte data) { + this.data = data; + } - @Override - public String toString() - { - if(getData() == 0) - { - return getMaterial().toString(); - } + @Override + public String toString() { + if (getData() == 0) { + return getMaterial().toString(); + } - return getMaterial().toString() + ":" + getData(); - } + return getMaterial().toString() + ":" + getData(); + } - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + ((data == null) ? 0 : data.hashCode()); - result = prime * result + ((material == null) ? 0 : material.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((data == null) ? 0 : data.hashCode()); + result = prime * result + ((material == null) ? 0 : material.hashCode()); + return result; + } - @Override - public boolean equals(Object obj) - { - if(this == obj) - { - return true; - } - if(obj == null) - { - return false; - } - if(getClass() != obj.getClass()) - { - return false; - } - MaterialBlock other = (MaterialBlock) obj; - if(data == null) - { - if(other.data != null) - { - return false; - } - } - else if(!data.equals(other.data)) - { - return false; - } - if(material != other.material) - { - return false; - } - return true; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (getClass() != obj.getClass()) { + return false; + } + MaterialBlock other = (MaterialBlock) obj; + if (data == null) { + if (other.data != null) { + return false; + } + } else if (!data.equals(other.data)) { + return false; + } + return material == other.material; + } } diff --git a/src/main/java/com/volmit/iris/util/MathHelper.java b/src/main/java/com/volmit/iris/util/MathHelper.java index 4c6f0d7fb..d45dd2bfa 100644 --- a/src/main/java/com/volmit/iris/util/MathHelper.java +++ b/src/main/java/com/volmit/iris/util/MathHelper.java @@ -5,575 +5,472 @@ import java.util.UUID; import java.util.function.Consumer; import java.util.function.IntPredicate; -public class MathHelper -{ - public static final float a = MathHelper.c(2.0f); - private static final float[] b = (float[]) a((Object) new float[65536], var0 -> - { - for(int var1 = 0; var1 < ((float[]) var0).length; ++var1) - { - ((float[]) var0)[var1] = (float) Math.sin((double) var1 * 3.141592653589793 * 2.0 / 65536.0); - } - }); +public class MathHelper { + public static final float a = MathHelper.c(2.0f); + private static final float[] b = (float[]) a((Object) new float[65536], var0 -> + { + for (int var1 = 0; var1 < ((float[]) var0).length; ++var1) { + ((float[]) var0)[var1] = (float) Math.sin((double) var1 * 3.141592653589793 * 2.0 / 65536.0); + } + }); - public static T a(T var0, Consumer var1) - { - var1.accept(var0); - return var0; - } + public static T a(T var0, Consumer var1) { + var1.accept(var0); + return var0; + } - private static final Random c = new Random(); - private static final int[] d = new int[] {0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9}; - private static final double e = Double.longBitsToDouble(4805340802404319232L); - private static final double[] f = new double[257]; - private static final double[] g = new double[257]; + private static final Random c = new Random(); + private static final int[] d = new int[]{0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9}; + private static final double e = Double.longBitsToDouble(4805340802404319232L); + private static final double[] f = new double[257]; + private static final double[] g = new double[257]; - public static float sin(float var0) - { - return b[(int) (var0 * 10430.378f) & 65535]; - } + public static float sin(float var0) { + return b[(int) (var0 * 10430.378f) & 65535]; + } - public static float cos(float var0) - { - return b[(int) (var0 * 10430.378f + 16384.0f) & 65535]; - } + public static float cos(float var0) { + return b[(int) (var0 * 10430.378f + 16384.0f) & 65535]; + } - public static float c(float var0) - { - return (float) Math.sqrt(var0); - } + public static float c(float var0) { + return (float) Math.sqrt(var0); + } - public static float sqrt(double var0) - { - return (float) Math.sqrt(var0); - } + public static float sqrt(double var0) { + return (float) Math.sqrt(var0); + } - public static int d(float var0) - { - int var1 = (int) var0; - return var0 < (float) var1 ? var1 - 1 : var1; - } + public static int d(float var0) { + int var1 = (int) var0; + return var0 < (float) var1 ? var1 - 1 : var1; + } - public static int floor(double var0) - { - int var2 = (int) var0; - return var0 < (double) var2 ? var2 - 1 : var2; - } + public static int floor(double var0) { + int var2 = (int) var0; + return var0 < (double) var2 ? var2 - 1 : var2; + } - public static long d(double var0) - { - long var2 = (long) var0; - return var0 < (double) var2 ? var2 - 1L : var2; - } + public static long d(double var0) { + long var2 = (long) var0; + return var0 < (double) var2 ? var2 - 1L : var2; + } - public static float e(float var0) - { - return Math.abs(var0); - } + public static float e(float var0) { + return Math.abs(var0); + } - public static int a(int var0) - { - return Math.abs(var0); - } + public static int a(int var0) { + return Math.abs(var0); + } - public static int f(float var0) - { - int var1 = (int) var0; - return var0 > (float) var1 ? var1 + 1 : var1; - } + public static int f(float var0) { + int var1 = (int) var0; + return var0 > (float) var1 ? var1 + 1 : var1; + } - public static int f(double var0) - { - int var2 = (int) var0; - return var0 > (double) var2 ? var2 + 1 : var2; - } + public static int f(double var0) { + int var2 = (int) var0; + return var0 > (double) var2 ? var2 + 1 : var2; + } - public static int clamp(int var0, int var1, int var2) - { - if(var0 < var1) - { - return var1; - } - if(var0 > var2) - { - return var2; - } - return var0; - } + public static int clamp(int var0, int var1, int var2) { + if (var0 < var1) { + return var1; + } + if (var0 > var2) { + return var2; + } + return var0; + } - public static float a(float var0, float var1, float var2) - { - if(var0 < var1) - { - return var1; - } - if(var0 > var2) - { - return var2; - } - return var0; - } + public static float a(float var0, float var1, float var2) { + if (var0 < var1) { + return var1; + } + if (var0 > var2) { + return var2; + } + return var0; + } - public static double a(double var0, double var2, double var4) - { - if(var0 < var2) - { - return var2; - } - if(var0 > var4) - { - return var4; - } - return var0; - } + public static double a(double var0, double var2, double var4) { + if (var0 < var2) { + return var2; + } + if (var0 > var4) { + return var4; + } + return var0; + } - public static double b(double var0, double var2, double var4) - { - if(var4 < 0.0) - { - return var0; - } - if(var4 > 1.0) - { - return var2; - } - return MathHelper.d(var4, var0, var2); - } + public static double b(double var0, double var2, double var4) { + if (var4 < 0.0) { + return var0; + } + if (var4 > 1.0) { + return var2; + } + return MathHelper.d(var4, var0, var2); + } - public static double a(double var0, double var2) - { - if(var0 < 0.0) - { - var0 = -var0; - } - if(var2 < 0.0) - { - var2 = -var2; - } - return var0 > var2 ? var0 : var2; - } + public static double a(double var0, double var2) { + if (var0 < 0.0) { + var0 = -var0; + } + if (var2 < 0.0) { + var2 = -var2; + } + return var0 > var2 ? var0 : var2; + } - public static int a(int var0, int var1) - { - return Math.floorDiv(var0, var1); - } + public static int a(int var0, int var1) { + return Math.floorDiv(var0, var1); + } - public static int nextInt(Random var0, int var1, int var2) - { - if(var1 >= var2) - { - return var1; - } - return var0.nextInt(var2 - var1 + 1) + var1; - } + public static int nextInt(Random var0, int var1, int var2) { + if (var1 >= var2) { + return var1; + } + return var0.nextInt(var2 - var1 + 1) + var1; + } - public static float a(Random var0, float var1, float var2) - { - if(var1 >= var2) - { - return var1; - } - return var0.nextFloat() * (var2 - var1) + var1; - } + public static float a(Random var0, float var1, float var2) { + if (var1 >= var2) { + return var1; + } + return var0.nextFloat() * (var2 - var1) + var1; + } - public static double a(Random var0, double var1, double var3) - { - if(var1 >= var3) - { - return var1; - } - return var0.nextDouble() * (var3 - var1) + var1; - } + public static double a(Random var0, double var1, double var3) { + if (var1 >= var3) { + return var1; + } + return var0.nextDouble() * (var3 - var1) + var1; + } - public static double a(long[] var0) - { - long var1 = 0L; - for(long var6 : var0) - { - var1 += var6; - } - return (double) var1 / (double) var0.length; - } + public static double a(long[] var0) { + long var1 = 0L; + for (long var6 : var0) { + var1 += var6; + } + return (double) var1 / (double) var0.length; + } - public static boolean b(double var0, double var2) - { - return Math.abs(var2 - var0) < 9.999999747378752E-6; - } + public static boolean b(double var0, double var2) { + return Math.abs(var2 - var0) < 9.999999747378752E-6; + } - public static int b(int var0, int var1) - { - return Math.floorMod(var0, var1); - } + public static int b(int var0, int var1) { + return Math.floorMod(var0, var1); + } - public static float g(float var0) - { - float var1 = var0 % 360.0f; - if(var1 >= 180.0f) - { - var1 -= 360.0f; - } - if(var1 < -180.0f) - { - var1 += 360.0f; - } - return var1; - } + public static float g(float var0) { + float var1 = var0 % 360.0f; + if (var1 >= 180.0f) { + var1 -= 360.0f; + } + if (var1 < -180.0f) { + var1 += 360.0f; + } + return var1; + } - public static double g(double var0) - { - double var2 = var0 % 360.0; - if(var2 >= 180.0) - { - var2 -= 360.0; - } - if(var2 < -180.0) - { - var2 += 360.0; - } - return var2; - } + public static double g(double var0) { + double var2 = var0 % 360.0; + if (var2 >= 180.0) { + var2 -= 360.0; + } + if (var2 < -180.0) { + var2 += 360.0; + } + return var2; + } - public static float c(float var0, float var1) - { - return MathHelper.g(var1 - var0); - } + public static float c(float var0, float var1) { + return MathHelper.g(var1 - var0); + } - public static float d(float var0, float var1) - { - return MathHelper.e(MathHelper.c(var0, var1)); - } + public static float d(float var0, float var1) { + return MathHelper.e(MathHelper.c(var0, var1)); + } - public static float b(float var0, float var1, float var2) - { - float var3 = MathHelper.c(var0, var1); - float var4 = MathHelper.a(var3, -var2, var2); - return var1 - var4; - } + public static float b(float var0, float var1, float var2) { + float var3 = MathHelper.c(var0, var1); + float var4 = MathHelper.a(var3, -var2, var2); + return var1 - var4; + } - public static float c(float var0, float var1, float var2) - { - var2 = MathHelper.e(var2); - if(var0 < var1) - { - return MathHelper.a(var0 + var2, var0, var1); - } - return MathHelper.a(var0 - var2, var1, var0); - } + public static float c(float var0, float var1, float var2) { + var2 = MathHelper.e(var2); + if (var0 < var1) { + return MathHelper.a(var0 + var2, var0, var1); + } + return MathHelper.a(var0 - var2, var1, var0); + } - public static float d(float var0, float var1, float var2) - { - float var3 = MathHelper.c(var0, var1); - return MathHelper.c(var0, var0 + var3, var2); - } + public static float d(float var0, float var1, float var2) { + float var3 = MathHelper.c(var0, var1); + return MathHelper.c(var0, var0 + var3, var2); + } - public static int c(int var0) - { - int var1 = var0 - 1; - var1 |= var1 >> 1; - var1 |= var1 >> 2; - var1 |= var1 >> 4; - var1 |= var1 >> 8; - var1 |= var1 >> 16; - return var1 + 1; - } + public static int c(int var0) { + int var1 = var0 - 1; + var1 |= var1 >> 1; + var1 |= var1 >> 2; + var1 |= var1 >> 4; + var1 |= var1 >> 8; + var1 |= var1 >> 16; + return var1 + 1; + } - public static boolean d(int var0) - { - return var0 != 0 && (var0 & var0 - 1) == 0; - } + public static boolean d(int var0) { + return var0 != 0 && (var0 & var0 - 1) == 0; + } - public static int e(int var0) - { - var0 = MathHelper.d(var0) ? var0 : MathHelper.c(var0); - return d[(int) ((long) var0 * 125613361L >> 27) & 31]; - } + public static int e(int var0) { + var0 = MathHelper.d(var0) ? var0 : MathHelper.c(var0); + return d[(int) ((long) var0 * 125613361L >> 27) & 31]; + } - public static int f(int var0) - { - return MathHelper.e(var0) - (MathHelper.d(var0) ? 0 : 1); - } + public static int f(int var0) { + return MathHelper.e(var0) - (MathHelper.d(var0) ? 0 : 1); + } - public static int c(int var0, int var1) - { - int var2; - if(var1 == 0) - { - return 0; - } - if(var0 == 0) - { - return var1; - } - if(var0 < 0) - { - var1 *= -1; - } - if((var2 = var0 % var1) == 0) - { - return var0; - } - return var0 + var1 - var2; - } + public static int c(int var0, int var1) { + int var2; + if (var1 == 0) { + return 0; + } + if (var0 == 0) { + return var1; + } + if (var0 < 0) { + var1 *= -1; + } + if ((var2 = var0 % var1) == 0) { + return var0; + } + return var0 + var1 - var2; + } - public static float h(float var0) - { - return var0 - (float) MathHelper.d(var0); - } + public static float h(float var0) { + return var0 - (float) MathHelper.d(var0); + } - public static double h(double var0) - { - return var0 - (double) MathHelper.d(var0); - } + public static double h(double var0) { + return var0 - (double) MathHelper.d(var0); + } - public static long a(BlockPosition var0) - { - return c(var0.getX(), var0.getY(), var0.getZ()); - } + public static long a(BlockPosition var0) { + return c(var0.getX(), var0.getY(), var0.getZ()); + } - public static long c(int var0, int var1, int var2) - { - long var3 = (long) (var0 * 3129871) ^ (long) var2 * 116129781L ^ (long) var1; - var3 = var3 * var3 * 42317861L + var3 * 11L; - return var3 >> 16; - } + public static long c(int var0, int var1, int var2) { + long var3 = (long) (var0 * 3129871) ^ (long) var2 * 116129781L ^ (long) var1; + var3 = var3 * var3 * 42317861L + var3 * 11L; + return var3 >> 16; + } - public static UUID a(Random var0) - { - long var1 = var0.nextLong() & -61441L | 16384L; - long var3 = var0.nextLong() & 0x3FFFFFFFFFFFFFFFL | Long.MIN_VALUE; - return new UUID(var1, var3); - } + public static UUID a(Random var0) { + long var1 = var0.nextLong() & -61441L | 16384L; + long var3 = var0.nextLong() & 0x3FFFFFFFFFFFFFFFL | Long.MIN_VALUE; + return new UUID(var1, var3); + } - public static UUID a() - { - return MathHelper.a(c); - } + public static UUID a() { + return MathHelper.a(c); + } - public static double c(double var0, double var2, double var4) - { - return (var0 - var2) / (var4 - var2); - } + public static double c(double var0, double var2, double var4) { + return (var0 - var2) / (var4 - var2); + } - public static double d(double var0, double var2) - { - double var9; - boolean var6; - boolean var7; - boolean var8; - double var4 = var2 * var2 + var0 * var0; - if(Double.isNaN(var4)) - { - return Double.NaN; - } - @SuppressWarnings("unused") - boolean bl = var6 = var0 < 0.0; - if(var6) - { - var0 = -var0; - } - @SuppressWarnings("unused") - boolean bl2 = var7 = var2 < 0.0; - if(var7) - { - var2 = -var2; - } - @SuppressWarnings("unused") - boolean bl3 = var8 = var0 > var2; - if(var8) - { - var9 = var2; - var2 = var0; - var0 = var9; - } - var9 = MathHelper.i(var4); - double var11 = e + (var0 *= var9); - int var13 = (int) Double.doubleToRawLongBits(var11); - double var14 = f[var13]; - double var16 = g[var13]; - double var18 = var11 - e; - double var20 = var0 * var16 - (var2 *= var9) * var18; - double var22 = (6.0 + var20 * var20) * var20 * 0.16666666666666666; - double var24 = var14 + var22; - if(var8) - { - var24 = 1.5707963267948966 - var24; - } - if(var7) - { - var24 = 3.141592653589793 - var24; - } - if(var6) - { - var24 = -var24; - } - return var24; - } + public static double d(double var0, double var2) { + double var9; + boolean var6; + boolean var7; + boolean var8; + double var4 = var2 * var2 + var0 * var0; + if (Double.isNaN(var4)) { + return Double.NaN; + } + @SuppressWarnings("unused") + boolean bl = var6 = var0 < 0.0; + if (var6) { + var0 = -var0; + } + @SuppressWarnings("unused") + boolean bl2 = var7 = var2 < 0.0; + if (var7) { + var2 = -var2; + } + @SuppressWarnings("unused") + boolean bl3 = var8 = var0 > var2; + if (var8) { + var9 = var2; + var2 = var0; + var0 = var9; + } + var9 = MathHelper.i(var4); + double var11 = e + (var0 *= var9); + int var13 = (int) Double.doubleToRawLongBits(var11); + double var14 = f[var13]; + double var16 = g[var13]; + double var18 = var11 - e; + double var20 = var0 * var16 - (var2 *= var9) * var18; + double var22 = (6.0 + var20 * var20) * var20 * 0.16666666666666666; + double var24 = var14 + var22; + if (var8) { + var24 = 1.5707963267948966 - var24; + } + if (var7) { + var24 = 3.141592653589793 - var24; + } + if (var6) { + var24 = -var24; + } + return var24; + } - public static double i(double var0) - { - double var2 = 0.5 * var0; - long var4 = Double.doubleToRawLongBits(var0); - var4 = 6910469410427058090L - (var4 >> 1); - var0 = Double.longBitsToDouble(var4); - var0 *= 1.5 - var2 * var0 * var0; - return var0; - } + public static double i(double var0) { + double var2 = 0.5 * var0; + long var4 = Double.doubleToRawLongBits(var0); + var4 = 6910469410427058090L - (var4 >> 1); + var0 = Double.longBitsToDouble(var4); + var0 *= 1.5 - var2 * var0 * var0; + return var0; + } - public static int f(float var0, float var1, float var2) - { - float var9; - float var8; - float var10; - int var3 = (int) (var0 * 6.0f) % 6; - float var4 = var0 * 6.0f - (float) var3; - float var5 = var2 * (1.0f - var1); - float var6 = var2 * (1.0f - var4 * var1); - float var7 = var2 * (1.0f - (1.0f - var4) * var1); - switch(var3) - { - case 0: - { - var8 = var2; - var9 = var7; - var10 = var5; - break; - } - case 1: - { - var8 = var6; - var9 = var2; - var10 = var5; - break; - } - case 2: - { - var8 = var5; - var9 = var2; - var10 = var7; - break; - } - case 3: - { - var8 = var5; - var9 = var6; - var10 = var2; - break; - } - case 4: - { - var8 = var7; - var9 = var5; - var10 = var2; - break; - } - case 5: - { - var8 = var2; - var9 = var5; - var10 = var6; - break; - } - default: - { - throw new RuntimeException("Something went wrong when converting from HSV to RGB. Input was " + var0 + ", " + var1 + ", " + var2); - } - } - int var11 = MathHelper.clamp((int) (var8 * 255.0f), 0, 255); - int var12 = MathHelper.clamp((int) (var9 * 255.0f), 0, 255); - int var13 = MathHelper.clamp((int) (var10 * 255.0f), 0, 255); - return var11 << 16 | var12 << 8 | var13; - } + public static int f(float var0, float var1, float var2) { + float var9; + float var8; + float var10; + int var3 = (int) (var0 * 6.0f) % 6; + float var4 = var0 * 6.0f - (float) var3; + float var5 = var2 * (1.0f - var1); + float var6 = var2 * (1.0f - var4 * var1); + float var7 = var2 * (1.0f - (1.0f - var4) * var1); + switch (var3) { + case 0: { + var8 = var2; + var9 = var7; + var10 = var5; + break; + } + case 1: { + var8 = var6; + var9 = var2; + var10 = var5; + break; + } + case 2: { + var8 = var5; + var9 = var2; + var10 = var7; + break; + } + case 3: { + var8 = var5; + var9 = var6; + var10 = var2; + break; + } + case 4: { + var8 = var7; + var9 = var5; + var10 = var2; + break; + } + case 5: { + var8 = var2; + var9 = var5; + var10 = var6; + break; + } + default: { + throw new RuntimeException("Something went wrong when converting from HSV to RGB. Input was " + var0 + ", " + var1 + ", " + var2); + } + } + int var11 = MathHelper.clamp((int) (var8 * 255.0f), 0, 255); + int var12 = MathHelper.clamp((int) (var9 * 255.0f), 0, 255); + int var13 = MathHelper.clamp((int) (var10 * 255.0f), 0, 255); + return var11 << 16 | var12 << 8 | var13; + } - public static int g(int var0) - { - var0 ^= var0 >>> 16; - var0 *= -2048144789; - var0 ^= var0 >>> 13; - var0 *= -1028477387; - var0 ^= var0 >>> 16; - return var0; - } + public static int g(int var0) { + var0 ^= var0 >>> 16; + var0 *= -2048144789; + var0 ^= var0 >>> 13; + var0 *= -1028477387; + var0 ^= var0 >>> 16; + return var0; + } - public static int a(int var0, int var1, IntPredicate var2) - { - int var3 = var1 - var0; - while(var3 > 0) - { - int var4 = var3 / 2; - int var5 = var0 + var4; - if(var2.test(var5)) - { - var3 = var4; - continue; - } - var0 = var5 + 1; - var3 -= var4 + 1; - } - return var0; - } + public static int a(int var0, int var1, IntPredicate var2) { + int var3 = var1 - var0; + while (var3 > 0) { + int var4 = var3 / 2; + int var5 = var0 + var4; + if (var2.test(var5)) { + var3 = var4; + continue; + } + var0 = var5 + 1; + var3 -= var4 + 1; + } + return var0; + } - public static float g(float var0, float var1, float var2) - { - return var1 + var0 * (var2 - var1); - } + public static float g(float var0, float var1, float var2) { + return var1 + var0 * (var2 - var1); + } - public static double d(double var0, double var2, double var4) - { - return var2 + var0 * (var4 - var2); - } + public static double d(double var0, double var2, double var4) { + return var2 + var0 * (var4 - var2); + } - public static double a(double var0, double var2, double var4, double var6, double var8, double var10) - { - return MathHelper.d(var2, MathHelper.d(var0, var4, var6), MathHelper.d(var0, var8, var10)); - } + public static double a(double var0, double var2, double var4, double var6, double var8, double var10) { + return MathHelper.d(var2, MathHelper.d(var0, var4, var6), MathHelper.d(var0, var8, var10)); + } - public static double a(double var0, double var2, double var4, double var6, double var8, double var10, double var12, double var14, double var16, double var18, double var20) - { - return MathHelper.d(var4, MathHelper.a(var0, var2, var6, var8, var10, var12), MathHelper.a(var0, var2, var14, var16, var18, var20)); - } + public static double a(double var0, double var2, double var4, double var6, double var8, double var10, double var12, double var14, double var16, double var18, double var20) { + return MathHelper.d(var4, MathHelper.a(var0, var2, var6, var8, var10, var12), MathHelper.a(var0, var2, var14, var16, var18, var20)); + } - public static double j(double var0) - { - return var0 * var0 * var0 * (var0 * (var0 * 6.0 - 15.0) + 10.0); - } + public static double j(double var0) { + return var0 * var0 * var0 * (var0 * (var0 * 6.0 - 15.0) + 10.0); + } - public static int k(double var0) - { - if(var0 == 0.0) - { - return 0; - } - return var0 > 0.0 ? 1 : -1; - } + public static int k(double var0) { + if (var0 == 0.0) { + return 0; + } + return var0 > 0.0 ? 1 : -1; + } - @Deprecated - public static float j(float var0, float var1, float var2) - { - float var3; - for(var3 = var1 - var0; var3 < -180.0f; var3 += 360.0f) - { - } - while(var3 >= 180.0f) - { - var3 -= 360.0f; - } - return var0 + var2 * var3; - } + @Deprecated + public static float j(float var0, float var1, float var2) { + float var3; + for (var3 = var1 - var0; var3 < -180.0f; var3 += 360.0f) { + } + while (var3 >= 180.0f) { + var3 -= 360.0f; + } + return var0 + var2 * var3; + } - public static float k(float var0) - { - return var0 * var0; - } + public static float k(float var0) { + return var0 * var0; + } - static - { - for(int var02 = 0; var02 < 257; ++var02) - { - // TODO: WARNING HEIGHT - double var1 = (double) var02 / 256.0; - double var3 = Math.asin(var1); - MathHelper.g[var02] = Math.cos(var3); - MathHelper.f[var02] = var3; - } - } + static { + for (int var02 = 0; var02 < 257; ++var02) { + // TODO: WARNING HEIGHT + double var1 = (double) var02 / 256.0; + double var3 = Math.asin(var1); + MathHelper.g[var02] = Math.cos(var3); + MathHelper.f[var02] = var3; + } + } } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/MaxNumber.java b/src/main/java/com/volmit/iris/util/MaxNumber.java index 3ceaba917..55b35c8b1 100644 --- a/src/main/java/com/volmit/iris/util/MaxNumber.java +++ b/src/main/java/com/volmit/iris/util/MaxNumber.java @@ -1,14 +1,13 @@ package com.volmit.iris.util; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - 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(); +public @interface MaxNumber { + double value(); } diff --git a/src/main/java/com/volmit/iris/util/Metrics.java b/src/main/java/com/volmit/iris/util/Metrics.java index 6be177f51..011188570 100644 --- a/src/main/java/com/volmit/iris/util/Metrics.java +++ b/src/main/java/com/volmit/iris/util/Metrics.java @@ -51,7 +51,7 @@ public class Metrics { private static final String URL = "https://bStats.org/submitData/bukkit"; // Is bStats enabled on this server? - private boolean enabled; + private final boolean enabled; // Should failed requests be logged? private static boolean logFailedRequests; @@ -77,7 +77,7 @@ public class Metrics { /** * Class constructor. * - * @param plugin The plugin which stats should be submitted. + * @param plugin The plugin which stats should be submitted. * @param pluginId The id of the plugin. * It can be found at What is my plugin id? */ @@ -116,7 +116,8 @@ public class Metrics { ).copyDefaults(true); try { config.save(configFile); - } catch (IOException ignored) { } + } catch (IOException ignored) { + } } // Load the data @@ -134,7 +135,8 @@ public class Metrics { service.getField("B_STATS_VERSION"); // Our identifier :) found = true; // We aren't the first break; - } catch (NoSuchFieldException ignored) { } + } catch (NoSuchFieldException ignored) { + } } // Register our service Bukkit.getServicesManager().register(Metrics.class, this, plugin, ServicePriority.Normal); @@ -298,9 +300,11 @@ public class Metrics { } } } - } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { } + } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { + } } - } catch (NoSuchFieldException ignored) { } + } catch (NoSuchFieldException ignored) { + } } data.add("plugins", pluginData); @@ -323,7 +327,7 @@ public class Metrics { * Sends the data to the bStats server. * * @param plugin Any plugin. It's just used to get a logger instance. - * @param data The data to send. + * @param data The data to send. * @throws Exception If the request failed. */ private static void sendData(Plugin plugin, JsonObject data) throws Exception { @@ -440,7 +444,7 @@ public class Metrics { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public SimplePie(String chartId, Callable callable) { @@ -471,7 +475,7 @@ public class Metrics { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public AdvancedPie(String chartId, Callable> callable) { @@ -515,7 +519,7 @@ public class Metrics { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public DrilldownPie(String chartId, Callable>> callable) { @@ -564,7 +568,7 @@ public class Metrics { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public SingleLineChart(String chartId, Callable callable) { @@ -596,7 +600,7 @@ public class Metrics { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public MultiLineChart(String chartId, Callable> callable) { @@ -641,7 +645,7 @@ public class Metrics { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public SimpleBarChart(String chartId, Callable> callable) { @@ -679,7 +683,7 @@ public class Metrics { /** * Class constructor. * - * @param chartId The id of the chart. + * @param chartId The id of the chart. * @param callable The callable which is used to request the chart data. */ public AdvancedBarChart(String chartId, Callable> callable) { diff --git a/src/main/java/com/volmit/iris/util/MetricsLite.java b/src/main/java/com/volmit/iris/util/MetricsLite.java index 71ec9b5da..ae01d86ac 100644 --- a/src/main/java/com/volmit/iris/util/MetricsLite.java +++ b/src/main/java/com/volmit/iris/util/MetricsLite.java @@ -28,407 +28,342 @@ import java.util.zip.GZIPOutputStream; *

* Check out https://bStats.org/ to learn more about bStats! */ -public class MetricsLite -{ +public class MetricsLite { - static - { - // You can use the property to disable the check in your test environment - if(System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) - { - // Maven's Relocate is clever and changes strings, too. So we have to use this - // little "trick" ... :D - final String defaultPackage = new String(new byte[] {'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'}); - final String examplePackage = new String(new byte[] {'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); - // We want to make sure nobody just copy & pastes the example and use the wrong - // package names - if(MetricsLite.class.getPackage().getName().equals(defaultPackage) || MetricsLite.class.getPackage().getName().equals(examplePackage)) - { - throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); - } - } - } + static { + // You can use the property to disable the check in your test environment + if (System.getProperty("bstats.relocatecheck") == null || !System.getProperty("bstats.relocatecheck").equals("false")) { + // Maven's Relocate is clever and changes strings, too. So we have to use this + // little "trick" ... :D + final String defaultPackage = new String(new byte[]{'o', 'r', 'g', '.', 'b', 's', 't', 'a', 't', 's', '.', 'b', 'u', 'k', 'k', 'i', 't'}); + final String examplePackage = new String(new byte[]{'y', 'o', 'u', 'r', '.', 'p', 'a', 'c', 'k', 'a', 'g', 'e'}); + // We want to make sure nobody just copy & pastes the example and use the wrong + // package names + if (MetricsLite.class.getPackage().getName().equals(defaultPackage) || MetricsLite.class.getPackage().getName().equals(examplePackage)) { + throw new IllegalStateException("bStats Metrics class has not been relocated correctly!"); + } + } + } - // The version of this bStats class - public static final int B_STATS_VERSION = 1; + // The version of this bStats class + public static final int B_STATS_VERSION = 1; - // The url to which the data is sent - private static final String URL = "https://bStats.org/submitData/bukkit"; + // The url to which the data is sent + private static final String URL = "https://bStats.org/submitData/bukkit"; - // Is bStats enabled on this server? - private boolean enabled; + // Is bStats enabled on this server? + private final boolean enabled; - // Should failed requests be logged? - private static boolean logFailedRequests; + // Should failed requests be logged? + private static boolean logFailedRequests; - // Should the sent data be logged? - private static boolean logSentData; + // Should the sent data be logged? + private static boolean logSentData; - // Should the response text be logged? - private static boolean logResponseStatusText; + // Should the response text be logged? + private static boolean logResponseStatusText; - // The uuid of the server - private static String serverUUID; + // The uuid of the server + private static String serverUUID; - // The plugin - private final Plugin plugin; + // The plugin + private final Plugin plugin; - // The plugin id - private final int pluginId; + // The plugin id + private final int pluginId; - /** - * Class constructor. - * - * @param plugin - * The plugin which stats should be submitted. - * @param pluginId - * The id of the plugin. It can be found at - * What is my - * plugin id? - */ - public MetricsLite(Plugin plugin, int pluginId) - { - if(plugin == null) - { - throw new IllegalArgumentException("Plugin cannot be null!"); - } - this.plugin = plugin; - this.pluginId = pluginId; + /** + * Class constructor. + * + * @param plugin The plugin which stats should be submitted. + * @param pluginId The id of the plugin. It can be found at + * What is my + * plugin id? + */ + public MetricsLite(Plugin plugin, int pluginId) { + if (plugin == null) { + throw new IllegalArgumentException("Plugin cannot be null!"); + } + this.plugin = plugin; + this.pluginId = pluginId; - // Get the config file - File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); - File configFile = new File(bStatsFolder, "config.yml"); - YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); + // Get the config file + File bStatsFolder = new File(plugin.getDataFolder().getParentFile(), "bStats"); + File configFile = new File(bStatsFolder, "config.yml"); + YamlConfiguration config = YamlConfiguration.loadConfiguration(configFile); - // Check if the config file exists - if(!config.isSet("serverUuid")) - { + // Check if the config file exists + if (!config.isSet("serverUuid")) { - // Add default values - config.addDefault("enabled", true); - // Every server gets it's unique random id. - config.addDefault("serverUuid", UUID.randomUUID().toString()); - // Should failed request be logged? - config.addDefault("logFailedRequests", false); - // Should the sent data be logged? - config.addDefault("logSentData", false); - // Should the response text be logged? - config.addDefault("logResponseStatusText", false); + // Add default values + config.addDefault("enabled", true); + // Every server gets it's unique random id. + config.addDefault("serverUuid", UUID.randomUUID().toString()); + // Should failed request be logged? + config.addDefault("logFailedRequests", false); + // Should the sent data be logged? + config.addDefault("logSentData", false); + // Should the response text be logged? + config.addDefault("logResponseStatusText", false); - // Inform the server owners about bStats - config.options().header("bStats collects some data for plugin authors like how many servers are using their plugins.\n" + "To honor their work, you should not disable it.\n" + "This has nearly no effect on the server performance!\n" + "Check out https://bStats.org/ to learn more :)").copyDefaults(true); - try - { - config.save(configFile); - } - catch(IOException ignored) - { - } - } + // Inform the server owners about bStats + config.options().header("bStats collects some data for plugin authors like how many servers are using their plugins.\n" + "To honor their work, you should not disable it.\n" + "This has nearly no effect on the server performance!\n" + "Check out https://bStats.org/ to learn more :)").copyDefaults(true); + try { + config.save(configFile); + } catch (IOException ignored) { + } + } - // Load the data - serverUUID = config.getString("serverUuid"); - logFailedRequests = config.getBoolean("logFailedRequests", false); - enabled = config.getBoolean("enabled", true); - logSentData = config.getBoolean("logSentData", false); - logResponseStatusText = config.getBoolean("logResponseStatusText", false); - if(enabled) - { - boolean found = false; - // Search for all other bStats Metrics classes to see if we are the first one - for(Class service : Bukkit.getServicesManager().getKnownServices()) - { - try - { - service.getField("B_STATS_VERSION"); // Our identifier :) - found = true; // We aren't the first - break; - } - catch(NoSuchFieldException ignored) - { - } - } - // Register our service - Bukkit.getServicesManager().register(MetricsLite.class, this, plugin, ServicePriority.Normal); - if(!found) - { - // We are the first! - startSubmitting(); - } - } - } + // Load the data + serverUUID = config.getString("serverUuid"); + logFailedRequests = config.getBoolean("logFailedRequests", false); + enabled = config.getBoolean("enabled", true); + logSentData = config.getBoolean("logSentData", false); + logResponseStatusText = config.getBoolean("logResponseStatusText", false); + if (enabled) { + boolean found = false; + // Search for all other bStats Metrics classes to see if we are the first one + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) + found = true; // We aren't the first + break; + } catch (NoSuchFieldException ignored) { + } + } + // Register our service + Bukkit.getServicesManager().register(MetricsLite.class, this, plugin, ServicePriority.Normal); + if (!found) { + // We are the first! + startSubmitting(); + } + } + } - /** - * Checks if bStats is enabled. - * - * @return Whether bStats is enabled or not. - */ - public boolean isEnabled() - { - return enabled; - } + /** + * Checks if bStats is enabled. + * + * @return Whether bStats is enabled or not. + */ + public boolean isEnabled() { + return enabled; + } - /** - * Starts the Scheduler which submits our data every 30 minutes. - */ - private void startSubmitting() - { - final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags - timer.scheduleAtFixedRate(new TimerTask() - { - @Override - public void run() - { - if(!plugin.isEnabled()) - { // Plugin was disabled - timer.cancel(); - return; - } - // Nevertheless we want our code to run in the Bukkit main thread, so we have to - // use the Bukkit scheduler - // Don't be afraid! The connection to the bStats server is still async, only the - // stats collection is sync ;) - Bukkit.getScheduler().runTask(plugin, () -> submitData()); - } - }, 1000 * 60 * 5, 1000 * 60 * 30); - // Submit the data every 30 minutes, first time after 5 minutes to give other - // plugins enough time to start - // WARNING: Changing the frequency has no effect but your plugin WILL be - // blocked/deleted! - // WARNING: Just don't do it! - } + /** + * Starts the Scheduler which submits our data every 30 minutes. + */ + private void startSubmitting() { + final Timer timer = new Timer(true); // We use a timer cause the Bukkit scheduler is affected by server lags + timer.scheduleAtFixedRate(new TimerTask() { + @Override + public void run() { + if (!plugin.isEnabled()) { // Plugin was disabled + timer.cancel(); + return; + } + // Nevertheless we want our code to run in the Bukkit main thread, so we have to + // use the Bukkit scheduler + // Don't be afraid! The connection to the bStats server is still async, only the + // stats collection is sync ;) + Bukkit.getScheduler().runTask(plugin, () -> submitData()); + } + }, 1000 * 60 * 5, 1000 * 60 * 30); + // Submit the data every 30 minutes, first time after 5 minutes to give other + // plugins enough time to start + // WARNING: Changing the frequency has no effect but your plugin WILL be + // blocked/deleted! + // WARNING: Just don't do it! + } - /** - * Gets the plugin specific data. This method is called using Reflection. - * - * @return The plugin specific data. - */ - public JsonObject getPluginData() - { - JsonObject data = new JsonObject(); + /** + * Gets the plugin specific data. This method is called using Reflection. + * + * @return The plugin specific data. + */ + public JsonObject getPluginData() { + JsonObject data = new JsonObject(); - String pluginName = plugin.getDescription().getName(); - String pluginVersion = plugin.getDescription().getVersion(); + String pluginName = plugin.getDescription().getName(); + String pluginVersion = plugin.getDescription().getVersion(); - data.addProperty("pluginName", pluginName); // Append the name of the plugin - data.addProperty("id", pluginId); // Append the id of the plugin - data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin - data.add("customCharts", new JsonArray()); + data.addProperty("pluginName", pluginName); // Append the name of the plugin + data.addProperty("id", pluginId); // Append the id of the plugin + data.addProperty("pluginVersion", pluginVersion); // Append the version of the plugin + data.add("customCharts", new JsonArray()); - return data; - } + return data; + } - /** - * Gets the server specific data. - * - * @return The server specific data. - */ - private JsonObject getServerData() - { - // Minecraft specific data - int playerAmount; - try - { - // Around MC 1.8 the return type was changed to a collection from an array, - // This fixes java.lang.NoSuchMethodError: - // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; - Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); - playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; - } - catch(Exception e) - { - playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed - } - int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; - String bukkitVersion = Bukkit.getVersion(); - String bukkitName = Bukkit.getName(); + /** + * Gets the server specific data. + * + * @return The server specific data. + */ + private JsonObject getServerData() { + // Minecraft specific data + int playerAmount; + try { + // Around MC 1.8 the return type was changed to a collection from an array, + // This fixes java.lang.NoSuchMethodError: + // org.bukkit.Bukkit.getOnlinePlayers()Ljava/util/Collection; + Method onlinePlayersMethod = Class.forName("org.bukkit.Server").getMethod("getOnlinePlayers"); + playerAmount = onlinePlayersMethod.getReturnType().equals(Collection.class) ? ((Collection) onlinePlayersMethod.invoke(Bukkit.getServer())).size() : ((Player[]) onlinePlayersMethod.invoke(Bukkit.getServer())).length; + } catch (Exception e) { + playerAmount = Bukkit.getOnlinePlayers().size(); // Just use the new method if the Reflection failed + } + int onlineMode = Bukkit.getOnlineMode() ? 1 : 0; + String bukkitVersion = Bukkit.getVersion(); + String bukkitName = Bukkit.getName(); - // OS/Java specific data - String javaVersion = System.getProperty("java.version"); - String osName = System.getProperty("os.name"); - String osArch = System.getProperty("os.arch"); - String osVersion = System.getProperty("os.version"); - int coreCount = Runtime.getRuntime().availableProcessors(); + // OS/Java specific data + String javaVersion = System.getProperty("java.version"); + String osName = System.getProperty("os.name"); + String osArch = System.getProperty("os.arch"); + String osVersion = System.getProperty("os.version"); + int coreCount = Runtime.getRuntime().availableProcessors(); - JsonObject data = new JsonObject(); + JsonObject data = new JsonObject(); - data.addProperty("serverUUID", serverUUID); + data.addProperty("serverUUID", serverUUID); - data.addProperty("playerAmount", playerAmount); - data.addProperty("onlineMode", onlineMode); - data.addProperty("bukkitVersion", bukkitVersion); - data.addProperty("bukkitName", bukkitName); + data.addProperty("playerAmount", playerAmount); + data.addProperty("onlineMode", onlineMode); + data.addProperty("bukkitVersion", bukkitVersion); + data.addProperty("bukkitName", bukkitName); - data.addProperty("javaVersion", javaVersion); - data.addProperty("osName", osName); - data.addProperty("osArch", osArch); - data.addProperty("osVersion", osVersion); - data.addProperty("coreCount", coreCount); + data.addProperty("javaVersion", javaVersion); + data.addProperty("osName", osName); + data.addProperty("osArch", osArch); + data.addProperty("osVersion", osVersion); + data.addProperty("coreCount", coreCount); - return data; - } + return data; + } - /** - * Collects the data and sends it afterwards. - */ - private void submitData() - { - final JsonObject data = getServerData(); + /** + * Collects the data and sends it afterwards. + */ + private void submitData() { + final JsonObject data = getServerData(); - JsonArray pluginData = new JsonArray(); - // Search for all other bStats Metrics classes to get their plugin data - for(Class service : Bukkit.getServicesManager().getKnownServices()) - { - try - { - service.getField("B_STATS_VERSION"); // Our identifier :) + JsonArray pluginData = new JsonArray(); + // Search for all other bStats Metrics classes to get their plugin data + for (Class service : Bukkit.getServicesManager().getKnownServices()) { + try { + service.getField("B_STATS_VERSION"); // Our identifier :) - for(RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) - { - try - { - Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider()); - if(plugin instanceof JsonObject) - { - pluginData.add((JsonObject) plugin); - } - else - { // old bstats version compatibility - try - { - Class jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject"); - if(plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) - { - Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString"); - jsonStringGetter.setAccessible(true); - String jsonString = (String) jsonStringGetter.invoke(plugin); - JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject(); - pluginData.add(object); - } - } - catch(ClassNotFoundException e) - { - // minecraft version 1.14+ - if(logFailedRequests) - { - this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception ", e); - } - } - } - } - catch(NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) - { - } - } - } - catch(NoSuchFieldException ignored) - { - } - } + for (RegisteredServiceProvider provider : Bukkit.getServicesManager().getRegistrations(service)) { + try { + Object plugin = provider.getService().getMethod("getPluginData").invoke(provider.getProvider()); + if (plugin instanceof JsonObject) { + pluginData.add((JsonObject) plugin); + } else { // old bstats version compatibility + try { + Class jsonObjectJsonSimple = Class.forName("org.json.simple.JSONObject"); + if (plugin.getClass().isAssignableFrom(jsonObjectJsonSimple)) { + Method jsonStringGetter = jsonObjectJsonSimple.getDeclaredMethod("toJSONString"); + jsonStringGetter.setAccessible(true); + String jsonString = (String) jsonStringGetter.invoke(plugin); + JsonObject object = new JsonParser().parse(jsonString).getAsJsonObject(); + pluginData.add(object); + } + } catch (ClassNotFoundException e) { + // minecraft version 1.14+ + if (logFailedRequests) { + this.plugin.getLogger().log(Level.SEVERE, "Encountered unexpected exception ", e); + } + } + } + } catch (NullPointerException | NoSuchMethodException | IllegalAccessException | InvocationTargetException ignored) { + } + } + } catch (NoSuchFieldException ignored) { + } + } - data.add("plugins", pluginData); + data.add("plugins", pluginData); - // Create a new thread for the connection to the bStats server - new Thread(() -> - { - try - { - // Send the data - sendData(plugin, data); - } - catch(Exception e) - { - // Something went wrong! :( - if(logFailedRequests) - { - plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); - } - } - }).start(); - } + // Create a new thread for the connection to the bStats server + new Thread(() -> + { + try { + // Send the data + sendData(plugin, data); + } catch (Exception e) { + // Something went wrong! :( + if (logFailedRequests) { + plugin.getLogger().log(Level.WARNING, "Could not submit plugin stats of " + plugin.getName(), e); + } + } + }).start(); + } - /** - * Sends the data to the bStats server. - * - * @param plugin - * Any plugin. It's just used to get a logger instance. - * @param data - * The data to send. - * @throws Exception - * If the request failed. - */ - private static void sendData(Plugin plugin, JsonObject data) throws Exception - { - if(data == null) - { - throw new IllegalArgumentException("Data cannot be null!"); - } - if(Bukkit.isPrimaryThread()) - { - throw new IllegalAccessException("This method must not be called from the main thread!"); - } - if(logSentData) - { - plugin.getLogger().info("Sending data to bStats: " + data); - } - HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); + /** + * Sends the data to the bStats server. + * + * @param plugin Any plugin. It's just used to get a logger instance. + * @param data The data to send. + * @throws Exception If the request failed. + */ + private static void sendData(Plugin plugin, JsonObject data) throws Exception { + if (data == null) { + throw new IllegalArgumentException("Data cannot be null!"); + } + if (Bukkit.isPrimaryThread()) { + throw new IllegalAccessException("This method must not be called from the main thread!"); + } + if (logSentData) { + plugin.getLogger().info("Sending data to bStats: " + data); + } + HttpsURLConnection connection = (HttpsURLConnection) new URL(URL).openConnection(); - // Compress the data to save bandwidth - byte[] compressedData = compress(data.toString()); + // Compress the data to save bandwidth + byte[] compressedData = compress(data.toString()); - // Add headers - connection.setRequestMethod("POST"); - connection.addRequestProperty("Accept", "application/json"); - connection.addRequestProperty("Connection", "close"); - connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request - connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); - connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format - connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); + // Add headers + connection.setRequestMethod("POST"); + connection.addRequestProperty("Accept", "application/json"); + connection.addRequestProperty("Connection", "close"); + connection.addRequestProperty("Content-Encoding", "gzip"); // We gzip our request + connection.addRequestProperty("Content-Length", String.valueOf(compressedData.length)); + connection.setRequestProperty("Content-Type", "application/json"); // We send our data in JSON format + connection.setRequestProperty("User-Agent", "MC-Server/" + B_STATS_VERSION); - // Send data - connection.setDoOutput(true); - try(DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) - { - outputStream.write(compressedData); - } + // Send data + connection.setDoOutput(true); + try (DataOutputStream outputStream = new DataOutputStream(connection.getOutputStream())) { + outputStream.write(compressedData); + } - StringBuilder builder = new StringBuilder(); - try(BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) - { - String line; - while((line = bufferedReader.readLine()) != null) - { - builder.append(line); - } - } + StringBuilder builder = new StringBuilder(); + try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) { + String line; + while ((line = bufferedReader.readLine()) != null) { + builder.append(line); + } + } - if(logResponseStatusText) - { - plugin.getLogger().info("Sent data to bStats and received response: " + builder); - } - } + if (logResponseStatusText) { + plugin.getLogger().info("Sent data to bStats and received response: " + builder); + } + } - /** - * Gzips the given String. - * - * @param str - * The string to gzip. - * @return The gzipped String. - * @throws IOException - * If the compression failed. - */ - private static byte[] compress(final String str) throws IOException - { - if(str == null) - { - return null; - } - ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); - try(GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) - { - gzip.write(str.getBytes(StandardCharsets.UTF_8)); - } - return outputStream.toByteArray(); - } + /** + * Gzips the given String. + * + * @param str The string to gzip. + * @return The gzipped String. + * @throws IOException If the compression failed. + */ + private static byte[] compress(final String str) throws IOException { + if (str == null) { + return null; + } + ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); + try (GZIPOutputStream gzip = new GZIPOutputStream(outputStream)) { + gzip.write(str.getBytes(StandardCharsets.UTF_8)); + } + return outputStream.toByteArray(); + } } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/MinNumber.java b/src/main/java/com/volmit/iris/util/MinNumber.java index 674117302..15877b1ec 100644 --- a/src/main/java/com/volmit/iris/util/MinNumber.java +++ b/src/main/java/com/volmit/iris/util/MinNumber.java @@ -1,14 +1,13 @@ package com.volmit.iris.util; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - 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(); +public @interface MinNumber { + double value(); } diff --git a/src/main/java/com/volmit/iris/util/MortarCommand.java b/src/main/java/com/volmit/iris/util/MortarCommand.java index 05532465b..fa856e749 100644 --- a/src/main/java/com/volmit/iris/util/MortarCommand.java +++ b/src/main/java/com/volmit/iris/util/MortarCommand.java @@ -10,231 +10,185 @@ import java.lang.reflect.InvocationTargetException; * Represents a pawn command * * @author cyberpwn - * */ -public abstract class MortarCommand implements ICommand -{ - private KList children; - private KList nodes; - private KList requiredPermissions; - private String node; - private String category; - private String description; +public abstract class MortarCommand implements ICommand { + private final KList children; + private final KList nodes; + private final KList requiredPermissions; + private final String node; + private String category; + private String description; - /** - * Override this with a super constructor as most commands shouldn't change - * these parameters - * - * @param node - * the node (primary node) i.e. volume - * @param nodes - * the aliases. i.e. v, vol, bile - */ - public MortarCommand(String node, String... nodes) - { - category = ""; - this.node = node; - this.nodes = new KList(nodes); - requiredPermissions = new KList<>(); - children = buildChildren(); - description = "No Description"; - } + /** + * Override this with a super constructor as most commands shouldn't change + * these parameters + * + * @param node the node (primary node) i.e. volume + * @param nodes the aliases. i.e. v, vol, bile + */ + public MortarCommand(String node, String... nodes) { + category = ""; + this.node = node; + this.nodes = new KList(nodes); + requiredPermissions = new KList<>(); + children = buildChildren(); + description = "No Description"; + } - @Override - public KList handleTab(MortarSender sender, String[] args) - { - KList v = new KList<>(); - if(args.length == 0) - { - for(MortarCommand i : getChildren()) - { - v.add(i.getNode()); - } - } + @Override + public KList handleTab(MortarSender sender, String[] args) { + KList v = new KList<>(); + if (args.length == 0) { + for (MortarCommand i : getChildren()) { + v.add(i.getNode()); + } + } - addTabOptions(sender, args, v); + addTabOptions(sender, args, v); - if(v.isEmpty()) - { - return null; - } + if (v.isEmpty()) { + return null; + } - if(sender.isPlayer() && IrisSettings.get().getGeneral().isCommandSounds()) - { - sender.player().getWorld().playSound(sender.player().getLocation(), Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 0.25f, 1.7f); - } + if (sender.isPlayer() && IrisSettings.get().getGeneral().isCommandSounds()) { + sender.player().getWorld().playSound(sender.player().getLocation(), Sound.ENTITY_ITEM_FRAME_ROTATE_ITEM, 0.25f, 1.7f); + } - return v; - } + return v; + } - public abstract void addTabOptions(MortarSender sender, String[] args, KList list); + public abstract void addTabOptions(MortarSender sender, String[] args, KList list); - public void printHelp(MortarSender sender) - { - boolean b = false; + public void printHelp(MortarSender sender) { + boolean b = false; - for(MortarCommand i : getChildren()) - { - for(String j : i.getRequiredPermissions()) - { - if(!sender.hasPermission(j)) - { - continue; - } - } + for (MortarCommand i : getChildren()) { + for (String j : i.getRequiredPermissions()) { + if (!sender.hasPermission(j)) { + continue; + } + } - b = true; + b = true; - sender.sendMessage(C.GREEN + i.getNode() + " " + C.WHITE + i.getArgsUsage() + C.GRAY + " - " + i.getDescription()); - } + sender.sendMessage(C.GREEN + i.getNode() + " " + C.WHITE + i.getArgsUsage() + C.GRAY + " - " + i.getDescription()); + } - if(!b) - { - sender.sendMessage("There are either no sub-commands or you do not have permission to use them."); - } + if (!b) { + sender.sendMessage("There are either no sub-commands or you do not have permission to use them."); + } - if(sender.isPlayer() && IrisSettings.get().getGeneral().isCommandSounds()) - { - sender.player().getWorld().playSound(sender.player().getLocation(), Sound.ITEM_BOOK_PAGE_TURN, 0.28f, 1.4f); - sender.player().getWorld().playSound(sender.player().getLocation(), Sound.ITEM_AXE_STRIP, 0.35f, 1.7f); - } - } + if (sender.isPlayer() && IrisSettings.get().getGeneral().isCommandSounds()) { + sender.player().getWorld().playSound(sender.player().getLocation(), Sound.ITEM_BOOK_PAGE_TURN, 0.28f, 1.4f); + sender.player().getWorld().playSound(sender.player().getLocation(), Sound.ITEM_AXE_STRIP, 0.35f, 1.7f); + } + } - protected abstract String getArgsUsage(); + protected abstract String getArgsUsage(); - public String getDescription() - { - return description; - } + public String getDescription() { + return description; + } - protected void setDescription(String description) - { - this.description = description; - } + protected void setDescription(String description) { + this.description = description; + } - protected void requiresPermission(MortarPermission node) - { - if(node == null) - { - return; - } + protected void requiresPermission(MortarPermission node) { + if (node == null) { + return; + } - requiresPermission(node.toString()); - } + requiresPermission(node.toString()); + } - protected void requiresPermission(String node) - { - if(node == null) - { - return; - } + protected void requiresPermission(String node) { + if (node == null) { + return; + } - requiredPermissions.add(node); - } + requiredPermissions.add(node); + } - public void rejectAny(int past, MortarSender sender, String[] a) - { - if(a.length > past) - { - int p = past; + public void rejectAny(int past, MortarSender sender, String[] a) { + if (a.length > past) { + int p = past; - String m = ""; + String m = ""; - for(String i : a) - { - p--; - if(p < 0) - { - m += i + ", "; - } - } + for (String i : a) { + p--; + if (p < 0) { + m += i + ", "; + } + } - if(!m.trim().isEmpty()) - { - sender.sendMessage("Parameters Ignored: " + m); - } - } - } + if (!m.trim().isEmpty()) { + sender.sendMessage("Parameters Ignored: " + m); + } + } + } - @Override - public String getNode() - { - return node; - } + @Override + public String getNode() { + return node; + } - @Override - public KList getNodes() - { - return nodes; - } + @Override + public KList getNodes() { + return nodes; + } - @Override - public KList getAllNodes() - { - return getNodes().copy().qadd(getNode()); - } + @Override + public KList getAllNodes() { + return getNodes().copy().qadd(getNode()); + } - @Override - public void addNode(String node) - { - getNodes().add(node); - } + @Override + public void addNode(String node) { + getNodes().add(node); + } - public KList getChildren() - { - return children; - } + public KList getChildren() { + return children; + } - private KList buildChildren() - { - KList p = new KList<>(); + private KList buildChildren() { + KList p = new KList<>(); - for(Field i : getClass().getDeclaredFields()) - { - if(i.isAnnotationPresent(Command.class)) - { - try - { - i.setAccessible(true); - MortarCommand pc = (MortarCommand) i.getType().getConstructor().newInstance(); - Command c = i.getAnnotation(Command.class); + for (Field i : getClass().getDeclaredFields()) { + if (i.isAnnotationPresent(Command.class)) { + try { + i.setAccessible(true); + MortarCommand pc = (MortarCommand) i.getType().getConstructor().newInstance(); + Command c = i.getAnnotation(Command.class); - if(!c.value().trim().isEmpty()) - { - pc.setCategory(c.value().trim()); - } + if (!c.value().trim().isEmpty()) { + pc.setCategory(c.value().trim()); + } else { + pc.setCategory(getCategory()); + } - else - { - pc.setCategory(getCategory()); - } + p.add(pc); + } catch (IllegalArgumentException | IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException | SecurityException e) { + e.printStackTrace(); + } + } + } - p.add(pc); - } + return p; + } - catch(IllegalArgumentException | IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException | SecurityException e) - { - e.printStackTrace(); - } - } - } + @Override + public KList getRequiredPermissions() { + return requiredPermissions; + } - return p; - } + public String getCategory() { + return category; + } - @Override - public KList getRequiredPermissions() - { - return requiredPermissions; - } - - public String getCategory() - { - return category; - } - - public void setCategory(String category) - { - this.category = category; - } + public void setCategory(String category) { + this.category = category; + } } diff --git a/src/main/java/com/volmit/iris/util/MortarPermission.java b/src/main/java/com/volmit/iris/util/MortarPermission.java index b774a6401..934b6e36a 100644 --- a/src/main/java/com/volmit/iris/util/MortarPermission.java +++ b/src/main/java/com/volmit/iris/util/MortarPermission.java @@ -1,98 +1,76 @@ package com.volmit.iris.util; +import org.bukkit.command.CommandSender; + import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; -import org.bukkit.command.CommandSender; +public abstract class MortarPermission { + private MortarPermission parent; -public abstract class MortarPermission -{ - private MortarPermission parent; + public MortarPermission() { + for (Field i : getClass().getDeclaredFields()) { + if (i.isAnnotationPresent(Permission.class)) { + try { + MortarPermission px = (MortarPermission) i.getType().getConstructor().newInstance(); + px.setParent(this); + i.set(Modifier.isStatic(i.getModifiers()) ? null : this, px); + } catch (IllegalArgumentException | IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException | SecurityException e) { + e.printStackTrace(); + } + } + } + } - public MortarPermission() - { - for(Field i : getClass().getDeclaredFields()) - { - if(i.isAnnotationPresent(Permission.class)) - { - try - { - MortarPermission px = (MortarPermission) i.getType().getConstructor().newInstance(); - px.setParent(this); - i.set(Modifier.isStatic(i.getModifiers()) ? null : this, px); - } + public KList getChildren() { + KList p = new KList<>(); - catch(IllegalArgumentException | IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException | SecurityException e) - { - e.printStackTrace(); - } - } - } - } + for (Field i : getClass().getDeclaredFields()) { + if (i.isAnnotationPresent(Permission.class)) { + try { + p.add((MortarPermission) i.get(Modifier.isStatic(i.getModifiers()) ? null : this)); + } catch (IllegalArgumentException | IllegalAccessException | SecurityException e) { + e.printStackTrace(); + } + } + } - public KList getChildren() - { - KList p = new KList<>(); + return p; + } - for(Field i : getClass().getDeclaredFields()) - { - if(i.isAnnotationPresent(Permission.class)) - { - try - { - p.add((MortarPermission) i.get(Modifier.isStatic(i.getModifiers()) ? null : this)); - } + public String getFullNode() { + if (hasParent()) { + return getParent().getFullNode() + "." + getNode(); + } - catch(IllegalArgumentException | IllegalAccessException | SecurityException e) - { - e.printStackTrace(); - } - } - } + return getNode(); + } - return p; - } + protected abstract String getNode(); - public String getFullNode() - { - if(hasParent()) - { - return getParent().getFullNode() + "." + getNode(); - } + public abstract String getDescription(); - return getNode(); - } + public abstract boolean isDefault(); - protected abstract String getNode(); + @Override + public String toString() { + return getFullNode(); + } - public abstract String getDescription(); + public boolean hasParent() { + return getParent() != null; + } - public abstract boolean isDefault(); + public MortarPermission getParent() { + return parent; + } - @Override - public String toString() - { - return getFullNode(); - } + public void setParent(MortarPermission parent) { + this.parent = parent; + } - public boolean hasParent() - { - return getParent() != null; - } - - public MortarPermission getParent() - { - return parent; - } - - public void setParent(MortarPermission parent) - { - this.parent = parent; - } - - public boolean has(CommandSender sender) - { - return sender.hasPermission(getFullNode()); - } + public boolean has(CommandSender sender) { + return sender.hasPermission(getFullNode()); + } } diff --git a/src/main/java/com/volmit/iris/util/MortarSender.java b/src/main/java/com/volmit/iris/util/MortarSender.java index 76ed8ae1a..25ff933a8 100644 --- a/src/main/java/com/volmit/iris/util/MortarSender.java +++ b/src/main/java/com/volmit/iris/util/MortarSender.java @@ -1,8 +1,7 @@ package com.volmit.iris.util; -import java.util.Set; -import java.util.UUID; - +import lombok.Getter; +import lombok.Setter; import org.bukkit.Server; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -10,217 +9,187 @@ import org.bukkit.permissions.Permission; import org.bukkit.permissions.PermissionAttachment; import org.bukkit.permissions.PermissionAttachmentInfo; import org.bukkit.plugin.Plugin; - -import lombok.Getter; -import lombok.Setter; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; +import java.util.Set; +import java.util.UUID; + /** * Represents a volume sender. A command sender with extra crap in it * * @author cyberpwn - * */ -public class MortarSender implements CommandSender -{ - private CommandSender s; - private String tag; +public class MortarSender implements CommandSender { + private final CommandSender s; + private String tag; - @Getter - @Setter - private String command; + @Getter + @Setter + private String command; - /** - * Wrap a command sender - * - * @param s - * the command sender - */ - public MortarSender(CommandSender s) - { - tag = ""; - this.s = s; - } + /** + * Wrap a command sender + * + * @param s the command sender + */ + public MortarSender(CommandSender s) { + tag = ""; + this.s = s; + } - public MortarSender(CommandSender s, String tag) - { - this.tag = tag; - this.s = s; - } + public MortarSender(CommandSender s, String tag) { + this.tag = tag; + this.s = s; + } - /** - * Set a command tag (prefix for sendMessage) - * - * @param tag - * the tag - */ - public void setTag(String tag) - { - this.tag = tag; - } + /** + * Set a command tag (prefix for sendMessage) + * + * @param tag the tag + */ + public void setTag(String tag) { + this.tag = tag; + } - /** - * Get the command tag - * - * @return the command tag - */ - public String getTag() - { - return tag; - } + /** + * Get the command tag + * + * @return the command tag + */ + public String getTag() { + return tag; + } - /** - * Is this sender a player? - * - * @return true if it is - */ - public boolean isPlayer() - { - return getS() instanceof Player; - } + /** + * Is this sender a player? + * + * @return true if it is + */ + public boolean isPlayer() { + return getS() instanceof Player; + } - /** - * Force cast to player (be sure to check first) - * - * @return a casted player - */ - public Player player() - { - return (Player) getS(); - } + /** + * Force cast to player (be sure to check first) + * + * @return a casted player + */ + public Player player() { + return (Player) getS(); + } - /** - * Get the origin sender this object is wrapping - * - * @return the command sender - */ - public CommandSender getS() - { - return s; - } + /** + * Get the origin sender this object is wrapping + * + * @return the command sender + */ + public CommandSender getS() { + return s; + } - @Override - public boolean isPermissionSet(String name) - { - return s.isPermissionSet(name); - } + @Override + public boolean isPermissionSet(String name) { + return s.isPermissionSet(name); + } - @Override - public boolean isPermissionSet(Permission perm) - { - return s.isPermissionSet(perm); - } + @Override + public boolean isPermissionSet(Permission perm) { + return s.isPermissionSet(perm); + } - @Override - public boolean hasPermission(String name) - { - return s.hasPermission(name); - } + @Override + public boolean hasPermission(String name) { + return s.hasPermission(name); + } - @Override - public boolean hasPermission(Permission perm) - { - return s.hasPermission(perm); - } + @Override + public boolean hasPermission(Permission perm) { + return s.hasPermission(perm); + } - @Override - public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) - { - return s.addAttachment(plugin, name, value); - } + @Override + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value) { + return s.addAttachment(plugin, name, value); + } - @Override - public PermissionAttachment addAttachment(Plugin plugin) - { - return s.addAttachment(plugin); - } + @Override + public PermissionAttachment addAttachment(Plugin plugin) { + return s.addAttachment(plugin); + } - @Override - public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) - { - return s.addAttachment(plugin, name, value, ticks); - } + @Override + public PermissionAttachment addAttachment(Plugin plugin, String name, boolean value, int ticks) { + return s.addAttachment(plugin, name, value, ticks); + } - @Override - public PermissionAttachment addAttachment(Plugin plugin, int ticks) - { - return s.addAttachment(plugin, ticks); - } + @Override + public PermissionAttachment addAttachment(Plugin plugin, int ticks) { + return s.addAttachment(plugin, ticks); + } - @Override - public void removeAttachment(PermissionAttachment attachment) - { - s.removeAttachment(attachment); - } + @Override + public void removeAttachment(PermissionAttachment attachment) { + s.removeAttachment(attachment); + } - @Override - public void recalculatePermissions() - { - s.recalculatePermissions(); - } + @Override + public void recalculatePermissions() { + s.recalculatePermissions(); + } - @Override - public Set getEffectivePermissions() - { - return s.getEffectivePermissions(); - } + @Override + public Set getEffectivePermissions() { + return s.getEffectivePermissions(); + } - @Override - public boolean isOp() - { - return s.isOp(); - } + @Override + public boolean isOp() { + return s.isOp(); + } - @Override - public void setOp(boolean value) - { - s.setOp(value); - } + @Override + public void setOp(boolean value) { + s.setOp(value); + } - public void hr() - { - s.sendMessage("========================================================"); - } + public void hr() { + s.sendMessage("========================================================"); + } - @Override - public void sendMessage(String message) - { - s.sendMessage(C.translateAlternateColorCodes('&', getTag()) + message); - } + @Override + public void sendMessage(String message) { + s.sendMessage(C.translateAlternateColorCodes('&', getTag()) + message); + } - @Override - public void sendMessage(String[] messages) - { - for(String str : messages) - s.sendMessage(C.translateAlternateColorCodes('&', getTag() + str)); - } + @Override + public void sendMessage(String[] messages) { + for (String str : messages) + s.sendMessage(C.translateAlternateColorCodes('&', getTag() + str)); + } - @Override - public void sendMessage(@Nullable UUID uuid, @NotNull String message) { - sendMessage(message); - } + @Override + public void sendMessage(@Nullable UUID uuid, @NotNull String message) { + sendMessage(message); + } - @Override - public void sendMessage(@Nullable UUID uuid, @NotNull String[] messages) { - sendMessage(messages); - } + @Override + public void sendMessage(@Nullable UUID uuid, @NotNull String[] messages) { + sendMessage(messages); + } - @Override - public Server getServer() - { - return s.getServer(); - } + @Override + public Server getServer() { + return s.getServer(); + } - @Override - public String getName() - { - return s.getName(); - } + @Override + public String getName() { + return s.getName(); + } - @Override - public Spigot spigot() - { - return s.spigot(); - } + @Override + public Spigot spigot() { + return s.spigot(); + } } diff --git a/src/main/java/com/volmit/iris/util/NBTConstants.java b/src/main/java/com/volmit/iris/util/NBTConstants.java index 25b6e8452..f1789065a 100644 --- a/src/main/java/com/volmit/iris/util/NBTConstants.java +++ b/src/main/java/com/volmit/iris/util/NBTConstants.java @@ -6,21 +6,21 @@ package com.volmit.iris.util; * Copyright (c) 2015 Neil Wightman * Copyright (c) 2010 Graham Edgecombe * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. - * + * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * * Neither the name of the JNBT team nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -31,25 +31,27 @@ package com.volmit.iris.util; * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * POSSIBILITY OF SUCH DAMAGE. */ + import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; /** * Changes : Neil Wightman - Support 19133 Tag_Int_Array tag */ + /** * A class which holds constant values. * * @author Graham Edgecombe - * */ public final class NBTConstants { /** * The character set used by NBT (UTF-8). */ - public static final Charset CHARSET = Charset.forName("UTF-8"); + public static final Charset CHARSET = StandardCharsets.UTF_8; /** * Tag type constants. diff --git a/src/main/java/com/volmit/iris/util/NBTInputStream.java b/src/main/java/com/volmit/iris/util/NBTInputStream.java index d5f892557..562c94b41 100644 --- a/src/main/java/com/volmit/iris/util/NBTInputStream.java +++ b/src/main/java/com/volmit/iris/util/NBTInputStream.java @@ -6,21 +6,21 @@ package com.volmit.iris.util; * Copyright (c) 2015 Neil Wightman * Copyright (c) 2010 Graham Edgecombe * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. - * + * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * * Neither the name of the JNBT team nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -46,7 +46,7 @@ import java.util.zip.GZIPInputStream; /** * Changes : - * Neil Wightman - Support 19133 Tag_Int_Array tag + * Neil Wightman - Support 19133 Tag_Int_Array tag */ /** diff --git a/src/main/java/com/volmit/iris/util/NBTOutputStream.java b/src/main/java/com/volmit/iris/util/NBTOutputStream.java index 7a16202e9..c3163ae99 100644 --- a/src/main/java/com/volmit/iris/util/NBTOutputStream.java +++ b/src/main/java/com/volmit/iris/util/NBTOutputStream.java @@ -6,21 +6,21 @@ package com.volmit.iris.util; * Copyright (c) 2015 Neil Wightman * Copyright (c) 2010 Graham Edgecombe * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. - * + * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * * Neither the name of the JNBT team nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -31,8 +31,9 @@ package com.volmit.iris.util; * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * POSSIBILITY OF SUCH DAMAGE. */ + import java.io.Closeable; import java.io.DataOutputStream; import java.io.IOException; @@ -53,7 +54,6 @@ import java.util.zip.GZIPOutputStream; * http://www.minecraft.net/docs/NBT.txt.

* * @author Graham Edgecombe - * */ public final class NBTOutputStream implements Closeable { @@ -64,6 +64,7 @@ public final class NBTOutputStream implements Closeable { /** * Create a new NBTOutputStream, which will write data to the specified underlying output stream. + * * @param os The output stream */ public NBTOutputStream(DataOutputStream os) { @@ -288,7 +289,7 @@ public final class NBTOutputStream implements Closeable { private void writeIntArrayTagPayload(IntArrayTag tag) throws IOException { final int[] values = tag.getValue(); os.writeInt(values.length); - for(final int value : values) { + for (final int value : values) { os.writeInt(value); } } diff --git a/src/main/java/com/volmit/iris/util/NBTUtils.java b/src/main/java/com/volmit/iris/util/NBTUtils.java index a890f5f4d..b11b7290e 100644 --- a/src/main/java/com/volmit/iris/util/NBTUtils.java +++ b/src/main/java/com/volmit/iris/util/NBTUtils.java @@ -6,21 +6,21 @@ package com.volmit.iris.util; * Copyright (c) 2015 Neil Wightman * Copyright (c) 2010 Graham Edgecombe * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. - * + * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * * Neither the name of the JNBT team nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -36,11 +36,11 @@ package com.volmit.iris.util; /** * Changes : Neil Wightman - Support 19133 Tag_Int_Array tag */ + /** * A class which contains NBT-related utility methods. This currently supports reading 19133 but only writing 19132. * * @author Graham Edgecombe - * */ public final class NBTUtils { diff --git a/src/main/java/com/volmit/iris/util/NMSVersion.java b/src/main/java/com/volmit/iris/util/NMSVersion.java index 016fc8dc2..10e42e62b 100644 --- a/src/main/java/com/volmit/iris/util/NMSVersion.java +++ b/src/main/java/com/volmit/iris/util/NMSVersion.java @@ -3,147 +3,118 @@ package com.volmit.iris.util; import java.util.ArrayList; import java.util.List; -public enum NMSVersion -{ - R1_16, - R1_15, - R1_14, - R1_13, - R1_13_1, - R1_12, - R1_11, - R1_10, - R1_9_4, - R1_9_2, - R1_8; +public enum NMSVersion { + R1_16, + R1_15, + R1_14, + R1_13, + R1_13_1, + R1_12, + R1_11, + R1_10, + R1_9_4, + R1_9_2, + R1_8; - public List getAboveInclusive() - { - List n = new ArrayList<>(); + public List getAboveInclusive() { + List n = new ArrayList<>(); - for(NMSVersion i : values()) - { - if(i.ordinal() >= ordinal()) - { - n.add(i); - } - } + for (NMSVersion i : values()) { + if (i.ordinal() >= ordinal()) { + n.add(i); + } + } - return n; - } + return n; + } - public List betweenInclusive(NMSVersion other) - { - List n = new ArrayList<>(); + public List betweenInclusive(NMSVersion other) { + List n = new ArrayList<>(); - for(NMSVersion i : values()) - { - if(i.ordinal() <= Math.max(other.ordinal(), ordinal()) && i.ordinal() >= Math.min(ordinal(), other.ordinal())) - { - n.add(i); - } - } + for (NMSVersion i : values()) { + if (i.ordinal() <= Math.max(other.ordinal(), ordinal()) && i.ordinal() >= Math.min(ordinal(), other.ordinal())) { + n.add(i); + } + } - return n; - } + return n; + } - public List getBelowInclusive() - { - List n = new ArrayList<>(); + public List getBelowInclusive() { + List n = new ArrayList<>(); - for(NMSVersion i : values()) - { - if(i.ordinal() <= ordinal()) - { - n.add(i); - } - } + for (NMSVersion i : values()) { + if (i.ordinal() <= ordinal()) { + n.add(i); + } + } - return n; - } + return n; + } - public static NMSVersion getMinimum() - { - return values()[values().length - 1]; - } + public static NMSVersion getMinimum() { + return values()[values().length - 1]; + } - public static NMSVersion getMaximum() - { - return values()[0]; - } + public static NMSVersion getMaximum() { + return values()[0]; + } - public static NMSVersion current() - { - if(tryVersion("1_8_R3")) - { - return R1_8; - } + public static NMSVersion current() { + if (tryVersion("1_8_R3")) { + return R1_8; + } - if(tryVersion("1_9_R1")) - { - return R1_9_2; - } + if (tryVersion("1_9_R1")) { + return R1_9_2; + } - if(tryVersion("1_9_R2")) - { - return R1_9_4; - } + if (tryVersion("1_9_R2")) { + return R1_9_4; + } - if(tryVersion("1_10_R1")) - { - return R1_10; - } + if (tryVersion("1_10_R1")) { + return R1_10; + } - if(tryVersion("1_11_R1")) - { - return R1_11; - } + if (tryVersion("1_11_R1")) { + return R1_11; + } - if(tryVersion("1_12_R1")) - { - return R1_12; - } + if (tryVersion("1_12_R1")) { + return R1_12; + } - if(tryVersion("1_13_R1")) - { - return R1_13; - } + if (tryVersion("1_13_R1")) { + return R1_13; + } - if(tryVersion("1_13_R2")) - { - return R1_13_1; - } + if (tryVersion("1_13_R2")) { + return R1_13_1; + } - if(tryVersion("1_14_R1")) - { - return R1_14; - } + if (tryVersion("1_14_R1")) { + return R1_14; + } - if(tryVersion("1_15_R1")) - { - return R1_15; - } + if (tryVersion("1_15_R1")) { + return R1_15; + } - if(tryVersion("1_16_R1")) - { - return R1_16; - } - return null; - } + if (tryVersion("1_16_R1")) { + return R1_16; + } + return null; + } - private static boolean tryVersion(String v) - { - try - { - Class.forName("org.bukkit.craftbukkit.v" + v + ".CraftWorld"); - return true; - } + private static boolean tryVersion(String v) { + try { + Class.forName("org.bukkit.craftbukkit.v" + v + ".CraftWorld"); + return true; + } catch (Throwable e) { - catch(Throwable e) - { + } - } - - return false; - } + return false; + } } diff --git a/src/main/java/com/volmit/iris/util/NastyFunction.java b/src/main/java/com/volmit/iris/util/NastyFunction.java index 60d58a129..d59423acc 100644 --- a/src/main/java/com/volmit/iris/util/NastyFunction.java +++ b/src/main/java/com/volmit/iris/util/NastyFunction.java @@ -1,6 +1,5 @@ package com.volmit.iris.util; -public interface NastyFunction -{ - public R run(T t) throws Throwable; +public interface NastyFunction { + R run(T t) throws Throwable; } diff --git a/src/main/java/com/volmit/iris/util/NastyFuture.java b/src/main/java/com/volmit/iris/util/NastyFuture.java index a5f813b8e..263d36968 100644 --- a/src/main/java/com/volmit/iris/util/NastyFuture.java +++ b/src/main/java/com/volmit/iris/util/NastyFuture.java @@ -1,6 +1,5 @@ package com.volmit.iris.util; -public interface NastyFuture -{ - public R run() throws Throwable; +public interface NastyFuture { + R run() throws Throwable; } diff --git a/src/main/java/com/volmit/iris/util/NastyRunnable.java b/src/main/java/com/volmit/iris/util/NastyRunnable.java index 815b20448..8b8328792 100644 --- a/src/main/java/com/volmit/iris/util/NastyRunnable.java +++ b/src/main/java/com/volmit/iris/util/NastyRunnable.java @@ -1,6 +1,5 @@ package com.volmit.iris.util; -public interface NastyRunnable -{ - public void run() throws Throwable; +public interface NastyRunnable { + void run() throws Throwable; } diff --git a/src/main/java/com/volmit/iris/util/NibbleArray.java b/src/main/java/com/volmit/iris/util/NibbleArray.java index bcc986e1f..a5ccaaedf 100644 --- a/src/main/java/com/volmit/iris/util/NibbleArray.java +++ b/src/main/java/com/volmit/iris/util/NibbleArray.java @@ -7,206 +7,172 @@ import java.nio.ByteOrder; import java.util.Arrays; import java.util.StringJoiner; -public class NibbleArray implements Writable -{ - private byte[] data; - private int depth; - private final int size; - private byte mask; - private final Object lock = new Object(); +public class NibbleArray implements Writable { + private byte[] data; + private int depth; + private final int size; + private byte mask; + private final Object lock = new Object(); - public NibbleArray(int capacity, DataInputStream in) throws IOException - { - size = capacity; - read(in); - } + public NibbleArray(int capacity, DataInputStream in) throws IOException { + size = capacity; + read(in); + } - public NibbleArray(int nibbleDepth, int capacity) - { - if(nibbleDepth > 8 || nibbleDepth < 1) - { - throw new IllegalArgumentException(); - } + public NibbleArray(int nibbleDepth, int capacity) { + if (nibbleDepth > 8 || nibbleDepth < 1) { + throw new IllegalArgumentException(); + } - int neededBits = nibbleDepth * capacity; + int neededBits = nibbleDepth * capacity; - size = capacity; - depth = nibbleDepth; - data = new byte[(neededBits + neededBits % 8) / 8]; - mask = (byte) maskFor(nibbleDepth); - } + size = capacity; + depth = nibbleDepth; + data = new byte[(neededBits + neededBits % 8) / 8]; + mask = (byte) maskFor(nibbleDepth); + } - public NibbleArray(int nibbleDepth, int capacity, NibbleArray existing) - { - if(nibbleDepth > 8 || nibbleDepth < 1) - { - throw new IllegalArgumentException(); - } + public NibbleArray(int nibbleDepth, int capacity, NibbleArray existing) { + if (nibbleDepth > 8 || nibbleDepth < 1) { + throw new IllegalArgumentException(); + } - int neededBits = nibbleDepth * capacity; - size = capacity; - depth = nibbleDepth; - data = new byte[(neededBits + neededBits % 8) / 8]; - mask = (byte) maskFor(nibbleDepth); + int neededBits = nibbleDepth * capacity; + size = capacity; + depth = nibbleDepth; + data = new byte[(neededBits + neededBits % 8) / 8]; + mask = (byte) maskFor(nibbleDepth); - for(int i = 0; i < Math.min(size, existing.size()); i++) - { - set(i, existing.get(i)); - } - } + for (int i = 0; i < Math.min(size, existing.size()); i++) { + set(i, existing.get(i)); + } + } - @Override - public void write(DataOutputStream o) throws IOException - { - o.writeByte(depth + Byte.MIN_VALUE); - o.write(data); - } + @Override + public void write(DataOutputStream o) throws IOException { + o.writeByte(depth + Byte.MIN_VALUE); + o.write(data); + } - @Override - public void read(DataInputStream i) throws IOException - { - depth = i.readByte() - Byte.MIN_VALUE; - int neededBits = depth * size; - data = new byte[(neededBits + neededBits % 8) / 8]; - mask = (byte) maskFor(depth); - i.read(data); - } + @Override + public void read(DataInputStream i) throws IOException { + depth = i.readByte() - Byte.MIN_VALUE; + int neededBits = depth * size; + data = new byte[(neededBits + neededBits % 8) / 8]; + mask = (byte) maskFor(depth); + i.read(data); + } - public int size() - { - return size; - } + public int size() { + return size; + } - public byte get(int index) - { - synchronized(lock) - { - bitIndex = index * depth; - byteIndex = bitIndex >> 3; - bitInByte = bitIndex & 7; - int value = data[byteIndex] >> bitInByte; + public byte get(int index) { + synchronized (lock) { + bitIndex = index * depth; + byteIndex = bitIndex >> 3; + bitInByte = bitIndex & 7; + int value = data[byteIndex] >> bitInByte; - if(bitInByte + depth > 8) - { - value |= data[byteIndex + 1] << bitInByte; - } + if (bitInByte + depth > 8) { + value |= data[byteIndex + 1] << bitInByte; + } - return (byte) (value & mask); - } - } + return (byte) (value & mask); + } + } - public byte getAsync(int index) - { - int bitIndex = index * depth; - int byteIndex = bitIndex >> 3; - int bitInByte = bitIndex & 7; - int value = data[byteIndex] >> bitInByte; + public byte getAsync(int index) { + int bitIndex = index * depth; + int byteIndex = bitIndex >> 3; + int bitInByte = bitIndex & 7; + int value = data[byteIndex] >> bitInByte; - if(bitInByte + depth > 8) - { - value |= data[byteIndex + 1] << bitInByte; - } + if (bitInByte + depth > 8) { + value |= data[byteIndex + 1] << bitInByte; + } - return (byte) (value & mask); - } + return (byte) (value & mask); + } - private transient int bitIndex, byteIndex, bitInByte; + private transient int bitIndex, byteIndex, bitInByte; - public void set(int index, int nibble) - { - set(index, (byte) nibble); - } + public void set(int index, int nibble) { + set(index, (byte) nibble); + } - public void set(int index, byte nybble) - { - synchronized(lock) - { - bitIndex = index * depth; - byteIndex = bitIndex >> 3; - bitInByte = bitIndex & 7; - data[byteIndex] = (byte) (((~(data[byteIndex] & (mask << bitInByte)) & data[byteIndex]) | ((nybble & mask) << bitInByte)) & 0xff); + public void set(int index, byte nybble) { + synchronized (lock) { + bitIndex = index * depth; + byteIndex = bitIndex >> 3; + bitInByte = bitIndex & 7; + data[byteIndex] = (byte) (((~(data[byteIndex] & (mask << bitInByte)) & data[byteIndex]) | ((nybble & mask) << bitInByte)) & 0xff); - if(bitInByte + depth > 8) - { - data[byteIndex + 1] = (byte) (((~(data[byteIndex + 1] & MASKS[bitInByte + depth - 8]) & data[byteIndex + 1]) | ((nybble & mask) >> (8 - bitInByte))) & 0xff); - } - } - } + if (bitInByte + depth > 8) { + data[byteIndex + 1] = (byte) (((~(data[byteIndex + 1] & MASKS[bitInByte + depth - 8]) & data[byteIndex + 1]) | ((nybble & mask) >> (8 - bitInByte))) & 0xff); + } + } + } - public String toBitsString() - { - return toBitsString(ByteOrder.BIG_ENDIAN); - } + public String toBitsString() { + return toBitsString(ByteOrder.BIG_ENDIAN); + } - public String toBitsString(ByteOrder byteOrder) - { - StringJoiner joiner = new StringJoiner(" "); + public String toBitsString(ByteOrder byteOrder) { + StringJoiner joiner = new StringJoiner(" "); - for(int i = 0; i < data.length; i++) - { - joiner.add(binaryString(data[i], byteOrder)); - } + for (int i = 0; i < data.length; i++) { + joiner.add(binaryString(data[i], byteOrder)); + } - return joiner.toString(); - } + return joiner.toString(); + } - public void clear() - { - Arrays.fill(data, (byte) 0); - } + public void clear() { + Arrays.fill(data, (byte) 0); + } - public void setAll(byte nibble) - { - for(int i = 0; i < size; i++) - { - set(i, nibble); - } - } + public void setAll(byte nibble) { + for (int i = 0; i < size; i++) { + set(i, nibble); + } + } - public void setAll(int nibble) - { - for(int i = 0; i < size; i++) - { - set(i, (byte) nibble); - } - } + public void setAll(int nibble) { + for (int i = 0; i < size; i++) { + set(i, (byte) nibble); + } + } - public static int maskFor(int amountOfBits) - { - return powerOfTwo(amountOfBits) - 1; - } + public static int maskFor(int amountOfBits) { + return powerOfTwo(amountOfBits) - 1; + } - public static int powerOfTwo(int power) - { - int result = 1; + public static int powerOfTwo(int power) { + int result = 1; - for(int i = 0; i < power; i++) - { - result *= 2; - } + for (int i = 0; i < power; i++) { + result *= 2; + } - return result; - } + return result; + } - private static final int[] MASKS = new int[8]; + private static final int[] MASKS = new int[8]; - static - { - for(int i = 0; i < MASKS.length; i++) - { - MASKS[i] = maskFor(i); - } - } + static { + for (int i = 0; i < MASKS.length; i++) { + MASKS[i] = maskFor(i); + } + } - public static String binaryString(byte b, ByteOrder byteOrder) - { - String str = String.format("%8s", Integer.toBinaryString(b & 0xff)).replace(' ', '0'); + public static String binaryString(byte b, ByteOrder byteOrder) { + String str = String.format("%8s", Integer.toBinaryString(b & 0xff)).replace(' ', '0'); - return byteOrder.equals(ByteOrder.BIG_ENDIAN) ? str : reverse(str); - } + return byteOrder.equals(ByteOrder.BIG_ENDIAN) ? str : reverse(str); + } - public static String reverse(String str) - { - return new StringBuilder(str).reverse().toString(); - } + public static String reverse(String str) { + return new StringBuilder(str).reverse().toString(); + } } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/NoiseInjector.java b/src/main/java/com/volmit/iris/util/NoiseInjector.java index bab689cfa..261a29363 100644 --- a/src/main/java/com/volmit/iris/util/NoiseInjector.java +++ b/src/main/java/com/volmit/iris/util/NoiseInjector.java @@ -1,7 +1,6 @@ package com.volmit.iris.util; @FunctionalInterface -public interface NoiseInjector -{ - public double[] combine(double src, double value); +public interface NoiseInjector { + double[] combine(double src, double value); } diff --git a/src/main/java/com/volmit/iris/util/NoiseProvider.java b/src/main/java/com/volmit/iris/util/NoiseProvider.java index d119b64d2..8fb360cdb 100644 --- a/src/main/java/com/volmit/iris/util/NoiseProvider.java +++ b/src/main/java/com/volmit/iris/util/NoiseProvider.java @@ -1,6 +1,6 @@ package com.volmit.iris.util; + @FunctionalInterface -public interface NoiseProvider -{ - public double noise(double x, double z); +public interface NoiseProvider { + double noise(double x, double z); } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/NoiseProvider3.java b/src/main/java/com/volmit/iris/util/NoiseProvider3.java index 33640aa47..e7019d35b 100644 --- a/src/main/java/com/volmit/iris/util/NoiseProvider3.java +++ b/src/main/java/com/volmit/iris/util/NoiseProvider3.java @@ -1,6 +1,6 @@ package com.volmit.iris.util; + @FunctionalInterface -public interface NoiseProvider3 -{ - public double noise(double x, double y, double z); +public interface NoiseProvider3 { + double noise(double x, double y, double z); } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/O.java b/src/main/java/com/volmit/iris/util/O.java index 6abd89e6d..e8613039b 100644 --- a/src/main/java/com/volmit/iris/util/O.java +++ b/src/main/java/com/volmit/iris/util/O.java @@ -1,53 +1,45 @@ package com.volmit.iris.util; -public class O implements Observable -{ - private T t = null; - private KList> observers; +public class O implements Observable { + private T t = null; + private KList> observers; - @Override - public T get() - { - return t; - } + @Override + public T get() { + return t; + } - @Override - public O set(T t) - { - T x = t; - this.t = t; + @Override + public O set(T t) { + T x = t; + this.t = t; - if(observers != null && observers.hasElements()) - { - observers.forEach((o) -> o.onChanged(x, t)); - } + if (observers != null && observers.hasElements()) { + observers.forEach((o) -> o.onChanged(x, t)); + } - return this; - } + return this; + } - @Override - public boolean has() - { - return t != null; - } + @Override + public boolean has() { + return t != null; + } - @Override - public O clearObservers() - { - observers.clear(); - return this; - } + @Override + public O clearObservers() { + observers.clear(); + return this; + } - @Override - public O observe(Observer t) - { - if(observers == null) - { - observers = new KList<>(); - } + @Override + public O observe(Observer t) { + if (observers == null) { + observers = new KList<>(); + } - observers.add(t); + observers.add(t); - return this; - } + return this; + } } diff --git a/src/main/java/com/volmit/iris/util/ObjectResourceLoader.java b/src/main/java/com/volmit/iris/util/ObjectResourceLoader.java index d6c3b9049..f1013fbcb 100644 --- a/src/main/java/com/volmit/iris/util/ObjectResourceLoader.java +++ b/src/main/java/com/volmit/iris/util/ObjectResourceLoader.java @@ -7,243 +7,195 @@ import com.volmit.iris.object.IrisObject; import java.io.File; import java.util.concurrent.atomic.AtomicInteger; -public class ObjectResourceLoader extends ResourceLoader -{ - private ChronoLatch useFlip = new ChronoLatch(2222); - private KMap useCache = new KMap<>(); - private ChronoLatch cl; - private AtomicInteger unload; +public class ObjectResourceLoader extends ResourceLoader { + private final ChronoLatch useFlip = new ChronoLatch(2222); + private final KMap useCache = new KMap<>(); + private final ChronoLatch cl; + private final AtomicInteger unload; - public ObjectResourceLoader(File root, IrisDataManager idm, String folderName, String resourceTypeName) - { - super(root, idm, folderName, resourceTypeName, IrisObject.class); - cl = new ChronoLatch(30000); - unload = new AtomicInteger(0); - } + public ObjectResourceLoader(File root, IrisDataManager idm, String folderName, String resourceTypeName) { + super(root, idm, folderName, resourceTypeName, IrisObject.class); + cl = new ChronoLatch(30000); + unload = new AtomicInteger(0); + } - public int getSize() - { - return loadCache.size(); - } + public int getSize() { + return loadCache.size(); + } - public int getTotalStorage() - { - int m = 0; + public int getTotalStorage() { + int m = 0; - for(IrisObject i : loadCache.values()) - { - m += i.getBlocks().size(); - } + for (IrisObject i : loadCache.values()) { + m += i.getBlocks().size(); + } - return m; - } + return m; + } - public void clean() - { - if(useFlip.flip()) - { - unloadLast(30000); - } - } + public void clean() { + if (useFlip.flip()) { + unloadLast(30000); + } + } - public void unloadLast(long age) - { - String v = getOldest(); + public void unloadLast(long age) { + String v = getOldest(); - if(v == null) - { - return; - } + if (v == null) { + return; + } - if(M.ms() - useCache.get(v) > age) - { - unload(v); - } - } + if (M.ms() - useCache.get(v) > age) { + unload(v); + } + } - private String getOldest() - { - long min = M.ms(); - String v = null; + private String getOldest() { + long min = M.ms(); + String v = null; - for(String i : useCache.k()) - { - long t = useCache.get(i); - if(t < min) - { - min = t; - v = i; - } - } + for (String i : useCache.k()) { + long t = useCache.get(i); + if (t < min) { + min = t; + v = i; + } + } - return v; - } + return v; + } - private void unload(String v) - { - lock.lock(); - useCache.remove(v); - loadCache.remove(v); - lock.unlock(); - unload.getAndIncrement(); + private void unload(String v) { + lock.lock(); + useCache.remove(v); + loadCache.remove(v); + lock.unlock(); + unload.getAndIncrement(); - if(unload.get() == 1) - { - cl.flip(); - } + if (unload.get() == 1) { + cl.flip(); + } - if(cl.flip()) - { - J.a(() -> { - Iris.verbose("Unloaded " + C.WHITE + unload.get() +" " + resourceTypeName + (unload.get() == 1 ? "" : "s") + C.GRAY + " to optimize memory usage." + " (" + Form.f(getLoadCache().size() )+ " " + resourceTypeName + (loadCache.size() == 1 ? "" : "s")+ " Loaded)"); - unload.set(0); - }); - } - } + if (cl.flip()) { + J.a(() -> { + Iris.verbose("Unloaded " + C.WHITE + unload.get() + " " + resourceTypeName + (unload.get() == 1 ? "" : "s") + C.GRAY + " to optimize memory usage." + " (" + Form.f(getLoadCache().size()) + " " + resourceTypeName + (loadCache.size() == 1 ? "" : "s") + " Loaded)"); + unload.set(0); + }); + } + } - public IrisObject loadFile(File j, String key, String name) - { - lock.lock(); - try - { - IrisObject t = new IrisObject(0, 0, 0); - t.read(j); - loadCache.put(key, t); - logLoad(j); - t.setLoadKey(name); - t.setLoader(manager); - t.setLoadFile(j); - lock.unlock(); - return t; - } + public IrisObject loadFile(File j, String key, String name) { + lock.lock(); + try { + IrisObject t = new IrisObject(0, 0, 0); + t.read(j); + loadCache.put(key, t); + logLoad(j); + t.setLoadKey(name); + t.setLoader(manager); + t.setLoadFile(j); + lock.unlock(); + return t; + } catch (Throwable e) { + lock.unlock(); + Iris.warn("Couldn't read " + resourceTypeName + " file: " + j.getPath() + ": " + e.getMessage()); + return null; + } + } - catch(Throwable e) - { - lock.unlock(); - Iris.warn("Couldn't read " + resourceTypeName + " file: " + j.getPath() + ": " + e.getMessage()); - return null; - } - } + public String[] getPossibleKeys() { + if (possibleKeys != null) { + return possibleKeys; + } - public String[] getPossibleKeys() - { - if(possibleKeys != null) - { - return possibleKeys; - } + Iris.info("Building " + resourceTypeName + " Possibility Lists"); + KSet m = new KSet<>(); - Iris.info("Building " + resourceTypeName + " Possibility Lists"); - KSet m = new KSet<>(); + for (File i : getFolders()) { + for (File j : i.listFiles()) { + if (j.isFile() && j.getName().endsWith(".iob")) { + m.add(j.getName().replaceAll("\\Q.iob\\E", "")); + } else if (j.isDirectory()) { + for (File k : j.listFiles()) { + if (k.isFile() && k.getName().endsWith(".iob")) { + m.add(j.getName() + "/" + k.getName().replaceAll("\\Q.iob\\E", "")); + } else if (k.isDirectory()) { + for (File l : k.listFiles()) { + if (l.isFile() && l.getName().endsWith(".iob")) { + m.add(j.getName() + "/" + k.getName() + "/" + l.getName().replaceAll("\\Q.iob\\E", "")); + } + } + } + } + } + } + } - for(File i : getFolders()) - { - for(File j : i.listFiles()) - { - if(j.isFile() && j.getName().endsWith(".iob")) - { - m.add(j.getName().replaceAll("\\Q.iob\\E", "")); - } + KList v = new KList<>(m); + possibleKeys = v.toArray(new String[v.size()]); + return possibleKeys; + } - else if(j.isDirectory()) - { - for(File k : j.listFiles()) - { - if(k.isFile() && k.getName().endsWith(".iob")) - { - m.add(j.getName() + "/" + k.getName().replaceAll("\\Q.iob\\E", "")); - } + public File findFile(String name) { + lock.lock(); + for (File i : getFolders(name)) { + for (File j : i.listFiles()) { + if (j.isFile() && j.getName().endsWith(".iob") && j.getName().split("\\Q.\\E")[0].equals(name)) { + lock.unlock(); + return j; + } + } - else if(k.isDirectory()) - { - for(File l : k.listFiles()) - { - if(l.isFile() && l.getName().endsWith(".iob")) - { - m.add(j.getName() + "/" + k.getName() + "/" + l.getName().replaceAll("\\Q.iob\\E", "")); - } - } - } - } - } - } - } + File file = new File(i, name + ".iob"); - KList v = new KList<>(m); - possibleKeys = v.toArray(new String[v.size()]); - return possibleKeys; - } + if (file.exists()) { + lock.unlock(); + return file; + } + } - public File findFile(String name) - { - lock.lock(); - for(File i : getFolders(name)) - { - for(File j : i.listFiles()) - { - if(j.isFile() && j.getName().endsWith(".iob") && j.getName().split("\\Q.\\E")[0].equals(name)) - { - lock.unlock(); - return j; - } - } + Iris.warn("Couldn't find " + resourceTypeName + ": " + name); - File file = new File(i, name + ".iob"); + lock.unlock(); + return null; + } - if(file.exists()) - { - lock.unlock(); - return file; - } - } + public IrisObject load(String name) { + return load(name, true); + } - Iris.warn("Couldn't find " + resourceTypeName + ": " + name); + public IrisObject load(String name, boolean warn) { + String key = name + "-" + objectClass.getCanonicalName(); - lock.unlock(); - return null; - } + if (loadCache.containsKey(key)) { + IrisObject t = loadCache.get(key); + useCache.put(key, M.ms()); + return t; + } - public IrisObject load(String name) - { - return load(name, true); - } + lock.lock(); + for (File i : getFolders(name)) { + for (File j : i.listFiles()) { + if (j.isFile() && j.getName().endsWith(".iob") && j.getName().split("\\Q.\\E")[0].equals(name)) { + useCache.put(key, M.ms()); + lock.unlock(); + return loadFile(j, key, name); + } + } - public IrisObject load(String name, boolean warn) - { - String key = name + "-" + objectClass.getCanonicalName(); + File file = new File(i, name + ".iob"); - if(loadCache.containsKey(key)) - { - IrisObject t = loadCache.get(key); - useCache.put(key, M.ms()); - return t; - } + if (file.exists()) { + useCache.put(key, M.ms()); + lock.unlock(); + return loadFile(file, key, name); + } + } - lock.lock(); - for(File i : getFolders(name)) - { - for(File j : i.listFiles()) - { - if(j.isFile() && j.getName().endsWith(".iob") && j.getName().split("\\Q.\\E")[0].equals(name)) - { - useCache.put(key, M.ms()); - lock.unlock(); - return loadFile(j, key, name); - } - } + Iris.warn("Couldn't find " + resourceTypeName + ": " + name); - File file = new File(i, name + ".iob"); - - if(file.exists()) - { - useCache.put(key, M.ms()); - lock.unlock(); - return loadFile(file, key, name); - } - } - - Iris.warn("Couldn't find " + resourceTypeName + ": " + name); - - lock.unlock(); - return null; - } + lock.unlock(); + return null; + } } diff --git a/src/main/java/com/volmit/iris/util/Observable.java b/src/main/java/com/volmit/iris/util/Observable.java index e6e0ecb54..2c900b78d 100644 --- a/src/main/java/com/volmit/iris/util/Observable.java +++ b/src/main/java/com/volmit/iris/util/Observable.java @@ -1,14 +1,13 @@ package com.volmit.iris.util; -public interface Observable -{ - public T get(); - - public Observable set(T t); - - public boolean has(); - - public Observable clearObservers(); - - public Observable observe(Observer t); +public interface Observable { + T get(); + + Observable set(T t); + + boolean has(); + + Observable clearObservers(); + + Observable observe(Observer t); } diff --git a/src/main/java/com/volmit/iris/util/Observer.java b/src/main/java/com/volmit/iris/util/Observer.java index 092d44eb5..d7b0af06d 100644 --- a/src/main/java/com/volmit/iris/util/Observer.java +++ b/src/main/java/com/volmit/iris/util/Observer.java @@ -1,7 +1,6 @@ package com.volmit.iris.util; @FunctionalInterface -public interface Observer -{ - public void onChanged(T from, T to); +public interface Observer { + void onChanged(T from, T to); } diff --git a/src/main/java/com/volmit/iris/util/ParticleSender.java b/src/main/java/com/volmit/iris/util/ParticleSender.java index d80794d8d..e69ee53ac 100644 --- a/src/main/java/com/volmit/iris/util/ParticleSender.java +++ b/src/main/java/com/volmit/iris/util/ParticleSender.java @@ -14,117 +14,91 @@ import org.bukkit.material.MaterialData; * @author MrMicky */ @SuppressWarnings("deprecation") -interface ParticleSender -{ +interface ParticleSender { - void spawnParticle(Object receiver, ParticleType particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, Object data); + void spawnParticle(Object receiver, ParticleType particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, Object data); - Object getParticle(ParticleType particle); + Object getParticle(ParticleType particle); - boolean isValidData(Object particle, Object data); + boolean isValidData(Object particle, Object data); - default double color(double color) - { - return color / 255.0; - } + default double color(double color) { + return color / 255.0; + } - class ParticleSenderImpl implements ParticleSender - { + class ParticleSenderImpl implements ParticleSender { - @Override - public void spawnParticle(Object receiver, ParticleType particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, Object data) - { - Particle bukkitParticle = Particle.valueOf(particle.toString()); + @Override + public void spawnParticle(Object receiver, ParticleType particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, Object data) { + Particle bukkitParticle = Particle.valueOf(particle.toString()); - if(data instanceof Color) - { - if(particle.getDataType() == Color.class) - { - Color color = (Color) data; - count = 0; - offsetX = color(color.getRed()); - offsetY = color(color.getGreen()); - offsetZ = color(color.getBlue()); - extra = 1.0; - } - data = null; - } + if (data instanceof Color) { + if (particle.getDataType() == Color.class) { + Color color = (Color) data; + count = 0; + offsetX = color(color.getRed()); + offsetY = color(color.getGreen()); + offsetZ = color(color.getBlue()); + extra = 1.0; + } + data = null; + } - if(receiver instanceof World) - { - ((World) receiver).spawnParticle(bukkitParticle, x, y, z, count, offsetX, offsetY, offsetZ, extra, data); - } - else if(receiver instanceof Player) - { - ((Player) receiver).spawnParticle(bukkitParticle, x, y, z, count, offsetX, offsetY, offsetZ, extra, data); - } - } + if (receiver instanceof World) { + ((World) receiver).spawnParticle(bukkitParticle, x, y, z, count, offsetX, offsetY, offsetZ, extra, data); + } else if (receiver instanceof Player) { + ((Player) receiver).spawnParticle(bukkitParticle, x, y, z, count, offsetX, offsetY, offsetZ, extra, data); + } + } - @Override - public Particle getParticle(ParticleType particle) - { - try - { - return Particle.valueOf(particle.toString()); - } - catch(IllegalArgumentException e) - { - return null; - } - } + @Override + public Particle getParticle(ParticleType particle) { + try { + return Particle.valueOf(particle.toString()); + } catch (IllegalArgumentException e) { + return null; + } + } - @Override - public boolean isValidData(Object particle, Object data) - { - return isValidDataBukkit((Particle) particle, data); - } + @Override + public boolean isValidData(Object particle, Object data) { + return isValidDataBukkit((Particle) particle, data); + } - public boolean isValidDataBukkit(Particle particle, Object data) - { - return particle.getDataType() == Void.class || particle.getDataType().isInstance(data); - } - } + public boolean isValidDataBukkit(Particle particle, Object data) { + return particle.getDataType() == Void.class || particle.getDataType().isInstance(data); + } + } - class ParticleSender1_13 extends ParticleSenderImpl - { - @Override - public void spawnParticle(Object receiver, ParticleType particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, Object data) - { - Particle bukkitParticle = Particle.valueOf(particle.toString()); + class ParticleSender1_13 extends ParticleSenderImpl { + @Override + public void spawnParticle(Object receiver, ParticleType particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, Object data) { + Particle bukkitParticle = Particle.valueOf(particle.toString()); - if(bukkitParticle.getDataType() == Particle.DustOptions.class) - { - if(data instanceof Color) - { - data = new Particle.DustOptions((Color) data, 1); - } - else if(data == null) - { - data = new Particle.DustOptions(Color.RED, 1); - } - } - else if(bukkitParticle.getDataType() == BlockData.class && data instanceof MaterialData) - { - data = Bukkit.createBlockData(((MaterialData) data).getItemType()); - } + if (bukkitParticle.getDataType() == Particle.DustOptions.class) { + if (data instanceof Color) { + data = new Particle.DustOptions((Color) data, 1); + } else if (data == null) { + data = new Particle.DustOptions(Color.RED, 1); + } + } else if (bukkitParticle.getDataType() == BlockData.class && data instanceof MaterialData) { + data = Bukkit.createBlockData(((MaterialData) data).getItemType()); + } - super.spawnParticle(receiver, particle, x, y, z, count, offsetX, offsetY, offsetZ, extra, data); - } + super.spawnParticle(receiver, particle, x, y, z, count, offsetX, offsetY, offsetZ, extra, data); + } - @Override - public boolean isValidDataBukkit(Particle particle, Object data) - { - if(particle.getDataType() == Particle.DustOptions.class && data instanceof Color) - { - return true; - } + @Override + public boolean isValidDataBukkit(Particle particle, Object data) { + if (particle.getDataType() == Particle.DustOptions.class && data instanceof Color) { + return true; + } - if(particle.getDataType() == BlockData.class && data instanceof MaterialData) - { - return true; - } + if (particle.getDataType() == BlockData.class && data instanceof MaterialData) { + return true; + } - return super.isValidDataBukkit(particle, data); - } - } + return super.isValidDataBukkit(particle, data); + } + } } diff --git a/src/main/java/com/volmit/iris/util/Permission.java b/src/main/java/com/volmit/iris/util/Permission.java index dc447d888..185bd5ed0 100644 --- a/src/main/java/com/volmit/iris/util/Permission.java +++ b/src/main/java/com/volmit/iris/util/Permission.java @@ -1,14 +1,13 @@ package com.volmit.iris.util; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - 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 Permission -{ +public @interface Permission { } diff --git a/src/main/java/com/volmit/iris/util/Point3d.java b/src/main/java/com/volmit/iris/util/Point3d.java index b41cc9f06..539fbf41f 100644 --- a/src/main/java/com/volmit/iris/util/Point3d.java +++ b/src/main/java/com/volmit/iris/util/Point3d.java @@ -31,12 +31,9 @@ package com.volmit.iris.util; -import java.lang.Math; - /** - * A 3 element point that is represented by double precision floating point + * A 3 element point that is represented by double precision floating point * x,y,z coordinates. - * */ public class Point3d extends Tuple3d implements java.io.Serializable { @@ -45,117 +42,117 @@ public class Point3d extends Tuple3d implements java.io.Serializable { /** * Constructs and initializes a Point3d from the specified xyz coordinates. + * * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate */ - public Point3d(double x, double y, double z) - { - super(x,y,z); + public Point3d(double x, double y, double z) { + super(x, y, z); } /** * Constructs and initializes a Point3d from the array of length 3. + * * @param p the array of length 3 containing xyz in order */ - public Point3d(double[] p) - { - super(p); + public Point3d(double[] p) { + super(p); } /** * Constructs and initializes a Point3d from the specified Point3d. + * * @param p1 the Point3d containing the initialization x y z data */ - public Point3d(Point3d p1) - { - super(p1); + public Point3d(Point3d p1) { + super(p1); } /** * Constructs and initializes a Point3d from the specified Point3f. + * * @param p1 the Point3f containing the initialization x y z data */ - public Point3d(Point3f p1) - { - super(p1); + public Point3d(Point3f p1) { + super(p1); } - /** - * Constructs and initializes a Point3d from the specified Tuple3f. - * @param t1 the Tuple3f containing the initialization x y z data - */ - public Point3d(Tuple3f t1) - { - super(t1); + /** + * Constructs and initializes a Point3d from the specified Tuple3f. + * + * @param t1 the Tuple3f containing the initialization x y z data + */ + public Point3d(Tuple3f t1) { + super(t1); } - - - /** - * Constructs and initializes a Point3d from the specified Tuple3d. - * @param t1 the Tuple3d containing the initialization x y z data - */ - public Point3d(Tuple3d t1) - { - super(t1); + + + /** + * Constructs and initializes a Point3d from the specified Tuple3d. + * + * @param t1 the Tuple3d containing the initialization x y z data + */ + public Point3d(Tuple3d t1) { + super(t1); } /** * Constructs and initializes a Point3d to (0,0,0). */ - public Point3d() - { - super(); + public Point3d() { + super(); } - /** - * Returns the square of the distance between this point and point p1. - * @param p1 the other point - * @return the square of the distance - */ - public final double distanceSquared(Point3d p1) - { - double dx, dy, dz; + /** + * Returns the square of the distance between this point and point p1. + * + * @param p1 the other point + * @return the square of the distance + */ + public final double distanceSquared(Point3d p1) { + double dx, dy, dz; - dx = this.x-p1.x; - dy = this.y-p1.y; - dz = this.z-p1.z; - return (dx*dx+dy*dy+dz*dz); + dx = this.x - p1.x; + dy = this.y - p1.y; + dz = this.z - p1.z; + return (dx * dx + dy * dy + dz * dz); } - /** - * Returns the distance between this point and point p1. - * @param p1 the other point - * @return the distance - */ - public final double distance(Point3d p1) - { - double dx, dy, dz; + /** + * Returns the distance between this point and point p1. + * + * @param p1 the other point + * @return the distance + */ + public final double distance(Point3d p1) { + double dx, dy, dz; - dx = this.x-p1.x; - dy = this.y-p1.y; - dz = this.z-p1.z; - return Math.sqrt(dx*dx+dy*dy+dz*dz); + dx = this.x - p1.x; + dy = this.y - p1.y; + dz = this.z - p1.z; + return Math.sqrt(dx * dx + dy * dy + dz * dz); } /** * Computes the L-1 (Manhattan) distance between this point and * point p1. The L-1 distance is equal to: - * abs(x1-x2) + abs(y1-y2) + abs(z1-z2). + * abs(x1-x2) + abs(y1-y2) + abs(z1-z2). + * * @param p1 the other point - * @return the L-1 distance + * @return the L-1 distance */ public final double distanceL1(Point3d p1) { - return Math.abs(this.x-p1.x) + Math.abs(this.y-p1.y) + - Math.abs(this.z-p1.z); + return Math.abs(this.x - p1.x) + Math.abs(this.y - p1.y) + + Math.abs(this.z - p1.z); } @@ -163,32 +160,33 @@ public class Point3d extends Tuple3d implements java.io.Serializable { * Computes the L-infinite distance between this point and * point p1. The L-infinite distance is equal to * MAX[abs(x1-x2), abs(y1-y2), abs(z1-z2)]. + * * @param p1 the other point - * @return the L-infinite distance + * @return the L-infinite distance */ public final double distanceLinf(Point3d p1) { - double tmp; - tmp = Math.max( Math.abs(this.x-p1.x), Math.abs(this.y-p1.y)); + double tmp; + tmp = Math.max(Math.abs(this.x - p1.x), Math.abs(this.y - p1.y)); - return Math.max(tmp,Math.abs(this.z-p1.z)); + return Math.max(tmp, Math.abs(this.z - p1.z)); } - /** - * Multiplies each of the x,y,z components of the Point4d parameter - * by 1/w and places the projected values into this point. - * @param p1 the source Point4d, which is not modified - */ - public final void project(Point4d p1) - { - double oneOw; + /** + * Multiplies each of the x,y,z components of the Point4d parameter + * by 1/w and places the projected values into this point. + * + * @param p1 the source Point4d, which is not modified + */ + public final void project(Point4d p1) { + double oneOw; - oneOw = 1/p1.w; - x = p1.x*oneOw; - y = p1.y*oneOw; - z = p1.z*oneOw; + oneOw = 1 / p1.w; + x = p1.x * oneOw; + y = p1.y * oneOw; + z = p1.z * oneOw; - } + } } diff --git a/src/main/java/com/volmit/iris/util/Point3f.java b/src/main/java/com/volmit/iris/util/Point3f.java index 9fbc47979..cd3dc20a1 100644 --- a/src/main/java/com/volmit/iris/util/Point3f.java +++ b/src/main/java/com/volmit/iris/util/Point3f.java @@ -31,12 +31,9 @@ package com.volmit.iris.util; -import java.lang.Math; - /** - * A 3 element point that is represented by single precision floating point + * A 3 element point that is represented by single precision floating point * x,y,z coordinates. - * */ public class Point3f extends Tuple3f implements java.io.Serializable { @@ -46,152 +43,151 @@ public class Point3f extends Tuple3f implements java.io.Serializable { /** * Constructs and initializes a Point3f from the specified xyz coordinates. + * * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate */ - public Point3f(float x, float y, float z) - { - super(x,y,z); + public Point3f(float x, float y, float z) { + super(x, y, z); } /** * Constructs and initializes a Point3f from the array of length 3. + * * @param p the array of length 3 containing xyz in order */ - public Point3f(float[] p) - { - super(p); + public Point3f(float[] p) { + super(p); } /** * Constructs and initializes a Point3f from the specified Point3f. + * * @param p1 the Point3f containing the initialization x y z data */ - public Point3f(Point3f p1) - { - super(p1); + public Point3f(Point3f p1) { + super(p1); } /** * Constructs and initializes a Point3f from the specified Point3d. + * * @param p1 the Point3d containing the initialization x y z data */ - public Point3f(Point3d p1) - { - super(p1); + public Point3f(Point3d p1) { + super(p1); } /** * Constructs and initializes a Point3f from the specified Tuple3f. + * * @param t1 the Tuple3f containing the initialization x y z data - */ - public Point3f(Tuple3f t1) - { - super(t1); + */ + public Point3f(Tuple3f t1) { + super(t1); } /** * Constructs and initializes a Point3f from the specified Tuple3d. + * * @param t1 the Tuple3d containing the initialization x y z data - */ - public Point3f(Tuple3d t1) - { - super(t1); + */ + public Point3f(Tuple3d t1) { + super(t1); } /** * Constructs and initializes a Point3f to (0,0,0). */ - public Point3f() - { + public Point3f() { super(); } - /** - * Computes the square of the distance between this point and - * point p1. - * @param p1 the other point - * @return the square of the distance - */ - public final float distanceSquared(Point3f p1) - { - float dx, dy, dz; + /** + * Computes the square of the distance between this point and + * point p1. + * + * @param p1 the other point + * @return the square of the distance + */ + public final float distanceSquared(Point3f p1) { + float dx, dy, dz; - dx = this.x-p1.x; - dy = this.y-p1.y; - dz = this.z-p1.z; - return dx*dx+dy*dy+dz*dz; + dx = this.x - p1.x; + dy = this.y - p1.y; + dz = this.z - p1.z; + return dx * dx + dy * dy + dz * dz; } - /** - * Computes the distance between this point and point p1. - * @param p1 the other point - * @return the distance - */ - public final float distance(Point3f p1) - { - float dx, dy, dz; + /** + * Computes the distance between this point and point p1. + * + * @param p1 the other point + * @return the distance + */ + public final float distance(Point3f p1) { + float dx, dy, dz; - dx = this.x-p1.x; - dy = this.y-p1.y; - dz = this.z-p1.z; - return (float) Math.sqrt(dx*dx+dy*dy+dz*dz); + dx = this.x - p1.x; + dy = this.y - p1.y; + dz = this.z - p1.z; + return (float) Math.sqrt(dx * dx + dy * dy + dz * dz); } - /** - * Computes the L-1 (Manhattan) distance between this point and - * point p1. The L-1 distance is equal to: - * abs(x1-x2) + abs(y1-y2) + abs(z1-z2). - * @param p1 the other point - * @return the L-1 distance - */ - public final float distanceL1(Point3f p1) - { - return( Math.abs(this.x-p1.x) + Math.abs(this.y-p1.y) + Math.abs(this.z-p1.z)); + /** + * Computes the L-1 (Manhattan) distance between this point and + * point p1. The L-1 distance is equal to: + * abs(x1-x2) + abs(y1-y2) + abs(z1-z2). + * + * @param p1 the other point + * @return the L-1 distance + */ + public final float distanceL1(Point3f p1) { + return (Math.abs(this.x - p1.x) + Math.abs(this.y - p1.y) + Math.abs(this.z - p1.z)); } - /** - * Computes the L-infinite distance between this point and - * point p1. The L-infinite distance is equal to - * MAX[abs(x1-x2), abs(y1-y2), abs(z1-z2)]. - * @param p1 the other point - * @return the L-infinite distance - */ - public final float distanceLinf(Point3f p1) - { - float tmp; - tmp = Math.max( Math.abs(this.x-p1.x), Math.abs(this.y-p1.y)); - return(Math.max(tmp,Math.abs(this.z-p1.z))); + /** + * Computes the L-infinite distance between this point and + * point p1. The L-infinite distance is equal to + * MAX[abs(x1-x2), abs(y1-y2), abs(z1-z2)]. + * + * @param p1 the other point + * @return the L-infinite distance + */ + public final float distanceLinf(Point3f p1) { + float tmp; + tmp = Math.max(Math.abs(this.x - p1.x), Math.abs(this.y - p1.y)); + return (Math.max(tmp, Math.abs(this.z - p1.z))); } - /** - * Multiplies each of the x,y,z components of the Point4f parameter - * by 1/w and places the projected values into this point. - * @param p1 the source Point4f, which is not modified - */ - public final void project(Point4f p1) - { - float oneOw; + /** + * Multiplies each of the x,y,z components of the Point4f parameter + * by 1/w and places the projected values into this point. + * + * @param p1 the source Point4f, which is not modified + */ + public final void project(Point4f p1) { + float oneOw; - oneOw = 1/p1.w; - x = p1.x*oneOw; - y = p1.y*oneOw; - z = p1.z*oneOw; + oneOw = 1 / p1.w; + x = p1.x * oneOw; + y = p1.y * oneOw; + z = p1.z * oneOw; - } + } } diff --git a/src/main/java/com/volmit/iris/util/Point4d.java b/src/main/java/com/volmit/iris/util/Point4d.java index 6f37f3ae5..970db5b44 100644 --- a/src/main/java/com/volmit/iris/util/Point4d.java +++ b/src/main/java/com/volmit/iris/util/Point4d.java @@ -31,12 +31,9 @@ package com.volmit.iris.util; -import java.lang.Math; - /** - * A 4 element vector represented by double precision floating point + * A 4 element vector represented by double precision floating point * x,y,z,w coordinates. - * */ public class Point4d extends Tuple4d implements java.io.Serializable { @@ -46,87 +43,86 @@ public class Point4d extends Tuple4d implements java.io.Serializable { /** * Constructs and initializes a Point4d from the specified xyzw coordinates. + * * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate * @param w the w coordinate */ - public Point4d(double x, double y, double z, double w) - { - super(x,y,z,w); + public Point4d(double x, double y, double z, double w) { + super(x, y, z, w); } /** * Constructs and initializes a Point4d from the coordinates contained * in the array. + * * @param p the array of length 4 containing xyzw in order */ - public Point4d(double[] p) - { + public Point4d(double[] p) { super(p); } /** * Constructs and initializes a Point4d from the specified Point4d. + * * @param p1 the Point4d containing the initialization x y z w data */ - public Point4d(Point4d p1) - { - super(p1); + public Point4d(Point4d p1) { + super(p1); } /** * Constructs and initializes a Point4d from the specified Point4f. + * * @param p1 the Point4f containing the initialization x y z w data */ - public Point4d(Point4f p1) - { - super(p1); + public Point4d(Point4f p1) { + super(p1); } - /** - * Constructs and initializes a Point4d from the specified Tuple4f. - * @param t1 the Tuple4f containing the initialization x y z w data - */ - public Point4d(Tuple4f t1) - { - super(t1); - } - - - /** - * Constructs and initializes a Point4d from the specified Tuple4d. - * @param t1 the Tuple4d containing the initialization x y z w data - */ - public Point4d(Tuple4d t1) - { - super(t1); - } - + /** + * Constructs and initializes a Point4d from the specified Tuple4f. + * + * @param t1 the Tuple4f containing the initialization x y z w data + */ + public Point4d(Tuple4f t1) { + super(t1); + } + + + /** + * Constructs and initializes a Point4d from the specified Tuple4d. + * + * @param t1 the Tuple4d containing the initialization x y z w data + */ + public Point4d(Tuple4d t1) { + super(t1); + } + /** * Constructs and initializes a Point4d from the specified Tuple3d. * The x,y,z components of this point are set to the corresponding * components of tuple t1. The w component of this point * is set to 1. - * @param t1 the tuple to be copied * + * @param t1 the tuple to be copied * @since vecmath 1.2 */ public Point4d(Tuple3d t1) { - super(t1.x, t1.y, t1.z, 1.0); + super(t1.x, t1.y, t1.z, 1.0); } /** * Constructs and initializes a Point4d to (0,0,0,0). */ - public Point4d() - { - super(); + public Point4d() { + super(); } @@ -134,96 +130,98 @@ public class Point4d extends Tuple4d implements java.io.Serializable { * Sets the x,y,z components of this point to the corresponding * components of tuple t1. The w component of this point * is set to 1. - * @param t1 the tuple to be copied * + * @param t1 the tuple to be copied * @since vecmath 1.2 */ public final void set(Tuple3d t1) { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; - this.w = 1.0; + this.x = t1.x; + this.y = t1.y; + this.z = t1.z; + this.w = 1.0; } - /** - * Returns the square of the distance between this point and point p1. - * @param p1 the first point - * @return the square of distance between this point and point p1 - */ - public final double distanceSquared(Point4d p1) - { - double dx, dy, dz, dw; + /** + * Returns the square of the distance between this point and point p1. + * + * @param p1 the first point + * @return the square of distance between this point and point p1 + */ + public final double distanceSquared(Point4d p1) { + double dx, dy, dz, dw; - dx = this.x-p1.x; - dy = this.y-p1.y; - dz = this.z-p1.z; - dw = this.w-p1.w; - return (dx*dx+dy*dy+dz*dz+dw*dw); + dx = this.x - p1.x; + dy = this.y - p1.y; + dz = this.z - p1.z; + dw = this.w - p1.w; + return (dx * dx + dy * dy + dz * dz + dw * dw); } - /** - * Returns the distance between this point and point p1. - * @param p1 the first point - * @return the distance between these this point and point p1. - */ - public final double distance(Point4d p1) - { - double dx, dy, dz, dw; + /** + * Returns the distance between this point and point p1. + * + * @param p1 the first point + * @return the distance between these this point and point p1. + */ + public final double distance(Point4d p1) { + double dx, dy, dz, dw; - dx = this.x-p1.x; - dy = this.y-p1.y; - dz = this.z-p1.z; - dw = this.w-p1.w; - return Math.sqrt(dx*dx+dy*dy+dz*dz+dw*dw); + dx = this.x - p1.x; + dy = this.y - p1.y; + dz = this.z - p1.z; + dw = this.w - p1.w; + return Math.sqrt(dx * dx + dy * dy + dz * dz + dw * dw); } - /** - * Computes the L-1 (Manhattan) distance between this point and - * point p1. The L-1 distance is equal to: - * abs(x1-x2) + abs(y1-y2) + abs(z1-z2) + abs(w1-w2). - * @param p1 the other point - * @return the L-1 distance - */ + /** + * Computes the L-1 (Manhattan) distance between this point and + * point p1. The L-1 distance is equal to: + * abs(x1-x2) + abs(y1-y2) + abs(z1-z2) + abs(w1-w2). + * + * @param p1 the other point + * @return the L-1 distance + */ public final double distanceL1(Point4d p1) { - return Math.abs(this.x-p1.x) + Math.abs(this.y-p1.y) + - Math.abs(this.z-p1.z) + Math.abs(this.w-p1.w); + return Math.abs(this.x - p1.x) + Math.abs(this.y - p1.y) + + Math.abs(this.z - p1.z) + Math.abs(this.w - p1.w); } /** * Computes the L-infinite distance between this point and * point p1. The L-infinite distance is equal to * MAX[abs(x1-x2), abs(y1-y2), abs(z1-z2), abs(w1-w2)]. + * * @param p1 the other point - * @return the L-infinite distance + * @return the L-infinite distance */ public final double distanceLinf(Point4d p1) { - double t1, t2; - t1 = Math.max( Math.abs(this.x-p1.x), Math.abs(this.y-p1.y)); - t2 = Math.max( Math.abs(this.z-p1.z), Math.abs(this.w-p1.w)); - - return Math.max(t1,t2); + double t1, t2; + t1 = Math.max(Math.abs(this.x - p1.x), Math.abs(this.y - p1.y)); + t2 = Math.max(Math.abs(this.z - p1.z), Math.abs(this.w - p1.w)); + + return Math.max(t1, t2); } - /** - * Multiplies each of the x,y,z components of the Point4d parameter - * by 1/w, places the projected values into this point, and places - * a 1 as the w parameter of this point. - * @param p1 the source Point4d, which is not modified - */ - public final void project(Point4d p1) - { - double oneOw; + /** + * Multiplies each of the x,y,z components of the Point4d parameter + * by 1/w, places the projected values into this point, and places + * a 1 as the w parameter of this point. + * + * @param p1 the source Point4d, which is not modified + */ + public final void project(Point4d p1) { + double oneOw; - oneOw = 1/p1.w; - x = p1.x*oneOw; - y = p1.y*oneOw; - z = p1.z*oneOw; - w = 1.0; + oneOw = 1 / p1.w; + x = p1.x * oneOw; + y = p1.y * oneOw; + z = p1.z * oneOw; + w = 1.0; - } + } } diff --git a/src/main/java/com/volmit/iris/util/Point4f.java b/src/main/java/com/volmit/iris/util/Point4f.java index ea0b0357c..8e9d79f58 100644 --- a/src/main/java/com/volmit/iris/util/Point4f.java +++ b/src/main/java/com/volmit/iris/util/Point4f.java @@ -31,12 +31,9 @@ package com.volmit.iris.util; -import java.lang.Math; - /** - * A 4 element point represented by single precision floating point x,y,z,w + * A 4 element point represented by single precision floating point x,y,z,w * coordinates. - * */ public class Point4f extends Tuple4f implements java.io.Serializable { @@ -44,188 +41,187 @@ public class Point4f extends Tuple4f implements java.io.Serializable { // Compatible with 1.1 static final long serialVersionUID = 4643134103185764459L; - /** - * Constructs and initializes a Point4f from the specified xyzw coordinates. - * @param x the x coordinate - * @param y the y coordinate - * @param z the z coordinate - * @param w the w coordinate - */ - public Point4f(float x, float y, float z, float w) - { - super(x,y,z,w); - } - - - /** - * Constructs and initializes a Point4f from the array of length 4. - * @param p the array of length 4 containing xyzw in order - */ - public Point4f(float[] p) - { - super(p); - } - - - /** - * Constructs and initializes a Point4f from the specified Point4f. - * @param p1 the Point4f containing the initialization x y z w data - */ - public Point4f(Point4f p1) - { - super(p1); - } - - - /** - * Constructs and initializes a Point4f from the specified Point4d. - * @param p1 the Point4d containing the initialization x y z w data - */ - public Point4f(Point4d p1) - { - super(p1); - } - - - /** - * Constructs and initializes a Point4f from the specified Tuple4f. - * @param t1 the Tuple4f containing the initialization x y z w data - */ - public Point4f(Tuple4f t1) - { - super(t1); + /** + * Constructs and initializes a Point4f from the specified xyzw coordinates. + * + * @param x the x coordinate + * @param y the y coordinate + * @param z the z coordinate + * @param w the w coordinate + */ + public Point4f(float x, float y, float z, float w) { + super(x, y, z, w); } - - - /** - * Constructs and initializes a Point4f from the specified Tuple4d. - * @param t1 the Tuple4d containing the initialization x y z w data - */ - public Point4f(Tuple4d t1) - { - super(t1); + + + /** + * Constructs and initializes a Point4f from the array of length 4. + * + * @param p the array of length 4 containing xyzw in order + */ + public Point4f(float[] p) { + super(p); } - + + + /** + * Constructs and initializes a Point4f from the specified Point4f. + * + * @param p1 the Point4f containing the initialization x y z w data + */ + public Point4f(Point4f p1) { + super(p1); + } + + + /** + * Constructs and initializes a Point4f from the specified Point4d. + * + * @param p1 the Point4d containing the initialization x y z w data + */ + public Point4f(Point4d p1) { + super(p1); + } + + + /** + * Constructs and initializes a Point4f from the specified Tuple4f. + * + * @param t1 the Tuple4f containing the initialization x y z w data + */ + public Point4f(Tuple4f t1) { + super(t1); + } + + + /** + * Constructs and initializes a Point4f from the specified Tuple4d. + * + * @param t1 the Tuple4d containing the initialization x y z w data + */ + public Point4f(Tuple4d t1) { + super(t1); + } + /** * Constructs and initializes a Point4f from the specified Tuple3f. * The x,y,z components of this point are set to the corresponding * components of tuple t1. The w component of this point * is set to 1. - * @param t1 the tuple to be copied * + * @param t1 the tuple to be copied * @since vecmath 1.2 */ public Point4f(Tuple3f t1) { - super(t1.x, t1.y, t1.z, 1.0f); + super(t1.x, t1.y, t1.z, 1.0f); } - /** - * Constructs and initializes a Point4f to (0,0,0,0). - */ - public Point4f() - { - super(); - } + /** + * Constructs and initializes a Point4f to (0,0,0,0). + */ + public Point4f() { + super(); + } /** * Sets the x,y,z components of this point to the corresponding * components of tuple t1. The w component of this point * is set to 1. - * @param t1 the tuple to be copied * + * @param t1 the tuple to be copied * @since vecmath 1.2 */ public final void set(Tuple3f t1) { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; - this.w = 1.0f; + this.x = t1.x; + this.y = t1.y; + this.z = t1.z; + this.w = 1.0f; } - /** - * Computes the square of the distance between this point and point p1. - * @param p1 the other point - * @return the square of distance between these two points as a float - */ - public final float distanceSquared(Point4f p1) - { - float dx, dy, dz, dw; + /** + * Computes the square of the distance between this point and point p1. + * + * @param p1 the other point + * @return the square of distance between these two points as a float + */ + public final float distanceSquared(Point4f p1) { + float dx, dy, dz, dw; - dx = this.x-p1.x; - dy = this.y-p1.y; - dz = this.z-p1.z; - dw = this.w-p1.w; - return (dx*dx+dy*dy+dz*dz+dw*dw); + dx = this.x - p1.x; + dy = this.y - p1.y; + dz = this.z - p1.z; + dw = this.w - p1.w; + return (dx * dx + dy * dy + dz * dz + dw * dw); } - /** - * Computes the distance between this point and point p1. - * @param p1 the other point - * @return the distance between the two points - */ - public final float distance(Point4f p1) - { - float dx, dy, dz, dw; + /** + * Computes the distance between this point and point p1. + * + * @param p1 the other point + * @return the distance between the two points + */ + public final float distance(Point4f p1) { + float dx, dy, dz, dw; - dx = this.x-p1.x; - dy = this.y-p1.y; - dz = this.z-p1.z; - dw = this.w-p1.w; - return (float) Math.sqrt(dx*dx+dy*dy+dz*dz+dw*dw); + dx = this.x - p1.x; + dy = this.y - p1.y; + dz = this.z - p1.z; + dw = this.w - p1.w; + return (float) Math.sqrt(dx * dx + dy * dy + dz * dz + dw * dw); } - /** - * Computes the L-1 (Manhattan) distance between this point and - * point p1. The L-1 distance is equal to: - * abs(x1-x2) + abs(y1-y2) + abs(z1-z2) + abs(w1-w2). - * @param p1 the other point - * @return the L-1 distance - */ - public final float distanceL1(Point4f p1) - { - return( Math.abs(this.x-p1.x) + Math.abs(this.y-p1.y) + Math.abs(this.z-p1.z) + Math.abs(this.w-p1.w)); + /** + * Computes the L-1 (Manhattan) distance between this point and + * point p1. The L-1 distance is equal to: + * abs(x1-x2) + abs(y1-y2) + abs(z1-z2) + abs(w1-w2). + * + * @param p1 the other point + * @return the L-1 distance + */ + public final float distanceL1(Point4f p1) { + return (Math.abs(this.x - p1.x) + Math.abs(this.y - p1.y) + Math.abs(this.z - p1.z) + Math.abs(this.w - p1.w)); } - /** - * Computes the L-infinite distance between this point and - * point p1. The L-infinite distance is equal to - * MAX[abs(x1-x2), abs(y1-y2), abs(z1-z2), abs(w1-w2)]. - * @param p1 the other point - * @return the L-infinite distance - */ - public final float distanceLinf(Point4f p1) - { - float t1, t2; - t1 = Math.max( Math.abs(this.x-p1.x), Math.abs(this.y-p1.y)); - t2 = Math.max( Math.abs(this.z-p1.z), Math.abs(this.w-p1.w)); - - return(Math.max(t1,t2)); + /** + * Computes the L-infinite distance between this point and + * point p1. The L-infinite distance is equal to + * MAX[abs(x1-x2), abs(y1-y2), abs(z1-z2), abs(w1-w2)]. + * + * @param p1 the other point + * @return the L-infinite distance + */ + public final float distanceLinf(Point4f p1) { + float t1, t2; + t1 = Math.max(Math.abs(this.x - p1.x), Math.abs(this.y - p1.y)); + t2 = Math.max(Math.abs(this.z - p1.z), Math.abs(this.w - p1.w)); + + return (Math.max(t1, t2)); } - /** - * Multiplies each of the x,y,z components of the Point4f parameter - * by 1/w, places the projected values into this point, and places - * a 1 as the w parameter of this point. - * @param p1 the source Point4f, which is not modified - */ - public final void project(Point4f p1) - { - float oneOw; + /** + * Multiplies each of the x,y,z components of the Point4f parameter + * by 1/w, places the projected values into this point, and places + * a 1 as the w parameter of this point. + * + * @param p1 the source Point4f, which is not modified + */ + public final void project(Point4f p1) { + float oneOw; - oneOw = 1/p1.w; - x = p1.x*oneOw; - y = p1.y*oneOw; - z = p1.z*oneOw; - w = 1.0f; + oneOw = 1 / p1.w; + x = p1.x * oneOw; + y = p1.y * oneOw; + z = p1.z * oneOw; + w = 1.0f; - } + } } diff --git a/src/main/java/com/volmit/iris/util/PrecisionStopwatch.java b/src/main/java/com/volmit/iris/util/PrecisionStopwatch.java index 5b6995c3d..1024ae2f2 100644 --- a/src/main/java/com/volmit/iris/util/PrecisionStopwatch.java +++ b/src/main/java/com/volmit/iris/util/PrecisionStopwatch.java @@ -1,106 +1,105 @@ package com.volmit.iris.util; public class PrecisionStopwatch { - private long nanos; - private long startNano; - private long millis; - private long startMillis; - private double time; - private boolean profiling; + private long nanos; + private long startNano; + private long millis; + private long startMillis; + private double time; + private boolean profiling; - public static PrecisionStopwatch start() { - PrecisionStopwatch p = new PrecisionStopwatch(); - p.begin(); + public static PrecisionStopwatch start() { + PrecisionStopwatch p = new PrecisionStopwatch(); + p.begin(); - return p; - } + return p; + } - public PrecisionStopwatch() { - reset(); - profiling = false; - } + public PrecisionStopwatch() { + reset(); + profiling = false; + } - public void begin() { - profiling = true; - startNano = System.nanoTime(); - startMillis = System.currentTimeMillis(); - } + public void begin() { + profiling = true; + startNano = System.nanoTime(); + startMillis = System.currentTimeMillis(); + } - public void end() { - if (!profiling) { - return; - } + public void end() { + if (!profiling) { + return; + } - profiling = false; - nanos = System.nanoTime() - startNano; - millis = System.currentTimeMillis() - startMillis; - time = (double) nanos / 1000000.0; - time = (double) millis - time > 1.01 ? millis : time; - } + profiling = false; + nanos = System.nanoTime() - startNano; + millis = System.currentTimeMillis() - startMillis; + time = (double) nanos / 1000000.0; + time = (double) millis - time > 1.01 ? millis : time; + } - public void reset() { - nanos = -1; - millis = -1; - startNano = -1; - startMillis = -1; - time = -0; - profiling = false; - } + public void reset() { + nanos = -1; + millis = -1; + startNano = -1; + startMillis = -1; + time = -0; + profiling = false; + } - public double getTicks() { - return getMilliseconds() / 50.0; - } + public double getTicks() { + return getMilliseconds() / 50.0; + } - public double getSeconds() { - return getMilliseconds() / 1000.0; - } + public double getSeconds() { + return getMilliseconds() / 1000.0; + } - public double getMinutes() { - return getSeconds() / 60.0; - } + public double getMinutes() { + return getSeconds() / 60.0; + } - public double getHours() { - return getMinutes() / 60.0; - } + public double getHours() { + return getMinutes() / 60.0; + } - public double getMilliseconds() { - nanos = System.nanoTime() - startNano; - millis = System.currentTimeMillis() - startMillis; - time = (double) nanos / 1000000.0; - time = (double) millis - time > 1.01 ? millis : time; - return time; - } + public double getMilliseconds() { + nanos = System.nanoTime() - startNano; + millis = System.currentTimeMillis() - startMillis; + time = (double) nanos / 1000000.0; + time = (double) millis - time > 1.01 ? millis : time; + return time; + } - public long getNanoseconds() { - return (long) (time * 1000000.0); - } + public long getNanoseconds() { + return (long) (time * 1000000.0); + } - public long getNanos() { - return nanos; - } + public long getNanos() { + return nanos; + } - public long getStartNano() { - return startNano; - } + public long getStartNano() { + return startNano; + } - public long getMillis() { - return millis; - } + public long getMillis() { + return millis; + } - public long getStartMillis() { - return startMillis; - } + public long getStartMillis() { + return startMillis; + } - public double getTime() { - return time; - } + public double getTime() { + return time; + } - public boolean isProfiling() { - return profiling; - } + public boolean isProfiling() { + return profiling; + } - public void rewind(long l) - { - startMillis -= l; - } + public void rewind(long l) { + startMillis -= l; + } } diff --git a/src/main/java/com/volmit/iris/util/Queue.java b/src/main/java/com/volmit/iris/util/Queue.java index 43a76c1fe..012d587b9 100644 --- a/src/main/java/com/volmit/iris/util/Queue.java +++ b/src/main/java/com/volmit/iris/util/Queue.java @@ -1,33 +1,30 @@ package com.volmit.iris.util; -public interface Queue -{ - public Queue queue(T t); +public interface Queue { + Queue queue(T t); - public Queue queue(KList t); + Queue queue(KList t); - public boolean hasNext(int amt); + boolean hasNext(int amt); - public boolean hasNext(); + boolean hasNext(); - public T next(); + T next(); - public KList next(int amt); + KList next(int amt); - public Queue clear(); + Queue clear(); - public int size(); + int size(); - public static Queue create(KList t) - { - return new ShurikenQueue().queue(t); - } + static Queue create(KList t) { + return new ShurikenQueue().queue(t); + } - @SuppressWarnings("unchecked") - public static Queue create(T... t) - { - return new ShurikenQueue().queue(new KList().add(t)); - } + @SuppressWarnings("unchecked") + static Queue create(T... t) { + return new ShurikenQueue().queue(new KList().add(t)); + } - public boolean contains(T p); + boolean contains(T p); } diff --git a/src/main/java/com/volmit/iris/util/QueueExecutor.java b/src/main/java/com/volmit/iris/util/QueueExecutor.java index fb53688a9..9d4b1cc35 100644 --- a/src/main/java/com/volmit/iris/util/QueueExecutor.java +++ b/src/main/java/com/volmit/iris/util/QueueExecutor.java @@ -1,53 +1,41 @@ package com.volmit.iris.util; -public class QueueExecutor extends Looper -{ - private Queue queue; - private boolean shutdown; +public class QueueExecutor extends Looper { + private final Queue queue; + private boolean shutdown; - public QueueExecutor() - { - queue = new ShurikenQueue(); - shutdown = false; - } + public QueueExecutor() { + queue = new ShurikenQueue(); + shutdown = false; + } - public Queue queue() - { - return queue; - } + public Queue queue() { + return queue; + } - @Override - protected long loop() - { - while(queue.hasNext()) - { - try - { - queue.next().run(); - } + @Override + protected long loop() { + while (queue.hasNext()) { + try { + queue.next().run(); + } catch (Throwable e) { + e.printStackTrace(); + } + } - catch(Throwable e) - { - e.printStackTrace(); - } - } + if (shutdown && !queue.hasNext()) { + interrupt(); + return -1; + } - if(shutdown && !queue.hasNext()) - { - interrupt(); - return -1; - } + return Math.max(500, (long) getRunTime() * 10); + } - return Math.max(500, (long) getRunTime() * 10); - } + public double getRunTime() { + return 0; + } - public double getRunTime() - { - return 0; - } - - public void shutdown() - { - shutdown = true; - } + public void shutdown() { + shutdown = true; + } } diff --git a/src/main/java/com/volmit/iris/util/RNG.java b/src/main/java/com/volmit/iris/util/RNG.java index d5986e08f..b096df76c 100644 --- a/src/main/java/com/volmit/iris/util/RNG.java +++ b/src/main/java/com/volmit/iris/util/RNG.java @@ -5,195 +5,161 @@ import java.util.List; import java.util.Random; import java.util.UUID; -public class RNG extends Random -{ - private static final char[] CHARGEN = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-=!@#$%^&*()_+`~[];',./<>?:\\\"{}|\\\\".toCharArray(); - private static final long serialVersionUID = 5222938581174415179L; - public static final RNG r = new RNG(); - private final long sx; +public class RNG extends Random { + private static final char[] CHARGEN = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-=!@#$%^&*()_+`~[];',./<>?:\\\"{}|\\\\".toCharArray(); + private static final long serialVersionUID = 5222938581174415179L; + public static final RNG r = new RNG(); + private final long sx; - public RNG() - { - super(); - sx = 0; - } + public RNG() { + super(); + sx = 0; + } - public RNG(long seed) - { - super(seed); - this.sx = seed; - } + public RNG(long seed) { + super(seed); + this.sx = seed; + } - /** - * Creates a seed (long) from the hash of the seed string - * - * @param seed - * the seed (string) - */ - public RNG(String seed) - { - this(UUID.nameUUIDFromBytes(seed.getBytes(StandardCharsets.UTF_8)).getLeastSignificantBits() + UUID.nameUUIDFromBytes(seed.getBytes(StandardCharsets.UTF_8)).getMostSignificantBits() + (seed.length() * 32564)); - } + /** + * Creates a seed (long) from the hash of the seed string + * + * @param seed the seed (string) + */ + public RNG(String seed) { + this(UUID.nameUUIDFromBytes(seed.getBytes(StandardCharsets.UTF_8)).getLeastSignificantBits() + UUID.nameUUIDFromBytes(seed.getBytes(StandardCharsets.UTF_8)).getMostSignificantBits() + (seed.length() * 32564)); + } - public RNG nextParallelRNG(int signature) - { - return new RNG(sx + signature); - } - - public RNG nextParallelRNG(long signature) - { - return new RNG(sx + signature); - } + public RNG nextParallelRNG(int signature) { + return new RNG(sx + signature); + } - public String s(int length) - { - StringBuilder sb = new StringBuilder(); + public RNG nextParallelRNG(long signature) { + return new RNG(sx + signature); + } - for(int i = 0; i < length; i++) - { - sb.append(c()); - } + public String s(int length) { + StringBuilder sb = new StringBuilder(); - return sb.toString(); - } + for (int i = 0; i < length; i++) { + sb.append(c()); + } - public char c() - { - return CHARGEN[i(CHARGEN.length - 1)]; - } + return sb.toString(); + } - /** - * Pick a random enum - * - * @param t - * the enum class - * @return the enum - */ - public T e(Class t) - { - T[] c = t.getEnumConstants(); - return c[i(c.length)]; - } + public char c() { + return CHARGEN[i(CHARGEN.length - 1)]; + } - public boolean b() - { - return nextBoolean(); - } + /** + * Pick a random enum + * + * @param t the enum class + * @return the enum + */ + public T e(Class t) { + T[] c = t.getEnumConstants(); + return c[i(c.length)]; + } - public boolean b(double percent) - { - return d() > percent; - } + public boolean b() { + return nextBoolean(); + } - public short si(int lowerBound, int upperBound) - { - return (short) (lowerBound + (nextFloat() * ((upperBound - lowerBound) + 1))); - } + public boolean b(double percent) { + return d() > percent; + } - public short si(int upperBound) - { - return si(0, upperBound); - } + public short si(int lowerBound, int upperBound) { + return (short) (lowerBound + (nextFloat() * ((upperBound - lowerBound) + 1))); + } - public short si() - { - return si(1); - } + public short si(int upperBound) { + return si(0, upperBound); + } - public float f(float lowerBound, float upperBound) - { - return lowerBound + (nextFloat() * ((upperBound - lowerBound))); - } + public short si() { + return si(1); + } - public float f(float upperBound) - { - return f(0, upperBound); - } + public float f(float lowerBound, float upperBound) { + return lowerBound + (nextFloat() * ((upperBound - lowerBound))); + } - public float f() - { - return f(1); - } + public float f(float upperBound) { + return f(0, upperBound); + } - public double d(double lowerBound, double upperBound) - { - return M.lerp(lowerBound, upperBound, nextDouble()); - } + public float f() { + return f(1); + } - public double d(double upperBound) - { - return d(0, upperBound); - } + public double d(double lowerBound, double upperBound) { + return M.lerp(lowerBound, upperBound, nextDouble()); + } - public double d() - { - return d(1); - } + public double d(double upperBound) { + return d(0, upperBound); + } - public int i(int lowerBound, int upperBound) - { - return (int) Math.floor(d(lowerBound, upperBound)); - } + public double d() { + return d(1); + } - public int i(int upperBound) - { - return i(Math.min(upperBound, 0), Math.max(0, upperBound)); - } + public int i(int lowerBound, int upperBound) { + return (int) Math.floor(d(lowerBound, upperBound)); + } - public long l(long lowerBound, long upperBound) - { - return Math.round(d(lowerBound, upperBound)); - } + public int i(int upperBound) { + return i(Math.min(upperBound, 0), Math.max(0, upperBound)); + } - public long l(long upperBound) - { - return l(0, upperBound); - } + public long l(long lowerBound, long upperBound) { + return Math.round(d(lowerBound, upperBound)); + } - public int imax() - { - return i(Integer.MIN_VALUE, Integer.MAX_VALUE); - } + public long l(long upperBound) { + return l(0, upperBound); + } - public long lmax() - { - return l(Long.MIN_VALUE, Long.MAX_VALUE); - } + public int imax() { + return i(Integer.MIN_VALUE, Integer.MAX_VALUE); + } - public float fmax() - { - return f(Float.MIN_VALUE, Float.MAX_VALUE); - } + public long lmax() { + return l(Long.MIN_VALUE, Long.MAX_VALUE); + } - public double dmax() - { - return d(Double.MIN_VALUE, Double.MAX_VALUE); - } + public float fmax() { + return f(Float.MIN_VALUE, Float.MAX_VALUE); + } - public short simax() - { - return si(Short.MIN_VALUE, Short.MAX_VALUE); - } + public double dmax() { + return d(Double.MIN_VALUE, Double.MAX_VALUE); + } + + public short simax() { + return si(Short.MIN_VALUE, Short.MAX_VALUE); + } public boolean chance(double chance) { - return chance >= nextDouble(); + return chance >= nextDouble(); } public T pick(List pieces) { - if(pieces.isEmpty()) - { - return null; - } + if (pieces.isEmpty()) { + return null; + } - if(pieces.size() == 1) - { - return pieces.get(0); - } + if (pieces.size() == 1) { + return pieces.get(0); + } - return pieces.get(nextInt(pieces.size())); + return pieces.get(nextInt(pieces.size())); } public long getSeed() { - return sx; - } + return sx; + } } diff --git a/src/main/java/com/volmit/iris/util/ReactiveFolder.java b/src/main/java/com/volmit/iris/util/ReactiveFolder.java index 73a44b94c..00f632ae1 100644 --- a/src/main/java/com/volmit/iris/util/ReactiveFolder.java +++ b/src/main/java/com/volmit/iris/util/ReactiveFolder.java @@ -2,58 +2,45 @@ package com.volmit.iris.util; import java.io.File; -public class ReactiveFolder -{ - private File folder; - private Consumer3, KList, KList> hotload; +public class ReactiveFolder { + private final File folder; + private final Consumer3, KList, KList> hotload; private FolderWatcher fw; - public ReactiveFolder(File folder, Consumer3, KList, KList> hotload) - { + public ReactiveFolder(File folder, Consumer3, KList, KList> hotload) { this.folder = folder; this.hotload = hotload; this.fw = new FolderWatcher(folder); fw.checkModified(); } - public void checkIgnore() - { + public void checkIgnore() { fw = new FolderWatcher(folder); } - public void check() - { + public void check() { boolean modified = false; - if(fw.checkModified()) - { - for(File i : fw.getCreated()) - { - if(i.getName().endsWith(".iob") || i.getName().endsWith(".json")) - { + if (fw.checkModified()) { + for (File i : fw.getCreated()) { + if (i.getName().endsWith(".iob") || i.getName().endsWith(".json")) { modified = true; break; } } - if(!modified) - { - for(File i : fw.getChanged()) - { - if(i.getName().endsWith(".iob") || i.getName().endsWith(".json")) - { + if (!modified) { + for (File i : fw.getChanged()) { + if (i.getName().endsWith(".iob") || i.getName().endsWith(".json")) { modified = true; break; } } } - if(!modified) - { - for(File i : fw.getDeleted()) - { - if(i.getName().endsWith(".iob") || i.getName().endsWith(".json")) - { + if (!modified) { + for (File i : fw.getDeleted()) { + if (i.getName().endsWith(".iob") || i.getName().endsWith(".json")) { modified = true; break; } @@ -61,8 +48,7 @@ public class ReactiveFolder } } - if(modified) - { + if (modified) { hotload.accept(fw.getCreated(), fw.getChanged(), fw.getDeleted()); } diff --git a/src/main/java/com/volmit/iris/util/RegistryListBiome.java b/src/main/java/com/volmit/iris/util/RegistryListBiome.java index 36c838c39..2e7ba549e 100644 --- a/src/main/java/com/volmit/iris/util/RegistryListBiome.java +++ b/src/main/java/com/volmit/iris/util/RegistryListBiome.java @@ -1,14 +1,13 @@ package com.volmit.iris.util; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - import java.lang.annotation.Retention; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + @Retention(RUNTIME) @Target({PARAMETER, TYPE, FIELD}) -public @interface RegistryListBiome -{ +public @interface RegistryListBiome { } diff --git a/src/main/java/com/volmit/iris/util/RegistryListBlockType.java b/src/main/java/com/volmit/iris/util/RegistryListBlockType.java index 094f3c58c..4a1b56dbf 100644 --- a/src/main/java/com/volmit/iris/util/RegistryListBlockType.java +++ b/src/main/java/com/volmit/iris/util/RegistryListBlockType.java @@ -1,14 +1,13 @@ package com.volmit.iris.util; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - import java.lang.annotation.Retention; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + @Retention(RUNTIME) @Target({PARAMETER, TYPE, FIELD}) -public @interface RegistryListBlockType -{ +public @interface RegistryListBlockType { } diff --git a/src/main/java/com/volmit/iris/util/RegistryListDimension.java b/src/main/java/com/volmit/iris/util/RegistryListDimension.java index 70e730d68..c53aac8ef 100644 --- a/src/main/java/com/volmit/iris/util/RegistryListDimension.java +++ b/src/main/java/com/volmit/iris/util/RegistryListDimension.java @@ -1,14 +1,13 @@ package com.volmit.iris.util; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - import java.lang.annotation.Retention; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + @Retention(RUNTIME) @Target({PARAMETER, TYPE, FIELD}) -public @interface RegistryListDimension -{ +public @interface RegistryListDimension { } diff --git a/src/main/java/com/volmit/iris/util/RegistryListEntity.java b/src/main/java/com/volmit/iris/util/RegistryListEntity.java index 37ecbdae4..189f0da76 100644 --- a/src/main/java/com/volmit/iris/util/RegistryListEntity.java +++ b/src/main/java/com/volmit/iris/util/RegistryListEntity.java @@ -1,14 +1,13 @@ package com.volmit.iris.util; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - import java.lang.annotation.Retention; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + @Retention(RUNTIME) @Target({PARAMETER, TYPE, FIELD}) -public @interface RegistryListEntity -{ +public @interface RegistryListEntity { } diff --git a/src/main/java/com/volmit/iris/util/RegistryListFont.java b/src/main/java/com/volmit/iris/util/RegistryListFont.java index bd0bbb8e0..3ff432db3 100644 --- a/src/main/java/com/volmit/iris/util/RegistryListFont.java +++ b/src/main/java/com/volmit/iris/util/RegistryListFont.java @@ -1,14 +1,13 @@ package com.volmit.iris.util; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - import java.lang.annotation.Retention; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + @Retention(RUNTIME) @Target({PARAMETER, TYPE, FIELD}) -public @interface RegistryListFont -{ +public @interface RegistryListFont { } diff --git a/src/main/java/com/volmit/iris/util/RegistryListGenerator.java b/src/main/java/com/volmit/iris/util/RegistryListGenerator.java index fefd8cd2c..c114b30b6 100644 --- a/src/main/java/com/volmit/iris/util/RegistryListGenerator.java +++ b/src/main/java/com/volmit/iris/util/RegistryListGenerator.java @@ -1,14 +1,13 @@ package com.volmit.iris.util; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - import java.lang.annotation.Retention; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + @Retention(RUNTIME) @Target({PARAMETER, TYPE, FIELD}) -public @interface RegistryListGenerator -{ +public @interface RegistryListGenerator { } diff --git a/src/main/java/com/volmit/iris/util/RegistryListItemType.java b/src/main/java/com/volmit/iris/util/RegistryListItemType.java index 830124659..a2940fc2b 100644 --- a/src/main/java/com/volmit/iris/util/RegistryListItemType.java +++ b/src/main/java/com/volmit/iris/util/RegistryListItemType.java @@ -1,14 +1,13 @@ package com.volmit.iris.util; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - import java.lang.annotation.Retention; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + @Retention(RUNTIME) @Target({PARAMETER, TYPE, FIELD}) -public @interface RegistryListItemType -{ +public @interface RegistryListItemType { } diff --git a/src/main/java/com/volmit/iris/util/RegistryListJigsaw.java b/src/main/java/com/volmit/iris/util/RegistryListJigsaw.java index ea4173c20..41d0358b5 100644 --- a/src/main/java/com/volmit/iris/util/RegistryListJigsaw.java +++ b/src/main/java/com/volmit/iris/util/RegistryListJigsaw.java @@ -8,7 +8,6 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; @Retention(RUNTIME) @Target({PARAMETER, TYPE, FIELD}) -public @interface RegistryListJigsaw -{ +public @interface RegistryListJigsaw { } diff --git a/src/main/java/com/volmit/iris/util/RegistryListJigsawPiece.java b/src/main/java/com/volmit/iris/util/RegistryListJigsawPiece.java index aca2497e3..cc440d16c 100644 --- a/src/main/java/com/volmit/iris/util/RegistryListJigsawPiece.java +++ b/src/main/java/com/volmit/iris/util/RegistryListJigsawPiece.java @@ -8,7 +8,6 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; @Retention(RUNTIME) @Target({PARAMETER, TYPE, FIELD}) -public @interface RegistryListJigsawPiece -{ +public @interface RegistryListJigsawPiece { } diff --git a/src/main/java/com/volmit/iris/util/RegistryListJigsawPool.java b/src/main/java/com/volmit/iris/util/RegistryListJigsawPool.java index eba39a50e..98e5c70fe 100644 --- a/src/main/java/com/volmit/iris/util/RegistryListJigsawPool.java +++ b/src/main/java/com/volmit/iris/util/RegistryListJigsawPool.java @@ -8,7 +8,6 @@ import static java.lang.annotation.RetentionPolicy.RUNTIME; @Retention(RUNTIME) @Target({PARAMETER, TYPE, FIELD}) -public @interface RegistryListJigsawPool -{ +public @interface RegistryListJigsawPool { } diff --git a/src/main/java/com/volmit/iris/util/RegistryListLoot.java b/src/main/java/com/volmit/iris/util/RegistryListLoot.java index a62b8f874..5f1e7b7cb 100644 --- a/src/main/java/com/volmit/iris/util/RegistryListLoot.java +++ b/src/main/java/com/volmit/iris/util/RegistryListLoot.java @@ -1,14 +1,13 @@ package com.volmit.iris.util; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - import java.lang.annotation.Retention; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + @Retention(RUNTIME) @Target({PARAMETER, TYPE, FIELD}) -public @interface RegistryListLoot -{ +public @interface RegistryListLoot { } diff --git a/src/main/java/com/volmit/iris/util/RegistryListMythical.java b/src/main/java/com/volmit/iris/util/RegistryListMythical.java index f2b6283e6..c7c5927b5 100644 --- a/src/main/java/com/volmit/iris/util/RegistryListMythical.java +++ b/src/main/java/com/volmit/iris/util/RegistryListMythical.java @@ -1,14 +1,13 @@ package com.volmit.iris.util; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - import java.lang.annotation.Retention; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + @Retention(RUNTIME) @Target({PARAMETER, TYPE, FIELD}) -public @interface RegistryListMythical -{ +public @interface RegistryListMythical { } diff --git a/src/main/java/com/volmit/iris/util/RegistryListObject.java b/src/main/java/com/volmit/iris/util/RegistryListObject.java index 52cac3729..6c7965c19 100644 --- a/src/main/java/com/volmit/iris/util/RegistryListObject.java +++ b/src/main/java/com/volmit/iris/util/RegistryListObject.java @@ -1,14 +1,13 @@ package com.volmit.iris.util; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - import java.lang.annotation.Retention; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + @Retention(RUNTIME) @Target({PARAMETER, TYPE, FIELD}) -public @interface RegistryListObject -{ +public @interface RegistryListObject { } diff --git a/src/main/java/com/volmit/iris/util/RegistryListRegion.java b/src/main/java/com/volmit/iris/util/RegistryListRegion.java index 4b89eda7c..509f61bdb 100644 --- a/src/main/java/com/volmit/iris/util/RegistryListRegion.java +++ b/src/main/java/com/volmit/iris/util/RegistryListRegion.java @@ -1,14 +1,13 @@ package com.volmit.iris.util; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - import java.lang.annotation.Retention; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + @Retention(RUNTIME) @Target({PARAMETER, TYPE, FIELD}) -public @interface RegistryListRegion -{ +public @interface RegistryListRegion { } diff --git a/src/main/java/com/volmit/iris/util/Required.java b/src/main/java/com/volmit/iris/util/Required.java index 24d46ef58..e76be4556 100644 --- a/src/main/java/com/volmit/iris/util/Required.java +++ b/src/main/java/com/volmit/iris/util/Required.java @@ -1,14 +1,13 @@ package com.volmit.iris.util; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - import java.lang.annotation.Retention; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + @Retention(RUNTIME) @Target({PARAMETER, TYPE, FIELD}) -public @interface Required -{ +public @interface Required { } diff --git a/src/main/java/com/volmit/iris/util/ResourceLoader.java b/src/main/java/com/volmit/iris/util/ResourceLoader.java index 126d01b0e..2f4c21f7d 100644 --- a/src/main/java/com/volmit/iris/util/ResourceLoader.java +++ b/src/main/java/com/volmit/iris/util/ResourceLoader.java @@ -10,262 +10,213 @@ import java.io.File; import java.util.concurrent.atomic.AtomicInteger; @Data -public class ResourceLoader -{ - protected File root; - protected String folderName; - protected String resourceTypeName; - protected KMap folderMapCache; - protected KMap loadCache; - protected KList folderCache; - protected Class objectClass; - protected String cname; - protected IrisLock lock; - protected String[] possibleKeys = null; - protected IrisDataManager manager; - protected AtomicInteger loads; - protected ChronoLatch sec; +public class ResourceLoader { + protected File root; + protected String folderName; + protected String resourceTypeName; + protected KMap folderMapCache; + protected KMap loadCache; + protected KList folderCache; + protected Class objectClass; + protected String cname; + protected IrisLock lock; + protected String[] possibleKeys = null; + protected IrisDataManager manager; + protected AtomicInteger loads; + protected ChronoLatch sec; - public ResourceLoader(File root, IrisDataManager manager, String folderName, String resourceTypeName, Class objectClass) - { - lock = new IrisLock("Res"); - this.manager = manager; - sec = new ChronoLatch(5000); - loads = new AtomicInteger(); - folderMapCache = new KMap<>(); - this.objectClass = objectClass; - cname = objectClass.getCanonicalName(); - this.resourceTypeName = resourceTypeName; - this.root = root; - this.folderName = folderName; - loadCache = new KMap<>(); - } + public ResourceLoader(File root, IrisDataManager manager, String folderName, String resourceTypeName, Class objectClass) { + lock = new IrisLock("Res"); + this.manager = manager; + sec = new ChronoLatch(5000); + loads = new AtomicInteger(); + folderMapCache = new KMap<>(); + this.objectClass = objectClass; + cname = objectClass.getCanonicalName(); + this.resourceTypeName = resourceTypeName; + this.root = root; + this.folderName = folderName; + loadCache = new KMap<>(); + } - public void logLoad(File path) - { - loads.getAndIncrement(); + public void logLoad(File path) { + loads.getAndIncrement(); - if(loads.get() == 1) - { - sec.flip(); - } + if (loads.get() == 1) { + sec.flip(); + } - if(sec.flip()) - { - J.a(() -> { - Iris.verbose("Loaded " + C.WHITE + loads.get() + " " + resourceTypeName + (loads.get() == 1 ? "" : "s") + C.GRAY + " (" + Form.f(getLoadCache().size() ) + " " + resourceTypeName + (loadCache.size() == 1 ? "" : "s") + " Loaded)"); - loads.set(0); - }); - } - } + if (sec.flip()) { + J.a(() -> { + Iris.verbose("Loaded " + C.WHITE + loads.get() + " " + resourceTypeName + (loads.get() == 1 ? "" : "s") + C.GRAY + " (" + Form.f(getLoadCache().size()) + " " + resourceTypeName + (loadCache.size() == 1 ? "" : "s") + " Loaded)"); + loads.set(0); + }); + } + } - public void failLoad(File path, Throwable e) - { - J.a(() -> Iris.warn("Couldn't Load " + resourceTypeName + " file: " + path.getPath() + ": " + e.getMessage())); - } + public void failLoad(File path, Throwable e) { + J.a(() -> Iris.warn("Couldn't Load " + resourceTypeName + " file: " + path.getPath() + ": " + e.getMessage())); + } - public String[] getPossibleKeys() - { - if(possibleKeys != null) - { - return possibleKeys; - } + public String[] getPossibleKeys() { + if (possibleKeys != null) { + return possibleKeys; + } - Iris.info("Building " + resourceTypeName + " Registry Lists"); - KSet m = new KSet<>(); + Iris.info("Building " + resourceTypeName + " Registry Lists"); + KSet m = new KSet<>(); - for(File i : getFolders()) - { - for(File j : i.listFiles()) - { - if(j.isFile() && j.getName().endsWith(".json")) - { - m.add(j.getName().replaceAll("\\Q.json\\E", "")); - } + for (File i : getFolders()) { + for (File j : i.listFiles()) { + if (j.isFile() && j.getName().endsWith(".json")) { + m.add(j.getName().replaceAll("\\Q.json\\E", "")); + } else if (j.isDirectory()) { + for (File k : j.listFiles()) { + if (k.isFile() && k.getName().endsWith(".json")) { + m.add(j.getName() + "/" + k.getName().replaceAll("\\Q.json\\E", "")); + } + } + } + } + } - else if(j.isDirectory()) - { - for(File k : j.listFiles()) - { - if(k.isFile() && k.getName().endsWith(".json")) - { - m.add(j.getName() + "/" + k.getName().replaceAll("\\Q.json\\E", "")); - } - } - } - } - } + KList v = new KList<>(m); + possibleKeys = v.toArray(new String[v.size()]); + return possibleKeys; + } - KList v = new KList<>(m); - possibleKeys = v.toArray(new String[v.size()]); - return possibleKeys; - } + public long count() { + return loadCache.size(); + } - public long count() - { - return loadCache.size(); - } + protected T loadFile(File j, String key, String name) { + try { + T t = new Gson().fromJson(IO.readAll(j), objectClass); + loadCache.put(key, t); + logLoad(j); + t.setLoadKey(name); + t.setLoadFile(j); + t.setLoader(manager); + lock.unlock(); + return t; + } catch (Throwable e) { + lock.unlock(); + failLoad(j, e); + return null; + } + } - protected T loadFile(File j, String key, String name) - { - try - { - T t = new Gson().fromJson(IO.readAll(j), objectClass); - loadCache.put(key, t); - logLoad(j); - t.setLoadKey(name); - t.setLoadFile(j); - t.setLoader(manager); - lock.unlock(); - return t; - } + public T load(String name) { + return load(name, true); + } - catch(Throwable e) - { - lock.unlock(); - failLoad(j, e); - return null; - } - } + public T load(String name, boolean warn) { + if (name == null) { + return null; + } - public T load(String name) - { - return load(name, true); - } + if (name.trim().isEmpty()) { + return null; + } - public T load(String name, boolean warn) - { - if(name == null) - { - return null; - } + String key = name + "-" + cname; - if(name.trim().isEmpty()) - { - return null; - } + if (loadCache.containsKey(key)) { + T t = loadCache.get(key); + return t; + } - String key = name + "-" + cname; + lock.lock(); + for (File i : getFolders(name)) { + for (File j : i.listFiles()) { + if (j.isFile() && j.getName().endsWith(".json") && j.getName().split("\\Q.\\E")[0].equals(name)) { + return loadFile(j, key, name); + } + } - if(loadCache.containsKey(key)) - { - T t = loadCache.get(key); - return t; - } + File file = new File(i, name + ".json"); - lock.lock(); - for(File i : getFolders(name)) - { - for(File j : i.listFiles()) - { - if(j.isFile() && j.getName().endsWith(".json") && j.getName().split("\\Q.\\E")[0].equals(name)) - { - return loadFile(j, key, name); - } - } + if (file.exists()) { + return loadFile(file, key, name); + } + } - File file = new File(i, name + ".json"); + if (warn && !resourceTypeName.equals("Dimension")) { + J.a(() -> Iris.warn("Couldn't find " + resourceTypeName + ": " + name)); + } - if(file.exists()) - { - return loadFile(file, key, name); - } - } + lock.unlock(); + return null; + } - if(warn && !resourceTypeName.equals("Dimension")) - { - J.a(() -> Iris.warn("Couldn't find " + resourceTypeName + ": " + name)); - } + public KList getFolders() { + lock.lock(); + if (folderCache == null) { + folderCache = new KList<>(); - lock.unlock(); - return null; - } + for (File i : root.listFiles()) { + if (i.isDirectory()) { + if (i.getName().equals(folderName)) { + folderCache.add(i); + break; + } + } + } + } - public KList getFolders() - { - lock.lock(); - if(folderCache == null) - { - folderCache = new KList<>(); + lock.unlock(); - for(File i : root.listFiles()) - { - if(i.isDirectory()) - { - if(i.getName().equals(folderName)) - { - folderCache.add(i); - break; - } - } - } - } + return folderCache; + } - lock.unlock(); + public KList getFolders(String rc) { + KList folders = getFolders().copy(); - return folderCache; - } + if (rc.contains(":")) { + for (File i : folders.copy()) { + if (!rc.startsWith(i.getName() + ":")) { + folders.remove(i); + } + } + } - public KList getFolders(String rc) - { - KList folders = getFolders().copy(); + return folders; + } - if(rc.contains(":")) - { - for(File i : folders.copy()) - { - if(!rc.startsWith(i.getName() + ":")) - { - folders.remove(i); - } - } - } + public void clearCache() { + lock.lock(); + possibleKeys = null; + loadCache.clear(); + folderCache = null; + lock.unlock(); + } - return folders; - } + public File fileFor(T b) { + for (File i : getFolders()) { + for (File j : i.listFiles()) { + if (j.isFile() && j.getName().endsWith(".json") && j.getName().split("\\Q.\\E")[0].equals(b.getLoadKey())) { + return j; + } + } - public void clearCache() - { - lock.lock(); - possibleKeys = null; - loadCache.clear(); - folderCache = null; - lock.unlock(); - } + File file = new File(i, b.getLoadKey() + ".json"); - public File fileFor(T b) - { - for(File i : getFolders()) - { - for(File j : i.listFiles()) - { - if(j.isFile() && j.getName().endsWith(".json") && j.getName().split("\\Q.\\E")[0].equals(b.getLoadKey())) - { - return j; - } - } + if (file.exists()) { + return file; + } + } - File file = new File(i, b.getLoadKey() + ".json"); + return null; + } - if(file.exists()) - { - return file; - } - } + public boolean isLoaded(String next) { + return loadCache.containsKey(next); + } - return null; - } - - public boolean isLoaded(String next) - { - return loadCache.containsKey(next); - } - - public void clearList() - { - lock.lock(); - folderCache = null; - possibleKeys = null; - lock.unlock(); - } + public void clearList() { + lock.lock(); + folderCache = null; + possibleKeys = null; + lock.unlock(); + } } diff --git a/src/main/java/com/volmit/iris/util/RollingSequence.java b/src/main/java/com/volmit/iris/util/RollingSequence.java index bff3165ab..543843e43 100644 --- a/src/main/java/com/volmit/iris/util/RollingSequence.java +++ b/src/main/java/com/volmit/iris/util/RollingSequence.java @@ -1,101 +1,85 @@ package com.volmit.iris.util; -public class RollingSequence extends Average -{ - private double median; - private double max; - private double min; - private boolean dirtyMedian; - private int dirtyExtremes; - private boolean precision; +public class RollingSequence extends Average { + private double median; + private double max; + private double min; + private boolean dirtyMedian; + private int dirtyExtremes; + private boolean precision; - public RollingSequence(int size) - { - super(size); - median = 0; - min = 0; - max = 0; - setPrecision(false); - } + public RollingSequence(int size) { + super(size); + median = 0; + min = 0; + max = 0; + setPrecision(false); + } - public double addLast(int amt) - { - double f = 0; + public double addLast(int amt) { + double f = 0; - for(int i = 0; i < Math.min(values.length, amt); i++) - { - f += values[i]; - } + for (int i = 0; i < Math.min(values.length, amt); i++) { + f += values[i]; + } - return f; - } + return f; + } - public void setPrecision(boolean p) - { - this.precision = p; - } + public void setPrecision(boolean p) { + this.precision = p; + } - public boolean isPrecision() - { - return precision; - } + public boolean isPrecision() { + return precision; + } - public double getMin() - { - if(dirtyExtremes > (isPrecision() ? 0 : values.length)) - { - resetExtremes(); - } + public double getMin() { + if (dirtyExtremes > (isPrecision() ? 0 : values.length)) { + resetExtremes(); + } - return min; - } + return min; + } - public double getMax() - { - if(dirtyExtremes > (isPrecision() ? 0 : values.length)) - { - resetExtremes(); - } + public double getMax() { + if (dirtyExtremes > (isPrecision() ? 0 : values.length)) { + resetExtremes(); + } - return max; - } + return max; + } - public double getMedian() - { - if(dirtyMedian) - { - recalculateMedian(); - } + public double getMedian() { + if (dirtyMedian) { + recalculateMedian(); + } - return median; - } + return median; + } - private void recalculateMedian() - { - median = new KList().forceAdd(values).sort().middleValue(); - dirtyMedian = false; - } + private void recalculateMedian() { + median = new KList().forceAdd(values).sort().middleValue(); + dirtyMedian = false; + } - public void resetExtremes() - { - max = Integer.MIN_VALUE; - min = Integer.MAX_VALUE; + public void resetExtremes() { + max = Integer.MIN_VALUE; + min = Integer.MAX_VALUE; - for(double i : values) - { - max = M.max(max, i); - min = M.min(min, i); - } + for (double i : values) { + max = M.max(max, i); + min = M.min(min, i); + } - dirtyExtremes = 0; - } + dirtyExtremes = 0; + } - public void put(double i) - { - super.put(i); - dirtyMedian = true; - dirtyExtremes++; - max = M.max(max, i); - min = M.min(min, i); - } + public void put(double i) { + super.put(i); + dirtyMedian = true; + dirtyExtremes++; + max = M.max(max, i); + min = M.min(min, i); + } } diff --git a/src/main/java/com/volmit/iris/util/RouterCommand.java b/src/main/java/com/volmit/iris/util/RouterCommand.java index 762e745d6..ce45130a7 100644 --- a/src/main/java/com/volmit/iris/util/RouterCommand.java +++ b/src/main/java/com/volmit/iris/util/RouterCommand.java @@ -8,45 +8,37 @@ import org.bukkit.command.CommandSender; * Assistive command router * * @author cyberpwn - * */ -public class RouterCommand extends org.bukkit.command.Command -{ - private CommandExecutor ex; - private String usage; +public class RouterCommand extends org.bukkit.command.Command { + private final CommandExecutor ex; + private String usage; - /** - * The router command routes commands to bukkit executors - * - * @param realCommand - * the real command - * @param ex - * the executor - */ - public RouterCommand(ICommand realCommand, CommandExecutor ex) - { - super(realCommand.getNode().toLowerCase()); - setAliases(realCommand.getNodes()); + /** + * The router command routes commands to bukkit executors + * + * @param realCommand the real command + * @param ex the executor + */ + public RouterCommand(ICommand realCommand, CommandExecutor ex) { + super(realCommand.getNode().toLowerCase()); + setAliases(realCommand.getNodes()); - this.ex = ex; - } + this.ex = ex; + } - @Override - public Command setUsage(String u) - { - this.usage = u; - return this; - } + @Override + public Command setUsage(String u) { + this.usage = u; + return this; + } - @Override - public String getUsage() - { - return usage; - } + @Override + public String getUsage() { + return usage; + } - @Override - public boolean execute(CommandSender sender, String commandLabel, String[] args) - { - return ex.onCommand(sender, this, commandLabel, args); - } + @Override + public boolean execute(CommandSender sender, String commandLabel, String[] args) { + return ex.onCommand(sender, this, commandLabel, args); + } } diff --git a/src/main/java/com/volmit/iris/util/S.java b/src/main/java/com/volmit/iris/util/S.java index 2199339d2..ccd271025 100644 --- a/src/main/java/com/volmit/iris/util/S.java +++ b/src/main/java/com/volmit/iris/util/S.java @@ -1,14 +1,11 @@ package com.volmit.iris.util; -public abstract class S implements Runnable -{ - public S() - { - J.s(this); - } +public abstract class S implements Runnable { + public S() { + J.s(this); + } - public S(int delay) - { - J.s(this, delay); - } + public S(int delay) { + J.s(this, delay); + } } diff --git a/src/main/java/com/volmit/iris/util/SKConversion.java b/src/main/java/com/volmit/iris/util/SKConversion.java index 4343dfac8..5f9570259 100644 --- a/src/main/java/com/volmit/iris/util/SKConversion.java +++ b/src/main/java/com/volmit/iris/util/SKConversion.java @@ -1,10 +1,5 @@ package com.volmit.iris.util; -import java.io.File; -import java.io.FileInputStream; -import java.io.FileNotFoundException; -import java.io.IOException; - import com.sk89q.worldedit.bukkit.BukkitAdapter; import com.sk89q.worldedit.extent.clipboard.Clipboard; import com.sk89q.worldedit.extent.clipboard.io.ClipboardFormat; @@ -13,37 +8,32 @@ import com.sk89q.worldedit.extent.clipboard.io.ClipboardReader; import com.sk89q.worldedit.math.BlockVector3; import com.volmit.iris.object.IrisObject; -public class SKConversion -{ - public static void convertSchematic(File in, File out) - { - ClipboardFormat format = ClipboardFormats.findByFile(in); - try(ClipboardReader reader = format.getReader(new FileInputStream(in))) - { - Clipboard clipboard = reader.read(); - BlockVector3 size = clipboard.getMaximumPoint().subtract(clipboard.getMinimumPoint()); - IrisObject o = new IrisObject(size.getBlockX() + 1, size.getBlockY() + 1, size.getBlockZ() + 1); +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; - for(int i = clipboard.getMinimumPoint().getBlockX(); i <= clipboard.getMaximumPoint().getBlockX(); i++) - { - for(int j = clipboard.getMinimumPoint().getBlockY(); j <= clipboard.getMaximumPoint().getBlockY(); j++) - { - for(int k = clipboard.getMinimumPoint().getBlockZ(); k <= clipboard.getMaximumPoint().getBlockZ(); k++) - { - o.setUnsigned(i - clipboard.getMinimumPoint().getBlockX(), j - clipboard.getMinimumPoint().getBlockY(), k - clipboard.getMinimumPoint().getBlockZ(), BukkitAdapter.adapt(clipboard.getFullBlock(BlockVector3.at(i, j, k)))); - } - } - } +public class SKConversion { + public static void convertSchematic(File in, File out) { + ClipboardFormat format = ClipboardFormats.findByFile(in); + try (ClipboardReader reader = format.getReader(new FileInputStream(in))) { + Clipboard clipboard = reader.read(); + BlockVector3 size = clipboard.getMaximumPoint().subtract(clipboard.getMinimumPoint()); + IrisObject o = new IrisObject(size.getBlockX() + 1, size.getBlockY() + 1, size.getBlockZ() + 1); - o.write(out); - } - catch(FileNotFoundException e) - { - e.printStackTrace(); - } - catch(IOException e) - { - e.printStackTrace(); - } - } + for (int i = clipboard.getMinimumPoint().getBlockX(); i <= clipboard.getMaximumPoint().getBlockX(); i++) { + for (int j = clipboard.getMinimumPoint().getBlockY(); j <= clipboard.getMaximumPoint().getBlockY(); j++) { + for (int k = clipboard.getMinimumPoint().getBlockZ(); k <= clipboard.getMaximumPoint().getBlockZ(); k++) { + o.setUnsigned(i - clipboard.getMinimumPoint().getBlockX(), j - clipboard.getMinimumPoint().getBlockY(), k - clipboard.getMinimumPoint().getBlockZ(), BukkitAdapter.adapt(clipboard.getFullBlock(BlockVector3.at(i, j, k)))); + } + } + } + + o.write(out); + } catch (FileNotFoundException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } } diff --git a/src/main/java/com/volmit/iris/util/SR.java b/src/main/java/com/volmit/iris/util/SR.java index 453977ddc..617a01b79 100644 --- a/src/main/java/com/volmit/iris/util/SR.java +++ b/src/main/java/com/volmit/iris/util/SR.java @@ -1,27 +1,22 @@ package com.volmit.iris.util; -public abstract class SR implements Runnable, CancellableTask -{ - private int id = 0; +public abstract class SR implements Runnable, CancellableTask { + private int id = 0; - public SR() - { - this(0); - } + public SR() { + this(0); + } - public SR(int interval) - { - id = J.sr(this, interval); - } + public SR(int interval) { + id = J.sr(this, interval); + } - @Override - public void cancel() - { - J.csr(id); - } + @Override + public void cancel() { + J.csr(id); + } - public int getId() - { - return id; - } + public int getId() { + return id; + } } diff --git a/src/main/java/com/volmit/iris/util/ScoreDirection.java b/src/main/java/com/volmit/iris/util/ScoreDirection.java index 664849e00..bc9ba3fd6 100644 --- a/src/main/java/com/volmit/iris/util/ScoreDirection.java +++ b/src/main/java/com/volmit/iris/util/ScoreDirection.java @@ -5,11 +5,10 @@ package com.volmit.iris.util; * @since 5/31/2018 */ @DontObfuscate -public enum ScoreDirection -{ - @DontObfuscate - UP, - - @DontObfuscate - DOWN +public enum ScoreDirection { + @DontObfuscate + UP, + + @DontObfuscate + DOWN } diff --git a/src/main/java/com/volmit/iris/util/ShortTag.java b/src/main/java/com/volmit/iris/util/ShortTag.java index 9cafbff87..cf1e40762 100644 --- a/src/main/java/com/volmit/iris/util/ShortTag.java +++ b/src/main/java/com/volmit/iris/util/ShortTag.java @@ -2,24 +2,24 @@ package com.volmit.iris.util; /* * JNBT License - * + * * Copyright (c) 2010 Graham Edgecombe * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. - * + * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * * Neither the name of the JNBT team nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -30,13 +30,13 @@ package com.volmit.iris.util; * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * POSSIBILITY OF SUCH DAMAGE. */ + /** * The TAG_Short tag. * * @author Graham Edgecombe - * */ public final class ShortTag extends Tag { @@ -48,7 +48,7 @@ public final class ShortTag extends Tag { /** * Creates the tag. * - * @param name The name. + * @param name The name. * @param value The value. */ public ShortTag(String name, short value) { diff --git a/src/main/java/com/volmit/iris/util/Shrinkwrap.java b/src/main/java/com/volmit/iris/util/Shrinkwrap.java index 94d762b32..b492b5a5a 100644 --- a/src/main/java/com/volmit/iris/util/Shrinkwrap.java +++ b/src/main/java/com/volmit/iris/util/Shrinkwrap.java @@ -1,26 +1,21 @@ package com.volmit.iris.util; -public class Shrinkwrap -{ - private T t; +public class Shrinkwrap { + private T t; - public Shrinkwrap(T t) - { - set(t); - } + public Shrinkwrap(T t) { + set(t); + } - public Shrinkwrap() - { - this(null); - } + public Shrinkwrap() { + this(null); + } - public T get() - { - return t; - } + public T get() { + return t; + } - public void set(T t) - { - this.t = t; - } + public void set(T t) { + this.t = t; + } } diff --git a/src/main/java/com/volmit/iris/util/ShurikenQueue.java b/src/main/java/com/volmit/iris/util/ShurikenQueue.java index faac242b6..26fef16d7 100644 --- a/src/main/java/com/volmit/iris/util/ShurikenQueue.java +++ b/src/main/java/com/volmit/iris/util/ShurikenQueue.java @@ -1,94 +1,79 @@ package com.volmit.iris.util; -public class ShurikenQueue implements Queue -{ - private KList queue; - private boolean randomPop; - private boolean reversePop; +public class ShurikenQueue implements Queue { + private KList queue; + private boolean randomPop; + private boolean reversePop; - public ShurikenQueue() - { - clear(); - } + public ShurikenQueue() { + clear(); + } - public ShurikenQueue responsiveMode() - { - reversePop = true; - return this; - } + public ShurikenQueue responsiveMode() { + reversePop = true; + return this; + } - public ShurikenQueue randomMode() - { - randomPop = true; - return this; - } + public ShurikenQueue randomMode() { + randomPop = true; + return this; + } - @Override - public ShurikenQueue queue(T t) - { - queue.add(t); - return this; - } + @Override + public ShurikenQueue queue(T t) { + queue.add(t); + return this; + } - @Override - public ShurikenQueue queue(KList t) - { - queue.add(t); - return this; - } + @Override + public ShurikenQueue queue(KList t) { + queue.add(t); + return this; + } - @Override - public boolean hasNext(int amt) - { - return queue.size() >= amt; - } + @Override + public boolean hasNext(int amt) { + return queue.size() >= amt; + } - @Override - public boolean hasNext() - { - return !queue.isEmpty(); - } + @Override + public boolean hasNext() { + return !queue.isEmpty(); + } - @Override - public T next() - { - return reversePop ? queue.popLast() : randomPop ? queue.popRandom() : queue.pop(); - } + @Override + public T next() { + return reversePop ? queue.popLast() : randomPop ? queue.popRandom() : queue.pop(); + } - @Override - public KList next(int amt) - { - KList t = new KList<>(); + @Override + public KList next(int amt) { + KList t = new KList<>(); - for(int i = 0; i < amt; i++) - { - if(!hasNext()) - { - break; - } + for (int i = 0; i < amt; i++) { + if (!hasNext()) { + break; + } - t.add(next()); - } + t.add(next()); + } - return t; - } + return t; + } - @Override - public ShurikenQueue clear() - { - queue = new KList(); - return this; - } + @Override + public ShurikenQueue clear() { + queue = new KList(); + return this; + } - @Override - public int size() - { - return queue.size(); - } + @Override + public int size() { + return queue.size(); + } - @Override - public boolean contains(T p) - { - return queue.contains(p); - } + @Override + public boolean contains(T p) { + return queue.contains(p); + } } diff --git a/src/main/java/com/volmit/iris/util/Spiraled.java b/src/main/java/com/volmit/iris/util/Spiraled.java index a606b3cc2..a11bcde95 100644 --- a/src/main/java/com/volmit/iris/util/Spiraled.java +++ b/src/main/java/com/volmit/iris/util/Spiraled.java @@ -1,7 +1,6 @@ package com.volmit.iris.util; @FunctionalInterface -public interface Spiraled -{ - public void on(int x, int z); +public interface Spiraled { + void on(int x, int z); } diff --git a/src/main/java/com/volmit/iris/util/Spiraler.java b/src/main/java/com/volmit/iris/util/Spiraler.java index f2fd39f03..5e3aad6f1 100644 --- a/src/main/java/com/volmit/iris/util/Spiraler.java +++ b/src/main/java/com/volmit/iris/util/Spiraler.java @@ -1,70 +1,59 @@ package com.volmit.iris.util; -public class Spiraler -{ - int x, z, dx, dz, sizeX, sizeZ, t, maxI, i; - int ox, oz; - private Spiraled spiraled; +public class Spiraler { + int x, z, dx, dz, sizeX, sizeZ, t, maxI, i; + int ox, oz; + private final Spiraled spiraled; - public Spiraler(int sizeX, int sizeZ, Spiraled spiraled) - { - ox = 0; - oz = 0; - this.spiraled = spiraled; - retarget(sizeX, sizeZ); - } + public Spiraler(int sizeX, int sizeZ, Spiraled spiraled) { + ox = 0; + oz = 0; + this.spiraled = spiraled; + retarget(sizeX, sizeZ); + } - public void drain() - { - while(hasNext()) - { - next(); - } - } + public void drain() { + while (hasNext()) { + next(); + } + } - static void Spiral(int X, int Y) - { + static void Spiral(int X, int Y) { - } + } - public Spiraler setOffset(int ox, int oz) - { - this.ox = ox; - this.oz = oz; - return this; - } + public Spiraler setOffset(int ox, int oz) { + this.ox = ox; + this.oz = oz; + return this; + } - public void retarget(int sizeX, int sizeZ) - { - this.sizeX = sizeX; - this.sizeZ = sizeZ; - x = z = dx = 0; - dz = -1; - i = 0; - t = Math.max(sizeX, sizeZ); - maxI = t * t; - } + public void retarget(int sizeX, int sizeZ) { + this.sizeX = sizeX; + this.sizeZ = sizeZ; + x = z = dx = 0; + dz = -1; + i = 0; + t = Math.max(sizeX, sizeZ); + maxI = t * t; + } - public boolean hasNext() - { - return i < maxI; - } + public boolean hasNext() { + return i < maxI; + } - public void next() - { - if((-sizeX / 2 <= x) && (x <= sizeX / 2) && (-sizeZ / 2 <= z) && (z <= sizeZ / 2)) - { - spiraled.on(x + ox, z + ox); - } + public void next() { + if ((-sizeX / 2 <= x) && (x <= sizeX / 2) && (-sizeZ / 2 <= z) && (z <= sizeZ / 2)) { + spiraled.on(x + ox, z + ox); + } - if((x == z) || ((x < 0) && (x == -z)) || ((x > 0) && (x == 1 - z))) - { - t = dx; - dx = -dz; - dz = t; - } - x += dx; - z += dz; - i++; - } + if ((x == z) || ((x < 0) && (x == -z)) || ((x > 0) && (x == 1 - z))) { + t = dx; + dx = -dz; + dz = t; + } + x += dx; + z += dz; + i++; + } } diff --git a/src/main/java/com/volmit/iris/util/StringTag.java b/src/main/java/com/volmit/iris/util/StringTag.java index 5823d4076..10ad9105e 100644 --- a/src/main/java/com/volmit/iris/util/StringTag.java +++ b/src/main/java/com/volmit/iris/util/StringTag.java @@ -2,24 +2,24 @@ package com.volmit.iris.util; /* * JNBT License - * + * * Copyright (c) 2010 Graham Edgecombe * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. - * + * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * * Neither the name of the JNBT team nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -30,13 +30,13 @@ package com.volmit.iris.util; * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * POSSIBILITY OF SUCH DAMAGE. */ + /** * The TAG_String tag. * * @author Graham Edgecombe - * */ public final class StringTag extends Tag { @@ -48,7 +48,7 @@ public final class StringTag extends Tag { /** * Creates the tag. * - * @param name The name. + * @param name The name. * @param value The value. */ public StringTag(String name, String value) { diff --git a/src/main/java/com/volmit/iris/util/Supplier2.java b/src/main/java/com/volmit/iris/util/Supplier2.java index 8e61ba0e5..ba0b2009b 100644 --- a/src/main/java/com/volmit/iris/util/Supplier2.java +++ b/src/main/java/com/volmit/iris/util/Supplier2.java @@ -1,6 +1,5 @@ package com.volmit.iris.util; -public interface Supplier2 -{ - public void get(T t, TT tt); +public interface Supplier2 { + void get(T t, TT tt); } diff --git a/src/main/java/com/volmit/iris/util/Supplier3.java b/src/main/java/com/volmit/iris/util/Supplier3.java index acb2e511d..e85c7b30c 100644 --- a/src/main/java/com/volmit/iris/util/Supplier3.java +++ b/src/main/java/com/volmit/iris/util/Supplier3.java @@ -1,6 +1,5 @@ package com.volmit.iris.util; -public interface Supplier3 -{ - public void get(T t, TT tt, TTT ttt); +public interface Supplier3 { + void get(T t, TT tt, TTT ttt); } diff --git a/src/main/java/com/volmit/iris/util/Switch.java b/src/main/java/com/volmit/iris/util/Switch.java index 0daadd99e..eb9512f36 100644 --- a/src/main/java/com/volmit/iris/util/Switch.java +++ b/src/main/java/com/volmit/iris/util/Switch.java @@ -1,29 +1,24 @@ package com.volmit.iris.util; -public class Switch -{ - private volatile boolean b; +public class Switch { + private volatile boolean b; - /** - * Defaulted off - */ - public Switch() - { - b = false; - } + /** + * Defaulted off + */ + public Switch() { + b = false; + } - public void flip() - { - b = true; - } + public void flip() { + b = true; + } - public boolean isFlipped() - { - return b; - } + public boolean isFlipped() { + return b; + } - public void reset() - { - b = false; - } + public void reset() { + b = false; + } } diff --git a/src/main/java/com/volmit/iris/util/Tag.java b/src/main/java/com/volmit/iris/util/Tag.java index e4c0d9b58..bda2b6637 100644 --- a/src/main/java/com/volmit/iris/util/Tag.java +++ b/src/main/java/com/volmit/iris/util/Tag.java @@ -2,24 +2,24 @@ package com.volmit.iris.util; /* * JNBT License - * + * * Copyright (c) 2010 Graham Edgecombe * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. - * + * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * * Neither the name of the JNBT team nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -30,13 +30,13 @@ package com.volmit.iris.util; * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * POSSIBILITY OF SUCH DAMAGE. */ + /** * Represents a single NBT tag. * * @author Graham Edgecombe - * */ public abstract class Tag { diff --git a/src/main/java/com/volmit/iris/util/TaskExecutor.java b/src/main/java/com/volmit/iris/util/TaskExecutor.java index da1eb93d1..bc91550f5 100644 --- a/src/main/java/com/volmit/iris/util/TaskExecutor.java +++ b/src/main/java/com/volmit/iris/util/TaskExecutor.java @@ -1,226 +1,184 @@ package com.volmit.iris.util; +import lombok.Getter; +import lombok.Setter; +import lombok.ToString; + import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory; import java.util.concurrent.ForkJoinWorkerThread; -import lombok.Getter; -import lombok.Setter; -import lombok.ToString; +public class TaskExecutor { + private int xc; + private final ExecutorService service; -public class TaskExecutor -{ - private int xc; - private ExecutorService service; + public TaskExecutor(int threadLimit, int priority, String name) { + xc = 1; - public TaskExecutor(int threadLimit, int priority, String name) - { - xc = 1; + if (threadLimit == 1) { + service = Executors.newSingleThreadExecutor((r) -> + { + Thread t = new Thread(r); + t.setName(name); + t.setPriority(priority); - if(threadLimit == 1) - { - service = Executors.newSingleThreadExecutor((r) -> - { - Thread t = new Thread(r); - t.setName(name); - t.setPriority(priority); + return t; + }); + } else if (threadLimit > 1) { + final ForkJoinWorkerThreadFactory factory = new ForkJoinWorkerThreadFactory() { + @Override + public ForkJoinWorkerThread newThread(ForkJoinPool pool) { + final ForkJoinWorkerThread worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool); + worker.setName(name + " " + xc++); + worker.setPriority(priority); + return worker; + } + }; - return t; - }); - } + service = new ForkJoinPool(threadLimit, factory, null, false); + } else { + service = Executors.newCachedThreadPool((r) -> + { + Thread t = new Thread(r); + t.setName(name + " " + xc++); + t.setPriority(priority); - else if(threadLimit > 1) - { - final ForkJoinWorkerThreadFactory factory = new ForkJoinWorkerThreadFactory() - { - @Override - public ForkJoinWorkerThread newThread(ForkJoinPool pool) - { - final ForkJoinWorkerThread worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool); - worker.setName(name + " " + xc++); - worker.setPriority(priority); - return worker; - } - }; + return t; + }); + } + } - service = new ForkJoinPool(threadLimit, factory, null, false); - } + public TaskGroup startWork() { + return new TaskGroup(this); + } - else - { - service = Executors.newCachedThreadPool((r) -> - { - Thread t = new Thread(r); - t.setName(name + " " + xc++); - t.setPriority(priority); + public void close() { + J.a(() -> + { + J.sleep(10000); + service.shutdown(); + }); + } - return t; - }); - } - } + public void closeNow() { + service.shutdown(); + } - public TaskGroup startWork() - { - return new TaskGroup(this); - } + public static class TaskGroup { + private final KList tasks; + private final TaskExecutor e; - public void close() - { - J.a(() -> - { - J.sleep(10000); - service.shutdown(); - }); - } + public TaskGroup(TaskExecutor e) { + tasks = new KList<>(); + this.e = e; + } - public void closeNow() - { - service.shutdown(); - } + public TaskGroup queue(NastyRunnable... r) { + for (NastyRunnable i : r) { + tasks.add(new AssignedTask(i)); + } - public static class TaskGroup - { - private KList tasks; - private TaskExecutor e; + return this; + } - public TaskGroup(TaskExecutor e) - { - tasks = new KList<>(); - this.e = e; - } + public TaskGroup queue(KList r) { + for (NastyRunnable i : r) { + tasks.add(new AssignedTask(i)); + } - public TaskGroup queue(NastyRunnable... r) - { - for(NastyRunnable i : r) - { - tasks.add(new AssignedTask(i)); - } + return this; + } - return this; - } + public TaskResult execute() { + double timeElapsed = 0; + int tasksExecuted = 0; + int tasksFailed = 0; + int tasksCompleted = 0; + tasks.forEach((t) -> t.go(e)); + long msv = M.ns(); - public TaskGroup queue(KList r) - { - for(NastyRunnable i : r) - { - tasks.add(new AssignedTask(i)); - } + waiting: + while (true) { + try { + Thread.sleep(0); + } catch (InterruptedException e1) { - return this; - } + } - public TaskResult execute() - { - double timeElapsed = 0; - int tasksExecuted = 0; - int tasksFailed = 0; - int tasksCompleted = 0; - tasks.forEach((t) -> t.go(e)); - long msv = M.ns(); + for (AssignedTask i : tasks) { + if (i.state.equals(TaskState.QUEUED) || i.state.equals(TaskState.RUNNING)) { + continue waiting; + } + } - waiting: while(true) - { - try - { - Thread.sleep(0); - } + timeElapsed = (double) (M.ns() - msv) / 1000000D; - catch(InterruptedException e1) - { + for (AssignedTask i : tasks) { + if (i.state.equals(TaskState.COMPLETED)) { + tasksCompleted++; + } else { + tasksFailed++; + } - } + tasksExecuted++; + } - for(AssignedTask i : tasks) - { - if(i.state.equals(TaskState.QUEUED) || i.state.equals(TaskState.RUNNING)) - { - continue waiting; - } - } + break; + } - timeElapsed = (double) (M.ns() - msv) / 1000000D; + return new TaskResult(timeElapsed, tasksExecuted, tasksFailed, tasksCompleted); + } + } - for(AssignedTask i : tasks) - { - if(i.state.equals(TaskState.COMPLETED)) - { - tasksCompleted++; - } + @ToString + public static class TaskResult { + public TaskResult(double timeElapsed, int tasksExecuted, int tasksFailed, int tasksCompleted) { + this.timeElapsed = timeElapsed; + this.tasksExecuted = tasksExecuted; + this.tasksFailed = tasksFailed; + this.tasksCompleted = tasksCompleted; + } - else - { - tasksFailed++; - } + public final double timeElapsed; + public final int tasksExecuted; + public final int tasksFailed; + public final int tasksCompleted; + } - tasksExecuted++; - } + public enum TaskState { + QUEUED, + RUNNING, + COMPLETED, + FAILED + } - break; - } + public static class AssignedTask { + @Getter + @Setter + private TaskState state; - return new TaskResult(timeElapsed, tasksExecuted, tasksFailed, tasksCompleted); - } - } + @Getter + private final NastyRunnable task; - @ToString - public static class TaskResult - { - public TaskResult(double timeElapsed, int tasksExecuted, int tasksFailed, int tasksCompleted) - { - this.timeElapsed = timeElapsed; - this.tasksExecuted = tasksExecuted; - this.tasksFailed = tasksFailed; - this.tasksCompleted = tasksCompleted; - } + public AssignedTask(NastyRunnable task) { + this.task = task; + state = TaskState.QUEUED; + } - public final double timeElapsed; - public final int tasksExecuted; - public final int tasksFailed; - public final int tasksCompleted; - } - - public enum TaskState - { - QUEUED, - RUNNING, - COMPLETED, - FAILED; - } - - public static class AssignedTask - { - @Getter - @Setter - private TaskState state; - - @Getter - private NastyRunnable task; - - public AssignedTask(NastyRunnable task) - { - this.task = task; - state = TaskState.QUEUED; - } - - public void go(TaskExecutor e) - { - e.service.execute(() -> - { - state = TaskState.RUNNING; - try - { - task.run(); - state = TaskState.COMPLETED; - } - - catch(Throwable ex) - { - ex.printStackTrace(); - state = TaskState.FAILED; - } - }); - } - } + public void go(TaskExecutor e) { + e.service.execute(() -> + { + state = TaskState.RUNNING; + try { + task.run(); + state = TaskState.COMPLETED; + } catch (Throwable ex) { + ex.printStackTrace(); + state = TaskState.FAILED; + } + }); + } + } } diff --git a/src/main/java/com/volmit/iris/util/TerrainChunk.java b/src/main/java/com/volmit/iris/util/TerrainChunk.java index 6e5ff8ba4..bd0b129c2 100644 --- a/src/main/java/com/volmit/iris/util/TerrainChunk.java +++ b/src/main/java/com/volmit/iris/util/TerrainChunk.java @@ -6,133 +6,108 @@ import org.bukkit.block.data.BlockData; import org.bukkit.generator.ChunkGenerator.BiomeGrid; import org.bukkit.generator.ChunkGenerator.ChunkData; -public interface TerrainChunk extends BiomeGrid, ChunkData -{ - public static TerrainChunk create(World world) - { - return create(world.getMaxHeight()); - } +public interface TerrainChunk extends BiomeGrid, ChunkData { + static TerrainChunk create(World world) { + return create(world.getMaxHeight()); + } - public static TerrainChunk create(int maxHeight) - { - return new LinkedTerrainChunk(maxHeight); - } + static TerrainChunk create(int maxHeight) { + return new LinkedTerrainChunk(maxHeight); + } - public static TerrainChunk create(World world, BiomeGrid grid) - { - return create(world.getMaxHeight(), grid); - } + static TerrainChunk create(World world, BiomeGrid grid) { + return create(world.getMaxHeight(), grid); + } - public static TerrainChunk create(ChunkData raw, BiomeGrid grid) - { - return new LinkedTerrainChunk(grid, raw); - } + static TerrainChunk create(ChunkData raw, BiomeGrid grid) { + return new LinkedTerrainChunk(grid, raw); + } - public static TerrainChunk create(int maxHeight, BiomeGrid grid) - { - return new LinkedTerrainChunk(grid, maxHeight); - } + static TerrainChunk create(int maxHeight, BiomeGrid grid) { + return new LinkedTerrainChunk(grid, maxHeight); + } - public void setRaw(ChunkData data); + void setRaw(ChunkData data); - /** - * Get biome at x, z within chunk being generated - * - * @param x - * - 0-15 - * @param z - * - 0-15 - * @return Biome value - * @deprecated biomes are now 3-dimensional - */ - @Deprecated - Biome getBiome(int x, int z); + /** + * Get biome at x, z within chunk being generated + * + * @param x - 0-15 + * @param z - 0-15 + * @return Biome value + * @deprecated biomes are now 3-dimensional + */ + @Deprecated + Biome getBiome(int x, int z); - /** - * Get biome at x, z within chunk being generated - * - * @param x - * - 0-15 - * @param y - * - 0-255 - * @param z - * - 0-15 - * @return Biome value - */ - Biome getBiome(int x, int y, int z); + /** + * Get biome at x, z within chunk being generated + * + * @param x - 0-15 + * @param y - 0-255 + * @param z - 0-15 + * @return Biome value + */ + Biome getBiome(int x, int y, int z); - /** - * Set biome at x, z within chunk being generated - * - * @param x - * - 0-15 - * @param z - * - 0-15 - * @param bio - * - Biome value - * @deprecated biomes are now 3-dimensional - */ - @Deprecated - void setBiome(int x, int z, Biome bio); + /** + * Set biome at x, z within chunk being generated + * + * @param x - 0-15 + * @param z - 0-15 + * @param bio - Biome value + * @deprecated biomes are now 3-dimensional + */ + @Deprecated + void setBiome(int x, int z, Biome bio); - /** - * Set biome at x, z within chunk being generated - * - * @param x - * - 0-15 - * @param y - * - 0-255 - * @param z - * - 0-15 - * @param bio - * - Biome value - */ - void setBiome(int x, int y, int z, Biome bio); + /** + * Set biome at x, z within chunk being generated + * + * @param x - 0-15 + * @param y - 0-255 + * @param z - 0-15 + * @param bio - Biome value + */ + void setBiome(int x, int y, int z, Biome bio); - /** - * Get the maximum height for the chunk. - * - * Setting blocks at or above this height will do nothing. - * - * @return the maximum height - */ - public int getMaxHeight(); + /** + * Get the maximum height for the chunk. + *

+ * Setting blocks at or above this height will do nothing. + * + * @return the maximum height + */ + int getMaxHeight(); - /** - * Set the block at x,y,z in the chunk data to material. - * - * Setting blocks outside the chunk's bounds does nothing. - * - * @param x - * the x location in the chunk from 0-15 inclusive - * @param y - * the y location in the chunk from 0 (inclusive) - maxHeight - * (exclusive) - * @param z - * the z location in the chunk from 0-15 inclusive - * @param blockData - * the type to set the block to - */ - public void setBlock(int x, int y, int z, BlockData blockData); + /** + * Set the block at x,y,z in the chunk data to material. + *

+ * Setting blocks outside the chunk's bounds does nothing. + * + * @param x the x location in the chunk from 0-15 inclusive + * @param y the y location in the chunk from 0 (inclusive) - maxHeight + * (exclusive) + * @param z the z location in the chunk from 0-15 inclusive + * @param blockData the type to set the block to + */ + void setBlock(int x, int y, int z, BlockData blockData); - /** - * Get the type and data of the block at x, y, z. - * - * Getting blocks outside the chunk's bounds returns air. - * - * @param x - * the x location in the chunk from 0-15 inclusive - * @param y - * the y location in the chunk from 0 (inclusive) - maxHeight - * (exclusive) - * @param z - * the z location in the chunk from 0-15 inclusive - * @return the data of the block or the BlockData for air if x, y or z are - * outside the chunk's bounds - */ - public BlockData getBlockData(int x, int y, int z); + /** + * Get the type and data of the block at x, y, z. + *

+ * Getting blocks outside the chunk's bounds returns air. + * + * @param x the x location in the chunk from 0-15 inclusive + * @param y the y location in the chunk from 0 (inclusive) - maxHeight + * (exclusive) + * @param z the z location in the chunk from 0-15 inclusive + * @return the data of the block or the BlockData for air if x, y or z are + * outside the chunk's bounds + */ + BlockData getBlockData(int x, int y, int z); - public ChunkData getRaw(); + ChunkData getRaw(); - public void inject(BiomeGrid biome); + void inject(BiomeGrid biome); } diff --git a/src/main/java/com/volmit/iris/util/ThreadMonitor.java b/src/main/java/com/volmit/iris/util/ThreadMonitor.java index 7e212a05c..dbf013b8c 100644 --- a/src/main/java/com/volmit/iris/util/ThreadMonitor.java +++ b/src/main/java/com/volmit/iris/util/ThreadMonitor.java @@ -5,84 +5,65 @@ import com.volmit.iris.Iris; /** * Not particularly efficient or perfectly accurate but is great at fast thread * switching detection - * - * @author dan * + * @author dan */ -public class ThreadMonitor extends Thread -{ - private Thread monitor; - private boolean running; - private State lastState; - private ChronoLatch cl; - private PrecisionStopwatch st; - int cycles = 0; - private RollingSequence sq = new RollingSequence(3); +public class ThreadMonitor extends Thread { + private final Thread monitor; + private boolean running; + private State lastState; + private final ChronoLatch cl; + private PrecisionStopwatch st; + int cycles = 0; + private final RollingSequence sq = new RollingSequence(3); - private ThreadMonitor(Thread monitor) - { - running = true; - st = PrecisionStopwatch.start(); - this.monitor = monitor; - lastState = State.NEW; - cl = new ChronoLatch(1000); - start(); - } + private ThreadMonitor(Thread monitor) { + running = true; + st = PrecisionStopwatch.start(); + this.monitor = monitor; + lastState = State.NEW; + cl = new ChronoLatch(1000); + start(); + } - public void run() - { - while(running) - { - try - { - Thread.sleep(0); - State s = monitor.getState(); - if(lastState != s) - { - cycles++; - pushState(s); - } + public void run() { + while (running) { + try { + Thread.sleep(0); + State s = monitor.getState(); + if (lastState != s) { + cycles++; + pushState(s); + } - lastState = s; + lastState = s; - if(cl.flip()) - { - Iris.info("Cycles: " + Form.f(cycles) + " (" + Form.duration(sq.getAverage(), 2) + ")"); - } - } + if (cl.flip()) { + Iris.info("Cycles: " + Form.f(cycles) + " (" + Form.duration(sq.getAverage(), 2) + ")"); + } + } catch (Throwable e) { + running = false; + break; + } + } + } - catch(Throwable e) - { - running = false; - break; - } - } - } + public void pushState(State s) { + if (s != State.RUNNABLE) { + if (st != null) { + sq.put(st.getMilliseconds()); + } + } else { - public void pushState(State s) - { - if(s != State.RUNNABLE) - { - if(st != null) - { - sq.put(st.getMilliseconds()); - } - } + st = PrecisionStopwatch.start(); + } + } - else - { + public void unbind() { + running = false; + } - st = PrecisionStopwatch.start(); - } - } - - public void unbind() - { - running = false; - } - - public static ThreadMonitor bind(Thread monitor) - { - return new ThreadMonitor(monitor); - } + public static ThreadMonitor bind(Thread monitor) { + return new ThreadMonitor(monitor); + } } diff --git a/src/main/java/com/volmit/iris/util/Tuple2d.java b/src/main/java/com/volmit/iris/util/Tuple2d.java index 13433939c..a90e9976b 100644 --- a/src/main/java/com/volmit/iris/util/Tuple2d.java +++ b/src/main/java/com/volmit/iris/util/Tuple2d.java @@ -31,12 +31,9 @@ package com.volmit.iris.util; -import java.lang.Math; - /** - * A generic 2-element tuple that is represented by double-precision + * A generic 2-element tuple that is represented by double-precision * floating point x,y coordinates. - * */ public abstract class Tuple2d implements java.io.Serializable, Cloneable { @@ -45,119 +42,118 @@ public abstract class Tuple2d implements java.io.Serializable, Cloneable { /** * The x coordinate. */ - public double x; + public double x; /** * The y coordinate. */ - public double y; + public double y; /** * Constructs and initializes a Tuple2d from the specified xy coordinates. + * * @param x the x coordinate * @param y the y coordinate */ - public Tuple2d(double x, double y) - { - this.x = x; - this.y = y; + public Tuple2d(double x, double y) { + this.x = x; + this.y = y; } /** * Constructs and initializes a Tuple2d from the specified array. + * * @param t the array of length 2 containing xy in order */ - public Tuple2d(double[] t) - { - this.x = t[0]; - this.y = t[1]; + public Tuple2d(double[] t) { + this.x = t[0]; + this.y = t[1]; } /** * Constructs and initializes a Tuple2d from the specified Tuple2d. + * * @param t1 the Tuple2d containing the initialization x y data */ - public Tuple2d(Tuple2d t1) - { - this.x = t1.x; - this.y = t1.y; + public Tuple2d(Tuple2d t1) { + this.x = t1.x; + this.y = t1.y; } /** * Constructs and initializes a Tuple2d from the specified Tuple2f. + * * @param t1 the Tuple2f containing the initialization x y data */ - public Tuple2d(Tuple2f t1) - { - this.x = (double) t1.x; - this.y = (double) t1.y; + public Tuple2d(Tuple2f t1) { + this.x = t1.x; + this.y = t1.y; } /** * Constructs and initializes a Tuple2d to (0,0). */ - public Tuple2d() - { - this.x = 0.0; - this.y = 0.0; + public Tuple2d() { + this.x = 0.0; + this.y = 0.0; } /** * Sets the value of this tuple to the specified xy coordinates. + * * @param x the x coordinate * @param y the y coordinate */ - public final void set(double x, double y) - { - this.x = x; - this.y = y; + public final void set(double x, double y) { + this.x = x; + this.y = y; } /** - * Sets the value of this tuple from the 2 values specified in + * Sets the value of this tuple from the 2 values specified in * the array. + * * @param t the array of length 2 containing xy in order */ - public final void set(double[] t) - { - this.x = t[0]; - this.y = t[1]; + public final void set(double[] t) { + this.x = t[0]; + this.y = t[1]; } /** * Sets the value of this tuple to the value of the Tuple2d argument. + * * @param t1 the tuple to be copied */ - public final void set(Tuple2d t1) - { - this.x = t1.x; - this.y = t1.y; + public final void set(Tuple2d t1) { + this.x = t1.x; + this.y = t1.y; } - + /** * Sets the value of this tuple to the value of Tuple2f t1. + * * @param t1 the tuple to be copied */ - public final void set(Tuple2f t1) - { - this.x = (double) t1.x; - this.y = (double) t1.y; + public final void set(Tuple2f t1) { + this.x = t1.x; + this.y = t1.y; } - /** - * Copies the value of the elements of this tuple into the array t. - * @param t the array that will contain the values of the vector - */ - public final void get(double[] t) - { + /** + * Copies the value of the elements of this tuple into the array t. + * + * @param t the array that will contain the values of the vector + */ + public final void get(double[] t) { t[0] = this.x; t[1] = this.y; } @@ -165,47 +161,47 @@ public abstract class Tuple2d implements java.io.Serializable, Cloneable { /** * Sets the value of this tuple to the vector sum of tuples t1 and t2. + * * @param t1 the first tuple * @param t2 the second tuple */ - public final void add(Tuple2d t1, Tuple2d t2) - { - this.x = t1.x + t2.x; - this.y = t1.y + t2.y; + public final void add(Tuple2d t1, Tuple2d t2) { + this.x = t1.x + t2.x; + this.y = t1.y + t2.y; } /** * Sets the value of this tuple to the vector sum of itself and tuple t1. + * * @param t1 the other tuple - */ - public final void add(Tuple2d t1) - { + */ + public final void add(Tuple2d t1) { this.x += t1.x; this.y += t1.y; } /** - * Sets the value of this tuple to the vector difference of - * tuple t1 and t2 (this = t1 - t2). + * Sets the value of this tuple to the vector difference of + * tuple t1 and t2 (this = t1 - t2). + * * @param t1 the first tuple * @param t2 the second tuple - */ - public final void sub(Tuple2d t1, Tuple2d t2) - { + */ + public final void sub(Tuple2d t1, Tuple2d t2) { this.x = t1.x - t2.x; this.y = t1.y - t2.y; - } + } /** * Sets the value of this tuple to the vector difference of * itself and tuple t1 (this = this - t1). + * * @param t1 the other vector - */ - public final void sub(Tuple2d t1) - { + */ + public final void sub(Tuple2d t1) { this.x -= t1.x; this.y -= t1.y; } @@ -213,394 +209,388 @@ public abstract class Tuple2d implements java.io.Serializable, Cloneable { /** * Sets the value of this tuple to the negation of tuple t1. + * * @param t1 the source vector */ - public final void negate(Tuple2d t1) - { - this.x = -t1.x; - this.y = -t1.y; + public final void negate(Tuple2d t1) { + this.x = -t1.x; + this.y = -t1.y; } /** * Negates the value of this vector in place. */ - public final void negate() - { - this.x = -this.x; - this.y = -this.y; + public final void negate() { + this.x = -this.x; + this.y = -this.y; } /** * Sets the value of this tuple to the scalar multiplication * of tuple t1. - * @param s the scalar value + * + * @param s the scalar value * @param t1 the source tuple */ - public final void scale(double s, Tuple2d t1) - { - this.x = s*t1.x; - this.y = s*t1.y; + public final void scale(double s, Tuple2d t1) { + this.x = s * t1.x; + this.y = s * t1.y; } /** * Sets the value of this tuple to the scalar multiplication * of itself. + * * @param s the scalar value */ - public final void scale(double s) - { - this.x *= s; - this.y *= s; + public final void scale(double s) { + this.x *= s; + this.y *= s; } /** * Sets the value of this tuple to the scalar multiplication * of tuple t1 and then adds tuple t2 (this = s*t1 + t2). - * @param s the scalar value + * + * @param s the scalar value * @param t1 the tuple to be multipled * @param t2 the tuple to be added - */ - public final void scaleAdd(double s, Tuple2d t1, Tuple2d t2) - { - this.x = s*t1.x + t2.x; - this.y = s*t1.y + t2.y; - } - + */ + public final void scaleAdd(double s, Tuple2d t1, Tuple2d t2) { + this.x = s * t1.x + t2.x; + this.y = s * t1.y + t2.y; + } + /** * Sets the value of this tuple to the scalar multiplication * of itself and then adds tuple t1 (this = s*this + t1). - * @param s the scalar value + * + * @param s the scalar value * @param t1 the tuple to be added */ - public final void scaleAdd(double s, Tuple2d t1) - { - this.x = s*this.x + t1.x; - this.y = s*this.y + t1.y; + public final void scaleAdd(double s, Tuple2d t1) { + this.x = s * this.x + t1.x; + this.y = s * this.y + t1.y; } - /** * Returns a hash code value based on the data values in this * object. Two different Tuple2d objects with identical data values * (i.e., Tuple2d.equals returns true) will return the same hash * code value. Two objects with different data members may return the * same hash value, although this is not likely. + * * @return the integer hash code value - */ + */ public int hashCode() { - long bits = 1L; - bits = 31L * bits + VecMathUtil.doubleToLongBits(x); - bits = 31L * bits + VecMathUtil.doubleToLongBits(y); - return (int) (bits ^ (bits >> 32)); + long bits = 1L; + bits = 31L * bits + VecMathUtil.doubleToLongBits(x); + bits = 31L * bits + VecMathUtil.doubleToLongBits(y); + return (int) (bits ^ (bits >> 32)); } - /** + /** * Returns true if all of the data members of Tuple2d t1 are * equal to the corresponding data members in this Tuple2d. - * @param t1 the vector with which the comparison is made - * @return true or false - */ - public boolean equals(Tuple2d t1) - { + * + * @param t1 the vector with which the comparison is made + * @return true or false + */ + public boolean equals(Tuple2d t1) { try { - return(this.x == t1.x && this.y == t1.y); + return (this.x == t1.x && this.y == t1.y); + } catch (NullPointerException e2) { + return false; } - catch (NullPointerException e2) {return false;} } - /** + /** * Returns true if the Object t1 is of type Tuple2d and all of the * data members of t1 are equal to the corresponding data members in * this Tuple2d. - * @param t1 the object with which the comparison is made - * @return true or false - */ - public boolean equals(Object t1) - { - try { - Tuple2d t2 = (Tuple2d) t1; - return(this.x == t2.x && this.y == t2.y); - } - catch (NullPointerException e2) {return false;} - catch (ClassCastException e1) {return false;} - - } - - /** - * Returns true if the L-infinite distance between this tuple - * and tuple t1 is less than or equal to the epsilon parameter, - * otherwise returns false. The L-infinite - * distance is equal to MAX[abs(x1-x2), abs(y1-y2)]. - * @param t1 the tuple to be compared to this tuple - * @param epsilon the threshold value - * @return true or false + * + * @param t1 the object with which the comparison is made + * @return true or false */ - public boolean epsilonEquals(Tuple2d t1, double epsilon) - { - double diff; + public boolean equals(Object t1) { + try { + Tuple2d t2 = (Tuple2d) t1; + return (this.x == t2.x && this.y == t2.y); + } catch (NullPointerException e2) { + return false; + } catch (ClassCastException e1) { + return false; + } - diff = x - t1.x; - if(Double.isNaN(diff)) return false; - if((diff<0?-diff:diff) > epsilon) return false; - - diff = y - t1.y; - if(Double.isNaN(diff)) return false; - if((diff<0?-diff:diff) > epsilon) return false; - - return true; } - /** + /** + * Returns true if the L-infinite distance between this tuple + * and tuple t1 is less than or equal to the epsilon parameter, + * otherwise returns false. The L-infinite + * distance is equal to MAX[abs(x1-x2), abs(y1-y2)]. + * + * @param t1 the tuple to be compared to this tuple + * @param epsilon the threshold value + * @return true or false + */ + public boolean epsilonEquals(Tuple2d t1, double epsilon) { + double diff; + + diff = x - t1.x; + if (Double.isNaN(diff)) return false; + if ((diff < 0 ? -diff : diff) > epsilon) return false; + + diff = y - t1.y; + if (Double.isNaN(diff)) return false; + return !((diff < 0 ? -diff : diff) > epsilon); + } + + /** * Returns a string that contains the values of this Tuple2d. * The form is (x,y). + * * @return the String representation - */ - public String toString() - { - return("(" + this.x + ", " + this.y + ")"); - } + */ + public String toString() { + return ("(" + this.x + ", " + this.y + ")"); + } - /** - * Clamps the tuple parameter to the range [low, high] and - * places the values into this tuple. - * @param min the lowest value in the tuple after clamping - * @param max the highest value in the tuple after clamping - * @param t the source tuple, which will not be modified - */ - public final void clamp(double min, double max, Tuple2d t) - { - if( t.x > max ) { - x = max; - } else if( t.x < min ){ - x = min; + /** + * Clamps the tuple parameter to the range [low, high] and + * places the values into this tuple. + * + * @param min the lowest value in the tuple after clamping + * @param max the highest value in the tuple after clamping + * @param t the source tuple, which will not be modified + */ + public final void clamp(double min, double max, Tuple2d t) { + if (t.x > max) { + x = max; + } else if (t.x < min) { + x = min; } else { - x = t.x; + x = t.x; } - if( t.y > max ) { - y = max; - } else if( t.y < min ){ - y = min; + if (t.y > max) { + y = max; + } else if (t.y < min) { + y = min; } else { - y = t.y; + y = t.y; } - } + } - /** - * Clamps the minimum value of the tuple parameter to the min - * parameter and places the values into this tuple. - * @param min the lowest value in the tuple after clamping - * @param t the source tuple, which will not be modified - */ - public final void clampMin(double min, Tuple2d t) - { - if( t.x < min ) { - x = min; + /** + * Clamps the minimum value of the tuple parameter to the min + * parameter and places the values into this tuple. + * + * @param min the lowest value in the tuple after clamping + * @param t the source tuple, which will not be modified + */ + public final void clampMin(double min, Tuple2d t) { + if (t.x < min) { + x = min; } else { - x = t.x; + x = t.x; } - if( t.y < min ) { - y = min; + if (t.y < min) { + y = min; } else { - y = t.y; + y = t.y; } - } + } - /** - * Clamps the maximum value of the tuple parameter to the max - * parameter and places the values into this tuple. - * @param max the highest value in the tuple after clamping - * @param t the source tuple, which will not be modified - */ - public final void clampMax(double max, Tuple2d t) - { - if( t.x > max ) { - x = max; - } else { - x = t.x; - } - - if( t.y > max ) { - y = max; + /** + * Clamps the maximum value of the tuple parameter to the max + * parameter and places the values into this tuple. + * + * @param max the highest value in the tuple after clamping + * @param t the source tuple, which will not be modified + */ + public final void clampMax(double max, Tuple2d t) { + if (t.x > max) { + x = max; } else { - y = t.y; + x = t.x; } - } - - - /** - * Sets each component of the tuple parameter to its absolute - * value and places the modified values into this tuple. - * @param t the source tuple, which will not be modified - */ - public final void absolute(Tuple2d t) - { - x = Math.abs(t.x); - y = Math.abs(t.y); - } - - - - /** - * Clamps this tuple to the range [low, high]. - * @param min the lowest value in this tuple after clamping - * @param max the highest value in this tuple after clamping - */ - public final void clamp(double min, double max) - { - if( x > max ) { - x = max; - } else if( x < min ){ - x = min; - } - - if( y > max ) { - y = max; - } else if( y < min ){ - y = min; + if (t.y > max) { + y = max; + } else { + y = t.y; } - } - - - /** - * Clamps the minimum value of this tuple to the min parameter. - * @param min the lowest value in this tuple after clamping - */ - public final void clampMin(double min) - { - if( x < min ) x=min; - if( y < min ) y=min; - } - - - /** - * Clamps the maximum value of this tuple to the max parameter. - * @param max the highest value in the tuple after clamping - */ - public final void clampMax(double max) - { - if( x > max ) x=max; - if( y > max ) y=max; - } + } - /** - * Sets each component of this tuple to its absolute value. - */ - public final void absolute() - { - x = Math.abs(x); - y = Math.abs(y); - } + /** + * Sets each component of the tuple parameter to its absolute + * value and places the modified values into this tuple. + * + * @param t the source tuple, which will not be modified + */ + public final void absolute(Tuple2d t) { + x = Math.abs(t.x); + y = Math.abs(t.y); + } - /** - * Linearly interpolates between tuples t1 and t2 and places the - * result into this tuple: this = (1-alpha)*t1 + alpha*t2. - * @param t1 the first tuple - * @param t2 the second tuple - * @param alpha the alpha interpolation parameter - */ - public final void interpolate(Tuple2d t1, Tuple2d t2, double alpha) - { - this.x = (1-alpha)*t1.x + alpha*t2.x; - this.y = (1-alpha)*t1.y + alpha*t2.y; - } + /** + * Clamps this tuple to the range [low, high]. + * + * @param min the lowest value in this tuple after clamping + * @param max the highest value in this tuple after clamping + */ + public final void clamp(double min, double max) { + if (x > max) { + x = max; + } else if (x < min) { + x = min; + } + + if (y > max) { + y = max; + } else if (y < min) { + y = min; + } + + } - /** - * Linearly interpolates between this tuple and tuple t1 and - * places the result into this tuple: this = (1-alpha)*this + alpha*t1. - * @param t1 the first tuple - * @param alpha the alpha interpolation parameter - */ - public final void interpolate(Tuple2d t1, double alpha) - { - this.x = (1-alpha)*this.x + alpha*t1.x; - this.y = (1-alpha)*this.y + alpha*t1.y; + /** + * Clamps the minimum value of this tuple to the min parameter. + * + * @param min the lowest value in this tuple after clamping + */ + public final void clampMin(double min) { + if (x < min) x = min; + if (y < min) y = min; + } - } + + /** + * Clamps the maximum value of this tuple to the max parameter. + * + * @param max the highest value in the tuple after clamping + */ + public final void clampMax(double max) { + if (x > max) x = max; + if (y > max) y = max; + } + + + /** + * Sets each component of this tuple to its absolute value. + */ + public final void absolute() { + x = Math.abs(x); + y = Math.abs(y); + } + + + /** + * Linearly interpolates between tuples t1 and t2 and places the + * result into this tuple: this = (1-alpha)*t1 + alpha*t2. + * + * @param t1 the first tuple + * @param t2 the second tuple + * @param alpha the alpha interpolation parameter + */ + public final void interpolate(Tuple2d t1, Tuple2d t2, double alpha) { + this.x = (1 - alpha) * t1.x + alpha * t2.x; + this.y = (1 - alpha) * t1.y + alpha * t2.y; + } + + + /** + * Linearly interpolates between this tuple and tuple t1 and + * places the result into this tuple: this = (1-alpha)*this + alpha*t1. + * + * @param t1 the first tuple + * @param alpha the alpha interpolation parameter + */ + public final void interpolate(Tuple2d t1, double alpha) { + this.x = (1 - alpha) * this.x + alpha * t1.x; + this.y = (1 - alpha) * this.y + alpha * t1.y; + + } /** * Creates a new object of the same class as this object. * * @return a clone of this instance. - * @exception OutOfMemoryError if there is not enough memory. + * @throws OutOfMemoryError if there is not enough memory. * @see java.lang.Cloneable * @since vecmath 1.3 */ public Object clone() { - // Since there are no arrays we can just use Object.clone() - try { - return super.clone(); - } catch (CloneNotSupportedException e) { - // this shouldn't happen, since we are Cloneable - throw new InternalError(); - } + // Since there are no arrays we can just use Object.clone() + try { + return super.clone(); + } catch (CloneNotSupportedException e) { + // this shouldn't happen, since we are Cloneable + throw new InternalError(); + } } - /** - * Get the x coordinate. - * - * @return the x coordinate. - * - * @since vecmath 1.5 - */ - public final double getX() { - return x; - } + /** + * Get the x coordinate. + * + * @return the x coordinate. + * @since vecmath 1.5 + */ + public final double getX() { + return x; + } - /** - * Set the x coordinate. - * - * @param x value to x coordinate. - * - * @since vecmath 1.5 - */ - public final void setX(double x) { - this.x = x; - } + /** + * Set the x coordinate. + * + * @param x value to x coordinate. + * @since vecmath 1.5 + */ + public final void setX(double x) { + this.x = x; + } - /** - * Get the y coordinate. - * - * @return the y coordinate. - * - * @since vecmath 1.5 - */ - public final double getY() { - return y; - } + /** + * Get the y coordinate. + * + * @return the y coordinate. + * @since vecmath 1.5 + */ + public final double getY() { + return y; + } - /** - * Set the y coordinate. - * - * @param y value to y coordinate. - * - * @since vecmath 1.5 - */ - public final void setY(double y) { - this.y = y; - } + /** + * Set the y coordinate. + * + * @param y value to y coordinate. + * @since vecmath 1.5 + */ + public final void setY(double y) { + this.y = y; + } } diff --git a/src/main/java/com/volmit/iris/util/Tuple2f.java b/src/main/java/com/volmit/iris/util/Tuple2f.java index 69f76affa..5adf18e44 100644 --- a/src/main/java/com/volmit/iris/util/Tuple2f.java +++ b/src/main/java/com/volmit/iris/util/Tuple2f.java @@ -31,12 +31,9 @@ package com.volmit.iris.util; -import java.lang.Math; - /** - * A generic 2-element tuple that is represented by single-precision + * A generic 2-element tuple that is represented by single-precision * floating point x,y coordinates. - * */ public abstract class Tuple2f implements java.io.Serializable, Cloneable { @@ -45,121 +42,120 @@ public abstract class Tuple2f implements java.io.Serializable, Cloneable { /** * The x coordinate. */ - public float x; + public float x; /** * The y coordinate. */ - public float y; + public float y; /** * Constructs and initializes a Tuple2f from the specified xy coordinates. + * * @param x the x coordinate * @param y the y coordinate */ - public Tuple2f(float x, float y) - { - this.x = x; - this.y = y; + public Tuple2f(float x, float y) { + this.x = x; + this.y = y; } /** * Constructs and initializes a Tuple2f from the specified array. + * * @param t the array of length 2 containing xy in order */ - public Tuple2f(float[] t) - { - this.x = t[0]; - this.y = t[1]; + public Tuple2f(float[] t) { + this.x = t[0]; + this.y = t[1]; } /** * Constructs and initializes a Tuple2f from the specified Tuple2f. + * * @param t1 the Tuple2f containing the initialization x y data */ - public Tuple2f(Tuple2f t1) - { - this.x = t1.x; - this.y = t1.y; + public Tuple2f(Tuple2f t1) { + this.x = t1.x; + this.y = t1.y; } /** * Constructs and initializes a Tuple2f from the specified Tuple2d. + * * @param t1 the Tuple2d containing the initialization x y data */ - public Tuple2f(Tuple2d t1) - { - this.x = (float) t1.x; - this.y = (float) t1.y; + public Tuple2f(Tuple2d t1) { + this.x = (float) t1.x; + this.y = (float) t1.y; } /** * Constructs and initializes a Tuple2f to (0,0). */ - public Tuple2f() - { - this.x = (float) 0.0; - this.y = (float) 0.0; + public Tuple2f() { + this.x = (float) 0.0; + this.y = (float) 0.0; } /** * Sets the value of this tuple to the specified xy coordinates. + * * @param x the x coordinate * @param y the y coordinate */ - public final void set(float x, float y) - { - this.x = x; - this.y = y; + public final void set(float x, float y) { + this.x = x; + this.y = y; } /** - * Sets the value of this tuple from the 2 values specified in + * Sets the value of this tuple from the 2 values specified in * the array. + * * @param t the array of length 2 containing xy in order */ - public final void set(float[] t) - { - this.x = t[0]; - this.y = t[1]; + public final void set(float[] t) { + this.x = t[0]; + this.y = t[1]; } /** * Sets the value of this tuple to the value of the Tuple2f argument. + * * @param t1 the tuple to be copied */ - public final void set(Tuple2f t1) - { - this.x = t1.x; - this.y = t1.y; + public final void set(Tuple2f t1) { + this.x = t1.x; + this.y = t1.y; } - + /** * Sets the value of this tuple to the value of the Tuple2d argument. + * * @param t1 the tuple to be copied */ - public final void set(Tuple2d t1) - { - this.x = (float) t1.x; - this.y = (float) t1.y; + public final void set(Tuple2d t1) { + this.x = (float) t1.x; + this.y = (float) t1.y; } - /** - * Copies the value of the elements of this tuple into the array t. - * @param t the array that will contain the values of the vector - */ - public final void get(float[] t) - { + /** + * Copies the value of the elements of this tuple into the array t. + * + * @param t the array that will contain the values of the vector + */ + public final void get(float[] t) { t[0] = this.x; t[1] = this.y; } @@ -167,47 +163,47 @@ public abstract class Tuple2f implements java.io.Serializable, Cloneable { /** * Sets the value of this tuple to the vector sum of tuples t1 and t2. + * * @param t1 the first tuple * @param t2 the second tuple */ - public final void add(Tuple2f t1, Tuple2f t2) - { - this.x = t1.x + t2.x; - this.y = t1.y + t2.y; + public final void add(Tuple2f t1, Tuple2f t2) { + this.x = t1.x + t2.x; + this.y = t1.y + t2.y; } /** * Sets the value of this tuple to the vector sum of itself and tuple t1. + * * @param t1 the other tuple - */ - public final void add(Tuple2f t1) - { + */ + public final void add(Tuple2f t1) { this.x += t1.x; this.y += t1.y; } /** - * Sets the value of this tuple to the vector difference of - * tuple t1 and t2 (this = t1 - t2). + * Sets the value of this tuple to the vector difference of + * tuple t1 and t2 (this = t1 - t2). + * * @param t1 the first tuple * @param t2 the second tuple - */ - public final void sub(Tuple2f t1, Tuple2f t2) - { + */ + public final void sub(Tuple2f t1, Tuple2f t2) { this.x = t1.x - t2.x; this.y = t1.y - t2.y; - } + } /** * Sets the value of this tuple to the vector difference of * itself and tuple t1 (this = this - t1). + * * @param t1 the other tuple - */ - public final void sub(Tuple2f t1) - { + */ + public final void sub(Tuple2f t1) { this.x -= t1.x; this.y -= t1.y; } @@ -215,395 +211,389 @@ public abstract class Tuple2f implements java.io.Serializable, Cloneable { /** * Sets the value of this tuple to the negation of tuple t1. + * * @param t1 the source tuple */ - public final void negate(Tuple2f t1) - { - this.x = -t1.x; - this.y = -t1.y; + public final void negate(Tuple2f t1) { + this.x = -t1.x; + this.y = -t1.y; } /** * Negates the value of this vector in place. */ - public final void negate() - { - this.x = -this.x; - this.y = -this.y; + public final void negate() { + this.x = -this.x; + this.y = -this.y; } /** * Sets the value of this tuple to the scalar multiplication * of tuple t1. - * @param s the scalar value + * + * @param s the scalar value * @param t1 the source tuple */ - public final void scale(float s, Tuple2f t1) - { - this.x = s*t1.x; - this.y = s*t1.y; + public final void scale(float s, Tuple2f t1) { + this.x = s * t1.x; + this.y = s * t1.y; } /** * Sets the value of this tuple to the scalar multiplication * of itself. + * * @param s the scalar value */ - public final void scale(float s) - { - this.x *= s; - this.y *= s; + public final void scale(float s) { + this.x *= s; + this.y *= s; } /** * Sets the value of this tuple to the scalar multiplication * of tuple t1 and then adds tuple t2 (this = s*t1 + t2). - * @param s the scalar value + * + * @param s the scalar value * @param t1 the tuple to be multipled * @param t2 the tuple to be added - */ - public final void scaleAdd(float s, Tuple2f t1, Tuple2f t2) - { - this.x = s*t1.x + t2.x; - this.y = s*t1.y + t2.y; - } - + */ + public final void scaleAdd(float s, Tuple2f t1, Tuple2f t2) { + this.x = s * t1.x + t2.x; + this.y = s * t1.y + t2.y; + } + /** * Sets the value of this tuple to the scalar multiplication * of itself and then adds tuple t1 (this = s*this + t1). - * @param s the scalar value + * + * @param s the scalar value * @param t1 the tuple to be added */ - public final void scaleAdd(float s, Tuple2f t1) - { - this.x = s*this.x + t1.x; - this.y = s*this.y + t1.y; + public final void scaleAdd(float s, Tuple2f t1) { + this.x = s * this.x + t1.x; + this.y = s * this.y + t1.y; } - /** * Returns a hash code value based on the data values in this * object. Two different Tuple2f objects with identical data values * (i.e., Tuple2f.equals returns true) will return the same hash * code value. Two objects with different data members may return the * same hash value, although this is not likely. + * * @return the integer hash code value - */ + */ public int hashCode() { - long bits = 1L; - bits = 31L * bits + (long)VecMathUtil.floatToIntBits(x); - bits = 31L * bits + (long)VecMathUtil.floatToIntBits(y); - return (int) (bits ^ (bits >> 32)); + long bits = 1L; + bits = 31L * bits + (long) VecMathUtil.floatToIntBits(x); + bits = 31L * bits + (long) VecMathUtil.floatToIntBits(y); + return (int) (bits ^ (bits >> 32)); } - /** + /** * Returns true if all of the data members of Tuple2f t1 are * equal to the corresponding data members in this Tuple2f. - * @param t1 the vector with which the comparison is made - * @return true or false - */ - public boolean equals(Tuple2f t1) - { + * + * @param t1 the vector with which the comparison is made + * @return true or false + */ + public boolean equals(Tuple2f t1) { try { - return(this.x == t1.x && this.y == t1.y); + return (this.x == t1.x && this.y == t1.y); + } catch (NullPointerException e2) { + return false; } - catch (NullPointerException e2) {return false;} } - /** + /** * Returns true if the Object t1 is of type Tuple2f and all of the * data members of t1 are equal to the corresponding data members in * this Tuple2f. - * @param t1 the object with which the comparison is made - * @return true or false - */ - public boolean equals(Object t1) - { - try { - Tuple2f t2 = (Tuple2f) t1; - return(this.x == t2.x && this.y == t2.y); - } - catch (NullPointerException e2) {return false;} - catch (ClassCastException e1) {return false;} - - } - - /** - * Returns true if the L-infinite distance between this tuple - * and tuple t1 is less than or equal to the epsilon parameter, - * otherwise returns false. The L-infinite - * distance is equal to MAX[abs(x1-x2), abs(y1-y2)]. - * @param t1 the tuple to be compared to this tuple - * @param epsilon the threshold value - * @return true or false + * + * @param t1 the object with which the comparison is made + * @return true or false */ - public boolean epsilonEquals(Tuple2f t1, float epsilon) - { - float diff; + public boolean equals(Object t1) { + try { + Tuple2f t2 = (Tuple2f) t1; + return (this.x == t2.x && this.y == t2.y); + } catch (NullPointerException e2) { + return false; + } catch (ClassCastException e1) { + return false; + } - diff = x - t1.x; - if(Float.isNaN(diff)) return false; - if((diff<0?-diff:diff) > epsilon) return false; - - diff = y - t1.y; - if(Float.isNaN(diff)) return false; - if((diff<0?-diff:diff) > epsilon) return false; - - return true; } - /** + /** + * Returns true if the L-infinite distance between this tuple + * and tuple t1 is less than or equal to the epsilon parameter, + * otherwise returns false. The L-infinite + * distance is equal to MAX[abs(x1-x2), abs(y1-y2)]. + * + * @param t1 the tuple to be compared to this tuple + * @param epsilon the threshold value + * @return true or false + */ + public boolean epsilonEquals(Tuple2f t1, float epsilon) { + float diff; + + diff = x - t1.x; + if (Float.isNaN(diff)) return false; + if ((diff < 0 ? -diff : diff) > epsilon) return false; + + diff = y - t1.y; + if (Float.isNaN(diff)) return false; + return !((diff < 0 ? -diff : diff) > epsilon); + } + + /** * Returns a string that contains the values of this Tuple2f. * The form is (x,y). + * * @return the String representation - */ - public String toString() - { - return("(" + this.x + ", " + this.y + ")"); - } + */ + public String toString() { + return ("(" + this.x + ", " + this.y + ")"); + } - /** - * Clamps the tuple parameter to the range [low, high] and - * places the values into this tuple. - * @param min the lowest value in the tuple after clamping - * @param max the highest value in the tuple after clamping - * @param t the source tuple, which will not be modified - */ - public final void clamp(float min, float max, Tuple2f t) - { - if( t.x > max ) { - x = max; - } else if( t.x < min ){ - x = min; + /** + * Clamps the tuple parameter to the range [low, high] and + * places the values into this tuple. + * + * @param min the lowest value in the tuple after clamping + * @param max the highest value in the tuple after clamping + * @param t the source tuple, which will not be modified + */ + public final void clamp(float min, float max, Tuple2f t) { + if (t.x > max) { + x = max; + } else if (t.x < min) { + x = min; } else { - x = t.x; + x = t.x; } - if( t.y > max ) { - y = max; - } else if( t.y < min ){ - y = min; + if (t.y > max) { + y = max; + } else if (t.y < min) { + y = min; } else { - y = t.y; + y = t.y; } - } + } - /** - * Clamps the minimum value of the tuple parameter to the min - * parameter and places the values into this tuple. - * @param min the lowest value in the tuple after clamping - * @param t the source tuple, which will not be modified - */ - public final void clampMin(float min, Tuple2f t) - { - if( t.x < min ) { - x = min; + /** + * Clamps the minimum value of the tuple parameter to the min + * parameter and places the values into this tuple. + * + * @param min the lowest value in the tuple after clamping + * @param t the source tuple, which will not be modified + */ + public final void clampMin(float min, Tuple2f t) { + if (t.x < min) { + x = min; } else { - x = t.x; + x = t.x; } - if( t.y < min ) { - y = min; + if (t.y < min) { + y = min; } else { - y = t.y; + y = t.y; } - } + } - /** - * Clamps the maximum value of the tuple parameter to the max - * parameter and places the values into this tuple. - * @param max the highest value in the tuple after clamping - * @param t the source tuple, which will not be modified - */ - public final void clampMax(float max, Tuple2f t) - { - if( t.x > max ) { - x = max; - } else { - x = t.x; - } - - if( t.y > max ) { - y = max; + /** + * Clamps the maximum value of the tuple parameter to the max + * parameter and places the values into this tuple. + * + * @param max the highest value in the tuple after clamping + * @param t the source tuple, which will not be modified + */ + public final void clampMax(float max, Tuple2f t) { + if (t.x > max) { + x = max; } else { - y = t.y; + x = t.x; } - } - - - /** - * Sets each component of the tuple parameter to its absolute - * value and places the modified values into this tuple. - * @param t the source tuple, which will not be modified - */ - public final void absolute(Tuple2f t) - { - x = Math.abs(t.x); - y = Math.abs(t.y); - } - - - - /** - * Clamps this tuple to the range [low, high]. - * @param min the lowest value in this tuple after clamping - * @param max the highest value in this tuple after clamping - */ - public final void clamp(float min, float max) - { - if( x > max ) { - x = max; - } else if( x < min ){ - x = min; - } - - if( y > max ) { - y = max; - } else if( y < min ){ - y = min; + if (t.y > max) { + y = max; + } else { + y = t.y; } - } - - - /** - * Clamps the minimum value of this tuple to the min parameter. - * @param min the lowest value in this tuple after clamping - */ - public final void clampMin(float min) - { - if( x < min ) x=min; - if( y < min ) y=min; - } - - - /** - * Clamps the maximum value of this tuple to the max parameter. - * @param max the highest value in the tuple after clamping - */ - public final void clampMax(float max) - { - if( x > max ) x=max; - if( y > max ) y=max; - } + } - /** - * Sets each component of this tuple to its absolute value. - */ - public final void absolute() - { - x = Math.abs(x); - y = Math.abs(y); - } + /** + * Sets each component of the tuple parameter to its absolute + * value and places the modified values into this tuple. + * + * @param t the source tuple, which will not be modified + */ + public final void absolute(Tuple2f t) { + x = Math.abs(t.x); + y = Math.abs(t.y); + } - /** - * Linearly interpolates between tuples t1 and t2 and places the - * result into this tuple: this = (1-alpha)*t1 + alpha*t2. - * @param t1 the first tuple - * @param t2 the second tuple - * @param alpha the alpha interpolation parameter - */ - public final void interpolate(Tuple2f t1, Tuple2f t2, float alpha) - { - this.x = (1-alpha)*t1.x + alpha*t2.x; - this.y = (1-alpha)*t1.y + alpha*t2.y; - - } + /** + * Clamps this tuple to the range [low, high]. + * + * @param min the lowest value in this tuple after clamping + * @param max the highest value in this tuple after clamping + */ + public final void clamp(float min, float max) { + if (x > max) { + x = max; + } else if (x < min) { + x = min; + } + + if (y > max) { + y = max; + } else if (y < min) { + y = min; + } + + } - /** - * Linearly interpolates between this tuple and tuple t1 and - * places the result into this tuple: this = (1-alpha)*this + alpha*t1. - * @param t1 the first tuple - * @param alpha the alpha interpolation parameter - */ - public final void interpolate(Tuple2f t1, float alpha) - { + /** + * Clamps the minimum value of this tuple to the min parameter. + * + * @param min the lowest value in this tuple after clamping + */ + public final void clampMin(float min) { + if (x < min) x = min; + if (y < min) y = min; + } - this.x = (1-alpha)*this.x + alpha*t1.x; - this.y = (1-alpha)*this.y + alpha*t1.y; - } + /** + * Clamps the maximum value of this tuple to the max parameter. + * + * @param max the highest value in the tuple after clamping + */ + public final void clampMax(float max) { + if (x > max) x = max; + if (y > max) y = max; + } + + + /** + * Sets each component of this tuple to its absolute value. + */ + public final void absolute() { + x = Math.abs(x); + y = Math.abs(y); + } + + + /** + * Linearly interpolates between tuples t1 and t2 and places the + * result into this tuple: this = (1-alpha)*t1 + alpha*t2. + * + * @param t1 the first tuple + * @param t2 the second tuple + * @param alpha the alpha interpolation parameter + */ + public final void interpolate(Tuple2f t1, Tuple2f t2, float alpha) { + this.x = (1 - alpha) * t1.x + alpha * t2.x; + this.y = (1 - alpha) * t1.y + alpha * t2.y; + + } + + + /** + * Linearly interpolates between this tuple and tuple t1 and + * places the result into this tuple: this = (1-alpha)*this + alpha*t1. + * + * @param t1 the first tuple + * @param alpha the alpha interpolation parameter + */ + public final void interpolate(Tuple2f t1, float alpha) { + + this.x = (1 - alpha) * this.x + alpha * t1.x; + this.y = (1 - alpha) * this.y + alpha * t1.y; + + } /** * Creates a new object of the same class as this object. * * @return a clone of this instance. - * @exception OutOfMemoryError if there is not enough memory. + * @throws OutOfMemoryError if there is not enough memory. * @see java.lang.Cloneable * @since vecmath 1.3 */ public Object clone() { - // Since there are no arrays we can just use Object.clone() - try { - return super.clone(); - } catch (CloneNotSupportedException e) { - // this shouldn't happen, since we are Cloneable - throw new InternalError(); - } + // Since there are no arrays we can just use Object.clone() + try { + return super.clone(); + } catch (CloneNotSupportedException e) { + // this shouldn't happen, since we are Cloneable + throw new InternalError(); + } } /** - * Get the x coordinate. - * - * @return the x coordinate. - * - * @since vecmath 1.5 - */ - public final float getX() { - return x; - } + * Get the x coordinate. + * + * @return the x coordinate. + * @since vecmath 1.5 + */ + public final float getX() { + return x; + } - /** - * Set the x coordinate. - * - * @param x value to x coordinate. - * - * @since vecmath 1.5 - */ - public final void setX(float x) { - this.x = x; - } + /** + * Set the x coordinate. + * + * @param x value to x coordinate. + * @since vecmath 1.5 + */ + public final void setX(float x) { + this.x = x; + } - /** - * Get the y coordinate. - * - * @return the y coordinate. - * - * @since vecmath 1.5 - */ - public final float getY() { - return y; - } + /** + * Get the y coordinate. + * + * @return the y coordinate. + * @since vecmath 1.5 + */ + public final float getY() { + return y; + } - /** - * Set the y coordinate. - * - * @param y value to y coordinate. - * - * @since vecmath 1.5 - */ - public final void setY(float y) { - this.y = y; - } + /** + * Set the y coordinate. + * + * @param y value to y coordinate. + * @since vecmath 1.5 + */ + public final void setY(float y) { + this.y = y; + } } diff --git a/src/main/java/com/volmit/iris/util/Tuple3d.java b/src/main/java/com/volmit/iris/util/Tuple3d.java index d7547d6b8..b64f1e56f 100644 --- a/src/main/java/com/volmit/iris/util/Tuple3d.java +++ b/src/main/java/com/volmit/iris/util/Tuple3d.java @@ -31,12 +31,9 @@ package com.volmit.iris.util; -import java.lang.Math; - /** - * A generic 3-element tuple that is represented by double-precision + * A generic 3-element tuple that is represented by double-precision * floating point x,y,z coordinates. - * */ public abstract class Tuple3d implements java.io.Serializable, Cloneable { @@ -45,141 +42,140 @@ public abstract class Tuple3d implements java.io.Serializable, Cloneable { /** * The x coordinate. */ - public double x; + public double x; /** * The y coordinate. */ - public double y; + public double y; /** * The z coordinate. */ - public double z; + public double z; /** * Constructs and initializes a Tuple3d from the specified xyz coordinates. + * * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate */ - public Tuple3d(double x, double y, double z) - { - this.x = x; - this.y = y; - this.z = z; + public Tuple3d(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; } /** * Constructs and initializes a Tuple3d from the array of length 3. + * * @param t the array of length 3 containing xyz in order */ - public Tuple3d(double[] t) - { - this.x = t[0]; - this.y = t[1]; - this.z = t[2]; + public Tuple3d(double[] t) { + this.x = t[0]; + this.y = t[1]; + this.z = t[2]; } /** * Constructs and initializes a Tuple3d from the specified Tuple3d. + * * @param t1 the Tuple3d containing the initialization x y z data */ - public Tuple3d(Tuple3d t1) - { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; + public Tuple3d(Tuple3d t1) { + this.x = t1.x; + this.y = t1.y; + this.z = t1.z; } /** * Constructs and initializes a Tuple3d from the specified Tuple3f. + * * @param t1 the Tuple3f containing the initialization x y z data */ - public Tuple3d(Tuple3f t1) - { - this.x = (double) t1.x; - this.y = (double) t1.y; - this.z = (double) t1.z; + public Tuple3d(Tuple3f t1) { + this.x = t1.x; + this.y = t1.y; + this.z = t1.z; } /** * Constructs and initializes a Tuple3d to (0,0,0). */ - public Tuple3d() - { - this.x = (double) 0.0; - this.y = (double) 0.0; - this.z = (double) 0.0; + public Tuple3d() { + this.x = 0.0; + this.y = 0.0; + this.z = 0.0; } /** * Sets the value of this tuple to the specified xyz coordinates. + * * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate */ - public final void set(double x, double y, double z) - { - this.x = x; - this.y = y; - this.z = z; + public final void set(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; } /** * Sets the value of this tuple to the value of the xyz coordinates * located in the array of length 3. + * * @param t the array of length 3 containing xyz in order */ - public final void set(double[] t) - { - this.x = t[0]; - this.y = t[1]; - this.z = t[2]; + public final void set(double[] t) { + this.x = t[0]; + this.y = t[1]; + this.z = t[2]; } /** * Sets the value of this tuple to the value of tuple t1. + * * @param t1 the tuple to be copied */ - public final void set(Tuple3d t1) - { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; + public final void set(Tuple3d t1) { + this.x = t1.x; + this.y = t1.y; + this.z = t1.z; } /** * Sets the value of this tuple to the value of tuple t1. + * * @param t1 the tuple to be copied */ - public final void set(Tuple3f t1) - { - this.x = (double) t1.x; - this.y = (double) t1.y; - this.z = (double) t1.z; + public final void set(Tuple3f t1) { + this.x = t1.x; + this.y = t1.y; + this.z = t1.z; } - /** + /** * Copies the x,y,z coordinates of this tuple into the array t * of length 3. - * @param t the target array + * + * @param t the target array */ - public final void get(double[] t) - { + public final void get(double[] t) { t[0] = this.x; t[1] = this.y; t[2] = this.z; } - /** + /** * Copies the x,y,z coordinates of this tuple into the tuple t. - * @param t the Tuple3d object into which the values of this object are copied + * + * @param t the Tuple3d object into which the values of this object are copied */ - public final void get(Tuple3d t) - { + public final void get(Tuple3d t) { t.x = this.x; t.y = this.y; t.z = this.z; @@ -188,23 +184,23 @@ public abstract class Tuple3d implements java.io.Serializable, Cloneable { /** * Sets the value of this tuple to the sum of tuples t1 and t2. + * * @param t1 the first tuple * @param t2 the second tuple */ - public final void add(Tuple3d t1, Tuple3d t2) - { - this.x = t1.x + t2.x; - this.y = t1.y + t2.y; - this.z = t1.z + t2.z; + public final void add(Tuple3d t1, Tuple3d t2) { + this.x = t1.x + t2.x; + this.y = t1.y + t2.y; + this.z = t1.z + t2.z; } - /** + /** * Sets the value of this tuple to the sum of itself and t1. + * * @param t1 the other tuple - */ - public final void add(Tuple3d t1) - { + */ + public final void add(Tuple3d t1) { this.x += t1.x; this.y += t1.y; this.z += t1.z; @@ -213,23 +209,23 @@ public abstract class Tuple3d implements java.io.Serializable, Cloneable { /** * Sets the value of this tuple to the difference of tuples * t1 and t2 (this = t1 - t2). + * * @param t1 the first tuple * @param t2 the second tuple */ - public final void sub(Tuple3d t1, Tuple3d t2) - { - this.x = t1.x - t2.x; - this.y = t1.y - t2.y; - this.z = t1.z - t2.z; + public final void sub(Tuple3d t1, Tuple3d t2) { + this.x = t1.x - t2.x; + this.y = t1.y - t2.y; + this.z = t1.z - t2.z; } - - /** + + /** * Sets the value of this tuple to the difference * of itself and t1 (this = this - t1). + * * @param t1 the other tuple - */ - public final void sub(Tuple3d t1) - { + */ + public final void sub(Tuple3d t1) { this.x -= t1.x; this.y -= t1.y; this.z -= t1.z; @@ -238,48 +234,47 @@ public abstract class Tuple3d implements java.io.Serializable, Cloneable { /** * Sets the value of this tuple to the negation of tuple t1. + * * @param t1 the source tuple */ - public final void negate(Tuple3d t1) - { - this.x = -t1.x; - this.y = -t1.y; - this.z = -t1.z; + public final void negate(Tuple3d t1) { + this.x = -t1.x; + this.y = -t1.y; + this.z = -t1.z; } /** * Negates the value of this tuple in place. */ - public final void negate() - { - this.x = -this.x; - this.y = -this.y; - this.z = -this.z; + public final void negate() { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; } /** * Sets the value of this tuple to the scalar multiplication * of tuple t1. - * @param s the scalar value + * + * @param s the scalar value * @param t1 the source tuple */ - public final void scale(double s, Tuple3d t1) - { - this.x = s*t1.x; - this.y = s*t1.y; - this.z = s*t1.z; + public final void scale(double s, Tuple3d t1) { + this.x = s * t1.x; + this.y = s * t1.y; + this.z = s * t1.z; } /** * Sets the value of this tuple to the scalar multiplication * of itself. + * * @param s the scalar value */ - public final void scale(double s) - { + public final void scale(double s) { this.x *= s; this.y *= s; this.z *= s; @@ -289,45 +284,46 @@ public abstract class Tuple3d implements java.io.Serializable, Cloneable { /** * Sets the value of this tuple to the scalar multiplication * of tuple t1 and then adds tuple t2 (this = s*t1 + t2). - * @param s the scalar value + * + * @param s the scalar value * @param t1 the tuple to be multipled * @param t2 the tuple to be added */ - public final void scaleAdd(double s, Tuple3d t1, Tuple3d t2) - { - this.x = s*t1.x + t2.x; - this.y = s*t1.y + t2.y; - this.z = s*t1.z + t2.z; + public final void scaleAdd(double s, Tuple3d t1, Tuple3d t2) { + this.x = s * t1.x + t2.x; + this.y = s * t1.y + t2.y; + this.z = s * t1.z + t2.z; } /** * @deprecated Use scaleAdd(double,Tuple3d) instead - */ + */ public final void scaleAdd(double s, Tuple3f t1) { - scaleAdd(s, new Point3d(t1)); + scaleAdd(s, new Point3d(t1)); } /** * Sets the value of this tuple to the scalar multiplication * of itself and then adds tuple t1 (this = s*this + t1). - * @param s the scalar value + * + * @param s the scalar value * @param t1 the tuple to be added - */ + */ public final void scaleAdd(double s, Tuple3d t1) { - this.x = s*this.x + t1.x; - this.y = s*this.y + t1.y; - this.z = s*this.z + t1.z; + this.x = s * this.x + t1.x; + this.y = s * this.y + t1.y; + this.z = s * this.z + t1.z; } - - /** + /** * Returns a string that contains the values of this Tuple3d. * The form is (x,y,z). + * * @return the String representation - */ + */ public String toString() { return "(" + this.x + ", " + this.y + ", " + this.z + ")"; } @@ -339,75 +335,77 @@ public abstract class Tuple3d implements java.io.Serializable, Cloneable { * (i.e., Tuple3d.equals returns true) will return the same hash * code value. Two objects with different data members may return the * same hash value, although this is not likely. + * * @return the integer hash code value - */ + */ public int hashCode() { - long bits = 1L; - bits = 31L * bits + VecMathUtil.doubleToLongBits(x); - bits = 31L * bits + VecMathUtil.doubleToLongBits(y); - bits = 31L * bits + VecMathUtil.doubleToLongBits(z); - return (int) (bits ^ (bits >> 32)); + long bits = 1L; + bits = 31L * bits + VecMathUtil.doubleToLongBits(x); + bits = 31L * bits + VecMathUtil.doubleToLongBits(y); + bits = 31L * bits + VecMathUtil.doubleToLongBits(z); + return (int) (bits ^ (bits >> 32)); } - /** + /** * Returns true if all of the data members of Tuple3d t1 are * equal to the corresponding data members in this Tuple3d. - * @param t1 the tuple with which the comparison is made - * @return true or false - */ - public boolean equals(Tuple3d t1) - { - try { - return(this.x == t1.x && this.y == t1.y && this.z == t1.z); - } - catch (NullPointerException e2) {return false;} + * + * @param t1 the tuple with which the comparison is made + * @return true or false + */ + public boolean equals(Tuple3d t1) { + try { + return (this.x == t1.x && this.y == t1.y && this.z == t1.z); + } catch (NullPointerException e2) { + return false; + } } - /** + /** * Returns true if the Object t1 is of type Tuple3d and all of the * data members of t1 are equal to the corresponding data members in * this Tuple3d. - * @param t1 the Object with which the comparison is made - * @return true or false - */ - public boolean equals(Object t1) - { - try { - Tuple3d t2 = (Tuple3d) t1; - return(this.x == t2.x && this.y == t2.y && this.z == t2.z); - } - catch (ClassCastException e1) {return false;} - catch (NullPointerException e2) {return false;} + * + * @param t1 the Object with which the comparison is made + * @return true or false + */ + public boolean equals(Object t1) { + try { + Tuple3d t2 = (Tuple3d) t1; + return (this.x == t2.x && this.y == t2.y && this.z == t2.z); + } catch (ClassCastException e1) { + return false; + } catch (NullPointerException e2) { + return false; + } } - /** + /** * Returns true if the L-infinite distance between this tuple - * and tuple t1 is less than or equal to the epsilon parameter, + * and tuple t1 is less than or equal to the epsilon parameter, * otherwise returns false. The L-infinite * distance is equal to MAX[abs(x1-x2), abs(y1-y2), abs(z1-z2)]. - * @param t1 the tuple to be compared to this tuple - * @param epsilon the threshold value - * @return true or false + * + * @param t1 the tuple to be compared to this tuple + * @param epsilon the threshold value + * @return true or false */ - public boolean epsilonEquals(Tuple3d t1, double epsilon) - { - double diff; + public boolean epsilonEquals(Tuple3d t1, double epsilon) { + double diff; - diff = x - t1.x; - if(Double.isNaN(diff)) return false; - if((diff<0?-diff:diff) > epsilon) return false; + diff = x - t1.x; + if (Double.isNaN(diff)) return false; + if ((diff < 0 ? -diff : diff) > epsilon) return false; - diff = y - t1.y; - if(Double.isNaN(diff)) return false; - if((diff<0?-diff:diff) > epsilon) return false; + diff = y - t1.y; + if (Double.isNaN(diff)) return false; + if ((diff < 0 ? -diff : diff) > epsilon) return false; - diff = z - t1.z; - if(Double.isNaN(diff)) return false; - if((diff<0?-diff:diff) > epsilon) return false; - - return true; + diff = z - t1.z; + if (Double.isNaN(diff)) return false; + return !((diff < 0 ? -diff : diff) > epsilon); } @@ -416,343 +414,344 @@ public abstract class Tuple3d implements java.io.Serializable, Cloneable { * @deprecated Use clamp(double,double,Tuple3d) instead */ public final void clamp(float min, float max, Tuple3d t) { - clamp((double)min, (double)max, t); + clamp(min, (double) max, t); } /** - * Clamps the tuple parameter to the range [low, high] and - * places the values into this tuple. - * @param min the lowest value in the tuple after clamping - * @param max the highest value in the tuple after clamping - * @param t the source tuple, which will not be modified + * Clamps the tuple parameter to the range [low, high] and + * places the values into this tuple. + * + * @param min the lowest value in the tuple after clamping + * @param max the highest value in the tuple after clamping + * @param t the source tuple, which will not be modified */ public final void clamp(double min, double max, Tuple3d t) { - if( t.x > max ) { - x = max; - } else if( t.x < min ){ - x = min; + if (t.x > max) { + x = max; + } else if (t.x < min) { + x = min; } else { - x = t.x; - } - - if( t.y > max ) { - y = max; - } else if( t.y < min ){ - y = min; - } else { - y = t.y; - } - - if( t.z > max ) { - z = max; - } else if( t.z < min ){ - z = min; - } else { - z = t.z; + x = t.x; } - } + if (t.y > max) { + y = max; + } else if (t.y < min) { + y = min; + } else { + y = t.y; + } + + if (t.z > max) { + z = max; + } else if (t.z < min) { + z = min; + } else { + z = t.z; + } + + } - /** + /** * @deprecated Use clampMin(double,Tuple3d) instead - */ + */ public final void clampMin(float min, Tuple3d t) { - clampMin((double)min, t); + clampMin((double) min, t); } - /** - * Clamps the minimum value of the tuple parameter to the min - * parameter and places the values into this tuple. - * @param min the lowest value in the tuple after clamping - * @param t the source tuple, which will not be modified - */ - public final void clampMin(double min, Tuple3d t) { - if( t.x < min ) { - x = min; + /** + * Clamps the minimum value of the tuple parameter to the min + * parameter and places the values into this tuple. + * + * @param min the lowest value in the tuple after clamping + * @param t the source tuple, which will not be modified + */ + public final void clampMin(double min, Tuple3d t) { + if (t.x < min) { + x = min; } else { - x = t.x; - } - - if( t.y < min ) { - y = min; - } else { - y = t.y; - } - - if( t.z < min ) { - z = min; - } else { - z = t.z; + x = t.x; } - } + if (t.y < min) { + y = min; + } else { + y = t.y; + } + + if (t.z < min) { + z = min; + } else { + z = t.z; + } + + } - /** + /** * @deprecated Use clampMax(double,Tuple3d) instead - */ + */ public final void clampMax(float max, Tuple3d t) { - clampMax((double)max, t); + clampMax((double) max, t); } - /** - * Clamps the maximum value of the tuple parameter to the max - * parameter and places the values into this tuple. - * @param max the highest value in the tuple after clamping - * @param t the source tuple, which will not be modified - */ - public final void clampMax(double max, Tuple3d t) { - if( t.x > max ) { - x = max; + /** + * Clamps the maximum value of the tuple parameter to the max + * parameter and places the values into this tuple. + * + * @param max the highest value in the tuple after clamping + * @param t the source tuple, which will not be modified + */ + public final void clampMax(double max, Tuple3d t) { + if (t.x > max) { + x = max; } else { - x = t.x; - } - - if( t.y > max ) { - y = max; - } else { - y = t.y; - } - - if( t.z > max ) { - z = max; - } else { - z = t.z; + x = t.x; } - } + if (t.y > max) { + y = max; + } else { + y = t.y; + } + + if (t.z > max) { + z = max; + } else { + z = t.z; + } + + } - /** - * Sets each component of the tuple parameter to its absolute - * value and places the modified values into this tuple. - * @param t the source tuple, which will not be modified - */ - public final void absolute(Tuple3d t) - { - x = Math.abs(t.x); - y = Math.abs(t.y); - z = Math.abs(t.z); + /** + * Sets each component of the tuple parameter to its absolute + * value and places the modified values into this tuple. + * + * @param t the source tuple, which will not be modified + */ + public final void absolute(Tuple3d t) { + x = Math.abs(t.x); + y = Math.abs(t.y); + z = Math.abs(t.z); - } + } /** * @deprecated Use clamp(double,double) instead */ public final void clamp(float min, float max) { - clamp((double)min, (double)max); + clamp(min, (double) max); } /** - * Clamps this tuple to the range [low, high]. - * @param min the lowest value in this tuple after clamping - * @param max the highest value in this tuple after clamping + * Clamps this tuple to the range [low, high]. + * + * @param min the lowest value in this tuple after clamping + * @param max the highest value in this tuple after clamping */ public final void clamp(double min, double max) { - if( x > max ) { - x = max; - } else if( x < min ){ - x = min; - } - - if( y > max ) { - y = max; - } else if( y < min ){ - y = min; - } - - if( z > max ) { - z = max; - } else if( z < min ){ - z = min; + if (x > max) { + x = max; + } else if (x < min) { + x = min; } - } + if (y > max) { + y = max; + } else if (y < min) { + y = min; + } - - /** + if (z > max) { + z = max; + } else if (z < min) { + z = min; + } + + } + + + /** * @deprecated Use clampMin(double) instead - */ + */ public final void clampMin(float min) { - clampMin((double)min); + clampMin((double) min); } /** - * Clamps the minimum value of this tuple to the min parameter. - * @param min the lowest value in this tuple after clamping + * Clamps the minimum value of this tuple to the min parameter. + * + * @param min the lowest value in this tuple after clamping */ - public final void clampMin(double min) { - if( x < min ) x=min; - if( y < min ) y=min; - if( z < min ) z=min; + public final void clampMin(double min) { + if (x < min) x = min; + if (y < min) y = min; + if (z < min) z = min; - } - - - /** + } + + + /** * @deprecated Use clampMax(double) instead - */ + */ public final void clampMax(float max) { - clampMax((double)max); + clampMax((double) max); } /** - * Clamps the maximum value of this tuple to the max parameter. - * @param max the highest value in the tuple after clamping + * Clamps the maximum value of this tuple to the max parameter. + * + * @param max the highest value in the tuple after clamping */ - public final void clampMax(double max) { - if( x > max ) x=max; - if( y > max ) y=max; - if( z > max ) z=max; - } + public final void clampMax(double max) { + if (x > max) x = max; + if (y > max) y = max; + if (z > max) z = max; + } - /** - * Sets each component of this tuple to its absolute value. - */ - public final void absolute() - { - x = Math.abs(x); - y = Math.abs(y); - z = Math.abs(z); - } + /** + * Sets each component of this tuple to its absolute value. + */ + public final void absolute() { + x = Math.abs(x); + y = Math.abs(y); + z = Math.abs(z); + } /** * @deprecated Use interpolate(Tuple3d,Tuple3d,double) instead */ public final void interpolate(Tuple3d t1, Tuple3d t2, float alpha) { - interpolate(t1, t2, (double)alpha); + interpolate(t1, t2, (double) alpha); } /** - * Linearly interpolates between tuples t1 and t2 and places the - * result into this tuple: this = (1-alpha)*t1 + alpha*t2. - * @param t1 the first tuple - * @param t2 the second tuple - * @param alpha the alpha interpolation parameter - */ + * Linearly interpolates between tuples t1 and t2 and places the + * result into this tuple: this = (1-alpha)*t1 + alpha*t2. + * + * @param t1 the first tuple + * @param t2 the second tuple + * @param alpha the alpha interpolation parameter + */ public final void interpolate(Tuple3d t1, Tuple3d t2, double alpha) { - this.x = (1-alpha)*t1.x + alpha*t2.x; - this.y = (1-alpha)*t1.y + alpha*t2.y; - this.z = (1-alpha)*t1.z + alpha*t2.z; + this.x = (1 - alpha) * t1.x + alpha * t2.x; + this.y = (1 - alpha) * t1.y + alpha * t2.y; + this.z = (1 - alpha) * t1.z + alpha * t2.z; } - - + + /** * @deprecated Use interpolate(Tuple3d,double) instead */ public final void interpolate(Tuple3d t1, float alpha) { - interpolate(t1, (double)alpha); + interpolate(t1, (double) alpha); } - /** - * Linearly interpolates between this tuple and tuple t1 and - * places the result into this tuple: this = (1-alpha)*this + alpha*t1. - * @param t1 the first tuple - * @param alpha the alpha interpolation parameter - */ + /** + * Linearly interpolates between this tuple and tuple t1 and + * places the result into this tuple: this = (1-alpha)*this + alpha*t1. + * + * @param t1 the first tuple + * @param alpha the alpha interpolation parameter + */ public final void interpolate(Tuple3d t1, double alpha) { - this.x = (1-alpha)*this.x + alpha*t1.x; - this.y = (1-alpha)*this.y + alpha*t1.y; - this.z = (1-alpha)*this.z + alpha*t1.z; - } - + this.x = (1 - alpha) * this.x + alpha * t1.x; + this.y = (1 - alpha) * this.y + alpha * t1.y; + this.z = (1 - alpha) * this.z + alpha * t1.z; + } + /** * Creates a new object of the same class as this object. * * @return a clone of this instance. - * @exception OutOfMemoryError if there is not enough memory. + * @throws OutOfMemoryError if there is not enough memory. * @see java.lang.Cloneable * @since vecmath 1.3 */ public Object clone() { - // Since there are no arrays we can just use Object.clone() - try { - return super.clone(); - } catch (CloneNotSupportedException e) { - // this shouldn't happen, since we are Cloneable - throw new InternalError(); - } + // Since there are no arrays we can just use Object.clone() + try { + return super.clone(); + } catch (CloneNotSupportedException e) { + // this shouldn't happen, since we are Cloneable + throw new InternalError(); + } } /** - * Get the x coordinate. - * - * @return the x coordinate. - * - * @since vecmath 1.5 - */ - public final double getX() { - return x; - } + * Get the x coordinate. + * + * @return the x coordinate. + * @since vecmath 1.5 + */ + public final double getX() { + return x; + } - /** - * Set the x coordinate. - * - * @param x value to x coordinate. - * - * @since vecmath 1.5 - */ - public final void setX(double x) { - this.x = x; - } + /** + * Set the x coordinate. + * + * @param x value to x coordinate. + * @since vecmath 1.5 + */ + public final void setX(double x) { + this.x = x; + } - /** - * Get the y coordinate. - * - * @return the y coordinate. - * - * @since vecmath 1.5 - */ - public final double getY() { - return y; - } + /** + * Get the y coordinate. + * + * @return the y coordinate. + * @since vecmath 1.5 + */ + public final double getY() { + return y; + } - /** - * Set the y coordinate. - * - * @param y value to y coordinate. - * - * @since vecmath 1.5 - */ - public final void setY(double y) { - this.y = y; - } + /** + * Set the y coordinate. + * + * @param y value to y coordinate. + * @since vecmath 1.5 + */ + public final void setY(double y) { + this.y = y; + } - /** - * Get the z coordinate. - * - * @return the z coordinate. - * - * @since vecmath 1.5 - */ - public final double getZ() { - return z; - } + /** + * Get the z coordinate. + * + * @return the z coordinate. + * @since vecmath 1.5 + */ + public final double getZ() { + return z; + } - /** - * Set the z coordinate. - * - * @param z value to z coordinate. - * - * @since vecmath 1.5 - */ - public final void setZ(double z) { - this.z = z; - } + /** + * Set the z coordinate. + * + * @param z value to z coordinate. + * @since vecmath 1.5 + */ + public final void setZ(double z) { + this.z = z; + } } diff --git a/src/main/java/com/volmit/iris/util/Tuple3f.java b/src/main/java/com/volmit/iris/util/Tuple3f.java index 1b34c2a69..8eb603c48 100644 --- a/src/main/java/com/volmit/iris/util/Tuple3f.java +++ b/src/main/java/com/volmit/iris/util/Tuple3f.java @@ -31,198 +31,195 @@ package com.volmit.iris.util; -import java.lang.Math; - /** - * A generic 3-element tuple that is represented by single precision-floating + * A generic 3-element tuple that is represented by single precision-floating * point x,y,z coordinates. - * */ public abstract class Tuple3f implements java.io.Serializable, Cloneable { - static final long serialVersionUID=5019834619484343712L; + static final long serialVersionUID = 5019834619484343712L; /** * The x coordinate. */ - public float x; + public float x; /** * The y coordinate. */ - public float y; + public float y; /** * The z coordinate. */ - public float z; + public float z; /** * Constructs and initializes a Tuple3f from the specified xyz coordinates. + * * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate */ - public Tuple3f(float x, float y, float z) - { - this.x = x; - this.y = y; - this.z = z; + public Tuple3f(float x, float y, float z) { + this.x = x; + this.y = y; + this.z = z; } /** * Constructs and initializes a Tuple3f from the array of length 3. + * * @param t the array of length 3 containing xyz in order */ - public Tuple3f(float[] t) - { - this.x = t[0]; - this.y = t[1]; - this.z = t[2]; + public Tuple3f(float[] t) { + this.x = t[0]; + this.y = t[1]; + this.z = t[2]; } /** * Constructs and initializes a Tuple3f from the specified Tuple3f. + * * @param t1 the Tuple3f containing the initialization x y z data */ - public Tuple3f(Tuple3f t1) - { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; + public Tuple3f(Tuple3f t1) { + this.x = t1.x; + this.y = t1.y; + this.z = t1.z; } /** * Constructs and initializes a Tuple3f from the specified Tuple3d. + * * @param t1 the Tuple3d containing the initialization x y z data */ - public Tuple3f(Tuple3d t1) - { - this.x = (float) t1.x; - this.y = (float) t1.y; - this.z = (float) t1.z; + public Tuple3f(Tuple3d t1) { + this.x = (float) t1.x; + this.y = (float) t1.y; + this.z = (float) t1.z; } /** * Constructs and initializes a Tuple3f to (0,0,0). */ - public Tuple3f() - { - this.x = 0.0f; - this.y = 0.0f; - this.z = 0.0f; + public Tuple3f() { + this.x = 0.0f; + this.y = 0.0f; + this.z = 0.0f; } - /** + /** * Returns a string that contains the values of this Tuple3f. * The form is (x,y,z). + * * @return the String representation - */ + */ public String toString() { - return "(" + this.x + ", " + this.y + ", " + this.z + ")"; + return "(" + this.x + ", " + this.y + ", " + this.z + ")"; } /** * Sets the value of this tuple to the specified xyz coordinates. + * * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate */ - public final void set(float x, float y, float z) - { - this.x = x; - this.y = y; - this.z = z; + public final void set(float x, float y, float z) { + this.x = x; + this.y = y; + this.z = z; } /** * Sets the value of this tuple to the xyz coordinates specified in * the array of length 3. + * * @param t the array of length 3 containing xyz in order */ - public final void set(float[] t) - { - this.x = t[0]; - this.y = t[1]; - this.z = t[2]; + public final void set(float[] t) { + this.x = t[0]; + this.y = t[1]; + this.z = t[2]; } /** * Sets the value of this tuple to the value of tuple t1. + * * @param t1 the tuple to be copied */ - public final void set(Tuple3f t1) - { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; + public final void set(Tuple3f t1) { + this.x = t1.x; + this.y = t1.y; + this.z = t1.z; } /** * Sets the value of this tuple to the value of tuple t1. + * * @param t1 the tuple to be copied */ - public final void set(Tuple3d t1) - { - this.x = (float) t1.x; - this.y = (float) t1.y; - this.z = (float) t1.z; + public final void set(Tuple3d t1) { + this.x = (float) t1.x; + this.y = (float) t1.y; + this.z = (float) t1.z; } - /** + /** * Gets the value of this tuple and copies the values into t. - * @param t the array of length 3 into which the values are copied + * + * @param t the array of length 3 into which the values are copied */ - public final void get(float[] t) - { - t[0] = this.x; - t[1] = this.y; - t[2] = this.z; + public final void get(float[] t) { + t[0] = this.x; + t[1] = this.y; + t[2] = this.z; } - /** + /** * Gets the value of this tuple and copies the values into t. - * @param t the Tuple3f object into which the values of this object are copied + * + * @param t the Tuple3f object into which the values of this object are copied */ - public final void get(Tuple3f t) - { - t.x = this.x; - t.y = this.y; - t.z = this.z; + public final void get(Tuple3f t) { + t.x = this.x; + t.y = this.y; + t.z = this.z; } /** * Sets the value of this tuple to the vector sum of tuples t1 and t2. + * * @param t1 the first tuple * @param t2 the second tuple */ - public final void add(Tuple3f t1, Tuple3f t2) - { - this.x = t1.x + t2.x; - this.y = t1.y + t2.y; - this.z = t1.z + t2.z; + public final void add(Tuple3f t1, Tuple3f t2) { + this.x = t1.x + t2.x; + this.y = t1.y + t2.y; + this.z = t1.z + t2.z; } - /** + /** * Sets the value of this tuple to the vector sum of itself and tuple t1. + * * @param t1 the other tuple - */ - public final void add(Tuple3f t1) - { + */ + public final void add(Tuple3f t1) { this.x += t1.x; this.y += t1.y; this.z += t1.z; @@ -232,24 +229,24 @@ public abstract class Tuple3f implements java.io.Serializable, Cloneable { /** * Sets the value of this tuple to the vector difference * of tuples t1 and t2 (this = t1 - t2). + * * @param t1 the first tuple * @param t2 the second tuple */ - public final void sub(Tuple3f t1, Tuple3f t2) - { - this.x = t1.x - t2.x; - this.y = t1.y - t2.y; - this.z = t1.z - t2.z; + public final void sub(Tuple3f t1, Tuple3f t2) { + this.x = t1.x - t2.x; + this.y = t1.y - t2.y; + this.z = t1.z - t2.z; } - /** + /** * Sets the value of this tuple to the vector difference of * itself and tuple t1 (this = this - t1) . + * * @param t1 the other tuple - */ - public final void sub(Tuple3f t1) - { + */ + public final void sub(Tuple3f t1) { this.x -= t1.x; this.y -= t1.y; this.z -= t1.z; @@ -258,142 +255,142 @@ public abstract class Tuple3f implements java.io.Serializable, Cloneable { /** * Sets the value of this tuple to the negation of tuple t1. + * * @param t1 the source tuple */ - public final void negate(Tuple3f t1) - { - this.x = -t1.x; - this.y = -t1.y; - this.z = -t1.z; + public final void negate(Tuple3f t1) { + this.x = -t1.x; + this.y = -t1.y; + this.z = -t1.z; } /** * Negates the value of this tuple in place. */ - public final void negate() - { - this.x = -this.x; - this.y = -this.y; - this.z = -this.z; + public final void negate() { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; } /** * Sets the value of this vector to the scalar multiplication * of tuple t1. - * @param s the scalar value + * + * @param s the scalar value * @param t1 the source tuple */ - public final void scale(float s, Tuple3f t1) - { - this.x = s*t1.x; - this.y = s*t1.y; - this.z = s*t1.z; + public final void scale(float s, Tuple3f t1) { + this.x = s * t1.x; + this.y = s * t1.y; + this.z = s * t1.z; } /** * Sets the value of this tuple to the scalar multiplication * of the scale factor with this. + * * @param s the scalar value */ - public final void scale(float s) - { - this.x *= s; - this.y *= s; - this.z *= s; + public final void scale(float s) { + this.x *= s; + this.y *= s; + this.z *= s; } /** * Sets the value of this tuple to the scalar multiplication * of tuple t1 and then adds tuple t2 (this = s*t1 + t2). - * @param s the scalar value + * + * @param s the scalar value * @param t1 the tuple to be scaled and added * @param t2 the tuple to be added without a scale */ - public final void scaleAdd(float s, Tuple3f t1, Tuple3f t2) - { - this.x = s*t1.x + t2.x; - this.y = s*t1.y + t2.y; - this.z = s*t1.z + t2.z; + public final void scaleAdd(float s, Tuple3f t1, Tuple3f t2) { + this.x = s * t1.x + t2.x; + this.y = s * t1.y + t2.y; + this.z = s * t1.z + t2.z; } - /** * Sets the value of this tuple to the scalar multiplication * of itself and then adds tuple t1 (this = s*this + t1). - * @param s the scalar value + * + * @param s the scalar value * @param t1 the tuple to be added */ - public final void scaleAdd(float s, Tuple3f t1) - { - this.x = s*this.x + t1.x; - this.y = s*this.y + t1.y; - this.z = s*this.z + t1.z; + public final void scaleAdd(float s, Tuple3f t1) { + this.x = s * this.x + t1.x; + this.y = s * this.y + t1.y; + this.z = s * this.z + t1.z; } - /** + /** * Returns true if the Object t1 is of type Tuple3f and all of the * data members of t1 are equal to the corresponding data members in * this Tuple3f. - * @param t1 the vector with which the comparison is made - * @return true or false - */ - public boolean equals(Tuple3f t1) - { + * + * @param t1 the vector with which the comparison is made + * @return true or false + */ + public boolean equals(Tuple3f t1) { try { - return(this.x == t1.x && this.y == t1.y && this.z == t1.z); + return (this.x == t1.x && this.y == t1.y && this.z == t1.z); + } catch (NullPointerException e2) { + return false; } - catch (NullPointerException e2) {return false;} } - /** + + /** * Returns true if the Object t1 is of type Tuple3f and all of the * data members of t1 are equal to the corresponding data members in * this Tuple3f. - * @param t1 the Object with which the comparison is made - * @return true or false - */ - public boolean equals(Object t1) - { + * + * @param t1 the Object with which the comparison is made + * @return true or false + */ + public boolean equals(Object t1) { try { - Tuple3f t2 = (Tuple3f) t1; - return(this.x == t2.x && this.y == t2.y && this.z == t2.z); + Tuple3f t2 = (Tuple3f) t1; + return (this.x == t2.x && this.y == t2.y && this.z == t2.z); + } catch (NullPointerException e2) { + return false; + } catch (ClassCastException e1) { + return false; } - catch (NullPointerException e2) {return false;} - catch (ClassCastException e1) {return false;} } - /** + /** * Returns true if the L-infinite distance between this tuple - * and tuple t1 is less than or equal to the epsilon parameter, + * and tuple t1 is less than or equal to the epsilon parameter, * otherwise returns false. The L-infinite * distance is equal to MAX[abs(x1-x2), abs(y1-y2), abs(z1-z2)]. - * @param t1 the tuple to be compared to this tuple - * @param epsilon the threshold value - * @return true or false + * + * @param t1 the tuple to be compared to this tuple + * @param epsilon the threshold value + * @return true or false */ - public boolean epsilonEquals(Tuple3f t1, float epsilon) - { - float diff; + public boolean epsilonEquals(Tuple3f t1, float epsilon) { + float diff; - diff = x - t1.x; - if(Float.isNaN(diff)) return false; - if((diff<0?-diff:diff) > epsilon) return false; + diff = x - t1.x; + if (Float.isNaN(diff)) return false; + if ((diff < 0 ? -diff : diff) > epsilon) return false; - diff = y - t1.y; - if(Float.isNaN(diff)) return false; - if((diff<0?-diff:diff) > epsilon) return false; + diff = y - t1.y; + if (Float.isNaN(diff)) return false; + if ((diff < 0 ? -diff : diff) > epsilon) return false; - diff = z - t1.z; - if(Float.isNaN(diff)) return false; - if((diff<0?-diff:diff) > epsilon) return false; - - return true; + diff = z - t1.z; + if (Float.isNaN(diff)) return false; + return !((diff < 0 ? -diff : diff) > epsilon); } @@ -404,310 +401,302 @@ public abstract class Tuple3f implements java.io.Serializable, Cloneable { * (i.e., Tuple3f.equals returns true) will return the same hash * code value. Two objects with different data members may return the * same hash value, although this is not likely. + * * @return the integer hash code value - */ + */ public int hashCode() { - long bits = 1L; - bits = 31L * bits + (long)VecMathUtil.floatToIntBits(x); - bits = 31L * bits + (long)VecMathUtil.floatToIntBits(y); - bits = 31L * bits + (long)VecMathUtil.floatToIntBits(z); - return (int) (bits ^ (bits >> 32)); + long bits = 1L; + bits = 31L * bits + (long) VecMathUtil.floatToIntBits(x); + bits = 31L * bits + (long) VecMathUtil.floatToIntBits(y); + bits = 31L * bits + (long) VecMathUtil.floatToIntBits(z); + return (int) (bits ^ (bits >> 32)); } - - /** - * Clamps the tuple parameter to the range [low, high] and - * places the values into this tuple. - * @param min the lowest value in the tuple after clamping - * @param max the highest value in the tuple after clamping - * @param t the source tuple, which will not be modified - */ - public final void clamp(float min, float max, Tuple3f t) - { - if( t.x > max ) { - x = max; - } else if( t.x < min ){ - x = min; + /** + * Clamps the tuple parameter to the range [low, high] and + * places the values into this tuple. + * + * @param min the lowest value in the tuple after clamping + * @param max the highest value in the tuple after clamping + * @param t the source tuple, which will not be modified + */ + public final void clamp(float min, float max, Tuple3f t) { + if (t.x > max) { + x = max; + } else if (t.x < min) { + x = min; } else { - x = t.x; + x = t.x; } - - if( t.y > max ) { - y = max; - } else if( t.y < min ){ - y = min; + + if (t.y > max) { + y = max; + } else if (t.y < min) { + y = min; } else { - y = t.y; + y = t.y; } - if( t.z > max ) { - z = max; - } else if( t.z < min ){ - z = min; + if (t.z > max) { + z = max; + } else if (t.z < min) { + z = min; } else { - z = t.z; + z = t.z; } - } - - - /** - * Clamps the minimum value of the tuple parameter to the min - * parameter and places the values into this tuple. - * @param min the lowest value in the tuple after clamping - * @param t the source tuple, which will not be modified - */ - public final void clampMin(float min, Tuple3f t) - { - if( t.x < min ) { - x = min; + } + + + /** + * Clamps the minimum value of the tuple parameter to the min + * parameter and places the values into this tuple. + * + * @param min the lowest value in the tuple after clamping + * @param t the source tuple, which will not be modified + */ + public final void clampMin(float min, Tuple3f t) { + if (t.x < min) { + x = min; } else { - x = t.x; + x = t.x; } - - if( t.y < min ) { - y = min; + + if (t.y < min) { + y = min; } else { - y = t.y; + y = t.y; } - - if( t.z < min ) { - z = min; + + if (t.z < min) { + z = min; } else { - z = t.z; + z = t.z; } - } - - - /** - * Clamps the maximum value of the tuple parameter to the max - * parameter and places the values into this tuple. - * @param max the highest value in the tuple after clamping - * @param t the source tuple, which will not be modified - */ - public final void clampMax(float max, Tuple3f t) - { - if( t.x > max ) { - x = max; + } + + + /** + * Clamps the maximum value of the tuple parameter to the max + * parameter and places the values into this tuple. + * + * @param max the highest value in the tuple after clamping + * @param t the source tuple, which will not be modified + */ + public final void clampMax(float max, Tuple3f t) { + if (t.x > max) { + x = max; } else { - x = t.x; + x = t.x; } - - if( t.y > max ) { - y = max; + + if (t.y > max) { + y = max; } else { - y = t.y; + y = t.y; } - - if( t.z > max ) { - z = max; + + if (t.z > max) { + z = max; } else { - z = t.z; + z = t.z; } - } - - - /** - * Sets each component of the tuple parameter to its absolute - * value and places the modified values into this tuple. - * @param t the source tuple, which will not be modified - */ - public final void absolute(Tuple3f t) - { - x = Math.abs(t.x); - y = Math.abs(t.y); - z = Math.abs(t.z); - } + } + /** + * Sets each component of the tuple parameter to its absolute + * value and places the modified values into this tuple. + * + * @param t the source tuple, which will not be modified + */ + public final void absolute(Tuple3f t) { + x = Math.abs(t.x); + y = Math.abs(t.y); + z = Math.abs(t.z); + } - /** - * Clamps this tuple to the range [low, high]. - * @param min the lowest value in this tuple after clamping - * @param max the highest value in this tuple after clamping - */ - public final void clamp(float min, float max) - { - if( x > max ) { - x = max; - } else if( x < min ){ - x = min; - } - - if( y > max ) { - y = max; - } else if( y < min ){ - y = min; - } - - if( z > max ) { - z = max; - } else if( z < min ){ - z = min; + + /** + * Clamps this tuple to the range [low, high]. + * + * @param min the lowest value in this tuple after clamping + * @param max the highest value in this tuple after clamping + */ + public final void clamp(float min, float max) { + if (x > max) { + x = max; + } else if (x < min) { + x = min; } - } + if (y > max) { + y = max; + } else if (y < min) { + y = min; + } - - /** - * Clamps the minimum value of this tuple to the min parameter. - * @param min the lowest value in this tuple after clamping - */ - public final void clampMin(float min) - { - if( x < min ) x=min; - if( y < min ) y=min; - if( z < min ) z=min; + if (z > max) { + z = max; + } else if (z < min) { + z = min; + } - } - - - /** - * Clamps the maximum value of this tuple to the max parameter. - * @param max the highest value in the tuple after clamping - */ - public final void clampMax(float max) - { - if( x > max ) x=max; - if( y > max ) y=max; - if( z > max ) z=max; - - } + } - /** - * Sets each component of this tuple to its absolute value. - */ - public final void absolute() - { - x = Math.abs(x); - y = Math.abs(y); - z = Math.abs(z); + /** + * Clamps the minimum value of this tuple to the min parameter. + * + * @param min the lowest value in this tuple after clamping + */ + public final void clampMin(float min) { + if (x < min) x = min; + if (y < min) y = min; + if (z < min) z = min; - } + } - /** - * Linearly interpolates between tuples t1 and t2 and places the - * result into this tuple: this = (1-alpha)*t1 + alpha*t2. - * @param t1 the first tuple - * @param t2 the second tuple - * @param alpha the alpha interpolation parameter - */ - public final void interpolate(Tuple3f t1, Tuple3f t2, float alpha) - { - this.x = (1-alpha)*t1.x + alpha*t2.x; - this.y = (1-alpha)*t1.y + alpha*t2.y; - this.z = (1-alpha)*t1.z + alpha*t2.z; - + /** + * Clamps the maximum value of this tuple to the max parameter. + * + * @param max the highest value in the tuple after clamping + */ + public final void clampMax(float max) { + if (x > max) x = max; + if (y > max) y = max; + if (z > max) z = max; - } - - - /** - * Linearly interpolates between this tuple and tuple t1 and - * places the result into this tuple: this = (1-alpha)*this + alpha*t1. - * @param t1 the first tuple - * @param alpha the alpha interpolation parameter - */ - public final void interpolate(Tuple3f t1, float alpha) - { - this.x = (1-alpha)*this.x + alpha*t1.x; - this.y = (1-alpha)*this.y + alpha*t1.y; - this.z = (1-alpha)*this.z + alpha*t1.z; + } - } - + /** + * Sets each component of this tuple to its absolute value. + */ + public final void absolute() { + x = Math.abs(x); + y = Math.abs(y); + z = Math.abs(z); + + } + + + /** + * Linearly interpolates between tuples t1 and t2 and places the + * result into this tuple: this = (1-alpha)*t1 + alpha*t2. + * + * @param t1 the first tuple + * @param t2 the second tuple + * @param alpha the alpha interpolation parameter + */ + public final void interpolate(Tuple3f t1, Tuple3f t2, float alpha) { + this.x = (1 - alpha) * t1.x + alpha * t2.x; + this.y = (1 - alpha) * t1.y + alpha * t2.y; + this.z = (1 - alpha) * t1.z + alpha * t2.z; + + + } + + + /** + * Linearly interpolates between this tuple and tuple t1 and + * places the result into this tuple: this = (1-alpha)*this + alpha*t1. + * + * @param t1 the first tuple + * @param alpha the alpha interpolation parameter + */ + public final void interpolate(Tuple3f t1, float alpha) { + this.x = (1 - alpha) * this.x + alpha * t1.x; + this.y = (1 - alpha) * this.y + alpha * t1.y; + this.z = (1 - alpha) * this.z + alpha * t1.z; + + + } + /** * Creates a new object of the same class as this object. * * @return a clone of this instance. - * @exception OutOfMemoryError if there is not enough memory. + * @throws OutOfMemoryError if there is not enough memory. * @see java.lang.Cloneable * @since vecmath 1.3 */ public Object clone() { - // Since there are no arrays we can just use Object.clone() - try { - return super.clone(); - } catch (CloneNotSupportedException e) { - // this shouldn't happen, since we are Cloneable - throw new InternalError(); - } + // Since there are no arrays we can just use Object.clone() + try { + return super.clone(); + } catch (CloneNotSupportedException e) { + // this shouldn't happen, since we are Cloneable + throw new InternalError(); + } } /** - * Get the x coordinate. - * - * @return the x coordinate. - * - * @since vecmath 1.5 - */ - public final float getX() { - return x; - } + * Get the x coordinate. + * + * @return the x coordinate. + * @since vecmath 1.5 + */ + public final float getX() { + return x; + } - /** - * Set the x coordinate. - * - * @param x value to x coordinate. - * - * @since vecmath 1.5 - */ - public final void setX(float x) { - this.x = x; - } + /** + * Set the x coordinate. + * + * @param x value to x coordinate. + * @since vecmath 1.5 + */ + public final void setX(float x) { + this.x = x; + } - /** - * Get the y coordinate. - * - * @return the y coordinate. - * - * @since vecmath 1.5 - */ - public final float getY() { - return y; - } + /** + * Get the y coordinate. + * + * @return the y coordinate. + * @since vecmath 1.5 + */ + public final float getY() { + return y; + } - /** - * Set the y coordinate. - * - * @param y value to y coordinate. - * - * @since vecmath 1.5 - */ - public final void setY(float y) { - this.y = y; - } + /** + * Set the y coordinate. + * + * @param y value to y coordinate. + * @since vecmath 1.5 + */ + public final void setY(float y) { + this.y = y; + } - /** - * Get the z coordinate. - * - * @return the z coordinate - * - * @since vecmath 1.5 - */ - public final float getZ() { - return z; - } + /** + * Get the z coordinate. + * + * @return the z coordinate + * @since vecmath 1.5 + */ + public final float getZ() { + return z; + } - /** - * Set the Z coordinate. - * - * @param z value to z coordinate. - * - * @since vecmath 1.5 - */ - public final void setZ(float z) { - this.z = z; - } + /** + * Set the Z coordinate. + * + * @param z value to z coordinate. + * @since vecmath 1.5 + */ + public final void setZ(float z) { + this.z = z; + } } diff --git a/src/main/java/com/volmit/iris/util/Tuple4d.java b/src/main/java/com/volmit/iris/util/Tuple4d.java index ae622f133..5bb5c85da 100644 --- a/src/main/java/com/volmit/iris/util/Tuple4d.java +++ b/src/main/java/com/volmit/iris/util/Tuple4d.java @@ -31,12 +31,9 @@ package com.volmit.iris.util; -import java.lang.Math; - /** - * A 4 element tuple represented by double precision floating point + * A 4 element tuple represented by double precision floating point * x,y,z,w coordinates. - * */ public abstract class Tuple4d implements java.io.Serializable, Cloneable { @@ -45,154 +42,153 @@ public abstract class Tuple4d implements java.io.Serializable, Cloneable { /** * The x coordinate. */ - public double x; + public double x; /** * The y coordinate. */ - public double y; + public double y; /** * The z coordinate. */ - public double z; + public double z; /** * The w coordinate. */ - public double w; + public double w; /** * Constructs and initializes a Tuple4d from the specified xyzw coordinates. + * * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate * @param w the w coordinate */ - public Tuple4d(double x, double y, double z, double w) - { - this.x = x; - this.y = y; - this.z = z; - this.w = w; + public Tuple4d(double x, double y, double z, double w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; } /** * Constructs and initializes a Tuple4d from the coordinates contained * in the array. + * * @param t the array of length 4 containing xyzw in order */ - public Tuple4d(double[] t) - { - this.x = t[0]; - this.y = t[1]; - this.z = t[2]; - this.w = t[3]; + public Tuple4d(double[] t) { + this.x = t[0]; + this.y = t[1]; + this.z = t[2]; + this.w = t[3]; } /** * Constructs and initializes a Tuple4d from the specified Tuple4d. + * * @param t1 the Tuple4d containing the initialization x y z w data */ - public Tuple4d(Tuple4d t1) - { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; - this.w = t1.w; + public Tuple4d(Tuple4d t1) { + this.x = t1.x; + this.y = t1.y; + this.z = t1.z; + this.w = t1.w; } /** * Constructs and initializes a Tuple4d from the specified Tuple4f. + * * @param t1 the Tuple4f containing the initialization x y z w data */ - public Tuple4d(Tuple4f t1) - { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; - this.w = t1.w; + public Tuple4d(Tuple4f t1) { + this.x = t1.x; + this.y = t1.y; + this.z = t1.z; + this.w = t1.w; } /** * Constructs and initializes a Tuple4d to (0,0,0,0). */ - public Tuple4d() - { - this.x = 0.0; - this.y = 0.0; - this.z = 0.0; - this.w = 0.0; + public Tuple4d() { + this.x = 0.0; + this.y = 0.0; + this.z = 0.0; + this.w = 0.0; } /** * Sets the value of this tuple to the specified xyzw coordinates. + * * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate * @param w the w coordinate */ - public final void set(double x, double y, double z, double w) - { - this.x = x; - this.y = y; - this.z = z; - this.w = w; + public final void set(double x, double y, double z, double w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; } /** * Sets the value of this tuple to the specified xyzw coordinates. + * * @param t the array of length 4 containing xyzw in order */ - public final void set(double[] t) - { - this.x = t[0]; - this.y = t[1]; - this.z = t[2]; - this.w = t[3]; + public final void set(double[] t) { + this.x = t[0]; + this.y = t[1]; + this.z = t[2]; + this.w = t[3]; } /** * Sets the value of this tuple to the value of tuple t1. + * * @param t1 the tuple to be copied */ - public final void set(Tuple4d t1) - { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; - this.w = t1.w; + public final void set(Tuple4d t1) { + this.x = t1.x; + this.y = t1.y; + this.z = t1.z; + this.w = t1.w; } /** * Sets the value of this tuple to the value of tuple t1. + * * @param t1 the tuple to be copied */ - public final void set(Tuple4f t1) - { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; - this.w = t1.w; + public final void set(Tuple4f t1) { + this.x = t1.x; + this.y = t1.y; + this.z = t1.z; + this.w = t1.w; } /** * Gets the value of this tuple and places it into the array t of * length four in x,y,z,w order. - * @param t the array of length four + * + * @param t the array of length four */ - public final void get(double[] t) - { + public final void get(double[] t) { t[0] = this.x; t[1] = this.y; t[2] = this.z; @@ -204,10 +200,10 @@ public abstract class Tuple4d implements java.io.Serializable, Cloneable { * Gets the value of this tuple and places it into the Tuple4d * argument of * length four in x,y,z,w order. - * @param t the Tuple into which the values will be copied + * + * @param t the Tuple into which the values will be copied */ - public final void get(Tuple4d t) - { + public final void get(Tuple4d t) { t.x = this.x; t.y = this.y; t.z = this.z; @@ -217,24 +213,24 @@ public abstract class Tuple4d implements java.io.Serializable, Cloneable { /** * Sets the value of this tuple to the tuple sum of tuples t1 and t2. + * * @param t1 the first tuple * @param t2 the second tuple */ - public final void add(Tuple4d t1, Tuple4d t2) - { - this.x = t1.x + t2.x; - this.y = t1.y + t2.y; - this.z = t1.z + t2.z; - this.w = t1.w + t2.w; + public final void add(Tuple4d t1, Tuple4d t2) { + this.x = t1.x + t2.x; + this.y = t1.y + t2.y; + this.z = t1.z + t2.z; + this.w = t1.w + t2.w; } - /** + /** * Sets the value of this tuple to the sum of itself and tuple t1. + * * @param t1 the other tuple */ - public final void add(Tuple4d t1) - { + public final void add(Tuple4d t1) { this.x += t1.x; this.y += t1.y; this.z += t1.z; @@ -245,25 +241,25 @@ public abstract class Tuple4d implements java.io.Serializable, Cloneable { /** * Sets the value of this tuple to the difference * of tuples t1 and t2 (this = t1 - t2). + * * @param t1 the first tuple * @param t2 the second tuple */ - public final void sub(Tuple4d t1, Tuple4d t2) - { - this.x = t1.x - t2.x; - this.y = t1.y - t2.y; - this.z = t1.z - t2.z; - this.w = t1.w - t2.w; + public final void sub(Tuple4d t1, Tuple4d t2) { + this.x = t1.x - t2.x; + this.y = t1.y - t2.y; + this.z = t1.z - t2.z; + this.w = t1.w - t2.w; } - /** + /** * Sets the value of this tuple to the difference of itself * and tuple t1 (this = this - t1). + * * @param t1 the other tuple */ - public final void sub(Tuple4d t1) - { + public final void sub(Tuple4d t1) { this.x -= t1.x; this.y -= t1.y; this.z -= t1.z; @@ -273,174 +269,174 @@ public abstract class Tuple4d implements java.io.Serializable, Cloneable { /** * Sets the value of this tuple to the negation of tuple t1. + * * @param t1 the source tuple */ - public final void negate(Tuple4d t1) - { - this.x = -t1.x; - this.y = -t1.y; - this.z = -t1.z; - this.w = -t1.w; + public final void negate(Tuple4d t1) { + this.x = -t1.x; + this.y = -t1.y; + this.z = -t1.z; + this.w = -t1.w; } /** * Negates the value of this tuple in place. */ - public final void negate() - { - this.x = -this.x; - this.y = -this.y; - this.z = -this.z; - this.w = -this.w; + public final void negate() { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + this.w = -this.w; } /** * Sets the value of this tuple to the scalar multiplication * of the scale factor with the tuple t1. - * @param s the scalar value + * + * @param s the scalar value * @param t1 the source tuple */ - public final void scale(double s, Tuple4d t1) - { - this.x = s*t1.x; - this.y = s*t1.y; - this.z = s*t1.z; - this.w = s*t1.w; + public final void scale(double s, Tuple4d t1) { + this.x = s * t1.x; + this.y = s * t1.y; + this.z = s * t1.z; + this.w = s * t1.w; } /** * Sets the value of this tuple to the scalar multiplication * of the scale factor with this. + * * @param s the scalar value */ - public final void scale(double s) - { - this.x *= s; - this.y *= s; - this.z *= s; - this.w *= s; + public final void scale(double s) { + this.x *= s; + this.y *= s; + this.z *= s; + this.w *= s; } /** * Sets the value of this tuple to the scalar multiplication by s * of tuple t1 plus tuple t2 (this = s*t1 + t2). - * @param s the scalar value + * + * @param s the scalar value * @param t1 the tuple to be multipled * @param t2 the tuple to be added */ - public final void scaleAdd(double s, Tuple4d t1, Tuple4d t2) - { - this.x = s*t1.x + t2.x; - this.y = s*t1.y + t2.y; - this.z = s*t1.z + t2.z; - this.w = s*t1.w + t2.w; + public final void scaleAdd(double s, Tuple4d t1, Tuple4d t2) { + this.x = s * t1.x + t2.x; + this.y = s * t1.y + t2.y; + this.z = s * t1.z + t2.z; + this.w = s * t1.w + t2.w; } - /** * @deprecated Use scaleAdd(double,Tuple4d) instead - */ + */ public final void scaleAdd(float s, Tuple4d t1) { - scaleAdd((double)s, t1); + scaleAdd((double) s, t1); } - /** + /** * Sets the value of this tuple to the scalar multiplication * of itself and then adds tuple t1 (this = s*this + t1). - * @param s the scalar value - * @param t1 the tuple to be added - */ + * + * @param s the scalar value + * @param t1 the tuple to be added + */ public final void scaleAdd(double s, Tuple4d t1) { - this.x = s*this.x + t1.x; - this.y = s*this.y + t1.y; - this.z = s*this.z + t1.z; - this.w = s*this.w + t1.w; - } - + this.x = s * this.x + t1.x; + this.y = s * this.y + t1.y; + this.z = s * this.z + t1.z; + this.w = s * this.w + t1.w; + } - /** + /** * Returns a string that contains the values of this Tuple4d. * The form is (x,y,z,w). + * * @return the String representation - */ + */ public String toString() { return "(" + this.x + ", " + this.y + ", " + this.z + ", " + this.w + ")"; } - /** + /** * Returns true if all of the data members of Tuple4d t1 are * equal to the corresponding data members in this Tuple4d. - * @param t1 the tuple with which the comparison is made - * @return true or false - */ - public boolean equals(Tuple4d t1) - { + * + * @param t1 the tuple with which the comparison is made + * @return true or false + */ + public boolean equals(Tuple4d t1) { try { - return(this.x == t1.x && this.y == t1.y && this.z == t1.z - && this.w == t1.w); + return (this.x == t1.x && this.y == t1.y && this.z == t1.z + && this.w == t1.w); + } catch (NullPointerException e2) { + return false; } - catch (NullPointerException e2) {return false;} } - /** + /** * Returns true if the Object t1 is of type Tuple4d and all of the * data members of t1 are equal to the corresponding data members in * this Tuple4d. - * @param t1 the object with which the comparison is made - * @return true or false + * + * @param t1 the object with which the comparison is made + * @return true or false */ - public boolean equals(Object t1) - { + public boolean equals(Object t1) { try { - Tuple4d t2 = (Tuple4d) t1; - return(this.x == t2.x && this.y == t2.y && - this.z == t2.z && this.w == t2.w); + Tuple4d t2 = (Tuple4d) t1; + return (this.x == t2.x && this.y == t2.y && + this.z == t2.z && this.w == t2.w); + } catch (NullPointerException e2) { + return false; + } catch (ClassCastException e1) { + return false; } - catch (NullPointerException e2) {return false;} - catch (ClassCastException e1) {return false;} } - /** + /** * Returns true if the L-infinite distance between this tuple - * and tuple t1 is less than or equal to the epsilon parameter, + * and tuple t1 is less than or equal to the epsilon parameter, * otherwise returns false. The L-infinite - * distance is equal to + * distance is equal to * MAX[abs(x1-x2), abs(y1-y2), abs(z1-z2), abs(w1-w2)]. - * @param t1 the tuple to be compared to this tuple - * @param epsilon the threshold value - * @return true or false + * + * @param t1 the tuple to be compared to this tuple + * @param epsilon the threshold value + * @return true or false */ - public boolean epsilonEquals(Tuple4d t1, double epsilon) - { - double diff; + public boolean epsilonEquals(Tuple4d t1, double epsilon) { + double diff; - diff = x - t1.x; - if(Double.isNaN(diff)) return false; - if((diff<0?-diff:diff) > epsilon) return false; + diff = x - t1.x; + if (Double.isNaN(diff)) return false; + if ((diff < 0 ? -diff : diff) > epsilon) return false; - diff = y - t1.y; - if(Double.isNaN(diff)) return false; - if((diff<0?-diff:diff) > epsilon) return false; + diff = y - t1.y; + if (Double.isNaN(diff)) return false; + if ((diff < 0 ? -diff : diff) > epsilon) return false; - diff = z - t1.z; - if(Double.isNaN(diff)) return false; - if((diff<0?-diff:diff) > epsilon) return false; + diff = z - t1.z; + if (Double.isNaN(diff)) return false; + if ((diff < 0 ? -diff : diff) > epsilon) return false; - diff = w - t1.w; - if(Double.isNaN(diff)) return false; - if((diff<0?-diff:diff) > epsilon) return false; - - return true; + diff = w - t1.w; + if (Double.isNaN(diff)) return false; + return !((diff < 0 ? -diff : diff) > epsilon); } @@ -451,15 +447,16 @@ public abstract class Tuple4d implements java.io.Serializable, Cloneable { * (i.e., Tuple4d.equals returns true) will return the same hash * code value. Two objects with different data members may return the * same hash value, although this is not likely. + * * @return the integer hash code value - */ + */ public int hashCode() { - long bits = 1L; - bits = 31L * bits + VecMathUtil.doubleToLongBits(x); - bits = 31L * bits + VecMathUtil.doubleToLongBits(y); - bits = 31L * bits + VecMathUtil.doubleToLongBits(z); - bits = 31L * bits + VecMathUtil.doubleToLongBits(w); - return (int) (bits ^ (bits >> 32)); + long bits = 1L; + bits = 31L * bits + VecMathUtil.doubleToLongBits(x); + bits = 31L * bits + VecMathUtil.doubleToLongBits(y); + bits = 31L * bits + VecMathUtil.doubleToLongBits(z); + bits = 31L * bits + VecMathUtil.doubleToLongBits(w); + return (int) (bits ^ (bits >> 32)); } @@ -467,401 +464,399 @@ public abstract class Tuple4d implements java.io.Serializable, Cloneable { * @deprecated Use clamp(double,double,Tuple4d) instead */ public final void clamp(float min, float max, Tuple4d t) { - clamp((double)min, (double)max, t); + clamp(min, (double) max, t); } /** - * Clamps the tuple parameter to the range [low, high] and - * places the values into this tuple. - * @param min the lowest value in the tuple after clamping - * @param max the highest value in the tuple after clamping - * @param t the source tuple, which will not be modified + * Clamps the tuple parameter to the range [low, high] and + * places the values into this tuple. + * + * @param min the lowest value in the tuple after clamping + * @param max the highest value in the tuple after clamping + * @param t the source tuple, which will not be modified */ public final void clamp(double min, double max, Tuple4d t) { - if( t.x > max ) { - x = max; - } else if( t.x < min ){ - x = min; - } else { - x = t.x; - } - - if( t.y > max ) { - y = max; - } else if( t.y < min ){ - y = min; + if (t.x > max) { + x = max; + } else if (t.x < min) { + x = min; } else { - y = t.y; - } - - if( t.z > max ) { - z = max; - } else if( t.z < min ){ - z = min; - } else { - z = t.z; + x = t.x; } - if( t.w > max ) { - w = max; - } else if( t.w < min ){ - w = min; + if (t.y > max) { + y = max; + } else if (t.y < min) { + y = min; } else { - w = t.w; + y = t.y; } - } + if (t.z > max) { + z = max; + } else if (t.z < min) { + z = min; + } else { + z = t.z; + } + + if (t.w > max) { + w = max; + } else if (t.w < min) { + w = min; + } else { + w = t.w; + } + + } /** * @deprecated Use clampMin(double,Tuple4d) instead */ public final void clampMin(float min, Tuple4d t) { - clampMin((double)min, t); + clampMin((double) min, t); } - /** - * Clamps the minimum value of the tuple parameter to the min - * parameter and places the values into this tuple. - * @param min the lowest value in the tuple after clamping - * @param t the source tuple, which will not be modified - */ - public final void clampMin(double min, Tuple4d t) { - if( t.x < min ) { - x = min; + /** + * Clamps the minimum value of the tuple parameter to the min + * parameter and places the values into this tuple. + * + * @param min the lowest value in the tuple after clamping + * @param t the source tuple, which will not be modified + */ + public final void clampMin(double min, Tuple4d t) { + if (t.x < min) { + x = min; } else { - x = t.x; - } - - if( t.y < min ) { - y = min; - } else { - y = t.y; - } - - if( t.z < min ) { - z = min; - } else { - z = t.z; - } - - if( t.w < min ) { - w = min; - } else { - w = t.w; + x = t.x; } - } + if (t.y < min) { + y = min; + } else { + y = t.y; + } + + if (t.z < min) { + z = min; + } else { + z = t.z; + } + + if (t.w < min) { + w = min; + } else { + w = t.w; + } + + } /** * @deprecated Use clampMax(double,Tuple4d) instead */ public final void clampMax(float max, Tuple4d t) { - clampMax((double)max, t); + clampMax((double) max, t); } - /** - * Clamps the maximum value of the tuple parameter to the max - * parameter and places the values into this tuple. - * @param max the highest value in the tuple after clamping - * @param t the source tuple, which will not be modified - */ - public final void clampMax(double max, Tuple4d t) { - if( t.x > max ) { - x = max; + /** + * Clamps the maximum value of the tuple parameter to the max + * parameter and places the values into this tuple. + * + * @param max the highest value in the tuple after clamping + * @param t the source tuple, which will not be modified + */ + public final void clampMax(double max, Tuple4d t) { + if (t.x > max) { + x = max; } else { - x = t.x; - } - - if( t.y > max ) { - y = max; - } else { - y = t.y; - } - - if( t.z > max ) { - z = max; - } else { - z = t.z; - } - - if( t.w > max ) { - w = max; - } else { - w = t.z; + x = t.x; } - } + if (t.y > max) { + y = max; + } else { + y = t.y; + } + + if (t.z > max) { + z = max; + } else { + z = t.z; + } + + if (t.w > max) { + w = max; + } else { + w = t.z; + } + + } - /** - * Sets each component of the tuple parameter to its absolute - * value and places the modified values into this tuple. - * @param t the source tuple, which will not be modified - */ - public final void absolute(Tuple4d t) - { - x = Math.abs(t.x); - y = Math.abs(t.y); - z = Math.abs(t.z); - w = Math.abs(t.w); - - } + /** + * Sets each component of the tuple parameter to its absolute + * value and places the modified values into this tuple. + * + * @param t the source tuple, which will not be modified + */ + public final void absolute(Tuple4d t) { + x = Math.abs(t.x); + y = Math.abs(t.y); + z = Math.abs(t.z); + w = Math.abs(t.w); + } /** * @deprecated Use clamp(double,double) instead */ public final void clamp(float min, float max) { - clamp((double)min, (double)max); + clamp(min, (double) max); } /** - * Clamps this tuple to the range [low, high]. - * @param min the lowest value in this tuple after clamping - * @param max the highest value in this tuple after clamping + * Clamps this tuple to the range [low, high]. + * + * @param min the lowest value in this tuple after clamping + * @param max the highest value in this tuple after clamping */ public final void clamp(double min, double max) { - if( x > max ) { - x = max; - } else if( x < min ){ - x = min; - } - - if( y > max ) { - y = max; - } else if( y < min ){ - y = min; - } - - if( z > max ) { - z = max; - } else if( z < min ){ - z = min; - } - - if( w > max ) { - w = max; - } else if( w < min ){ - w = min; + if (x > max) { + x = max; + } else if (x < min) { + x = min; } - } + if (y > max) { + y = max; + } else if (y < min) { + y = min; + } + + if (z > max) { + z = max; + } else if (z < min) { + z = min; + } + + if (w > max) { + w = max; + } else if (w < min) { + w = min; + } + + } + - /** * @deprecated Use clampMin(double) instead */ public final void clampMin(float min) { - clampMin((double)min); + clampMin((double) min); } /** - * Clamps the minimum value of this tuple to the min parameter. - * @param min the lowest value in this tuple after clamping + * Clamps the minimum value of this tuple to the min parameter. + * + * @param min the lowest value in this tuple after clamping */ - public final void clampMin(double min) { - if( x < min ) x=min; - if( y < min ) y=min; - if( z < min ) z=min; - if( w < min ) w=min; - } - - + public final void clampMin(double min) { + if (x < min) x = min; + if (y < min) y = min; + if (z < min) z = min; + if (w < min) w = min; + } + + /** * @deprecated Use clampMax(double) instead */ public final void clampMax(float max) { - clampMax((double)max); + clampMax((double) max); } /** - * Clamps the maximum value of this tuple to the max parameter. - * @param max the highest value in the tuple after clamping + * Clamps the maximum value of this tuple to the max parameter. + * + * @param max the highest value in the tuple after clamping */ - public final void clampMax(double max) { - if( x > max ) x=max; - if( y > max ) y=max; - if( z > max ) z=max; - if( w > max ) w=max; + public final void clampMax(double max) { + if (x > max) x = max; + if (y > max) y = max; + if (z > max) z = max; + if (w > max) w = max; - } + } - /** - * Sets each component of this tuple to its absolute value. - */ - public final void absolute() - { - x = Math.abs(x); - y = Math.abs(y); - z = Math.abs(z); - w = Math.abs(w); + /** + * Sets each component of this tuple to its absolute value. + */ + public final void absolute() { + x = Math.abs(x); + y = Math.abs(y); + z = Math.abs(z); + w = Math.abs(w); - } + } /** * @deprecated Use interpolate(Tuple4d,Tuple4d,double) instead */ public void interpolate(Tuple4d t1, Tuple4d t2, float alpha) { - interpolate(t1, t2, (double)alpha); + interpolate(t1, t2, (double) alpha); } /** - * Linearly interpolates between tuples t1 and t2 and places the - * result into this tuple: this = (1-alpha)*t1 + alpha*t2. - * @param t1 the first tuple - * @param t2 the second tuple - * @param alpha the alpha interpolation parameter - */ + * Linearly interpolates between tuples t1 and t2 and places the + * result into this tuple: this = (1-alpha)*t1 + alpha*t2. + * + * @param t1 the first tuple + * @param t2 the second tuple + * @param alpha the alpha interpolation parameter + */ public void interpolate(Tuple4d t1, Tuple4d t2, double alpha) { - this.x = (1-alpha)*t1.x + alpha*t2.x; - this.y = (1-alpha)*t1.y + alpha*t2.y; - this.z = (1-alpha)*t1.z + alpha*t2.z; - this.w = (1-alpha)*t1.w + alpha*t2.w; - } - - + this.x = (1 - alpha) * t1.x + alpha * t2.x; + this.y = (1 - alpha) * t1.y + alpha * t2.y; + this.z = (1 - alpha) * t1.z + alpha * t2.z; + this.w = (1 - alpha) * t1.w + alpha * t2.w; + } + + /** * @deprecated Use interpolate(Tuple4d,double) instead */ public void interpolate(Tuple4d t1, float alpha) { - interpolate(t1, (double)alpha); + interpolate(t1, (double) alpha); } /** - * Linearly interpolates between this tuple and tuple t1 and - * places the result into this tuple: this = (1-alpha)*this + alpha*t1. - * @param t1 the first tuple - * @param alpha the alpha interpolation parameter - */ + * Linearly interpolates between this tuple and tuple t1 and + * places the result into this tuple: this = (1-alpha)*this + alpha*t1. + * + * @param t1 the first tuple + * @param alpha the alpha interpolation parameter + */ public void interpolate(Tuple4d t1, double alpha) { - this.x = (1-alpha)*this.x + alpha*t1.x; - this.y = (1-alpha)*this.y + alpha*t1.y; - this.z = (1-alpha)*this.z + alpha*t1.z; - this.w = (1-alpha)*this.w + alpha*t1.w; + this.x = (1 - alpha) * this.x + alpha * t1.x; + this.y = (1 - alpha) * this.y + alpha * t1.y; + this.z = (1 - alpha) * this.z + alpha * t1.z; + this.w = (1 - alpha) * this.w + alpha * t1.w; } /** * Creates a new object of the same class as this object. * * @return a clone of this instance. - * @exception OutOfMemoryError if there is not enough memory. + * @throws OutOfMemoryError if there is not enough memory. * @see java.lang.Cloneable * @since vecmath 1.3 */ public Object clone() { - // Since there are no arrays we can just use Object.clone() - try { - return super.clone(); - } catch (CloneNotSupportedException e) { - // this shouldn't happen, since we are Cloneable - throw new InternalError(); - } + // Since there are no arrays we can just use Object.clone() + try { + return super.clone(); + } catch (CloneNotSupportedException e) { + // this shouldn't happen, since we are Cloneable + throw new InternalError(); + } } /** - * Get the x coordinate. - * - * @return the x coordinate. - * - * @since vecmath 1.5 - */ - public final double getX() { - return x; - } + * Get the x coordinate. + * + * @return the x coordinate. + * @since vecmath 1.5 + */ + public final double getX() { + return x; + } - /** - * Set the x coordinate. - * - * @param x value to x coordinate. - * - * @since vecmath 1.5 - */ - public final void setX(double x) { - this.x = x; - } + /** + * Set the x coordinate. + * + * @param x value to x coordinate. + * @since vecmath 1.5 + */ + public final void setX(double x) { + this.x = x; + } - /** - * Get the y coordinate. - * - * @return the y coordinate. - * - * @since vecmath 1.5 - */ - public final double getY() { - return y; - } + /** + * Get the y coordinate. + * + * @return the y coordinate. + * @since vecmath 1.5 + */ + public final double getY() { + return y; + } - /** - * Set the y coordinate. - * - * @param y value to y coordinate. - * - * @since vecmath 1.5 - */ - public final void setY(double y) { - this.y = y; - } + /** + * Set the y coordinate. + * + * @param y value to y coordinate. + * @since vecmath 1.5 + */ + public final void setY(double y) { + this.y = y; + } - /** - * Get the z coordinate. - * - * @return the z coordinate. - * - * @since vecmath 1.5 - */ - public final double getZ() { - return z; - } + /** + * Get the z coordinate. + * + * @return the z coordinate. + * @since vecmath 1.5 + */ + public final double getZ() { + return z; + } - /** - * Set the z coordinate. - * - * @param z value to z coordinate. - * - * @since vecmath 1.5 - */ - public final void setZ(double z) { - this.z = z; - } + /** + * Set the z coordinate. + * + * @param z value to z coordinate. + * @since vecmath 1.5 + */ + public final void setZ(double z) { + this.z = z; + } - /** - * Get the w coordinate. - * - * @return the w coordinate. - * - * @since vecmath 1.5 - */ - public final double getW() { - return w; - } + /** + * Get the w coordinate. + * + * @return the w coordinate. + * @since vecmath 1.5 + */ + public final double getW() { + return w; + } - /** - * Set the w coordinate. - * - * @param w value to w coordinate. - * - * @since vecmath 1.5 - */ - public final void setW(double w) { - this.w = w; - } + /** + * Set the w coordinate. + * + * @param w value to w coordinate. + * @since vecmath 1.5 + */ + public final void setW(double w) { + this.w = w; + } } diff --git a/src/main/java/com/volmit/iris/util/Tuple4f.java b/src/main/java/com/volmit/iris/util/Tuple4f.java index 0809ffe81..d31b34a66 100644 --- a/src/main/java/com/volmit/iris/util/Tuple4f.java +++ b/src/main/java/com/volmit/iris/util/Tuple4f.java @@ -31,403 +31,399 @@ package com.volmit.iris.util; -import java.lang.Math; - /** - * A 4-element tuple represented by single-precision floating point x,y,z,w + * A 4-element tuple represented by single-precision floating point x,y,z,w * coordinates. - * */ public abstract class Tuple4f implements java.io.Serializable, Cloneable { - static final long serialVersionUID = 7068460319248845763L; + static final long serialVersionUID = 7068460319248845763L; - /** - * The x coordinate. - */ - public float x; + /** + * The x coordinate. + */ + public float x; - /** - * The y coordinate. - */ - public float y; + /** + * The y coordinate. + */ + public float y; - /** - * The z coordinate. - */ - public float z; + /** + * The z coordinate. + */ + public float z; - /** - * The w coordinate. - */ - public float w; - - - /** - * Constructs and initializes a Tuple4f from the specified xyzw coordinates. - * @param x the x coordinate - * @param y the y coordinate - * @param z the z coordinate - * @param w the w coordinate - */ - public Tuple4f(float x, float y, float z, float w) - { - this.x = x; - this.y = y; - this.z = z; - this.w = w; - } - - - /** - * Constructs and initializes a Tuple4f from the array of length 4. - * @param t the array of length 4 containing xyzw in order - */ - public Tuple4f(float[] t) - { - this.x = t[0]; - this.y = t[1]; - this.z = t[2]; - this.w = t[3]; - } - - - /** - * Constructs and initializes a Tuple4f from the specified Tuple4f. - * @param t1 the Tuple4f containing the initialization x y z w data - */ - public Tuple4f(Tuple4f t1) - { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; - this.w = t1.w; - } - - - /** - * Constructs and initializes a Tuple4f from the specified Tuple4d. - * @param t1 the Tuple4d containing the initialization x y z w data - */ - public Tuple4f(Tuple4d t1) - { - this.x = (float) t1.x; - this.y = (float) t1.y; - this.z = (float) t1.z; - this.w = (float) t1.w; - } - - - /** - * Constructs and initializes a Tuple4f to (0,0,0,0). - */ - public Tuple4f() - { - this.x = 0.0f; - this.y = 0.0f; - this.z = 0.0f; - this.w = 0.0f; - } + /** + * The w coordinate. + */ + public float w; /** - * Sets the value of this tuple to the specified xyzw coordinates. + * Constructs and initializes a Tuple4f from the specified xyzw coordinates. + * * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate * @param w the w coordinate */ - public final void set(float x, float y, float z, float w) - { - this.x = x; - this.y = y; - this.z = z; - this.w = w; + public Tuple4f(float x, float y, float z, float w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; + } + + + /** + * Constructs and initializes a Tuple4f from the array of length 4. + * + * @param t the array of length 4 containing xyzw in order + */ + public Tuple4f(float[] t) { + this.x = t[0]; + this.y = t[1]; + this.z = t[2]; + this.w = t[3]; + } + + + /** + * Constructs and initializes a Tuple4f from the specified Tuple4f. + * + * @param t1 the Tuple4f containing the initialization x y z w data + */ + public Tuple4f(Tuple4f t1) { + this.x = t1.x; + this.y = t1.y; + this.z = t1.z; + this.w = t1.w; + } + + + /** + * Constructs and initializes a Tuple4f from the specified Tuple4d. + * + * @param t1 the Tuple4d containing the initialization x y z w data + */ + public Tuple4f(Tuple4d t1) { + this.x = (float) t1.x; + this.y = (float) t1.y; + this.z = (float) t1.z; + this.w = (float) t1.w; + } + + + /** + * Constructs and initializes a Tuple4f to (0,0,0,0). + */ + public Tuple4f() { + this.x = 0.0f; + this.y = 0.0f; + this.z = 0.0f; + this.w = 0.0f; + } + + + /** + * Sets the value of this tuple to the specified xyzw coordinates. + * + * @param x the x coordinate + * @param y the y coordinate + * @param z the z coordinate + * @param w the w coordinate + */ + public final void set(float x, float y, float z, float w) { + this.x = x; + this.y = y; + this.z = z; + this.w = w; } /** * Sets the value of this tuple to the specified coordinates in the * array of length 4. + * * @param t the array of length 4 containing xyzw in order */ - public final void set(float[] t) - { - this.x = t[0]; - this.y = t[1]; - this.z = t[2]; - this.w = t[3]; + public final void set(float[] t) { + this.x = t[0]; + this.y = t[1]; + this.z = t[2]; + this.w = t[3]; } /** * Sets the value of this tuple to the value of tuple t1. + * * @param t1 the tuple to be copied */ - public final void set(Tuple4f t1) - { - this.x = t1.x; - this.y = t1.y; - this.z = t1.z; - this.w = t1.w; + public final void set(Tuple4f t1) { + this.x = t1.x; + this.y = t1.y; + this.z = t1.z; + this.w = t1.w; } /** * Sets the value of this tuple to the value of tuple t1. + * * @param t1 the tuple to be copied */ - public final void set(Tuple4d t1) - { - this.x = (float) t1.x; - this.y = (float) t1.y; - this.z = (float) t1.z; - this.w = (float) t1.w; + public final void set(Tuple4d t1) { + this.x = (float) t1.x; + this.y = (float) t1.y; + this.z = (float) t1.z; + this.w = (float) t1.w; } /** * Copies the values of this tuple into the array t. - * @param t the array + * + * @param t the array */ - public final void get(float[] t) - { - t[0] = this.x; - t[1] = this.y; - t[2] = this.z; - t[3] = this.w; - } + public final void get(float[] t) { + t[0] = this.x; + t[1] = this.y; + t[2] = this.z; + t[3] = this.w; + } - - /** + + /** * Copies the values of this tuple into the tuple t. + * * @param t the target tuple - */ - public final void get(Tuple4f t) - { - t.x = this.x; - t.y = this.y; - t.z = this.z; - t.w = this.w; - } + */ + public final void get(Tuple4f t) { + t.x = this.x; + t.y = this.y; + t.z = this.z; + t.w = this.w; + } - /** - * Sets the value of this tuple to the sum of tuples t1 and t2. - * @param t1 the first tuple - * @param t2 the second tuple - */ - public final void add(Tuple4f t1, Tuple4f t2) - { - this.x = t1.x + t2.x; - this.y = t1.y + t2.y; - this.z = t1.z + t2.z; - this.w = t1.w + t2.w; - } + /** + * Sets the value of this tuple to the sum of tuples t1 and t2. + * + * @param t1 the first tuple + * @param t2 the second tuple + */ + public final void add(Tuple4f t1, Tuple4f t2) { + this.x = t1.x + t2.x; + this.y = t1.y + t2.y; + this.z = t1.z + t2.z; + this.w = t1.w + t2.w; + } - /** - * Sets the value of this tuple to the sum of itself and t1. - * @param t1 the other tuple - */ - public final void add(Tuple4f t1) - { - this.x += t1.x; - this.y += t1.y; - this.z += t1.z; - this.w += t1.w; - } + /** + * Sets the value of this tuple to the sum of itself and t1. + * + * @param t1 the other tuple + */ + public final void add(Tuple4f t1) { + this.x += t1.x; + this.y += t1.y; + this.z += t1.z; + this.w += t1.w; + } - /** - * Sets the value of this tuple to the difference - * of tuples t1 and t2 (this = t1 - t2). - * @param t1 the first tuple - * @param t2 the second tuple - */ - public final void sub(Tuple4f t1, Tuple4f t2) - { - this.x = t1.x - t2.x; - this.y = t1.y - t2.y; - this.z = t1.z - t2.z; - this.w = t1.w - t2.w; - } + /** + * Sets the value of this tuple to the difference + * of tuples t1 and t2 (this = t1 - t2). + * + * @param t1 the first tuple + * @param t2 the second tuple + */ + public final void sub(Tuple4f t1, Tuple4f t2) { + this.x = t1.x - t2.x; + this.y = t1.y - t2.y; + this.z = t1.z - t2.z; + this.w = t1.w - t2.w; + } - /** - * Sets the value of this tuple to the difference - * of itself and t1 (this = this - t1). - * @param t1 the other tuple - */ - public final void sub(Tuple4f t1) - { - this.x -= t1.x; - this.y -= t1.y; - this.z -= t1.z; - this.w -= t1.w; - } + /** + * Sets the value of this tuple to the difference + * of itself and t1 (this = this - t1). + * + * @param t1 the other tuple + */ + public final void sub(Tuple4f t1) { + this.x -= t1.x; + this.y -= t1.y; + this.z -= t1.z; + this.w -= t1.w; + } - /** - * Sets the value of this tuple to the negation of tuple t1. - * @param t1 the source tuple - */ - public final void negate(Tuple4f t1) - { - this.x = -t1.x; - this.y = -t1.y; - this.z = -t1.z; - this.w = -t1.w; - } + /** + * Sets the value of this tuple to the negation of tuple t1. + * + * @param t1 the source tuple + */ + public final void negate(Tuple4f t1) { + this.x = -t1.x; + this.y = -t1.y; + this.z = -t1.z; + this.w = -t1.w; + } - /** - * Negates the value of this tuple in place. - */ - public final void negate() - { - this.x = -this.x; - this.y = -this.y; - this.z = -this.z; - this.w = -this.w; - } + /** + * Negates the value of this tuple in place. + */ + public final void negate() { + this.x = -this.x; + this.y = -this.y; + this.z = -this.z; + this.w = -this.w; + } - /** - * Sets the value of this tuple to the scalar multiplication - * of tuple t1. - * @param s the scalar value - * @param t1 the source tuple - */ - public final void scale(float s, Tuple4f t1) - { - this.x = s*t1.x; - this.y = s*t1.y; - this.z = s*t1.z; - this.w = s*t1.w; - } + /** + * Sets the value of this tuple to the scalar multiplication + * of tuple t1. + * + * @param s the scalar value + * @param t1 the source tuple + */ + public final void scale(float s, Tuple4f t1) { + this.x = s * t1.x; + this.y = s * t1.y; + this.z = s * t1.z; + this.w = s * t1.w; + } - /** - * Sets the value of this tuple to the scalar multiplication - * of the scale factor with this. - * @param s the scalar value - */ - public final void scale(float s) - { - this.x *= s; - this.y *= s; - this.z *= s; - this.w *= s; - } + /** + * Sets the value of this tuple to the scalar multiplication + * of the scale factor with this. + * + * @param s the scalar value + */ + public final void scale(float s) { + this.x *= s; + this.y *= s; + this.z *= s; + this.w *= s; + } - /** - * Sets the value of this tuple to the scalar multiplication - * of tuple t1 plus tuple t2 (this = s*t1 + t2). - * @param s the scalar value - * @param t1 the tuple to be multipled - * @param t2 the tuple to be added - */ - public final void scaleAdd(float s, Tuple4f t1, Tuple4f t2) - { - this.x = s*t1.x + t2.x; - this.y = s*t1.y + t2.y; - this.z = s*t1.z + t2.z; - this.w = s*t1.w + t2.w; - } + /** + * Sets the value of this tuple to the scalar multiplication + * of tuple t1 plus tuple t2 (this = s*t1 + t2). + * + * @param s the scalar value + * @param t1 the tuple to be multipled + * @param t2 the tuple to be added + */ + public final void scaleAdd(float s, Tuple4f t1, Tuple4f t2) { + this.x = s * t1.x + t2.x; + this.y = s * t1.y + t2.y; + this.z = s * t1.z + t2.z; + this.w = s * t1.w + t2.w; + } /** * Sets the value of this tuple to the scalar multiplication * of itself and then adds tuple t1 (this = s*this + t1). - * @param s the scalar value + * + * @param s the scalar value * @param t1 the tuple to be added - */ - public final void scaleAdd(float s, Tuple4f t1) - { - this.x = s*this.x + t1.x; - this.y = s*this.y + t1.y; - this.z = s*this.z + t1.z; - this.w = s*this.w + t1.w; + */ + public final void scaleAdd(float s, Tuple4f t1) { + this.x = s * this.x + t1.x; + this.y = s * this.y + t1.y; + this.z = s * this.z + t1.z; + this.w = s * this.w + t1.w; } - - /** + /** * Returns a string that contains the values of this Tuple4f. * The form is (x,y,z,w). + * * @return the String representation - */ + */ public String toString() { return "(" + this.x + ", " + this.y + ", " + this.z + ", " + this.w + ")"; } - /** + /** * Returns true if all of the data members of Tuple4f t1 are * equal to the corresponding data members in this Tuple4f. - * @param t1 the vector with which the comparison is made - * @return true or false - */ - public boolean equals(Tuple4f t1) - { + * + * @param t1 the vector with which the comparison is made + * @return true or false + */ + public boolean equals(Tuple4f t1) { try { - return(this.x == t1.x && this.y == t1.y && this.z == t1.z - && this.w == t1.w); + return (this.x == t1.x && this.y == t1.y && this.z == t1.z + && this.w == t1.w); + } catch (NullPointerException e2) { + return false; } - catch (NullPointerException e2) {return false;} } - /** + /** * Returns true if the Object t1 is of type Tuple4f and all of the * data members of t1 are equal to the corresponding data members in * this Tuple4f. - * @param t1 the object with which the comparison is made - * @return true or false + * + * @param t1 the object with which the comparison is made + * @return true or false */ - public boolean equals(Object t1) - { + public boolean equals(Object t1) { try { - Tuple4f t2 = (Tuple4f) t1; - return(this.x == t2.x && this.y == t2.y && - this.z == t2.z && this.w == t2.w); + Tuple4f t2 = (Tuple4f) t1; + return (this.x == t2.x && this.y == t2.y && + this.z == t2.z && this.w == t2.w); + } catch (NullPointerException e2) { + return false; + } catch (ClassCastException e1) { + return false; } - catch (NullPointerException e2) {return false;} - catch (ClassCastException e1) {return false;} } - /** + /** * Returns true if the L-infinite distance between this tuple - * and tuple t1 is less than or equal to the epsilon parameter, + * and tuple t1 is less than or equal to the epsilon parameter, * otherwise returns false. The L-infinite - * distance is equal to + * distance is equal to * MAX[abs(x1-x2), abs(y1-y2), abs(z1-z2), abs(w1-w2)]. - * @param t1 the tuple to be compared to this tuple - * @param epsilon the threshold value - * @return true or false + * + * @param t1 the tuple to be compared to this tuple + * @param epsilon the threshold value + * @return true or false */ - public boolean epsilonEquals(Tuple4f t1, float epsilon) - { - float diff; + public boolean epsilonEquals(Tuple4f t1, float epsilon) { + float diff; - diff = x - t1.x; - if(Float.isNaN(diff)) return false; - if((diff<0?-diff:diff) > epsilon) return false; + diff = x - t1.x; + if (Float.isNaN(diff)) return false; + if ((diff < 0 ? -diff : diff) > epsilon) return false; - diff = y - t1.y; - if(Float.isNaN(diff)) return false; - if((diff<0?-diff:diff) > epsilon) return false; + diff = y - t1.y; + if (Float.isNaN(diff)) return false; + if ((diff < 0 ? -diff : diff) > epsilon) return false; - diff = z - t1.z; - if(Float.isNaN(diff)) return false; - if((diff<0?-diff:diff) > epsilon) return false; + diff = z - t1.z; + if (Float.isNaN(diff)) return false; + if ((diff < 0 ? -diff : diff) > epsilon) return false; - diff = w - t1.w; - if(Float.isNaN(diff)) return false; - if((diff<0?-diff:diff) > epsilon) return false; - - return true; + diff = w - t1.w; + if (Float.isNaN(diff)) return false; + return !((diff < 0 ? -diff : diff) > epsilon); } @@ -437,362 +433,354 @@ public abstract class Tuple4f implements java.io.Serializable, Cloneable { * (i.e., Tuple4f.equals returns true) will return the same hash * code value. Two objects with different data members may return the * same hash value, although this is not likely. + * * @return the integer hash code value - */ + */ public int hashCode() { - long bits = 1L; - bits = 31L * bits + (long)VecMathUtil.floatToIntBits(x); - bits = 31L * bits + (long)VecMathUtil.floatToIntBits(y); - bits = 31L * bits + (long)VecMathUtil.floatToIntBits(z); - bits = 31L * bits + (long)VecMathUtil.floatToIntBits(w); - return (int) (bits ^ (bits >> 32)); + long bits = 1L; + bits = 31L * bits + (long) VecMathUtil.floatToIntBits(x); + bits = 31L * bits + (long) VecMathUtil.floatToIntBits(y); + bits = 31L * bits + (long) VecMathUtil.floatToIntBits(z); + bits = 31L * bits + (long) VecMathUtil.floatToIntBits(w); + return (int) (bits ^ (bits >> 32)); } - /** - * Clamps the tuple parameter to the range [low, high] and - * places the values into this tuple. - * @param min the lowest value in the tuple after clamping - * @param max the highest value in the tuple after clamping - * @param t the source tuple, which will not be modified - */ - public final void clamp(float min, float max, Tuple4f t) - { - if( t.x > max ) { - x = max; - } else if( t.x < min ){ - x = min; - } else { - x = t.x; - } - - if( t.y > max ) { - y = max; - } else if( t.y < min ){ - y = min; + /** + * Clamps the tuple parameter to the range [low, high] and + * places the values into this tuple. + * + * @param min the lowest value in the tuple after clamping + * @param max the highest value in the tuple after clamping + * @param t the source tuple, which will not be modified + */ + public final void clamp(float min, float max, Tuple4f t) { + if (t.x > max) { + x = max; + } else if (t.x < min) { + x = min; } else { - y = t.y; + x = t.x; } - - if( t.z > max ) { - z = max; - } else if( t.z < min ){ - z = min; + + if (t.y > max) { + y = max; + } else if (t.y < min) { + y = min; } else { - z = t.z; + y = t.y; } - if( t.w > max ) { - w = max; - } else if( t.w < min ){ - w = min; + if (t.z > max) { + z = max; + } else if (t.z < min) { + z = min; } else { - w = t.w; + z = t.z; } - } - - - /** - * Clamps the minimum value of the tuple parameter to the min - * parameter and places the values into this tuple. - * @param min the lowest value in the tuple after clamping - * @param t the source tuple, which will not be modified - */ - public final void clampMin(float min, Tuple4f t) - { - if( t.x < min ) { - x = min; + if (t.w > max) { + w = max; + } else if (t.w < min) { + w = min; } else { - x = t.x; + w = t.w; } - - if( t.y < min ) { - y = min; + + } + + + /** + * Clamps the minimum value of the tuple parameter to the min + * parameter and places the values into this tuple. + * + * @param min the lowest value in the tuple after clamping + * @param t the source tuple, which will not be modified + */ + public final void clampMin(float min, Tuple4f t) { + if (t.x < min) { + x = min; } else { - y = t.y; + x = t.x; } - - if( t.z < min ) { - z = min; + + if (t.y < min) { + y = min; } else { - z = t.z; + y = t.y; } - - if( t.w < min ) { - w = min; + + if (t.z < min) { + z = min; } else { - w = t.w; + z = t.z; } - - } - - - /** - * Clamps the maximum value of the tuple parameter to the max - * parameter and places the values into this tuple. - * @param max the highest value in the tuple after clamping - * @param t the source tuple, which will not be modified - */ - public final void clampMax(float max, Tuple4f t) - { - if( t.x > max ) { - x = max; + if (t.w < min) { + w = min; } else { - x = t.x; + w = t.w; } - - if( t.y > max ) { - y = max; + + + } + + + /** + * Clamps the maximum value of the tuple parameter to the max + * parameter and places the values into this tuple. + * + * @param max the highest value in the tuple after clamping + * @param t the source tuple, which will not be modified + */ + public final void clampMax(float max, Tuple4f t) { + if (t.x > max) { + x = max; } else { - y = t.y; + x = t.x; } - - if( t.z > max ) { - z = max; + + if (t.y > max) { + y = max; } else { - z = t.z; + y = t.y; } - - if( t.w > max ) { - w = max; + + if (t.z > max) { + z = max; } else { - w = t.z; + z = t.z; } - } - - - /** - * Sets each component of the tuple parameter to its absolute - * value and places the modified values into this tuple. - * @param t the source tuple, which will not be modified - */ - public final void absolute(Tuple4f t) - { - x = Math.abs(t.x); - y = Math.abs(t.y); - z = Math.abs(t.z); - w = Math.abs(t.w); - } - - - /** - * Clamps this tuple to the range [low, high]. - * @param min the lowest value in this tuple after clamping - * @param max the highest value in this tuple after clamping - */ - public final void clamp(float min, float max) - { - if( x > max ) { - x = max; - } else if( x < min ){ - x = min; - } - - if( y > max ) { - y = max; - } else if( y < min ){ - y = min; - } - - if( z > max ) { - z = max; - } else if( z < min ){ - z = min; - } - - if( w > max ) { - w = max; - } else if( w < min ){ - w = min; + if (t.w > max) { + w = max; + } else { + w = t.z; } - } - - - /** - * Clamps the minimum value of this tuple to the min parameter. - * @param min the lowest value in this tuple after clamping - */ - public final void clampMin(float min) - { - if( x < min ) x=min; - if( y < min ) y=min; - if( z < min ) z=min; - if( w < min ) w=min; - - } - - - /** - * Clamps the maximum value of this tuple to the max parameter. - * @param max the highest value in the tuple after clamping - */ - public final void clampMax(float max) - { - if( x > max ) x=max; - if( y > max ) y=max; - if( z > max ) z=max; - if( w > max ) w=max; - - } + } - /** - * Sets each component of this tuple to its absolute value. - */ - public final void absolute() - { - x = Math.abs(x); - y = Math.abs(y); - z = Math.abs(z); - w = Math.abs(w); - } + /** + * Sets each component of the tuple parameter to its absolute + * value and places the modified values into this tuple. + * + * @param t the source tuple, which will not be modified + */ + public final void absolute(Tuple4f t) { + x = Math.abs(t.x); + y = Math.abs(t.y); + z = Math.abs(t.z); + w = Math.abs(t.w); + } - /** - * Linearly interpolates between tuples t1 and t2 and places the - * result into this tuple: this = (1-alpha)*t1 + alpha*t2. - * @param t1 the first tuple - * @param t2 the second tuple - * @param alpha the alpha interpolation parameter - */ - public void interpolate(Tuple4f t1, Tuple4f t2, float alpha) - { - this.x = (1-alpha)*t1.x + alpha*t2.x; - this.y = (1-alpha)*t1.y + alpha*t2.y; - this.z = (1-alpha)*t1.z + alpha*t2.z; - this.w = (1-alpha)*t1.w + alpha*t2.w; + /** + * Clamps this tuple to the range [low, high]. + * + * @param min the lowest value in this tuple after clamping + * @param max the highest value in this tuple after clamping + */ + public final void clamp(float min, float max) { + if (x > max) { + x = max; + } else if (x < min) { + x = min; + } - } - - - /** - * Linearly interpolates between this tuple and tuple t1 and - * places the result into this tuple: this = (1-alpha)*this + alpha*t1. - * @param t1 the first tuple - * @param alpha the alpha interpolation parameter - */ - public void interpolate(Tuple4f t1, float alpha) - { - this.x = (1-alpha)*this.x + alpha*t1.x; - this.y = (1-alpha)*this.y + alpha*t1.y; - this.z = (1-alpha)*this.z + alpha*t1.z; - this.w = (1-alpha)*this.w + alpha*t1.w; + if (y > max) { + y = max; + } else if (y < min) { + y = min; + } + + if (z > max) { + z = max; + } else if (z < min) { + z = min; + } + + if (w > max) { + w = max; + } else if (w < min) { + w = min; + } + + } + + + /** + * Clamps the minimum value of this tuple to the min parameter. + * + * @param min the lowest value in this tuple after clamping + */ + public final void clampMin(float min) { + if (x < min) x = min; + if (y < min) y = min; + if (z < min) z = min; + if (w < min) w = min; + + } + + + /** + * Clamps the maximum value of this tuple to the max parameter. + * + * @param max the highest value in the tuple after clamping + */ + public final void clampMax(float max) { + if (x > max) x = max; + if (y > max) y = max; + if (z > max) z = max; + if (w > max) w = max; + + } + + + /** + * Sets each component of this tuple to its absolute value. + */ + public final void absolute() { + x = Math.abs(x); + y = Math.abs(y); + z = Math.abs(z); + w = Math.abs(w); + } + + + /** + * Linearly interpolates between tuples t1 and t2 and places the + * result into this tuple: this = (1-alpha)*t1 + alpha*t2. + * + * @param t1 the first tuple + * @param t2 the second tuple + * @param alpha the alpha interpolation parameter + */ + public void interpolate(Tuple4f t1, Tuple4f t2, float alpha) { + this.x = (1 - alpha) * t1.x + alpha * t2.x; + this.y = (1 - alpha) * t1.y + alpha * t2.y; + this.z = (1 - alpha) * t1.z + alpha * t2.z; + this.w = (1 - alpha) * t1.w + alpha * t2.w; + + } + + + /** + * Linearly interpolates between this tuple and tuple t1 and + * places the result into this tuple: this = (1-alpha)*this + alpha*t1. + * + * @param t1 the first tuple + * @param alpha the alpha interpolation parameter + */ + public void interpolate(Tuple4f t1, float alpha) { + this.x = (1 - alpha) * this.x + alpha * t1.x; + this.y = (1 - alpha) * this.y + alpha * t1.y; + this.z = (1 - alpha) * this.z + alpha * t1.z; + this.w = (1 - alpha) * this.w + alpha * t1.w; + + } - } - /** * Creates a new object of the same class as this object. * * @return a clone of this instance. - * @exception OutOfMemoryError if there is not enough memory. + * @throws OutOfMemoryError if there is not enough memory. * @see java.lang.Cloneable * @since vecmath 1.3 */ public Object clone() { - // Since there are no arrays we can just use Object.clone() - try { - return super.clone(); - } catch (CloneNotSupportedException e) { - // this shouldn't happen, since we are Cloneable - throw new InternalError(); - } + // Since there are no arrays we can just use Object.clone() + try { + return super.clone(); + } catch (CloneNotSupportedException e) { + // this shouldn't happen, since we are Cloneable + throw new InternalError(); + } } /** - * Get the x coordinate. - * - * @return the x coordinate. - * - * @since vecmath 1.5 - */ - public final float getX() { - return x; - } + * Get the x coordinate. + * + * @return the x coordinate. + * @since vecmath 1.5 + */ + public final float getX() { + return x; + } - /** - * Set the x coordinate. - * - * @param x value to x coordinate. - * - * @since vecmath 1.5 - */ - public final void setX(float x) { - this.x = x; - } + /** + * Set the x coordinate. + * + * @param x value to x coordinate. + * @since vecmath 1.5 + */ + public final void setX(float x) { + this.x = x; + } - /** - * Get the y coordinate. - * - * @return the y coordinate. - * - * @since vecmath 1.5 - */ - public final float getY() { - return y; - } + /** + * Get the y coordinate. + * + * @return the y coordinate. + * @since vecmath 1.5 + */ + public final float getY() { + return y; + } - /** - * Set the y coordinate. - * - * @param y value to y coordinate. - * - * @since vecmath 1.5 - */ - public final void setY(float y) { - this.y = y; - } + /** + * Set the y coordinate. + * + * @param y value to y coordinate. + * @since vecmath 1.5 + */ + public final void setY(float y) { + this.y = y; + } - /** - * Get the z coordinate. - * - * @return the z coordinate. - * - * @since vecmath 1.5 - */ - public final float getZ() { - return z; - } + /** + * Get the z coordinate. + * + * @return the z coordinate. + * @since vecmath 1.5 + */ + public final float getZ() { + return z; + } - /** - * Set the z coordinate. - * - * @param z value to z coordinate. - * - * @since vecmath 1.5 - */ - public final void setZ(float z) { - this.z = z; - } + /** + * Set the z coordinate. + * + * @param z value to z coordinate. + * @since vecmath 1.5 + */ + public final void setZ(float z) { + this.z = z; + } - /** - * Get the w coordinate. - * - * @return the w coordinate. - * - * @since vecmath 1.5 - */ - public final float getW() { - return w; - } + /** + * Get the w coordinate. + * + * @return the w coordinate. + * @since vecmath 1.5 + */ + public final float getW() { + return w; + } - /** - * Set the w coordinate. - * - * @param w value to w coordinate. - * - * @since vecmath 1.5 - */ - public final void setW(float w) { - this.w = w; - } + /** + * Set the w coordinate. + * + * @param w value to w coordinate. + * @since vecmath 1.5 + */ + public final void setW(float w) { + this.w = w; + } } diff --git a/src/main/java/com/volmit/iris/util/UIElement.java b/src/main/java/com/volmit/iris/util/UIElement.java index 789f6ba5a..033031cc0 100644 --- a/src/main/java/com/volmit/iris/util/UIElement.java +++ b/src/main/java/com/volmit/iris/util/UIElement.java @@ -5,257 +5,213 @@ import org.bukkit.enchantments.Enchantment; import org.bukkit.inventory.ItemStack; import org.bukkit.inventory.meta.ItemMeta; -public class UIElement implements Element -{ - private MaterialBlock material; - private boolean enchanted; - private final String id; - private String name; - private double progress; - private boolean bg; - private final KList lore; - private Callback eLeft; - private Callback eRight; - private Callback eShiftLeft; - private Callback eShiftRight; - private Callback eDraggedInto; - private Callback eOtherDraggedInto; - private int count; +public class UIElement implements Element { + private MaterialBlock material; + private boolean enchanted; + private final String id; + private String name; + private double progress; + private boolean bg; + private final KList lore; + private Callback eLeft; + private Callback eRight; + private Callback eShiftLeft; + private Callback eShiftRight; + private Callback eDraggedInto; + private Callback eOtherDraggedInto; + private int count; - public UIElement(String id) - { - this.id = id; - lore = new KList<>(); - enchanted = false; - count = 1; - material = new MaterialBlock(Material.AIR); - } + public UIElement(String id) { + this.id = id; + lore = new KList<>(); + enchanted = false; + count = 1; + material = new MaterialBlock(Material.AIR); + } - @Override - public MaterialBlock getMaterial() - { - return material; - } + @Override + public MaterialBlock getMaterial() { + return material; + } - public Double clip(double value, double min, double max) - { - return Double.valueOf(Math.min(max, Math.max(min, value))); - } + public Double clip(double value, double min, double max) { + return Double.valueOf(Math.min(max, Math.max(min, value))); + } - @Override - public UIElement setMaterial(MaterialBlock material) - { - this.material = material; - return this; - } + @Override + public UIElement setMaterial(MaterialBlock material) { + this.material = material; + return this; + } - @Override - public boolean isEnchanted() - { - return enchanted; - } + @Override + public boolean isEnchanted() { + return enchanted; + } - @Override - public UIElement setEnchanted(boolean enchanted) - { - this.enchanted = enchanted; - return this; - } + @Override + public UIElement setEnchanted(boolean enchanted) { + this.enchanted = enchanted; + return this; + } - @Override - public String getId() - { - return id; - } + @Override + public String getId() { + return id; + } - @Override - public String getName() - { - return name; - } + @Override + public String getName() { + return name; + } - @Override - public UIElement setName(String name) - { - this.name = name; - return this; - } + @Override + public UIElement setName(String name) { + this.name = name; + return this; + } - @Override - public KList getLore() - { - return lore; - } + @Override + public KList getLore() { + return lore; + } - @Override - public UIElement onLeftClick(Callback clicked) - { - eLeft = clicked; - return this; - } + @Override + public UIElement onLeftClick(Callback clicked) { + eLeft = clicked; + return this; + } - @Override - public UIElement onRightClick(Callback clicked) - { - eRight = clicked; - return this; - } + @Override + public UIElement onRightClick(Callback clicked) { + eRight = clicked; + return this; + } - @Override - public UIElement onShiftLeftClick(Callback clicked) - { - eShiftLeft = clicked; - return this; - } + @Override + public UIElement onShiftLeftClick(Callback clicked) { + eShiftLeft = clicked; + return this; + } - @Override - public UIElement onShiftRightClick(Callback clicked) - { - eShiftRight = clicked; - return this; - } + @Override + public UIElement onShiftRightClick(Callback clicked) { + eShiftRight = clicked; + return this; + } - @Override - public UIElement onDraggedInto(Callback into) - { - eDraggedInto = into; - return this; - } + @Override + public UIElement onDraggedInto(Callback into) { + eDraggedInto = into; + return this; + } - @Override - public UIElement onOtherDraggedInto(Callback other) - { - eOtherDraggedInto = other; - return this; - } + @Override + public UIElement onOtherDraggedInto(Callback other) { + eOtherDraggedInto = other; + return this; + } - @Override - public Element call(ElementEvent event, Element context) - { - try - { - switch(event) - { - case DRAG_INTO: - eDraggedInto.run(context); - return this; - case LEFT: - eLeft.run(context); - return this; - case OTHER_DRAG_INTO: - eOtherDraggedInto.run(context); - return this; - case RIGHT: - eRight.run(context); - return this; - case SHIFT_LEFT: - eShiftLeft.run(context); - return this; - case SHIFT_RIGHT: - eShiftRight.run(context); - return this; - } - } + @Override + public Element call(ElementEvent event, Element context) { + try { + switch (event) { + case DRAG_INTO: + eDraggedInto.run(context); + return this; + case LEFT: + eLeft.run(context); + return this; + case OTHER_DRAG_INTO: + eOtherDraggedInto.run(context); + return this; + case RIGHT: + eRight.run(context); + return this; + case SHIFT_LEFT: + eShiftLeft.run(context); + return this; + case SHIFT_RIGHT: + eShiftRight.run(context); + return this; + } + } catch (NullPointerException e) { - catch(NullPointerException e) - { + } catch (Throwable e) { + e.printStackTrace(); + } - } + return this; + } - catch(Throwable e) - { - e.printStackTrace(); - } + @Override + public Element addLore(String loreLine) { + getLore().add(loreLine); + return this; + } - return this; - } + @Override + public Element setBackground(boolean bg) { + this.bg = bg; + return this; + } - @Override - public Element addLore(String loreLine) - { - getLore().add(loreLine); - return this; - } + @Override + public boolean isBackgrond() { + return bg; + } - @Override - public Element setBackground(boolean bg) - { - this.bg = bg; - return this; - } + @Override + public Element setCount(int c) { + count = clip(c, 1, 64).intValue(); + return this; + } - @Override - public boolean isBackgrond() - { - return bg; - } + @Override + public int getCount() { + return count; + } - @Override - public Element setCount(int c) - { - count = (int) clip(c, 1, 64).intValue(); - return this; - } + @SuppressWarnings("deprecation") + @Override + public ItemStack computeItemStack() { + try { + ItemStack is = new ItemStack(getMaterial().getMaterial(), getCount(), getEffectiveDurability()); + ItemMeta im = is.getItemMeta(); + im.setDisplayName(getName()); + im.setLore(getLore().copy()); - @Override - public int getCount() - { - return count; - } + if (isEnchanted()) { + im.addEnchant(Enchantment.DURABILITY, 1, true); + } - @SuppressWarnings("deprecation") - @Override - public ItemStack computeItemStack() - { - try - { - ItemStack is = new ItemStack(getMaterial().getMaterial(), getCount(), getEffectiveDurability()); - ItemMeta im = is.getItemMeta(); - im.setDisplayName(getName()); - im.setLore(getLore().copy()); + is.setItemMeta(im); + return is; + } catch (Throwable e) { + e.printStackTrace(); + } - if(isEnchanted()) - { - im.addEnchant(Enchantment.DURABILITY, 1, true); - } + return null; + } - is.setItemMeta(im); - return is; - } + @Override + public Element setProgress(double progress) { + this.progress = clip(progress, 0D, 1D); + return this; + } - catch(Throwable e) - { - e.printStackTrace(); - } + @Override + public double getProgress() { + return progress; + } - return null; - } - - @Override - public Element setProgress(double progress) - { - this.progress = clip(progress, 0D, 1D); - return this; - } - - @Override - public double getProgress() - { - return progress; - } - - @Override - public short getEffectiveDurability() - { - if(getMaterial().getMaterial().getMaxDurability() == 0) - { - return 0; - } - - else - { - int prog = (int) ((double) getMaterial().getMaterial().getMaxDurability() * (1D - getProgress())); - return clip(prog, 1, (getMaterial().getMaterial().getMaxDurability() - 1)).shortValue(); - } - } + @Override + public short getEffectiveDurability() { + if (getMaterial().getMaterial().getMaxDurability() == 0) { + return 0; + } else { + int prog = (int) ((double) getMaterial().getMaterial().getMaxDurability() * (1D - getProgress())); + return clip(prog, 1, (getMaterial().getMaterial().getMaxDurability() - 1)).shortValue(); + } + } } diff --git a/src/main/java/com/volmit/iris/util/UIStaticDecorator.java b/src/main/java/com/volmit/iris/util/UIStaticDecorator.java index a4da090da..125c5e321 100644 --- a/src/main/java/com/volmit/iris/util/UIStaticDecorator.java +++ b/src/main/java/com/volmit/iris/util/UIStaticDecorator.java @@ -2,18 +2,15 @@ package com.volmit.iris.util; import org.bukkit.Material; -public class UIStaticDecorator implements WindowDecorator -{ - private Element element; +public class UIStaticDecorator implements WindowDecorator { + private final Element element; - public UIStaticDecorator(Element element) - { - this.element = element == null ? new UIElement("bg").setMaterial(new MaterialBlock(Material.AIR)) : element; - } + public UIStaticDecorator(Element element) { + this.element = element == null ? new UIElement("bg").setMaterial(new MaterialBlock(Material.AIR)) : element; + } - @Override - public Element onDecorateBackground(Window window, int position, int row) - { - return element; - } + @Override + public Element onDecorateBackground(Window window, int position, int row) { + return element; + } } diff --git a/src/main/java/com/volmit/iris/util/UIVoidDecorator.java b/src/main/java/com/volmit/iris/util/UIVoidDecorator.java index 2a6f5220b..f69c6d7fc 100644 --- a/src/main/java/com/volmit/iris/util/UIVoidDecorator.java +++ b/src/main/java/com/volmit/iris/util/UIVoidDecorator.java @@ -1,11 +1,9 @@ package com.volmit.iris.util; -public class UIVoidDecorator implements WindowDecorator -{ - @Override - public Element onDecorateBackground(Window window, int position, int row) - { - return null; - } +public class UIVoidDecorator implements WindowDecorator { + @Override + public Element onDecorateBackground(Window window, int position, int row) { + return null; + } } diff --git a/src/main/java/com/volmit/iris/util/UIWindow.java b/src/main/java/com/volmit/iris/util/UIWindow.java index 661b46229..bde0854db 100644 --- a/src/main/java/com/volmit/iris/util/UIWindow.java +++ b/src/main/java/com/volmit/iris/util/UIWindow.java @@ -1,5 +1,6 @@ package com.volmit.iris.util; +import com.volmit.iris.Iris; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.event.EventHandler; @@ -11,536 +12,451 @@ import org.bukkit.event.inventory.InventoryType; import org.bukkit.inventory.Inventory; import org.bukkit.inventory.ItemStack; -import com.volmit.iris.Iris; - -public class UIWindow implements Window, Listener -{ - private WindowDecorator decorator; - private final Player viewer; - private Callback eClose; - private WindowResolution resolution; - private KMap elements; - private String title; - private boolean visible; - private int viewportPosition; - private int viewportSize; - private int highestRow; - private Inventory inventory; - private int clickcheck; - private boolean doubleclicked; - - public UIWindow(Player viewer) - { - clickcheck = 0; - doubleclicked = false; - this.viewer = viewer; - this.elements = new KMap<>(); - setTitle(""); - setDecorator(new UIVoidDecorator()); - setResolution(WindowResolution.W9_H6); - setViewportHeight((int) clip(3, 1, getResolution().getMaxHeight()).intValue()); - setViewportPosition(0); - } - - @EventHandler - public void on(InventoryClickEvent e) - { - if(!e.getWhoClicked().equals(viewer)) - { - return; - } - - if(!isVisible()) - { - return; - } - - // 1.14 bukkit api change, removed getTitle() and getName() from Inventory.class - if(!viewer.getOpenInventory().getTitle().equals(title)) - { - return; - } - - if(e.getClickedInventory() == null) - { - return; - } - - if(!e.getView().getType().equals(getResolution().getType())) - { - return; - } - - if(e.getClickedInventory().getType().equals(getResolution().getType())) - { - Element element = getElement(getLayoutPosition(e.getSlot()), getLayoutRow(e.getSlot())); - - switch(e.getAction()) - { - case CLONE_STACK: - break; - case COLLECT_TO_CURSOR: - break; - case DROP_ALL_CURSOR: - break; - case DROP_ALL_SLOT: - break; - case DROP_ONE_CURSOR: - break; - case DROP_ONE_SLOT: - break; - case HOTBAR_MOVE_AND_READD: - break; - case HOTBAR_SWAP: - break; - case MOVE_TO_OTHER_INVENTORY: - break; - case NOTHING: - break; - case PICKUP_ALL: - break; - case PICKUP_HALF: - break; - case PICKUP_ONE: - break; - case PICKUP_SOME: - break; - case PLACE_ALL: - break; - case PLACE_ONE: - break; - case PLACE_SOME: - break; - case SWAP_WITH_CURSOR: - break; - case UNKNOWN: - break; - } - - switch(e.getClick()) - { - case CONTROL_DROP: - break; - case CREATIVE: - break; - case DOUBLE_CLICK: - doubleclicked = true; - break; - case DROP: - break; - case LEFT: - - clickcheck++; - - if(clickcheck == 1) - { - J.s(() -> - { - if(clickcheck == 1) - { - clickcheck = 0; - - if(element != null) - { - element.call(ElementEvent.LEFT, element); - } - } - }); - } - - else if(clickcheck == 2) - { - J.s(() -> - { - if(doubleclicked) - { - doubleclicked = false; - } - - else - { - scroll(1); - } - - clickcheck = 0; - }); - } - - break; - case MIDDLE: - break; - case NUMBER_KEY: - break; - case RIGHT: - if(element != null) - { - element.call(ElementEvent.RIGHT, element); - } - - else - { - scroll(-1); - } - break; - case SHIFT_LEFT: - if(element != null) - { - element.call(ElementEvent.SHIFT_LEFT, element); - } - break; - case SHIFT_RIGHT: - if(element != null) - { - element.call(ElementEvent.SHIFT_RIGHT, element); - } - break; - case WINDOW_BORDER_LEFT: - break; - case WINDOW_BORDER_RIGHT: - break; - case UNKNOWN: - break; - case SWAP_OFFHAND: - break; - default: - break; - } - } - - e.setCancelled(true); - - } - - @EventHandler - public void on(InventoryCloseEvent e) - { - if(!e.getPlayer().equals(viewer)) - { - return; - } - - if(!e.getPlayer().getOpenInventory().getTitle().equals(title)) - { - return; - } - - if(isVisible()) - { - close(); - callClosed(); - } - } - - @Override - public UIWindow setDecorator(WindowDecorator decorator) - { - this.decorator = decorator; - return this; - } - - @Override - public WindowDecorator getDecorator() - { - return decorator; - } - - @Override - public UIWindow close() - { - setVisible(false); - return this; - } - - @Override - public UIWindow open() - { - setVisible(true); - return this; - } - - @Override - public UIWindow setVisible(boolean visible) - { - if(isVisible() == visible) - { - return this; - } - - if(visible) - { - Bukkit.getPluginManager().registerEvents(this, Iris.instance); - - if(getResolution().getType().equals(InventoryType.CHEST)) - { - inventory = Bukkit.createInventory(null, getViewportHeight() * 9, getTitle()); - } - - else - { - inventory = Bukkit.createInventory(null, getResolution().getType(), getTitle()); - } - - viewer.openInventory(inventory); - this.visible = visible; - updateInventory(); - } - - else - { - this.visible = visible; - HandlerList.unregisterAll(this); - viewer.closeInventory(); - } - - this.visible = visible; - return this; - } - - @Override - public boolean isVisible() - { - return visible; - } - - @Override - public int getViewportPosition() - { - return viewportPosition; - } - - @Override - public UIWindow setViewportPosition(int viewportPosition) - { - this.viewportPosition = viewportPosition; - scroll(0); - updateInventory(); - - return this; - } - - @Override - public int getMaxViewportPosition() - { - return Math.max(0, highestRow - getViewportHeight()); - } - - @Override - public UIWindow scroll(int direction) - { - viewportPosition = (int) clip(viewportPosition + direction, 0, getMaxViewportPosition()).doubleValue(); - updateInventory(); - - return this; - } - - @Override - public int getViewportHeight() - { - return viewportSize; - } - - @Override - public UIWindow setViewportHeight(int height) - { - viewportSize = (int) clip(height, 1, getResolution().getMaxHeight()).doubleValue(); - - if(isVisible()) - { - reopen(); - } - - return this; - } - - @Override - public String getTitle() - { - return title; - } - - @Override - public UIWindow setTitle(String title) - { - this.title = title; - - if(isVisible()) - { - reopen(); - } - - return this; - } - - @Override - public UIWindow setElement(int position, int row, Element e) - { - if(row > highestRow) - { - highestRow = row; - } - - elements.put(getRealPosition((int) clip(position, -getResolution().getMaxWidthOffset(), getResolution().getMaxWidthOffset()).doubleValue(), row), e); - updateInventory(); - return this; - } - - @Override - public Element getElement(int position, int row) - { - return elements.get(getRealPosition((int) clip(position, -getResolution().getMaxWidthOffset(), getResolution().getMaxWidthOffset()).doubleValue(), row)); - } - - @Override - public Player getViewer() - { - return viewer; - } - - @Override - public UIWindow onClosed(Callback window) - { - eClose = window; - return this; - } - - @Override - public int getViewportSlots() - { - return getViewportHeight() * getResolution().getWidth(); - } - - @Override - public int getLayoutRow(int viewportSlottedPosition) - { - return getRow(getRealLayoutPosition(viewportSlottedPosition)); - } - - @Override - public int getLayoutPosition(int viewportSlottedPosition) - { - return getPosition(viewportSlottedPosition); - } - - @Override - public int getRealLayoutPosition(int viewportSlottedPosition) - { - return getRealPosition(getPosition(viewportSlottedPosition), getRow(viewportSlottedPosition) + getViewportPosition()); - } - - @Override - public int getRealPosition(int position, int row) - { - return (int) (((row * getResolution().getWidth()) + getResolution().getMaxWidthOffset()) + clip(position, -getResolution().getMaxWidthOffset(), getResolution().getMaxWidthOffset())); - } - - @Override - public int getRow(int realPosition) - { - return realPosition / getResolution().getWidth(); - } - - @Override - public int getPosition(int realPosition) - { - return (realPosition % getResolution().getWidth()) - getResolution().getMaxWidthOffset(); - } - - @Override - public Window callClosed() - { - if(eClose != null) - { - eClose.run(this); - } - - return this; - } - - @Override - public boolean hasElement(int position, int row) - { - return getElement(position, row) != null; - } - - @Override - public WindowResolution getResolution() - { - return resolution; - } - - public Double clip(double value, double min, double max) - { - return Double.valueOf(Math.min(max, Math.max(min, value))); - } - - @Override - public Window setResolution(WindowResolution resolution) - { - close(); - this.resolution = resolution; - setViewportHeight((int) clip(getViewportHeight(), 1, getResolution().getMaxHeight()).doubleValue()); - return this; - } - - @Override - public Window clearElements() - { - highestRow = 0; - elements.clear(); - updateInventory(); - return this; - } - - @Override - public Window updateInventory() - { - if(isVisible()) - { - ItemStack[] is = inventory.getContents(); - KSet isf = new KSet(); - - for(int i = 0; i < is.length; i++) - { - ItemStack isc = is[i]; - ItemStack isx = computeItemStack(i); - int layoutRow = getLayoutRow(i); - int layoutPosition = getLayoutPosition(i); - - if(isx != null && !hasElement(layoutPosition, layoutRow)) - { - ItemStack gg = isx.clone(); - gg.setAmount(gg.getAmount() + 1); - isf.add(gg); - } - - if(((isc == null) != (isx == null)) || isx != null && isc != null && !isc.equals(isx)) - { - inventory.setItem(i, isx); - } - } - } - - return this; - } - - @Override - public ItemStack computeItemStack(int viewportSlot) - { - int layoutRow = getLayoutRow(viewportSlot); - int layoutPosition = getLayoutPosition(viewportSlot); - Element e = hasElement(layoutPosition, layoutRow) ? getElement(layoutPosition, layoutRow) : getDecorator().onDecorateBackground(this, layoutPosition, layoutRow); - - if(e != null) - { - return e.computeItemStack(); - } - - return null; - } - - @Override - public Window reopen() - { - return this.close().open(); - } +public class UIWindow implements Window, Listener { + private WindowDecorator decorator; + private final Player viewer; + private Callback eClose; + private WindowResolution resolution; + private final KMap elements; + private String title; + private boolean visible; + private int viewportPosition; + private int viewportSize; + private int highestRow; + private Inventory inventory; + private int clickcheck; + private boolean doubleclicked; + + public UIWindow(Player viewer) { + clickcheck = 0; + doubleclicked = false; + this.viewer = viewer; + this.elements = new KMap<>(); + setTitle(""); + setDecorator(new UIVoidDecorator()); + setResolution(WindowResolution.W9_H6); + setViewportHeight(clip(3, 1, getResolution().getMaxHeight()).intValue()); + setViewportPosition(0); + } + + @EventHandler + public void on(InventoryClickEvent e) { + if (!e.getWhoClicked().equals(viewer)) { + return; + } + + if (!isVisible()) { + return; + } + + // 1.14 bukkit api change, removed getTitle() and getName() from Inventory.class + if (!viewer.getOpenInventory().getTitle().equals(title)) { + return; + } + + if (e.getClickedInventory() == null) { + return; + } + + if (!e.getView().getType().equals(getResolution().getType())) { + return; + } + + if (e.getClickedInventory().getType().equals(getResolution().getType())) { + Element element = getElement(getLayoutPosition(e.getSlot()), getLayoutRow(e.getSlot())); + + switch (e.getAction()) { + case CLONE_STACK: + break; + case COLLECT_TO_CURSOR: + break; + case DROP_ALL_CURSOR: + break; + case DROP_ALL_SLOT: + break; + case DROP_ONE_CURSOR: + break; + case DROP_ONE_SLOT: + break; + case HOTBAR_MOVE_AND_READD: + break; + case HOTBAR_SWAP: + break; + case MOVE_TO_OTHER_INVENTORY: + break; + case NOTHING: + break; + case PICKUP_ALL: + break; + case PICKUP_HALF: + break; + case PICKUP_ONE: + break; + case PICKUP_SOME: + break; + case PLACE_ALL: + break; + case PLACE_ONE: + break; + case PLACE_SOME: + break; + case SWAP_WITH_CURSOR: + break; + case UNKNOWN: + break; + } + + switch (e.getClick()) { + case CONTROL_DROP: + break; + case CREATIVE: + break; + case DOUBLE_CLICK: + doubleclicked = true; + break; + case DROP: + break; + case LEFT: + + clickcheck++; + + if (clickcheck == 1) { + J.s(() -> + { + if (clickcheck == 1) { + clickcheck = 0; + + if (element != null) { + element.call(ElementEvent.LEFT, element); + } + } + }); + } else if (clickcheck == 2) { + J.s(() -> + { + if (doubleclicked) { + doubleclicked = false; + } else { + scroll(1); + } + + clickcheck = 0; + }); + } + + break; + case MIDDLE: + break; + case NUMBER_KEY: + break; + case RIGHT: + if (element != null) { + element.call(ElementEvent.RIGHT, element); + } else { + scroll(-1); + } + break; + case SHIFT_LEFT: + if (element != null) { + element.call(ElementEvent.SHIFT_LEFT, element); + } + break; + case SHIFT_RIGHT: + if (element != null) { + element.call(ElementEvent.SHIFT_RIGHT, element); + } + break; + case WINDOW_BORDER_LEFT: + break; + case WINDOW_BORDER_RIGHT: + break; + case UNKNOWN: + break; + case SWAP_OFFHAND: + break; + default: + break; + } + } + + e.setCancelled(true); + + } + + @EventHandler + public void on(InventoryCloseEvent e) { + if (!e.getPlayer().equals(viewer)) { + return; + } + + if (!e.getPlayer().getOpenInventory().getTitle().equals(title)) { + return; + } + + if (isVisible()) { + close(); + callClosed(); + } + } + + @Override + public UIWindow setDecorator(WindowDecorator decorator) { + this.decorator = decorator; + return this; + } + + @Override + public WindowDecorator getDecorator() { + return decorator; + } + + @Override + public UIWindow close() { + setVisible(false); + return this; + } + + @Override + public UIWindow open() { + setVisible(true); + return this; + } + + @Override + public UIWindow setVisible(boolean visible) { + if (isVisible() == visible) { + return this; + } + + if (visible) { + Bukkit.getPluginManager().registerEvents(this, Iris.instance); + + if (getResolution().getType().equals(InventoryType.CHEST)) { + inventory = Bukkit.createInventory(null, getViewportHeight() * 9, getTitle()); + } else { + inventory = Bukkit.createInventory(null, getResolution().getType(), getTitle()); + } + + viewer.openInventory(inventory); + this.visible = visible; + updateInventory(); + } else { + this.visible = visible; + HandlerList.unregisterAll(this); + viewer.closeInventory(); + } + + this.visible = visible; + return this; + } + + @Override + public boolean isVisible() { + return visible; + } + + @Override + public int getViewportPosition() { + return viewportPosition; + } + + @Override + public UIWindow setViewportPosition(int viewportPosition) { + this.viewportPosition = viewportPosition; + scroll(0); + updateInventory(); + + return this; + } + + @Override + public int getMaxViewportPosition() { + return Math.max(0, highestRow - getViewportHeight()); + } + + @Override + public UIWindow scroll(int direction) { + viewportPosition = (int) clip(viewportPosition + direction, 0, getMaxViewportPosition()).doubleValue(); + updateInventory(); + + return this; + } + + @Override + public int getViewportHeight() { + return viewportSize; + } + + @Override + public UIWindow setViewportHeight(int height) { + viewportSize = (int) clip(height, 1, getResolution().getMaxHeight()).doubleValue(); + + if (isVisible()) { + reopen(); + } + + return this; + } + + @Override + public String getTitle() { + return title; + } + + @Override + public UIWindow setTitle(String title) { + this.title = title; + + if (isVisible()) { + reopen(); + } + + return this; + } + + @Override + public UIWindow setElement(int position, int row, Element e) { + if (row > highestRow) { + highestRow = row; + } + + elements.put(getRealPosition((int) clip(position, -getResolution().getMaxWidthOffset(), getResolution().getMaxWidthOffset()).doubleValue(), row), e); + updateInventory(); + return this; + } + + @Override + public Element getElement(int position, int row) { + return elements.get(getRealPosition((int) clip(position, -getResolution().getMaxWidthOffset(), getResolution().getMaxWidthOffset()).doubleValue(), row)); + } + + @Override + public Player getViewer() { + return viewer; + } + + @Override + public UIWindow onClosed(Callback window) { + eClose = window; + return this; + } + + @Override + public int getViewportSlots() { + return getViewportHeight() * getResolution().getWidth(); + } + + @Override + public int getLayoutRow(int viewportSlottedPosition) { + return getRow(getRealLayoutPosition(viewportSlottedPosition)); + } + + @Override + public int getLayoutPosition(int viewportSlottedPosition) { + return getPosition(viewportSlottedPosition); + } + + @Override + public int getRealLayoutPosition(int viewportSlottedPosition) { + return getRealPosition(getPosition(viewportSlottedPosition), getRow(viewportSlottedPosition) + getViewportPosition()); + } + + @Override + public int getRealPosition(int position, int row) { + return (int) (((row * getResolution().getWidth()) + getResolution().getMaxWidthOffset()) + clip(position, -getResolution().getMaxWidthOffset(), getResolution().getMaxWidthOffset())); + } + + @Override + public int getRow(int realPosition) { + return realPosition / getResolution().getWidth(); + } + + @Override + public int getPosition(int realPosition) { + return (realPosition % getResolution().getWidth()) - getResolution().getMaxWidthOffset(); + } + + @Override + public Window callClosed() { + if (eClose != null) { + eClose.run(this); + } + + return this; + } + + @Override + public boolean hasElement(int position, int row) { + return getElement(position, row) != null; + } + + @Override + public WindowResolution getResolution() { + return resolution; + } + + public Double clip(double value, double min, double max) { + return Double.valueOf(Math.min(max, Math.max(min, value))); + } + + @Override + public Window setResolution(WindowResolution resolution) { + close(); + this.resolution = resolution; + setViewportHeight((int) clip(getViewportHeight(), 1, getResolution().getMaxHeight()).doubleValue()); + return this; + } + + @Override + public Window clearElements() { + highestRow = 0; + elements.clear(); + updateInventory(); + return this; + } + + @Override + public Window updateInventory() { + if (isVisible()) { + ItemStack[] is = inventory.getContents(); + KSet isf = new KSet(); + + for (int i = 0; i < is.length; i++) { + ItemStack isc = is[i]; + ItemStack isx = computeItemStack(i); + int layoutRow = getLayoutRow(i); + int layoutPosition = getLayoutPosition(i); + + if (isx != null && !hasElement(layoutPosition, layoutRow)) { + ItemStack gg = isx.clone(); + gg.setAmount(gg.getAmount() + 1); + isf.add(gg); + } + + if (((isc == null) != (isx == null)) || isx != null && isc != null && !isc.equals(isx)) { + inventory.setItem(i, isx); + } + } + } + + return this; + } + + @Override + public ItemStack computeItemStack(int viewportSlot) { + int layoutRow = getLayoutRow(viewportSlot); + int layoutPosition = getLayoutPosition(viewportSlot); + Element e = hasElement(layoutPosition, layoutRow) ? getElement(layoutPosition, layoutRow) : getDecorator().onDecorateBackground(this, layoutPosition, layoutRow); + + if (e != null) { + return e.computeItemStack(); + } + + return null; + } + + @Override + public Window reopen() { + return this.close().open(); + } } diff --git a/src/main/java/com/volmit/iris/util/V.java b/src/main/java/com/volmit/iris/util/V.java index 7bde92bdf..db7584c1b 100644 --- a/src/main/java/com/volmit/iris/util/V.java +++ b/src/main/java/com/volmit/iris/util/V.java @@ -2,153 +2,111 @@ package com.volmit.iris.util; import java.lang.annotation.Annotation; -public class V -{ - private Object o; - private boolean local; - private boolean suppress = false; +public class V { + private final Object o; + private boolean local; + private boolean suppress = false; - public V(Class c, Object... parameters) - { - this.o = Violator.construct(c, parameters); - this.local = true; - } + public V(Class c, Object... parameters) { + this.o = Violator.construct(c, parameters); + this.local = true; + } - public V(Object o) - { - this.o = o; - this.local = true; - } + public V(Object o) { + this.o = o; + this.local = true; + } - public V(Object o, boolean local, boolean suppress) - { - this(o); - this.local = local; - this.suppress = suppress; - } + public V(Object o, boolean local, boolean suppress) { + this(o); + this.local = local; + this.suppress = suppress; + } - public V(Object o, boolean local) - { - this(o); - this.local = local; - } + public V(Object o, boolean local) { + this(o); + this.local = local; + } - public T get(Class t) - { - try - { - return (T) (local ? Violator.getDeclaredAnnotation(o.getClass(), t) : Violator.getAnnotation(o.getClass(), t)); - } + public T get(Class t) { + try { + return local ? Violator.getDeclaredAnnotation(o.getClass(), t) : Violator.getAnnotation(o.getClass(), t); + } catch (Throwable e) { + if (!suppress) { + e.printStackTrace(); + } + } - catch(Throwable e) - { - if(!suppress) - { - e.printStackTrace(); - } - } + return null; + } - return null; - } + public T get(Class t, String mn, Class... pars) { + try { + return local ? Violator.getDeclaredAnnotation(Violator.getDeclaredMethod(o.getClass(), mn, pars), t) : Violator.getAnnotation(Violator.getMethod(o.getClass(), mn, pars), t); + } catch (Throwable e) { + if (!suppress) { + e.printStackTrace(); + } + } - public T get(Class t, String mn, Class... pars) - { - try - { - return (T) (local ? Violator.getDeclaredAnnotation(Violator.getDeclaredMethod(o.getClass(), mn, pars), t) : Violator.getAnnotation(Violator.getMethod(o.getClass(), mn, pars), t)); - } + return null; + } - catch(Throwable e) - { - if(!suppress) - { - e.printStackTrace(); - } - } + public T get(Class t, String mn) { + try { + return local ? Violator.getDeclaredAnnotation(Violator.getDeclaredField(o.getClass(), mn), t) : Violator.getAnnotation(Violator.getField(o.getClass(), mn), t); + } catch (Throwable e) { + if (!suppress) { + e.printStackTrace(); + } + } - return null; - } + return null; + } - public T get(Class t, String mn) - { - try - { - return (T) (local ? Violator.getDeclaredAnnotation(Violator.getDeclaredField(o.getClass(), mn), t) : Violator.getAnnotation(Violator.getField(o.getClass(), mn), t)); - } + @SuppressWarnings("unchecked") + public T get(String field) { + try { + return (T) (local ? Violator.getDeclaredField(o.getClass(), field) : Violator.getField(o.getClass(), field)).get(o); + } catch (Throwable e) { + if (!suppress) { + e.printStackTrace(); + } + } - catch(Throwable e) - { - if(!suppress) - { - e.printStackTrace(); - } - } + return null; + } - return null; - } + public Object getSelf() { + return o; + } - @SuppressWarnings("unchecked") - public T get(String field) - { - try - { - return (T) (local ? Violator.getDeclaredField(o.getClass(), field) : Violator.getField(o.getClass(), field)).get(o); - } + public Object invoke(String method, Object... parameters) { + KList> par = new KList>(); - catch(Throwable e) - { - if(!suppress) - { - e.printStackTrace(); - } - } + for (Object i : parameters) { + par.add(i.getClass()); + } - return null; - } + try { + return (local ? Violator.getDeclaredMethod(o.getClass(), method, par.toArray(new Class[par.size()])) : Violator.getMethod(o.getClass(), method, par.toArray(new Class[par.size()]))).invoke(o, parameters); + } catch (Throwable e) { + if (!suppress) { + e.printStackTrace(); + } + } - public Object getSelf() { - return o; - } + return null; + } - public Object invoke(String method, Object... parameters) - { - KList> par = new KList>(); - - for(Object i : parameters) - { - par.add(i.getClass()); - } - - try - { - return (local ? Violator.getDeclaredMethod(o.getClass(), method, par.toArray(new Class[par.size()])) : Violator.getMethod(o.getClass(), method, par.toArray(new Class[par.size()]))).invoke(o, parameters); - } - - catch(Throwable e) - { - if(!suppress) - { - e.printStackTrace(); - } - } - - return null; - } - - public void set(String field, Object value) - { - try - { - // https://github.com/VolmitSoftware/Mortar/issues/5 - (local ? Violator.getDeclaredField(o.getClass(), field) : Violator.getField(o.getClass(), field)).set(o, value); - } - - catch(Throwable e) - { - if(!suppress) - { - e.printStackTrace(); - } - } - } + public void set(String field, Object value) { + try { + // https://github.com/VolmitSoftware/Mortar/issues/5 + (local ? Violator.getDeclaredField(o.getClass(), field) : Violator.getField(o.getClass(), field)).set(o, value); + } catch (Throwable e) { + if (!suppress) { + e.printStackTrace(); + } + } + } } diff --git a/src/main/java/com/volmit/iris/util/VecMathUtil.java b/src/main/java/com/volmit/iris/util/VecMathUtil.java index 9663f3e1c..7843bcf43 100644 --- a/src/main/java/com/volmit/iris/util/VecMathUtil.java +++ b/src/main/java/com/volmit/iris/util/VecMathUtil.java @@ -56,13 +56,12 @@ class VecMathUtil { * number, after first mapping -0.0f to 0.0f */ static int floatToIntBits(float f) { - // Check for +0 or -0 - if (f == 0.0f) { - return 0; - } - else { - return Float.floatToIntBits(f); - } + // Check for +0 or -0 + if (f == 0.0f) { + return 0; + } else { + return Float.floatToIntBits(f); + } } /** @@ -85,13 +84,12 @@ class VecMathUtil { * number, after first mapping -0.0f to 0.0f */ static long doubleToLongBits(double d) { - // Check for +0 or -0 - if (d == 0.0) { - return 0L; - } - else { - return Double.doubleToLongBits(d); - } + // Check for +0 or -0 + if (d == 0.0) { + return 0L; + } else { + return Double.doubleToLongBits(d); + } } diff --git a/src/main/java/com/volmit/iris/util/Vector2d.java b/src/main/java/com/volmit/iris/util/Vector2d.java index ba837a852..28832de38 100644 --- a/src/main/java/com/volmit/iris/util/Vector2d.java +++ b/src/main/java/com/volmit/iris/util/Vector2d.java @@ -31,12 +31,9 @@ package com.volmit.iris.util; -import java.lang.Math; - /** - * A 2-element vector that is represented by double-precision floating + * A 2-element vector that is represented by double-precision floating * point x,y coordinates. - * */ public class Vector2d extends Tuple2d implements java.io.Serializable { @@ -45,143 +42,140 @@ public class Vector2d extends Tuple2d implements java.io.Serializable { /** * Constructs and initializes a Vector2d from the specified xy coordinates. + * * @param x the x coordinate * @param y the y coordinate */ - public Vector2d(double x, double y) - { - super(x,y); + public Vector2d(double x, double y) { + super(x, y); } /** * Constructs and initializes a Vector2d from the specified array. + * * @param v the array of length 2 containing xy in order */ - public Vector2d(double[] v) - { - super(v); + public Vector2d(double[] v) { + super(v); } /** * Constructs and initializes a Vector2d from the specified Vector2d. + * * @param v1 the Vector2d containing the initialization x y data */ - public Vector2d(Vector2d v1) - { - super(v1); + public Vector2d(Vector2d v1) { + super(v1); } /** * Constructs and initializes a Vector2d from the specified Vector2f. + * * @param v1 the Vector2f containing the initialization x y data */ - public Vector2d(Vector2f v1) - { - super(v1); + public Vector2d(Vector2f v1) { + super(v1); } /** * Constructs and initializes a Vector2d from the specified Tuple2d. + * * @param t1 the Tuple2d containing the initialization x y data - */ - public Vector2d(Tuple2d t1) - { - super(t1); + */ + public Vector2d(Tuple2d t1) { + super(t1); } /** * Constructs and initializes a Vector2d from the specified Tuple2f. + * * @param t1 the Tuple2f containing the initialization x y data - */ - public Vector2d(Tuple2f t1) - { - super(t1); + */ + public Vector2d(Tuple2f t1) { + super(t1); } /** * Constructs and initializes a Vector2d to (0,0). */ - public Vector2d() - { + public Vector2d() { super(); } - /** - * Computes the dot product of the this vector and vector v1. - * @param v1 the other vector - */ - public final double dot(Vector2d v1) - { - return (this.x*v1.x + this.y*v1.y); + /** + * Computes the dot product of the this vector and vector v1. + * + * @param v1 the other vector + */ + public final double dot(Vector2d v1) { + return (this.x * v1.x + this.y * v1.y); } - /** + /** * Returns the length of this vector. + * * @return the length of this vector - */ - public final double length() - { - return (double) Math.sqrt(this.x*this.x + this.y*this.y); + */ + public final double length() { + return Math.sqrt(this.x * this.x + this.y * this.y); } - /** + /** * Returns the squared length of this vector. + * * @return the squared length of this vector - */ - public final double lengthSquared() - { - return (this.x*this.x + this.y*this.y); + */ + public final double lengthSquared() { + return (this.x * this.x + this.y * this.y); } /** * Sets the value of this vector to the normalization of vector v1. + * * @param v1 the un-normalized vector - */ - public final void normalize(Vector2d v1) - { + */ + public final void normalize(Vector2d v1) { double norm; - norm = (double) (1.0/Math.sqrt(v1.x*v1.x + v1.y*v1.y)); - this.x = v1.x*norm; - this.y = v1.y*norm; + norm = 1.0 / Math.sqrt(v1.x * v1.x + v1.y * v1.y); + this.x = v1.x * norm; + this.y = v1.y * norm; } /** * Normalizes this vector in place. - */ - public final void normalize() - { + */ + public final void normalize() { double norm; - norm = (double) - (1.0/Math.sqrt(this.x*this.x + this.y*this.y)); + norm = 1.0 / Math.sqrt(this.x * this.x + this.y * this.y); this.x *= norm; this.y *= norm; } - /** - * Returns the angle in radians between this vector and the vector - * parameter; the return value is constrained to the range [0,PI]. - * @param v1 the other vector - * @return the angle in radians in the range [0,PI] - */ - public final double angle(Vector2d v1) - { - double vDot = this.dot(v1) / ( this.length()*v1.length() ); - if( vDot < -1.0) vDot = -1.0; - if( vDot > 1.0) vDot = 1.0; - return((double) (Math.acos( vDot ))); + /** + * Returns the angle in radians between this vector and the vector + * parameter; the return value is constrained to the range [0,PI]. + * + * @param v1 the other vector + * @return the angle in radians in the range [0,PI] + */ + public final double angle(Vector2d v1) { + double vDot = this.dot(v1) / (this.length() * v1.length()); + if (vDot < -1.0) vDot = -1.0; + if (vDot > 1.0) vDot = 1.0; + return Math.acos(vDot); - } + } } diff --git a/src/main/java/com/volmit/iris/util/Vector2f.java b/src/main/java/com/volmit/iris/util/Vector2f.java index c4036afea..c148580c1 100644 --- a/src/main/java/com/volmit/iris/util/Vector2f.java +++ b/src/main/java/com/volmit/iris/util/Vector2f.java @@ -31,12 +31,9 @@ package com.volmit.iris.util; -import java.lang.Math; - /** - * A 2-element vector that is represented by single-precision floating + * A 2-element vector that is represented by single-precision floating * point x,y coordinates. - * */ public class Vector2f extends Tuple2f implements java.io.Serializable { @@ -45,143 +42,140 @@ public class Vector2f extends Tuple2f implements java.io.Serializable { /** * Constructs and initializes a Vector2f from the specified xy coordinates. + * * @param x the x coordinate * @param y the y coordinate */ - public Vector2f(float x, float y) - { - super(x,y); + public Vector2f(float x, float y) { + super(x, y); } /** * Constructs and initializes a Vector2f from the specified array. + * * @param v the array of length 2 containing xy in order */ - public Vector2f(float[] v) - { - super(v); + public Vector2f(float[] v) { + super(v); } /** * Constructs and initializes a Vector2f from the specified Vector2f. + * * @param v1 the Vector2f containing the initialization x y data */ - public Vector2f(Vector2f v1) - { - super(v1); + public Vector2f(Vector2f v1) { + super(v1); } /** * Constructs and initializes a Vector2f from the specified Vector2d. + * * @param v1 the Vector2d containing the initialization x y data */ - public Vector2f(Vector2d v1) - { - super(v1); + public Vector2f(Vector2d v1) { + super(v1); } /** * Constructs and initializes a Vector2f from the specified Tuple2f. + * * @param t1 the Tuple2f containing the initialization x y data - */ - public Vector2f(Tuple2f t1) - { - super(t1); + */ + public Vector2f(Tuple2f t1) { + super(t1); } /** * Constructs and initializes a Vector2f from the specified Tuple2d. + * * @param t1 the Tuple2d containing the initialization x y data - */ - public Vector2f(Tuple2d t1) - { - super(t1); + */ + public Vector2f(Tuple2d t1) { + super(t1); } - /** * Constructs and initializes a Vector2f to (0,0). */ - public Vector2f() - { + public Vector2f() { super(); } - /** - * Computes the dot product of the this vector and vector v1. - * @param v1 the other vector - */ - public final float dot(Vector2f v1) - { - return (this.x*v1.x + this.y*v1.y); + /** + * Computes the dot product of the this vector and vector v1. + * + * @param v1 the other vector + */ + public final float dot(Vector2f v1) { + return (this.x * v1.x + this.y * v1.y); } - /** + /** * Returns the length of this vector. + * * @return the length of this vector - */ - public final float length() - { - return (float) Math.sqrt(this.x*this.x + this.y*this.y); + */ + public final float length() { + return (float) Math.sqrt(this.x * this.x + this.y * this.y); } - /** + /** * Returns the squared length of this vector. + * * @return the squared length of this vector - */ - public final float lengthSquared() - { - return (this.x*this.x + this.y*this.y); + */ + public final float lengthSquared() { + return (this.x * this.x + this.y * this.y); } /** * Sets the value of this vector to the normalization of vector v1. + * * @param v1 the un-normalized vector - */ - public final void normalize(Vector2f v1) - { + */ + public final void normalize(Vector2f v1) { float norm; - norm = (float) (1.0/Math.sqrt(v1.x*v1.x + v1.y*v1.y)); - this.x = v1.x*norm; - this.y = v1.y*norm; + norm = (float) (1.0 / Math.sqrt(v1.x * v1.x + v1.y * v1.y)); + this.x = v1.x * norm; + this.y = v1.y * norm; } /** * Normalizes this vector in place. - */ - public final void normalize() - { + */ + public final void normalize() { float norm; norm = (float) - (1.0/Math.sqrt(this.x*this.x + this.y*this.y)); + (1.0 / Math.sqrt(this.x * this.x + this.y * this.y)); this.x *= norm; this.y *= norm; } - /** - * Returns the angle in radians between this vector and the vector - * parameter; the return value is constrained to the range [0,PI]. - * @param v1 the other vector - * @return the angle in radians in the range [0,PI] - */ - public final float angle(Vector2f v1) - { - double vDot = this.dot(v1) / ( this.length()*v1.length() ); - if( vDot < -1.0) vDot = -1.0; - if( vDot > 1.0) vDot = 1.0; - return((float) (Math.acos( vDot ))); - } + /** + * Returns the angle in radians between this vector and the vector + * parameter; the return value is constrained to the range [0,PI]. + * + * @param v1 the other vector + * @return the angle in radians in the range [0,PI] + */ + public final float angle(Vector2f v1) { + double vDot = this.dot(v1) / (this.length() * v1.length()); + if (vDot < -1.0) vDot = -1.0; + if (vDot > 1.0) vDot = 1.0; + return ((float) (Math.acos(vDot))); + } } diff --git a/src/main/java/com/volmit/iris/util/Vector3d.java b/src/main/java/com/volmit/iris/util/Vector3d.java index 11fe91b01..584d729bf 100644 --- a/src/main/java/com/volmit/iris/util/Vector3d.java +++ b/src/main/java/com/volmit/iris/util/Vector3d.java @@ -31,13 +31,10 @@ package com.volmit.iris.util; -import java.lang.Math; - /** - * A 3-element vector that is represented by double-precision floating point + * A 3-element vector that is represented by double-precision floating point * x,y,z coordinates. If this value represents a normal, then it should * be normalized. - * */ public class Vector3d extends Tuple3d implements java.io.Serializable { @@ -46,87 +43,86 @@ public class Vector3d extends Tuple3d implements java.io.Serializable { /** * Constructs and initializes a Vector3d from the specified xyz coordinates. + * * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate */ - public Vector3d(double x, double y, double z) - { - super(x,y,z); + public Vector3d(double x, double y, double z) { + super(x, y, z); } /** * Constructs and initializes a Vector3d from the array of length 3. + * * @param v the array of length 3 containing xyz in order */ - public Vector3d(double[] v) - { - super(v); + public Vector3d(double[] v) { + super(v); } /** * Constructs and initializes a Vector3d from the specified Vector3d. + * * @param v1 the Vector3d containing the initialization x y z data */ - public Vector3d(Vector3d v1) - { - super(v1); + public Vector3d(Vector3d v1) { + super(v1); } /** * Constructs and initializes a Vector3d from the specified Vector3f. + * * @param v1 the Vector3f containing the initialization x y z data */ - public Vector3d(Vector3f v1) - { - super(v1); + public Vector3d(Vector3f v1) { + super(v1); } /** * Constructs and initializes a Vector3d from the specified Tuple3f. + * * @param t1 the Tuple3f containing the initialization x y z data - */ - public Vector3d(Tuple3f t1) - { - super(t1); + */ + public Vector3d(Tuple3f t1) { + super(t1); } /** * Constructs and initializes a Vector3d from the specified Tuple3d. - * @param t1 the Tuple3d containing the initialization x y z data - */ - public Vector3d(Tuple3d t1) - { - super(t1); + * + * @param t1 the Tuple3d containing the initialization x y z data + */ + public Vector3d(Tuple3d t1) { + super(t1); } /** * Constructs and initializes a Vector3d to (0,0,0). */ - public Vector3d() - { - super(); + public Vector3d() { + super(); } - /** + /** * Sets this vector to the vector cross product of vectors v1 and v2. + * * @param v1 the first vector * @param v2 the second vector */ - public final void cross(Vector3d v1, Vector3d v2) - { - double x,y; + public final void cross(Vector3d v1, Vector3d v2) { + double x, y; - x = v1.y*v2.z - v1.z*v2.y; - y = v2.x*v1.z - v2.z*v1.x; - this.z = v1.x*v2.y - v1.y*v2.x; + x = v1.y * v2.z - v1.z * v2.y; + y = v2.x * v1.z - v2.z * v1.x; + this.z = v1.x * v2.y - v1.y * v2.x; this.x = x; this.y = y; } @@ -134,77 +130,76 @@ public class Vector3d extends Tuple3d implements java.io.Serializable { /** * Sets the value of this vector to the normalization of vector v1. + * * @param v1 the un-normalized vector */ - public final void normalize(Vector3d v1) - { + public final void normalize(Vector3d v1) { double norm; - norm = 1.0/Math.sqrt(v1.x*v1.x + v1.y*v1.y + v1.z*v1.z); - this.x = v1.x*norm; - this.y = v1.y*norm; - this.z = v1.z*norm; + norm = 1.0 / Math.sqrt(v1.x * v1.x + v1.y * v1.y + v1.z * v1.z); + this.x = v1.x * norm; + this.y = v1.y * norm; + this.z = v1.z * norm; } /** * Normalizes this vector in place. */ - public final void normalize() - { + public final void normalize() { double norm; - norm = 1.0/Math.sqrt(this.x*this.x + this.y*this.y + this.z*this.z); + norm = 1.0 / Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); this.x *= norm; this.y *= norm; this.z *= norm; } - /** - * Returns the dot product of this vector and vector v1. - * @param v1 the other vector - * @return the dot product of this and v1 - */ - public final double dot(Vector3d v1) - { - return (this.x*v1.x + this.y*v1.y + this.z*v1.z); + /** + * Returns the dot product of this vector and vector v1. + * + * @param v1 the other vector + * @return the dot product of this and v1 + */ + public final double dot(Vector3d v1) { + return (this.x * v1.x + this.y * v1.y + this.z * v1.z); } /** * Returns the squared length of this vector. + * * @return the squared length of this vector */ - public final double lengthSquared() - { - return (this.x*this.x + this.y*this.y + this.z*this.z); + public final double lengthSquared() { + return (this.x * this.x + this.y * this.y + this.z * this.z); } /** * Returns the length of this vector. + * * @return the length of this vector */ - public final double length() - { - return Math.sqrt(this.x*this.x + this.y*this.y + this.z*this.z); + public final double length() { + return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); } - /** - * Returns the angle in radians between this vector and the vector - * parameter; the return value is constrained to the range [0,PI]. - * @param v1 the other vector - * @return the angle in radians in the range [0,PI] - */ - public final double angle(Vector3d v1) - { - double vDot = this.dot(v1) / ( this.length()*v1.length() ); - if( vDot < -1.0) vDot = -1.0; - if( vDot > 1.0) vDot = 1.0; - return((double) (Math.acos( vDot ))); - } - + /** + * Returns the angle in radians between this vector and the vector + * parameter; the return value is constrained to the range [0,PI]. + * + * @param v1 the other vector + * @return the angle in radians in the range [0,PI] + */ + public final double angle(Vector3d v1) { + double vDot = this.dot(v1) / (this.length() * v1.length()); + if (vDot < -1.0) vDot = -1.0; + if (vDot > 1.0) vDot = 1.0; + return Math.acos(vDot); + } + } diff --git a/src/main/java/com/volmit/iris/util/Vector3f.java b/src/main/java/com/volmit/iris/util/Vector3f.java index ae95498ea..329b6959e 100644 --- a/src/main/java/com/volmit/iris/util/Vector3f.java +++ b/src/main/java/com/volmit/iris/util/Vector3f.java @@ -31,13 +31,10 @@ package com.volmit.iris.util; -import java.lang.Math; - /** - * A 3-element vector that is represented by single-precision floating point + * A 3-element vector that is represented by single-precision floating point * x,y,z coordinates. If this value represents a normal, then it should * be normalized. - * */ public class Vector3f extends Tuple3f implements java.io.Serializable { @@ -46,160 +43,160 @@ public class Vector3f extends Tuple3f implements java.io.Serializable { /** * Constructs and initializes a Vector3f from the specified xyz coordinates. + * * @param x the x coordinate * @param y the y coordinate * @param z the z coordinate */ - public Vector3f(float x, float y, float z) - { - super(x,y,z); + public Vector3f(float x, float y, float z) { + super(x, y, z); } /** * Constructs and initializes a Vector3f from the array of length 3. + * * @param v the array of length 3 containing xyz in order */ - public Vector3f(float[] v) - { - super(v); + public Vector3f(float[] v) { + super(v); } /** * Constructs and initializes a Vector3f from the specified Vector3f. + * * @param v1 the Vector3f containing the initialization x y z data */ - public Vector3f(Vector3f v1) - { - super(v1); + public Vector3f(Vector3f v1) { + super(v1); } /** * Constructs and initializes a Vector3f from the specified Vector3d. + * * @param v1 the Vector3d containing the initialization x y z data */ - public Vector3f(Vector3d v1) - { - super(v1); + public Vector3f(Vector3d v1) { + super(v1); } /** * Constructs and initializes a Vector3f from the specified Tuple3f. + * * @param t1 the Tuple3f containing the initialization x y z data - */ + */ public Vector3f(Tuple3f t1) { - super(t1); + super(t1); } /** * Constructs and initializes a Vector3f from the specified Tuple3d. + * * @param t1 the Tuple3d containing the initialization x y z data - */ + */ public Vector3f(Tuple3d t1) { - super(t1); + super(t1); } /** * Constructs and initializes a Vector3f to (0,0,0). */ - public Vector3f() - { + public Vector3f() { super(); } - /** + /** * Returns the squared length of this vector. + * * @return the squared length of this vector */ - public final float lengthSquared() - { - return (this.x*this.x + this.y*this.y + this.z*this.z); + public final float lengthSquared() { + return (this.x * this.x + this.y * this.y + this.z * this.z); } /** * Returns the length of this vector. + * * @return the length of this vector */ - public final float length() - { + public final float length() { return (float) - Math.sqrt(this.x*this.x + this.y*this.y + this.z*this.z); + Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); } - /** + /** * Sets this vector to be the vector cross product of vectors v1 and v2. + * * @param v1 the first vector * @param v2 the second vector */ - public final void cross(Vector3f v1, Vector3f v2) - { - float x,y; + public final void cross(Vector3f v1, Vector3f v2) { + float x, y; - x = v1.y*v2.z - v1.z*v2.y; - y = v2.x*v1.z - v2.z*v1.x; - this.z = v1.x*v2.y - v1.y*v2.x; + x = v1.y * v2.z - v1.z * v2.y; + y = v2.x * v1.z - v2.z * v1.x; + this.z = v1.x * v2.y - v1.y * v2.x; this.x = x; this.y = y; } - /** - * Computes the dot product of this vector and vector v1. - * @param v1 the other vector - * @return the dot product of this vector and v1 - */ - public final float dot(Vector3f v1) - { - return (this.x*v1.x + this.y*v1.y + this.z*v1.z); + /** + * Computes the dot product of this vector and vector v1. + * + * @param v1 the other vector + * @return the dot product of this vector and v1 + */ + public final float dot(Vector3f v1) { + return (this.x * v1.x + this.y * v1.y + this.z * v1.z); } - /** + /** * Sets the value of this vector to the normalization of vector v1. + * * @param v1 the un-normalized vector */ - public final void normalize(Vector3f v1) - { + public final void normalize(Vector3f v1) { float norm; - norm = (float) (1.0/Math.sqrt(v1.x*v1.x + v1.y*v1.y + v1.z*v1.z)); - this.x = v1.x*norm; - this.y = v1.y*norm; - this.z = v1.z*norm; + norm = (float) (1.0 / Math.sqrt(v1.x * v1.x + v1.y * v1.y + v1.z * v1.z)); + this.x = v1.x * norm; + this.y = v1.y * norm; + this.z = v1.z * norm; } /** * Normalizes this vector in place. */ - public final void normalize() - { + public final void normalize() { float norm; norm = (float) - (1.0/Math.sqrt(this.x*this.x + this.y*this.y + this.z*this.z)); + (1.0 / Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z)); this.x *= norm; this.y *= norm; this.z *= norm; } - /** - * Returns the angle in radians between this vector and the vector - * parameter; the return value is constrained to the range [0,PI]. - * @param v1 the other vector - * @return the angle in radians in the range [0,PI] - */ - public final float angle(Vector3f v1) - { - double vDot = this.dot(v1) / ( this.length()*v1.length() ); - if( vDot < -1.0) vDot = -1.0; - if( vDot > 1.0) vDot = 1.0; - return((float) (Math.acos( vDot ))); - } + /** + * Returns the angle in radians between this vector and the vector + * parameter; the return value is constrained to the range [0,PI]. + * + * @param v1 the other vector + * @return the angle in radians in the range [0,PI] + */ + public final float angle(Vector3f v1) { + double vDot = this.dot(v1) / (this.length() * v1.length()); + if (vDot < -1.0) vDot = -1.0; + if (vDot > 1.0) vDot = 1.0; + return ((float) (Math.acos(vDot))); + } } diff --git a/src/main/java/com/volmit/iris/util/VectorMath.java b/src/main/java/com/volmit/iris/util/VectorMath.java index c0061c8a0..cd587f343 100644 --- a/src/main/java/com/volmit/iris/util/VectorMath.java +++ b/src/main/java/com/volmit/iris/util/VectorMath.java @@ -12,741 +12,588 @@ import org.bukkit.util.Vector; * * @author cyberpwn */ -public class VectorMath -{ - public static Vector scaleStatic(Axis x, Vector v, double amt) - { - switch(x) - { - case X: - return scaleX(v, amt); - case Y: - return scaleY(v, amt); - case Z: - return scaleZ(v, amt); - } - - return null; - } - - public static Vector scaleX(Vector v, double amt) - { - double x = v.getX(); - double y = v.getY(); - double z = v.getZ(); - double rx = x == 0 ? 1 : amt / x; - - return new Vector(x * rx, y * rx, z * rx); - } - - public static Vector scaleY(Vector v, double amt) - { - double x = v.getX(); - double y = v.getY(); - double z = v.getZ(); - double rx = y == 0 ? 1 : amt / y; - - return new Vector(x * rx, y * rx, z * rx); - } - - public static Vector scaleZ(Vector v, double amt) - { - double x = v.getX(); - double y = v.getY(); - double z = v.getZ(); - double rx = z == 0 ? 1 : amt / z; - - return new Vector(x * rx, y * rx, z * rx); - } - - public static Vector reverseXZ(Vector v) - { - v.setX(-v.getX()); - v.setZ(-v.getZ()); - return v; - } - - public static boolean isLookingNear(Location a, Location b, double maxOff) - { - Vector perfect = VectorMath.direction(a, b); - Vector actual = a.getDirection(); - - return perfect.distance(actual) <= maxOff; - } - - public static Vector rotate(Direction current, Direction to, Vector v) - { - if(current.equals(to)) - { - return v; - } - - else if(current.equals(to.reverse())) - { - if(current.isVertical()) - { - return new Vector(v.getX(), -v.getY(), v.getZ()); - } - - else - { - return new Vector(-v.getX(), v.getY(), -v.getZ()); - } - } - - else - { - Vector c = current.toVector().clone().add(to.toVector()); - - if(c.getX() == 0) - { - if(c.getY() != c.getZ()) - { - return rotate90CX(v); - } - - return rotate90CCX(v); - } - - else if(c.getY() == 0) - { - if(c.getX() != c.getZ()) - { - return rotate90CY(v); - } - - return rotate90CCY(v); - } - - else if(c.getZ() == 0) - { - if(c.getX() != c.getY()) - { - return rotate90CZ(v); - } - - return rotate90CCZ(v); - } - } - - return v; - } - - // Y X 0 0 - // X Z 0 0 - - // 0 X Y 0 - // 0 Z X 0 - - public static Vector rotate(Direction current, Direction to, Vector v, int w, int h, int d) - { - if(current.equals(to)) - { - return v; - } - - else if(current.equals(to.reverse())) - { - if(current.isVertical()) - { - return new Vector(v.getX(), -v.getY() + h, v.getZ()); - } - - else - { - return new Vector(-v.getX() + w, v.getY(), -v.getZ() + d); - } - } - - else - { - Vector c = current.toVector().clone().add(to.toVector()); - - if(c.getX() == 0) - { - if(c.getY() != c.getZ()) - { - return rotate90CX(v, d); - } - - return rotate90CCX(v, h); - } - - else if(c.getY() == 0) - { - if(c.getX() != c.getZ()) - { - return rotate90CY(v, d); - } - - return rotate90CCY(v, w); - } - - else if(c.getZ() == 0) - { - if(c.getX() != c.getY()) - { - return rotate90CZ(v, w); - } - - return rotate90CCZ(v, h); - } - } - - return v; - } - - public static Vector rotate90CX(Vector v) - { - return new Vector(v.getX(), -v.getZ(), v.getY()); - } - - public static Vector rotate90CCX(Vector v) - { - return new Vector(v.getX(), v.getZ(), -v.getY()); - } - - public static Vector rotate90CY(Vector v) - { - return new Vector(-v.getZ(), v.getY(), v.getX()); - } - - public static Vector rotate90CCY(Vector v) - { - return new Vector(v.getZ(), v.getY(), -v.getX()); - } - - public static Vector rotate90CZ(Vector v) - { - return new Vector(v.getY(), -v.getX(), v.getZ()); - } - - public static Vector rotate90CCZ(Vector v) - { - return new Vector(-v.getY(), v.getX(), v.getZ()); - } - - public static Vector rotate90CX(Vector v, int s) - { - return new Vector(v.getX(), -v.getZ() + s, v.getY()); - } - - public static Vector rotate90CCX(Vector v, int s) - { - return new Vector(v.getX(), v.getZ(), -v.getY() + s); - } - - public static Vector rotate90CY(Vector v, int s) - { - return new Vector(-v.getZ() + s, v.getY(), v.getX()); - } - - public static Vector rotate90CCY(Vector v, int s) - { - return new Vector(v.getZ(), v.getY(), -v.getX() + s); - } - - public static Vector rotate90CZ(Vector v, int s) - { - return new Vector(v.getY(), -v.getX() + s, v.getZ()); - } - - public static Vector rotate90CCZ(Vector v, int s) - { - return new Vector(-v.getY() + s, v.getX(), v.getZ()); - } - - public static Vector getAxis(Direction current, Direction to) - { - if(current.equals(Direction.U) || current.equals(Direction.D)) - { - if(to.equals(Direction.U) || to.equals(Direction.D)) - { - return new Vector(1, 0, 0); - } - - else - { - if(current.equals(Direction.N) || current.equals(Direction.S)) - { - return Direction.E.toVector(); - } - - else - { - return Direction.S.toVector(); - } - } - } - - return new Vector(0, 1, 0); - } - - private static double round(double value, int precision) - { - return Double.valueOf(Form.f(value, precision)); - } - - public static Vector clip(Vector v, int decimals) - { - v.setX(round(v.getX(), decimals)); - v.setY(round(v.getY(), decimals)); - v.setZ(round(v.getZ(), decimals)); - return v; - } - - public static Vector rotateVectorCC(Vector vec, Vector axis, double deg) - { - double theta = Math.toRadians(deg); - double x, y, z; - double u, v, w; - x = vec.getX(); - y = vec.getY(); - z = vec.getZ(); - u = axis.getX(); - v = axis.getY(); - w = axis.getZ(); - double xPrime = u * (u * x + v * y + w * z) * (1d - Math.cos(theta)) + x * Math.cos(theta) + (-w * y + v * z) * Math.sin(theta); - double yPrime = v * (u * x + v * y + w * z) * (1d - Math.cos(theta)) + y * Math.cos(theta) + (w * x - u * z) * Math.sin(theta); - double zPrime = w * (u * x + v * y + w * z) * (1d - Math.cos(theta)) + z * Math.cos(theta) + (-v * x + u * y) * Math.sin(theta); - - return clip(new Vector(xPrime, yPrime, zPrime), 4); - } - - /** - * Get all SIMPLE block faces from a more specific block face (SOUTH_EAST) = - * (south, east) - * - * @param f - * the block face - * @return multiple faces, or one if the face is already simple - */ - public static KList split(BlockFace f) - { - KList faces = new KList(); - - switch(f) - { - case DOWN: - faces.add(BlockFace.DOWN); - break; - case EAST: - faces.add(BlockFace.EAST); - break; - case EAST_NORTH_EAST: - faces.add(BlockFace.EAST); - faces.add(BlockFace.EAST); - faces.add(BlockFace.NORTH); - break; - case EAST_SOUTH_EAST: - faces.add(BlockFace.EAST); - faces.add(BlockFace.EAST); - faces.add(BlockFace.SOUTH); - break; - case NORTH: - faces.add(BlockFace.NORTH); - break; - case NORTH_EAST: - faces.add(BlockFace.NORTH); - faces.add(BlockFace.EAST); - break; - case NORTH_NORTH_EAST: - faces.add(BlockFace.NORTH); - faces.add(BlockFace.NORTH); - faces.add(BlockFace.EAST); - break; - case NORTH_NORTH_WEST: - faces.add(BlockFace.NORTH); - faces.add(BlockFace.NORTH); - faces.add(BlockFace.WEST); - break; - case NORTH_WEST: - faces.add(BlockFace.NORTH); - faces.add(BlockFace.WEST); - break; - case SELF: - faces.add(BlockFace.SELF); - break; - case SOUTH: - faces.add(BlockFace.SOUTH); - break; - case SOUTH_EAST: - faces.add(BlockFace.SOUTH); - faces.add(BlockFace.EAST); - break; - case SOUTH_SOUTH_EAST: - faces.add(BlockFace.SOUTH); - faces.add(BlockFace.SOUTH); - faces.add(BlockFace.EAST); - break; - case SOUTH_SOUTH_WEST: - faces.add(BlockFace.SOUTH); - faces.add(BlockFace.SOUTH); - faces.add(BlockFace.WEST); - break; - case SOUTH_WEST: - faces.add(BlockFace.SOUTH); - faces.add(BlockFace.WEST); - break; - case UP: - faces.add(BlockFace.UP); - break; - case WEST: - faces.add(BlockFace.WEST); - break; - case WEST_NORTH_WEST: - faces.add(BlockFace.WEST); - faces.add(BlockFace.WEST); - faces.add(BlockFace.NORTH); - break; - case WEST_SOUTH_WEST: - faces.add(BlockFace.WEST); - faces.add(BlockFace.WEST); - faces.add(BlockFace.SOUTH); - break; - default: - break; - } - - return faces; - } - - /** - * Get a normalized vector going from a location to another - * - * @param from - * from here - * @param to - * to here - * @return the normalized vector direction - */ - public static Vector direction(Location from, Location to) - { - return to.clone().subtract(from.clone()).toVector().normalize(); - } - - public static Vector directionNoNormal(Location from, Location to) - { - return to.clone().subtract(from.clone()).toVector(); - } - - /** - * Get the vector direction from the yaw and pitch - * - * @param yaw - * the yaw - * @param pitch - * the pitch - * @return the vector - */ - public static Vector toVector(float yaw, float pitch) - { - return new Vector(Math.cos(pitch) * Math.cos(yaw), Math.sin(pitch), Math.cos(pitch) * Math.sin(-yaw)); - } - - /** - * Add an impulse (force) to an entity - * - * @param e - * the entity - * @param v - * the vector - */ - public static void impulse(Entity e, Vector v) - { - impulse(e, v, 1.0); - } - - /** - * Add an impulse (force) on an entity - * - * @param e - * the entity - * @param v - * the vector - * @param effectiveness - * the effectiveness - */ - public static void impulse(Entity e, Vector v, double effectiveness) - { - Vector vx = e.getVelocity(); - vx.add(v.clone().multiply(effectiveness)); - e.setVelocity(vx); - } - - /** - * Reverse a direction - * - * @param v - * the direction - * @return the reversed direction - */ - public static Vector reverse(Vector v) - { - if(v.getX() != 0) - { - v.setX(-v.getX()); - } - - if(v.getY() != 0) - { - v.setY(-v.getY()); - } - - if(v.getZ() != 0) - { - v.setZ(-v.getZ()); - } - - return v; - } - - /** - * Get a speed value from a vector (velocity) - * - * @param v - * the vector - * @return the speed - */ - public static double getSpeed(Vector v) - { - Vector vi = new Vector(0, 0, 0); - Vector vt = new Vector(0, 0, 0).add(v); - - return vi.distance(vt); - } - - /** - * Shift all vectors based on the given vector - * - * @param vector - * the vector direction to shift the vectors - * @param vectors - * the vectors to be shifted - * @return the shifted vectors - */ - public static KList shift(Vector vector, KList vectors) - { - return new KList(new GListAdapter() - { - @Override - public Vector onAdapt(Vector from) - { - return from.add(vector); - } - }.adapt(vectors)); - } - - /** - * Attempt to get the blockFace for the vector (will be tri-normalized) - * - * @param v - * the vector - * @return the block face or null - */ - public static BlockFace getBlockFace(Vector v) - { - Vector p = triNormalize(v); - - for(BlockFace i : BlockFace.values()) - { - if(p.getX() == i.getModX() && p.getY() == i.getModY() && p.getZ() == i.getModZ()) - { - return i; - } - } - - for(BlockFace i : BlockFace.values()) - { - if(p.getX() == i.getModX() && p.getZ() == i.getModZ()) - { - return i; - } - } - - for(BlockFace i : BlockFace.values()) - { - if(p.getY() == i.getModY() && p.getZ() == i.getModZ()) - { - return i; - } - } - - for(BlockFace i : BlockFace.values()) - { - if(p.getX() == i.getModX() || p.getY() == i.getModY()) - { - return i; - } - } - - for(BlockFace i : BlockFace.values()) - { - if(p.getX() == i.getModX() || p.getY() == i.getModY() || p.getZ() == i.getModZ()) - { - return i; - } - } - - return null; - } - - /** - * Angle the vector in a self relative direction - * - * @param v - * the initial direction - * @param amt - * the amount to shift in the direction - * @return the shifted direction - */ - public static Vector angleLeft(Vector v, float amt) - { - Location l = new Location(Bukkit.getWorlds().get(0), 0, 0, 0); - l.setDirection(v); - float y = l.getYaw(); - float p = l.getPitch(); - CDou cy = new CDou(360); - CDou cp = new CDou(180); - cy.set(y); - cp.set(p); - cy.sub(amt); - l.setYaw((float) cy.get()); - l.setPitch((float) cp.get()); - - return l.getDirection(); - } - - /** - * Angle the vector in a self relative direction - * - * @param v - * the initial direction - * @param amt - * the amount to shift in the direction - * @return the shifted direction - */ - public static Vector angleRight(Vector v, float amt) - { - Location l = new Location(Bukkit.getWorlds().get(0), 0, 0, 0); - l.setDirection(v); - float y = l.getYaw(); - float p = l.getPitch(); - CDou cy = new CDou(360); - CDou cp = new CDou(180); - cy.set(y); - cp.set(p); - cy.add(amt); - l.setYaw((float) cy.get()); - l.setPitch((float) cp.get()); - - return l.getDirection(); - } - - /** - * Angle the vector in a self relative direction - * - * @param v - * the initial direction - * @param amt - * the amount to shift in the direction - * @return the shifted direction - */ - public static Vector angleUp(Vector v, float amt) - { - Location l = new Location(Bukkit.getWorlds().get(0), 0, 0, 0); - l.setDirection(v); - float y = l.getYaw(); - float p = l.getPitch(); - CDou cy = new CDou(360); - cy.set(y); - l.setYaw((float) cy.get()); - l.setPitch((float) Math.max(-90, p - amt)); - - return l.getDirection(); - } - - /** - * Angle the vector in a self relative direction - * - * @param v - * the initial direction - * @param amt - * the amount to shift in the direction - * @return the shifted direction - */ - public static Vector angleDown(Vector v, float amt) - { - Location l = new Location(Bukkit.getWorlds().get(0), 0, 0, 0); - l.setDirection(v); - float y = l.getYaw(); - float p = l.getPitch(); - CDou cy = new CDou(360); - cy.set(y); - l.setYaw((float) cy.get()); - l.setPitch((float) Math.min(90, p + amt)); - - return l.getDirection(); - } - - /** - * (clone) Force normalize the vector into three points, 1, 0, or -1. If the - * value is > 0.333 (1) if the value is less than -0.333 (-1) else 0 - * - * @param direction - * the direction - * @return the vector - */ - public static Vector triNormalize(Vector direction) - { - Vector v = direction.clone(); - v.normalize(); - - if(v.getX() > 0.333) - { - v.setX(1); - } - - else if(v.getX() < -0.333) - { - v.setX(-1); - } - - else - { - v.setX(0); - } - - if(v.getY() > 0.333) - { - v.setY(1); - } - - else if(v.getY() < -0.333) - { - v.setY(-1); - } - - else - { - v.setY(0); - } - - if(v.getZ() > 0.333) - { - v.setZ(1); - } - - else if(v.getZ() < -0.333) - { - v.setZ(-1); - } - - else - { - v.setZ(0); - } - - return v; - } +public class VectorMath { + public static Vector scaleStatic(Axis x, Vector v, double amt) { + switch (x) { + case X: + return scaleX(v, amt); + case Y: + return scaleY(v, amt); + case Z: + return scaleZ(v, amt); + } + + return null; + } + + public static Vector scaleX(Vector v, double amt) { + double x = v.getX(); + double y = v.getY(); + double z = v.getZ(); + double rx = x == 0 ? 1 : amt / x; + + return new Vector(x * rx, y * rx, z * rx); + } + + public static Vector scaleY(Vector v, double amt) { + double x = v.getX(); + double y = v.getY(); + double z = v.getZ(); + double rx = y == 0 ? 1 : amt / y; + + return new Vector(x * rx, y * rx, z * rx); + } + + public static Vector scaleZ(Vector v, double amt) { + double x = v.getX(); + double y = v.getY(); + double z = v.getZ(); + double rx = z == 0 ? 1 : amt / z; + + return new Vector(x * rx, y * rx, z * rx); + } + + public static Vector reverseXZ(Vector v) { + v.setX(-v.getX()); + v.setZ(-v.getZ()); + return v; + } + + public static boolean isLookingNear(Location a, Location b, double maxOff) { + Vector perfect = VectorMath.direction(a, b); + Vector actual = a.getDirection(); + + return perfect.distance(actual) <= maxOff; + } + + public static Vector rotate(Direction current, Direction to, Vector v) { + if (current.equals(to)) { + return v; + } else if (current.equals(to.reverse())) { + if (current.isVertical()) { + return new Vector(v.getX(), -v.getY(), v.getZ()); + } else { + return new Vector(-v.getX(), v.getY(), -v.getZ()); + } + } else { + Vector c = current.toVector().clone().add(to.toVector()); + + if (c.getX() == 0) { + if (c.getY() != c.getZ()) { + return rotate90CX(v); + } + + return rotate90CCX(v); + } else if (c.getY() == 0) { + if (c.getX() != c.getZ()) { + return rotate90CY(v); + } + + return rotate90CCY(v); + } else if (c.getZ() == 0) { + if (c.getX() != c.getY()) { + return rotate90CZ(v); + } + + return rotate90CCZ(v); + } + } + + return v; + } + + // Y X 0 0 + // X Z 0 0 + + // 0 X Y 0 + // 0 Z X 0 + + public static Vector rotate(Direction current, Direction to, Vector v, int w, int h, int d) { + if (current.equals(to)) { + return v; + } else if (current.equals(to.reverse())) { + if (current.isVertical()) { + return new Vector(v.getX(), -v.getY() + h, v.getZ()); + } else { + return new Vector(-v.getX() + w, v.getY(), -v.getZ() + d); + } + } else { + Vector c = current.toVector().clone().add(to.toVector()); + + if (c.getX() == 0) { + if (c.getY() != c.getZ()) { + return rotate90CX(v, d); + } + + return rotate90CCX(v, h); + } else if (c.getY() == 0) { + if (c.getX() != c.getZ()) { + return rotate90CY(v, d); + } + + return rotate90CCY(v, w); + } else if (c.getZ() == 0) { + if (c.getX() != c.getY()) { + return rotate90CZ(v, w); + } + + return rotate90CCZ(v, h); + } + } + + return v; + } + + public static Vector rotate90CX(Vector v) { + return new Vector(v.getX(), -v.getZ(), v.getY()); + } + + public static Vector rotate90CCX(Vector v) { + return new Vector(v.getX(), v.getZ(), -v.getY()); + } + + public static Vector rotate90CY(Vector v) { + return new Vector(-v.getZ(), v.getY(), v.getX()); + } + + public static Vector rotate90CCY(Vector v) { + return new Vector(v.getZ(), v.getY(), -v.getX()); + } + + public static Vector rotate90CZ(Vector v) { + return new Vector(v.getY(), -v.getX(), v.getZ()); + } + + public static Vector rotate90CCZ(Vector v) { + return new Vector(-v.getY(), v.getX(), v.getZ()); + } + + public static Vector rotate90CX(Vector v, int s) { + return new Vector(v.getX(), -v.getZ() + s, v.getY()); + } + + public static Vector rotate90CCX(Vector v, int s) { + return new Vector(v.getX(), v.getZ(), -v.getY() + s); + } + + public static Vector rotate90CY(Vector v, int s) { + return new Vector(-v.getZ() + s, v.getY(), v.getX()); + } + + public static Vector rotate90CCY(Vector v, int s) { + return new Vector(v.getZ(), v.getY(), -v.getX() + s); + } + + public static Vector rotate90CZ(Vector v, int s) { + return new Vector(v.getY(), -v.getX() + s, v.getZ()); + } + + public static Vector rotate90CCZ(Vector v, int s) { + return new Vector(-v.getY() + s, v.getX(), v.getZ()); + } + + public static Vector getAxis(Direction current, Direction to) { + if (current.equals(Direction.U) || current.equals(Direction.D)) { + if (to.equals(Direction.U) || to.equals(Direction.D)) { + return new Vector(1, 0, 0); + } else { + if (current.equals(Direction.N) || current.equals(Direction.S)) { + return Direction.E.toVector(); + } else { + return Direction.S.toVector(); + } + } + } + + return new Vector(0, 1, 0); + } + + private static double round(double value, int precision) { + return Double.valueOf(Form.f(value, precision)); + } + + public static Vector clip(Vector v, int decimals) { + v.setX(round(v.getX(), decimals)); + v.setY(round(v.getY(), decimals)); + v.setZ(round(v.getZ(), decimals)); + return v; + } + + public static Vector rotateVectorCC(Vector vec, Vector axis, double deg) { + double theta = Math.toRadians(deg); + double x, y, z; + double u, v, w; + x = vec.getX(); + y = vec.getY(); + z = vec.getZ(); + u = axis.getX(); + v = axis.getY(); + w = axis.getZ(); + double xPrime = u * (u * x + v * y + w * z) * (1d - Math.cos(theta)) + x * Math.cos(theta) + (-w * y + v * z) * Math.sin(theta); + double yPrime = v * (u * x + v * y + w * z) * (1d - Math.cos(theta)) + y * Math.cos(theta) + (w * x - u * z) * Math.sin(theta); + double zPrime = w * (u * x + v * y + w * z) * (1d - Math.cos(theta)) + z * Math.cos(theta) + (-v * x + u * y) * Math.sin(theta); + + return clip(new Vector(xPrime, yPrime, zPrime), 4); + } + + /** + * Get all SIMPLE block faces from a more specific block face (SOUTH_EAST) = + * (south, east) + * + * @param f the block face + * @return multiple faces, or one if the face is already simple + */ + public static KList split(BlockFace f) { + KList faces = new KList(); + + switch (f) { + case DOWN: + faces.add(BlockFace.DOWN); + break; + case EAST: + faces.add(BlockFace.EAST); + break; + case EAST_NORTH_EAST: + faces.add(BlockFace.EAST); + faces.add(BlockFace.EAST); + faces.add(BlockFace.NORTH); + break; + case EAST_SOUTH_EAST: + faces.add(BlockFace.EAST); + faces.add(BlockFace.EAST); + faces.add(BlockFace.SOUTH); + break; + case NORTH: + faces.add(BlockFace.NORTH); + break; + case NORTH_EAST: + faces.add(BlockFace.NORTH); + faces.add(BlockFace.EAST); + break; + case NORTH_NORTH_EAST: + faces.add(BlockFace.NORTH); + faces.add(BlockFace.NORTH); + faces.add(BlockFace.EAST); + break; + case NORTH_NORTH_WEST: + faces.add(BlockFace.NORTH); + faces.add(BlockFace.NORTH); + faces.add(BlockFace.WEST); + break; + case NORTH_WEST: + faces.add(BlockFace.NORTH); + faces.add(BlockFace.WEST); + break; + case SELF: + faces.add(BlockFace.SELF); + break; + case SOUTH: + faces.add(BlockFace.SOUTH); + break; + case SOUTH_EAST: + faces.add(BlockFace.SOUTH); + faces.add(BlockFace.EAST); + break; + case SOUTH_SOUTH_EAST: + faces.add(BlockFace.SOUTH); + faces.add(BlockFace.SOUTH); + faces.add(BlockFace.EAST); + break; + case SOUTH_SOUTH_WEST: + faces.add(BlockFace.SOUTH); + faces.add(BlockFace.SOUTH); + faces.add(BlockFace.WEST); + break; + case SOUTH_WEST: + faces.add(BlockFace.SOUTH); + faces.add(BlockFace.WEST); + break; + case UP: + faces.add(BlockFace.UP); + break; + case WEST: + faces.add(BlockFace.WEST); + break; + case WEST_NORTH_WEST: + faces.add(BlockFace.WEST); + faces.add(BlockFace.WEST); + faces.add(BlockFace.NORTH); + break; + case WEST_SOUTH_WEST: + faces.add(BlockFace.WEST); + faces.add(BlockFace.WEST); + faces.add(BlockFace.SOUTH); + break; + default: + break; + } + + return faces; + } + + /** + * Get a normalized vector going from a location to another + * + * @param from from here + * @param to to here + * @return the normalized vector direction + */ + public static Vector direction(Location from, Location to) { + return to.clone().subtract(from.clone()).toVector().normalize(); + } + + public static Vector directionNoNormal(Location from, Location to) { + return to.clone().subtract(from.clone()).toVector(); + } + + /** + * Get the vector direction from the yaw and pitch + * + * @param yaw the yaw + * @param pitch the pitch + * @return the vector + */ + public static Vector toVector(float yaw, float pitch) { + return new Vector(Math.cos(pitch) * Math.cos(yaw), Math.sin(pitch), Math.cos(pitch) * Math.sin(-yaw)); + } + + /** + * Add an impulse (force) to an entity + * + * @param e the entity + * @param v the vector + */ + public static void impulse(Entity e, Vector v) { + impulse(e, v, 1.0); + } + + /** + * Add an impulse (force) on an entity + * + * @param e the entity + * @param v the vector + * @param effectiveness the effectiveness + */ + public static void impulse(Entity e, Vector v, double effectiveness) { + Vector vx = e.getVelocity(); + vx.add(v.clone().multiply(effectiveness)); + e.setVelocity(vx); + } + + /** + * Reverse a direction + * + * @param v the direction + * @return the reversed direction + */ + public static Vector reverse(Vector v) { + if (v.getX() != 0) { + v.setX(-v.getX()); + } + + if (v.getY() != 0) { + v.setY(-v.getY()); + } + + if (v.getZ() != 0) { + v.setZ(-v.getZ()); + } + + return v; + } + + /** + * Get a speed value from a vector (velocity) + * + * @param v the vector + * @return the speed + */ + public static double getSpeed(Vector v) { + Vector vi = new Vector(0, 0, 0); + Vector vt = new Vector(0, 0, 0).add(v); + + return vi.distance(vt); + } + + /** + * Shift all vectors based on the given vector + * + * @param vector the vector direction to shift the vectors + * @param vectors the vectors to be shifted + * @return the shifted vectors + */ + public static KList shift(Vector vector, KList vectors) { + return new KList(new GListAdapter() { + @Override + public Vector onAdapt(Vector from) { + return from.add(vector); + } + }.adapt(vectors)); + } + + /** + * Attempt to get the blockFace for the vector (will be tri-normalized) + * + * @param v the vector + * @return the block face or null + */ + public static BlockFace getBlockFace(Vector v) { + Vector p = triNormalize(v); + + for (BlockFace i : BlockFace.values()) { + if (p.getX() == i.getModX() && p.getY() == i.getModY() && p.getZ() == i.getModZ()) { + return i; + } + } + + for (BlockFace i : BlockFace.values()) { + if (p.getX() == i.getModX() && p.getZ() == i.getModZ()) { + return i; + } + } + + for (BlockFace i : BlockFace.values()) { + if (p.getY() == i.getModY() && p.getZ() == i.getModZ()) { + return i; + } + } + + for (BlockFace i : BlockFace.values()) { + if (p.getX() == i.getModX() || p.getY() == i.getModY()) { + return i; + } + } + + for (BlockFace i : BlockFace.values()) { + if (p.getX() == i.getModX() || p.getY() == i.getModY() || p.getZ() == i.getModZ()) { + return i; + } + } + + return null; + } + + /** + * Angle the vector in a self relative direction + * + * @param v the initial direction + * @param amt the amount to shift in the direction + * @return the shifted direction + */ + public static Vector angleLeft(Vector v, float amt) { + Location l = new Location(Bukkit.getWorlds().get(0), 0, 0, 0); + l.setDirection(v); + float y = l.getYaw(); + float p = l.getPitch(); + CDou cy = new CDou(360); + CDou cp = new CDou(180); + cy.set(y); + cp.set(p); + cy.sub(amt); + l.setYaw((float) cy.get()); + l.setPitch((float) cp.get()); + + return l.getDirection(); + } + + /** + * Angle the vector in a self relative direction + * + * @param v the initial direction + * @param amt the amount to shift in the direction + * @return the shifted direction + */ + public static Vector angleRight(Vector v, float amt) { + Location l = new Location(Bukkit.getWorlds().get(0), 0, 0, 0); + l.setDirection(v); + float y = l.getYaw(); + float p = l.getPitch(); + CDou cy = new CDou(360); + CDou cp = new CDou(180); + cy.set(y); + cp.set(p); + cy.add(amt); + l.setYaw((float) cy.get()); + l.setPitch((float) cp.get()); + + return l.getDirection(); + } + + /** + * Angle the vector in a self relative direction + * + * @param v the initial direction + * @param amt the amount to shift in the direction + * @return the shifted direction + */ + public static Vector angleUp(Vector v, float amt) { + Location l = new Location(Bukkit.getWorlds().get(0), 0, 0, 0); + l.setDirection(v); + float y = l.getYaw(); + float p = l.getPitch(); + CDou cy = new CDou(360); + cy.set(y); + l.setYaw((float) cy.get()); + l.setPitch(Math.max(-90, p - amt)); + + return l.getDirection(); + } + + /** + * Angle the vector in a self relative direction + * + * @param v the initial direction + * @param amt the amount to shift in the direction + * @return the shifted direction + */ + public static Vector angleDown(Vector v, float amt) { + Location l = new Location(Bukkit.getWorlds().get(0), 0, 0, 0); + l.setDirection(v); + float y = l.getYaw(); + float p = l.getPitch(); + CDou cy = new CDou(360); + cy.set(y); + l.setYaw((float) cy.get()); + l.setPitch(Math.min(90, p + amt)); + + return l.getDirection(); + } + + /** + * (clone) Force normalize the vector into three points, 1, 0, or -1. If the + * value is > 0.333 (1) if the value is less than -0.333 (-1) else 0 + * + * @param direction the direction + * @return the vector + */ + public static Vector triNormalize(Vector direction) { + Vector v = direction.clone(); + v.normalize(); + + if (v.getX() > 0.333) { + v.setX(1); + } else if (v.getX() < -0.333) { + v.setX(-1); + } else { + v.setX(0); + } + + if (v.getY() > 0.333) { + v.setY(1); + } else if (v.getY() < -0.333) { + v.setY(-1); + } else { + v.setY(0); + } + + if (v.getZ() > 0.333) { + v.setZ(1); + } else if (v.getZ() < -0.333) { + v.setZ(-1); + } else { + v.setZ(0); + } + + return v; + } } diff --git a/src/main/java/com/volmit/iris/util/Violator.java b/src/main/java/com/volmit/iris/util/Violator.java index cf1de4b8c..e4a7c240e 100644 --- a/src/main/java/com/volmit/iris/util/Violator.java +++ b/src/main/java/com/volmit/iris/util/Violator.java @@ -6,297 +6,245 @@ import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.concurrent.ConcurrentSkipListMap; -public class Violator -{ - protected static ConcurrentSkipListMap nodes = new ConcurrentSkipListMap(); +public class Violator { + protected static ConcurrentSkipListMap nodes = new ConcurrentSkipListMap(); - private static String id(Object o, Object h) - { - if(o instanceof Field) - { - return id(((Field) o).getDeclaringClass(), null) + "." + ((Field) o).getName(); - } + private static String id(Object o, Object h) { + if (o instanceof Field) { + return id(((Field) o).getDeclaringClass(), null) + "." + ((Field) o).getName(); + } - if(o instanceof String) - { - return (String) o; - } + if (o instanceof String) { + return (String) o; + } - if(o instanceof Class) - { - return ((Class) o).getCanonicalName(); - } + if (o instanceof Class) { + return ((Class) o).getCanonicalName(); + } - if(o instanceof Constructor) - { - Constructor co = (Constructor) o; + if (o instanceof Constructor) { + Constructor co = (Constructor) o; - String mx = ""; + String mx = ""; - for(Class i : co.getParameterTypes()) - { - mx += "," + i.getCanonicalName(); - } + for (Class i : co.getParameterTypes()) { + mx += "," + i.getCanonicalName(); + } - mx = mx.length() >= 1 ? mx.substring(1) : mx; + mx = mx.length() >= 1 ? mx.substring(1) : mx; - return id(co.getDeclaringClass(), null) + "(" + mx + ")"; - } + return id(co.getDeclaringClass(), null) + "(" + mx + ")"; + } - if(o instanceof Method) - { - String mx = ""; + if (o instanceof Method) { + String mx = ""; - for(Class i : ((Method) o).getParameterTypes()) - { - mx += "," + i.getCanonicalName(); - } + for (Class i : ((Method) o).getParameterTypes()) { + mx += "," + i.getCanonicalName(); + } - mx = mx.length() >= 1 ? mx.substring(1) : mx; + mx = mx.length() >= 1 ? mx.substring(1) : mx; - return id(((Method) o).getDeclaringClass(), null) + "." + ((Method) o).getName() + "(" + mx + ")"; - } + return id(((Method) o).getDeclaringClass(), null) + "." + ((Method) o).getName() + "(" + mx + ")"; + } - if(o instanceof Annotation) - { - Annotation a = (Annotation) o; - return "@" + a.annotationType().getCanonicalName() + "[" + id(h, null) + "]"; - } + if (o instanceof Annotation) { + Annotation a = (Annotation) o; + return "@" + a.annotationType().getCanonicalName() + "[" + id(h, null) + "]"; + } - return o.hashCode() + o.toString(); - } + return o.hashCode() + o.toString(); + } - private static void p(String n, Object o) - { - nodes.put(n, o); - } + private static void p(String n, Object o) { + nodes.put(n, o); + } - private static boolean h(String n) - { - return nodes.containsKey(n); - } + private static boolean h(String n) { + return nodes.containsKey(n); + } - private static Object g(String n) - { - return nodes.get(n); - } + private static Object g(String n) { + return nodes.get(n); + } - public static Constructor getConstructor(Class c, Class... params) throws NoSuchMethodException, SecurityException - { - String mx = ""; + public static Constructor getConstructor(Class c, Class... params) throws NoSuchMethodException, SecurityException { + String mx = ""; - for(Class i : params) - { - mx += "," + i.getCanonicalName(); - } + for (Class i : params) { + mx += "," + i.getCanonicalName(); + } - mx = mx.length() >= 1 ? mx.substring(1) : mx; + mx = mx.length() >= 1 ? mx.substring(1) : mx; - if(!h(id(c, null) + "(" + mx + ")")) - { - Constructor co = c.getConstructor(params); - co.setAccessible(true); - p(id(co, null), co); - } + if (!h(id(c, null) + "(" + mx + ")")) { + Constructor co = c.getConstructor(params); + co.setAccessible(true); + p(id(co, null), co); + } - return (Constructor) g(id(c, null) + "(" + mx + ")"); - } + return (Constructor) g(id(c, null) + "(" + mx + ")"); + } - @SuppressWarnings("rawtypes") - public static Field getField(Class c, String name) throws Throwable - { - if(!h(id(c, null) + "." + name)) - { - try - { - Field f = c.getField(name); - f.setAccessible(true); - p(id(c, null) + "." + name, f); - } - catch(NoSuchFieldException e) - { - Class s = c.getSuperclass(); - if(null == s) - { - throw e; - } - Field f = s.getField(name); - f.setAccessible(true); - p(id(c, null) + "." + name, f); - } - } + @SuppressWarnings("rawtypes") + public static Field getField(Class c, String name) throws Throwable { + if (!h(id(c, null) + "." + name)) { + try { + Field f = c.getField(name); + f.setAccessible(true); + p(id(c, null) + "." + name, f); + } catch (NoSuchFieldException e) { + Class s = c.getSuperclass(); + if (null == s) { + throw e; + } + Field f = s.getField(name); + f.setAccessible(true); + p(id(c, null) + "." + name, f); + } + } - return (Field) g(id(c, null) + "." + name); - } + return (Field) g(id(c, null) + "." + name); + } - @SuppressWarnings("rawtypes") - public static Field getDeclaredField(Class c, String name) throws Throwable - { - if(!h(id(c, null) + "." + name)) - { - try - { - Field f = c.getDeclaredField(name); - f.setAccessible(true); - p(id(c, null) + "." + name, f); - } - catch(NoSuchFieldException e) - { - Class s = c.getSuperclass(); - if(null == s) - { - throw e; - } - Field f = s.getDeclaredField(name); - f.setAccessible(true); - p(id(c, null) + "." + name, f); - } - } + @SuppressWarnings("rawtypes") + public static Field getDeclaredField(Class c, String name) throws Throwable { + if (!h(id(c, null) + "." + name)) { + try { + Field f = c.getDeclaredField(name); + f.setAccessible(true); + p(id(c, null) + "." + name, f); + } catch (NoSuchFieldException e) { + Class s = c.getSuperclass(); + if (null == s) { + throw e; + } + Field f = s.getDeclaredField(name); + f.setAccessible(true); + p(id(c, null) + "." + name, f); + } + } - return (Field) g(id(c, null) + "." + name); - } + return (Field) g(id(c, null) + "." + name); + } - public static Method getMethod(Class c, String name, Class... pars) throws Throwable - { - String iv = ""; - String mx = ""; + public static Method getMethod(Class c, String name, Class... pars) throws Throwable { + String iv = ""; + String mx = ""; - for(Class i : pars) - { - mx += "," + i.getCanonicalName(); - } + for (Class i : pars) { + mx += "," + i.getCanonicalName(); + } - mx = mx.length() >= 1 ? mx.substring(1) : mx; - iv = id(c, null) + "." + name + "(" + mx + ")"; + mx = mx.length() >= 1 ? mx.substring(1) : mx; + iv = id(c, null) + "." + name + "(" + mx + ")"; - if(!h(iv)) - { - Method f = c.getMethod(name, pars); - f.setAccessible(true); - p(iv, f); - } + if (!h(iv)) { + Method f = c.getMethod(name, pars); + f.setAccessible(true); + p(iv, f); + } - return (Method) g(iv); - } + return (Method) g(iv); + } - @SuppressWarnings("unchecked") - public static T construct(Class c, Object... parameters) - { - KList> cv = new KList>(); + @SuppressWarnings("unchecked") + public static T construct(Class c, Object... parameters) { + KList> cv = new KList>(); - for(Object i : parameters) - { - cv.add(i.getClass()); - } + for (Object i : parameters) { + cv.add(i.getClass()); + } - try - { - Constructor co = getConstructor(c, cv.toArray(new Class[cv.size()])); - return (T) co.newInstance(parameters); - } + try { + Constructor co = getConstructor(c, cv.toArray(new Class[cv.size()])); + return (T) co.newInstance(parameters); + } catch (Exception e) { + e.printStackTrace(); + } - catch(Exception e) - { - e.printStackTrace(); - } + return null; + } - return null; - } + public static Method getDeclaredMethod(Class c, String name, Class... pars) throws Throwable { + String iv = ""; + String mx = ""; - public static Method getDeclaredMethod(Class c, String name, Class... pars) throws Throwable - { - String iv = ""; - String mx = ""; + for (Class i : pars) { + mx += "," + i.getCanonicalName(); + } - for(Class i : pars) - { - mx += "," + i.getCanonicalName(); - } + mx = mx.length() >= 1 ? mx.substring(1) : mx; + iv = id(c, null) + "." + name + "(" + mx + ")"; - mx = mx.length() >= 1 ? mx.substring(1) : mx; - iv = id(c, null) + "." + name + "(" + mx + ")"; + if (!h(iv)) { + Method f = c.getDeclaredMethod(name, pars); + f.setAccessible(true); + p(iv, f); + } - if(!h(iv)) - { - Method f = c.getDeclaredMethod(name, pars); - f.setAccessible(true); - p(iv, f); - } + return (Method) g(iv); + } - return (Method) g(iv); - } + @SuppressWarnings("unchecked") + public static T getAnnotation(Class c, Class a) throws Throwable { + if (!h("@" + a.getCanonicalName() + "[" + c.getCanonicalName() + "]")) { + T f = c.getAnnotation(a); + p(id(f, c), f); + } - @SuppressWarnings("unchecked") - public static T getAnnotation(Class c, Class a) throws Throwable - { - if(!h("@" + a.getCanonicalName() + "[" + c.getCanonicalName() + "]")) - { - T f = c.getAnnotation(a); - p(id(f, c), f); - } + return (T) g("@" + a.getCanonicalName() + "[" + c.getCanonicalName() + "]"); + } - return (T) g("@" + a.getCanonicalName() + "[" + c.getCanonicalName() + "]"); - } + @SuppressWarnings("unchecked") + public static T getDeclaredAnnotation(Class c, Class a) throws Throwable { + if (!h("@" + a.getCanonicalName() + "[" + c.getCanonicalName() + "]")) { + T f = c.getDeclaredAnnotation(a); + p(id(f, c), f); + } - @SuppressWarnings("unchecked") - public static T getDeclaredAnnotation(Class c, Class a) throws Throwable - { - if(!h("@" + a.getCanonicalName() + "[" + c.getCanonicalName() + "]")) - { - T f = c.getDeclaredAnnotation(a); - p(id(f, c), f); - } + return (T) g("@" + a.getCanonicalName() + "[" + c.getCanonicalName() + "]"); + } - return (T) g("@" + a.getCanonicalName() + "[" + c.getCanonicalName() + "]"); - } + @SuppressWarnings("unchecked") + public static T getAnnotation(Field c, Class a) throws Throwable { + if (!h("@" + a.getCanonicalName() + "[" + id(c, null) + "]")) { + T f = c.getAnnotation(a); + p(id(f, c), f); + } - @SuppressWarnings("unchecked") - public static T getAnnotation(Field c, Class a) throws Throwable - { - if(!h("@" + a.getCanonicalName() + "[" + id(c, null) + "]")) - { - T f = c.getAnnotation(a); - p(id(f, c), f); - } + return (T) g("@" + a.getCanonicalName() + "[" + id(c, null) + "]"); + } - return (T) g("@" + a.getCanonicalName() + "[" + id(c, null) + "]"); - } + @SuppressWarnings("unchecked") + public static T getDeclaredAnnotation(Field c, Class a) throws Throwable { + if (!h("@" + a.getCanonicalName() + "[" + id(c, null) + "]")) { + T f = c.getDeclaredAnnotation(a); + p(id(f, c), f); + } - @SuppressWarnings("unchecked") - public static T getDeclaredAnnotation(Field c, Class a) throws Throwable - { - if(!h("@" + a.getCanonicalName() + "[" + id(c, null) + "]")) - { - T f = c.getDeclaredAnnotation(a); - p(id(f, c), f); - } + return (T) g("@" + a.getCanonicalName() + "[" + id(c, null) + "]"); + } - return (T) g("@" + a.getCanonicalName() + "[" + id(c, null) + "]"); - } + @SuppressWarnings("unchecked") + public static T getAnnotation(Method c, Class a) throws Throwable { + if (!h("@" + a.getCanonicalName() + "[" + id(c, null) + "]")) { + T f = c.getAnnotation(a); + p(id(f, c), f); + } - @SuppressWarnings("unchecked") - public static T getAnnotation(Method c, Class a) throws Throwable - { - if(!h("@" + a.getCanonicalName() + "[" + id(c, null) + "]")) - { - T f = c.getAnnotation(a); - p(id(f, c), f); - } + return (T) g("@" + a.getCanonicalName() + "[" + id(c, null) + "]"); + } - return (T) g("@" + a.getCanonicalName() + "[" + id(c, null) + "]"); - } + @SuppressWarnings("unchecked") + public static T getDeclaredAnnotation(Method c, Class a) throws Throwable { + if (!h("@" + a.getCanonicalName() + "[" + id(c, null) + "]")) { + T f = c.getDeclaredAnnotation(a); + p(id(f, c), f); - @SuppressWarnings("unchecked") - public static T getDeclaredAnnotation(Method c, Class a) throws Throwable - { - if(!h("@" + a.getCanonicalName() + "[" + id(c, null) + "]")) - { - T f = c.getDeclaredAnnotation(a); - p(id(f, c), f); + System.out.println("Set as " + id(f, c) + " as " + ("@" + a.getCanonicalName() + "[" + id(c, null) + "]")); + } - System.out.println("Set as " + id(f, c) + " as " + ("@" + a.getCanonicalName() + "[" + id(c, null) + "]")); - } - - return (T) g("@" + a.getCanonicalName() + "[" + id(c, null) + "]"); - } + return (T) g("@" + a.getCanonicalName() + "[" + id(c, null) + "]"); + } } diff --git a/src/main/java/com/volmit/iris/util/VirtualCommand.java b/src/main/java/com/volmit/iris/util/VirtualCommand.java index 688219703..08604881d 100644 --- a/src/main/java/com/volmit/iris/util/VirtualCommand.java +++ b/src/main/java/com/volmit/iris/util/VirtualCommand.java @@ -13,185 +13,149 @@ import java.lang.reflect.Field; * subcommands. * * @author cyberpwn - * */ -public class VirtualCommand -{ - private ICommand command; - private String tag; +public class VirtualCommand { + private final ICommand command; + private final String tag; - private KMap, VirtualCommand> children; + private final KMap, VirtualCommand> children; - public VirtualCommand(ICommand command) - { - this(command, ""); - } + public VirtualCommand(ICommand command) { + this(command, ""); + } - public VirtualCommand(ICommand command, String tag) - { - this.command = command; - children = new KMap, VirtualCommand>(); - this.tag = tag; + public VirtualCommand(ICommand command, String tag) { + this.command = command; + children = new KMap, VirtualCommand>(); + this.tag = tag; - for(Field i : command.getClass().getDeclaredFields()) - { - if(i.isAnnotationPresent(Command.class)) - { - try - { - Command cc = i.getAnnotation(Command.class); - ICommand cmd = (ICommand) i.getType().getConstructor().newInstance(); - new V(command, true, true).set(i.getName(), cmd); - children.put(cmd.getAllNodes(), new VirtualCommand(cmd, cc.value().trim().isEmpty() ? tag : cc.value().trim())); - } + for (Field i : command.getClass().getDeclaredFields()) { + if (i.isAnnotationPresent(Command.class)) { + try { + Command cc = i.getAnnotation(Command.class); + ICommand cmd = (ICommand) i.getType().getConstructor().newInstance(); + new V(command, true, true).set(i.getName(), cmd); + children.put(cmd.getAllNodes(), new VirtualCommand(cmd, cc.value().trim().isEmpty() ? tag : cc.value().trim())); + } catch (Exception e) { + e.printStackTrace(); + } + } + } + } - catch(Exception e) - { - e.printStackTrace(); - } - } - } - } + public String getTag() { + return tag; + } - public String getTag() - { - return tag; - } + public ICommand getCommand() { + return command; + } - public ICommand getCommand() - { - return command; - } + public KMap, VirtualCommand> getChildren() { + return children; + } - public KMap, VirtualCommand> getChildren() - { - return children; - } + public boolean hit(CommandSender sender, KList chain) { + return hit(sender, chain, null); + } - public boolean hit(CommandSender sender, KList chain) - { - return hit(sender, chain, null); - } + public boolean hit(CommandSender sender, KList chain, String label) { + MortarSender vs = new MortarSender(sender); + vs.setTag(tag); - public boolean hit(CommandSender sender, KList chain, String label) - { - MortarSender vs = new MortarSender(sender); - vs.setTag(tag); + if (label != null) { + vs.setCommand(label); + } - if(label != null) - { - vs.setCommand(label); - } + if (chain.isEmpty()) { + if (!checkPermissions(sender, command)) { + return true; + } - if(chain.isEmpty()) - { - if(!checkPermissions(sender, command)) - { - return true; - } + return command.handle(vs, new String[0]); + } - return command.handle(vs, new String[0]); - } + String nl = chain.get(0); - String nl = chain.get(0); + for (KList i : children.k()) { + for (String j : i) { + if (j.equalsIgnoreCase(nl)) { + vs.setCommand(chain.get(0)); + VirtualCommand cmd = children.get(i); + KList c = chain.copy(); + c.remove(0); + if (cmd.hit(sender, c, vs.getCommand())) { + if (vs.isPlayer() && IrisSettings.get().getGeneral().isCommandSounds()) { + vs.player().getWorld().playSound(vs.player().getLocation(), Sound.ITEM_AXE_STRIP, 0.35f, 1.8f); + } - for(KList i : children.k()) - { - for(String j : i) - { - if(j.equalsIgnoreCase(nl)) - { - vs.setCommand(chain.get(0)); - VirtualCommand cmd = children.get(i); - KList c = chain.copy(); - c.remove(0); - if(cmd.hit(sender, c, vs.getCommand())) - { - if(vs.isPlayer() && IrisSettings.get().getGeneral().isCommandSounds()) - { - vs.player().getWorld().playSound(vs.player().getLocation(), Sound.ITEM_AXE_STRIP, 0.35f, 1.8f); - } + return true; + } + } + } + } - return true; - } - } - } - } + if (!checkPermissions(sender, command)) { + return true; + } - if(!checkPermissions(sender, command)) - { - return true; - } + return command.handle(vs, chain.toArray(new String[chain.size()])); + } - return command.handle(vs, chain.toArray(new String[chain.size()])); - } + public KList hitTab(CommandSender sender, KList chain, String label) { + MortarSender vs = new MortarSender(sender); + vs.setTag(tag); - public KList hitTab(CommandSender sender, KList chain, String label) - { - MortarSender vs = new MortarSender(sender); - vs.setTag(tag); + if (label != null) + vs.setCommand(label); - if(label != null) - vs.setCommand(label); + if (chain.isEmpty()) { + if (!checkPermissions(sender, command)) { + return null; + } - if(chain.isEmpty()) - { - if(!checkPermissions(sender, command)) - { - return null; - } + return command.handleTab(vs, new String[0]); + } - return command.handleTab(vs, new String[0]); - } + String nl = chain.get(0); - String nl = chain.get(0); + for (KList i : children.k()) { + for (String j : i) { + if (j.equalsIgnoreCase(nl)) { + vs.setCommand(chain.get(0)); + VirtualCommand cmd = children.get(i); + KList c = chain.copy(); + c.remove(0); + KList v = cmd.hitTab(sender, c, vs.getCommand()); + if (v != null) { + return v; + } + } + } + } - for(KList i : children.k()) - { - for(String j : i) - { - if(j.equalsIgnoreCase(nl)) - { - vs.setCommand(chain.get(0)); - VirtualCommand cmd = children.get(i); - KList c = chain.copy(); - c.remove(0); - KList v = cmd.hitTab(sender, c, vs.getCommand()); - if(v != null) - { - return v; - } - } - } - } + if (!checkPermissions(sender, command)) { + return null; + } - if(!checkPermissions(sender, command)) - { - return null; - } + return command.handleTab(vs, chain.toArray(new String[chain.size()])); + } - return command.handleTab(vs, chain.toArray(new String[chain.size()])); - } + private boolean checkPermissions(CommandSender sender, ICommand command2) { + boolean failed = false; - private boolean checkPermissions(CommandSender sender, ICommand command2) - { - boolean failed = false; + for (String i : command.getRequiredPermissions()) { + if (!sender.hasPermission(i)) { + failed = true; + Bukkit.getScheduler().scheduleSyncDelayedTask(Iris.instance, () -> sender.sendMessage("- " + C.WHITE + i), 0); + } + } - for(String i : command.getRequiredPermissions()) - { - if(!sender.hasPermission(i)) - { - failed = true; - Bukkit.getScheduler().scheduleSyncDelayedTask(Iris.instance, () -> sender.sendMessage("- " + C.WHITE + i), 0); - } - } + if (failed) { + sender.sendMessage("Insufficient Permissions"); + return false; + } - if(failed) - { - sender.sendMessage("Insufficient Permissions"); - return false; - } - - return true; - } + return true; + } } diff --git a/src/main/java/com/volmit/iris/util/VoidOutputStream.java b/src/main/java/com/volmit/iris/util/VoidOutputStream.java index f30c0b7ba..9bf19202d 100644 --- a/src/main/java/com/volmit/iris/util/VoidOutputStream.java +++ b/src/main/java/com/volmit/iris/util/VoidOutputStream.java @@ -3,11 +3,9 @@ package com.volmit.iris.util; import java.io.IOException; import java.io.OutputStream; -public class VoidOutputStream extends OutputStream -{ - @Override - public void write(int b) throws IOException - { - // poof - } +public class VoidOutputStream extends OutputStream { + @Override + public void write(int b) throws IOException { + // poof + } } diff --git a/src/main/java/com/volmit/iris/util/VolmitPlugin.java b/src/main/java/com/volmit/iris/util/VolmitPlugin.java index 94f8842db..aa89f29b3 100644 --- a/src/main/java/com/volmit/iris/util/VolmitPlugin.java +++ b/src/main/java/com/volmit/iris/util/VolmitPlugin.java @@ -27,836 +27,652 @@ import java.util.List; import java.util.Map; import java.util.SortedSet; -public abstract class VolmitPlugin extends JavaPlugin implements Listener -{ - public static boolean bad = false; - private KMap, VirtualCommand> commands; - private KList commandCache; - private KList permissionCache; - private KMap controllers; - private KList cachedControllers; - private KMap, IController> cachedClassControllers; - - public void selfDistruct() - { - HandlerList.unregisterAll((Plugin)this); - getServer().getScheduler().cancelTasks(this); - File me = getFile(); - Plugin plugin = this; - String name = plugin.getName(); - SimpleCommandMap commandMap = null; - List plugins = null; - Map names = null; - Map commands = null; - Map> listeners = null; - - try - { - - Field pluginsField = Bukkit.getPluginManager().getClass().getDeclaredField("plugins"); - pluginsField.setAccessible(true); - plugins = (List) pluginsField.get(getServer().getPluginManager()); - Field lookupNamesField = Bukkit.getPluginManager().getClass().getDeclaredField("lookupNames"); - lookupNamesField.setAccessible(true); - names = (Map) lookupNamesField.get(getServer().getPluginManager()); - - try - { - Field listenersField = Bukkit.getPluginManager().getClass().getDeclaredField("listeners"); - listenersField.setAccessible(true); - listeners = (Map>) listenersField.get(getServer().getPluginManager()); - } - - catch(Throwable ignored) - { - - } - - Field commandMapField = Bukkit.getPluginManager().getClass().getDeclaredField("commandMap"); - commandMapField.setAccessible(true); - commandMap = (SimpleCommandMap) commandMapField.get(getServer().getPluginManager()); - Field knownCommandsField = SimpleCommandMap.class.getDeclaredField("knownCommands"); - knownCommandsField.setAccessible(true); - commands = (Map) knownCommandsField.get(commandMap); - - } - - catch(Throwable e) - { - - } - - getServer().getPluginManager().disablePlugin(plugin); - plugins.remove(plugin); - names.remove(name); - - if(listeners != null) - { - for(SortedSet set : listeners.values()) - { - set.removeIf(value -> value.getPlugin().equals(plugin)); - } - } - - for(Iterator> it = commands.entrySet().iterator(); it.hasNext();) - { - Map.Entry entry = it.next(); - if(entry.getValue() instanceof PluginCommand) - { - PluginCommand c = (PluginCommand) entry.getValue(); - if(c.getPlugin() == plugin) - { - c.unregister(commandMap); - it.remove(); - } - } - } - - new Thread(() -> { - // Attempt to close the classloader to unlock any handles on the - // plugin's - // jar file. - ClassLoader cl = plugin.getClass().getClassLoader(); - - if(cl instanceof URLClassLoader) - { - try - { - ((URLClassLoader) cl).close(); - } - catch(IOException ignored) - { - - } - } - - // Will not work on processes started with the -XX:+DisableExplicitGC - // flag, - // but lets try it anyway. This tries to get around the issue where - // Windows - // refuses to unlock jar files that were previously loaded into the JVM. - System.gc(); - if(!me.delete()) - { - me.deleteOnExit(); - } - }).start(); - } - - public void l(Object l) - { - Iris.info("[" + getName() + "]: " + l); - } - - public void w(Object l) - { - Iris.warn("[" + getName() + "]: " + l); - } - - public void f(Object l) - { - Iris.error("[" + getName() + "]: " + l); - } - - public void v(Object l) - { - Iris.verbose("[" + getName() + "]: " + l); - } - - public void onEnable() - { - registerInstance(); - registerPermissions(); - registerCommands(); - registerControllers(); - Bukkit.getScheduler().scheduleSyncRepeatingTask(this, this::tickControllers, 0, 0); - J.a(() -> outputInfo()); - registerListener(this); - start(); - } - - public void unregisterAll() - { - stopControllers(); - unregisterListeners(); - unregisterCommands(); - unregisterPermissions(); - unregisterInstance(); - } - - private void outputInfo() - { - try - { - IO.delete(getDataFolder("info")); - getDataFolder("info").mkdirs(); - outputPluginInfo(); - outputCommandInfo(); - outputPermissionInfo(); - } - - catch(Throwable e) - { - - } - } - - private void outputPermissionInfo() throws IOException - { - FileConfiguration fc = new YamlConfiguration(); - - for(MortarPermission i : permissionCache) - { - chain(i, fc); - } - - fc.save(getDataFile("info", "permissions.yml")); - } - - private void chain(MortarPermission i, FileConfiguration fc) - { - KList ff = new KList(); - - for(MortarPermission j : i.getChildren()) - { - ff.add(j.getFullNode()); - } - - fc.set(i.getFullNode().replaceAll("\\Q.\\E", ",") + "." + "description", i.getDescription()); - fc.set(i.getFullNode().replaceAll("\\Q.\\E", ",") + "." + "default", i.isDefault()); - fc.set(i.getFullNode().replaceAll("\\Q.\\E", ",") + "." + "children", ff); - - for(MortarPermission j : i.getChildren()) - { - chain(j, fc); - } - } - - private void outputCommandInfo() throws IOException - { - FileConfiguration fc = new YamlConfiguration(); - - for(MortarCommand i : commandCache) - { - chain(i, "/", fc); - } - - fc.save(getDataFile("info", "commands.yml")); - } - - private void chain(MortarCommand i, String c, FileConfiguration fc) - { - String n = c + (c.length() == 1 ? "" : " ") + i.getNode(); - fc.set(n + "." + "description", i.getDescription()); - fc.set(n + "." + "required-permissions", i.getRequiredPermissions()); - fc.set(n + "." + "aliases", i.getAllNodes()); - - for(MortarCommand j : i.getChildren()) - { - chain(j, n, fc); - } - } - - private void outputPluginInfo() throws IOException - { - FileConfiguration fc = new YamlConfiguration(); - fc.set("version", getDescription().getVersion()); - fc.set("name", getDescription().getName()); - fc.save(getDataFile("info", "plugin.yml")); - } - - private void registerPermissions() - { - permissionCache = new KList<>(); - - for(Field i : getClass().getDeclaredFields()) - { - if(i.isAnnotationPresent(Permission.class)) - { - try - { - i.setAccessible(true); - MortarPermission pc = (MortarPermission) i.getType().getConstructor().newInstance(); - i.set(Modifier.isStatic(i.getModifiers()) ? null : this, pc); - registerPermission(pc); - permissionCache.add(pc); - v("Registered Permissions " + pc.getFullNode() + " (" + i.getName() + ")"); - } - - catch(IllegalArgumentException | IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException | SecurityException e) - { - w("Failed to register permission (field " + i.getName() + ")"); - e.printStackTrace(); - } - } - } - - for(org.bukkit.permissions.Permission i : computePermissions()) - { - try - { - Bukkit.getPluginManager().addPermission(i); - } - - catch(Throwable e) - { - - } - } - } - - private KList computePermissions() - { - KList g = new KList<>(); - for(Field i : getClass().getDeclaredFields()) - { - if(i.isAnnotationPresent(Permission.class)) - { - try - { - MortarPermission x = (MortarPermission) i.get(Modifier.isStatic(i.getModifiers()) ? null : this); - g.add(toPermission(x)); - g.addAll(computePermissions(x)); - } - - catch(IllegalArgumentException | IllegalAccessException | SecurityException e) - { - e.printStackTrace(); - } - } - } - - return g.removeDuplicates(); - } - - private KList computePermissions(MortarPermission p) - { - KList g = new KList<>(); - - if(p == null) - { - return g; - } - - for(MortarPermission i : p.getChildren()) - { - if(i == null) - { - continue; - } - - g.add(toPermission(i)); - g.addAll(computePermissions(i)); - } - - return g; - } - - private org.bukkit.permissions.Permission toPermission(MortarPermission p) - { - if(p == null) - { - return null; - } - - org.bukkit.permissions.Permission perm = new org.bukkit.permissions.Permission(p.getFullNode() + (p.hasParent() ? "" : ".*")); - perm.setDescription(p.getDescription() == null ? "" : p.getDescription()); - perm.setDefault(p.isDefault() ? PermissionDefault.TRUE : PermissionDefault.OP); - - for(MortarPermission i : p.getChildren()) - { - perm.getChildren().put(i.getFullNode(), true); - } - - return perm; - } - - private void registerPermission(MortarPermission pc) - { - - } - - @Override - public void onDisable() - { - stop(); - Bukkit.getScheduler().cancelTasks(this); - unregisterListener(this); - unregisterAll(); - } - - private void tickControllers() - { - if(bad) - { - return; - } - - for(IController i : getControllers()) - { - tickController(i); - } - } - - private void tickController(IController i) - { - if(bad) - { - return; - } - - if(i.getTickInterval() < 0) - { - return; - } - - M.tick++; - if(M.interval(i.getTickInterval())) - { - try - { - i.tick(); - } - - catch(Throwable e) - { - w("Failed to tick controller " + i.getName()); - e.printStackTrace(); - } - } - } - - public KList getControllers() - { - if(bad) - { - return new KList<>(); - } - - return cachedControllers; - } - - private void registerControllers() - { - if(bad) - { - return; - } - controllers = new KMap<>(); - cachedClassControllers = new KMap<>(); - - for(Field i : getClass().getDeclaredFields()) - { - if(i.isAnnotationPresent(Control.class)) - { - try - { - i.setAccessible(true); - IController pc = (IController) i.getType().getConstructor().newInstance(); - registerController(pc); - i.set(this, pc); - v("Registered " + pc.getName() + " (" + i.getName() + ")"); - } - - catch(IllegalArgumentException | IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException | SecurityException e) - { - w("Failed to register controller (field " + i.getName() + ")"); - e.printStackTrace(); - } - } - } - - cachedControllers = controllers.v(); - } - - public IController getController(Class c) - { - return cachedClassControllers.get(c); - } - - private void registerController(IController pc) - { - if(bad) - { - return; - } - controllers.put(pc.getName(), pc); - cachedClassControllers.put(pc.getClass(), pc); - registerListener(pc); - - try - { - pc.start(); - v("Started " + pc.getName()); - } - - catch(Throwable e) - { - w("Failed to start controller " + pc.getName()); - e.printStackTrace(); - } - } - - private void registerInstance() - { - if(bad) - { - return; - } - for(Field i : getClass().getDeclaredFields()) - { - if(i.isAnnotationPresent(Instance.class)) - { - try - { - i.setAccessible(true); - i.set(Modifier.isStatic(i.getModifiers()) ? null : this, this); - v("Registered Instance " + i.getName()); - } - - catch(IllegalArgumentException | IllegalAccessException | SecurityException e) - { - w("Failed to register instance (field " + i.getName() + ")"); - e.printStackTrace(); - } - } - } - } - - private void unregisterInstance() - { - if(bad) - { - return; - } - for(Field i : getClass().getDeclaredFields()) - { - if(i.isAnnotationPresent(Instance.class)) - { - try - { - i.setAccessible(true); - i.set(Modifier.isStatic(i.getModifiers()) ? null : this, null); - v("Unregistered Instance " + i.getName()); - } - - catch(IllegalArgumentException | IllegalAccessException | SecurityException e) - { - w("Failed to unregister instance (field " + i.getName() + ")"); - e.printStackTrace(); - } - } - } - } - - private void registerCommands() - { - if(bad) - { - return; - } - commands = new KMap<>(); - commandCache = new KList<>(); - - for(Field i : getClass().getDeclaredFields()) - { - if(i.isAnnotationPresent(com.volmit.iris.util.Command.class)) - { - try - { - i.setAccessible(true); - MortarCommand pc = (MortarCommand) i.getType().getConstructor().newInstance(); - com.volmit.iris.util.Command c = i.getAnnotation(com.volmit.iris.util.Command.class); - registerCommand(pc, c.value()); - commandCache.add(pc); - v("Registered Commands /" + pc.getNode() + " (" + i.getName() + ")"); - } - - catch(IllegalArgumentException | IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException | SecurityException e) - { - w("Failed to register command (field " + i.getName() + ")"); - e.printStackTrace(); - } - } - } - } - - @Nullable - @Override - public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, - @NotNull String alias, @NotNull String[] args) { - KList chain = new KList(); - - for(String i : args) - { - if(i.trim().isEmpty()) - { - continue; - } - - chain.add(i.trim()); - } - - for(KList i : commands.k()) - { - for(String j : i) - { - if(j.equalsIgnoreCase(alias)) - { - VirtualCommand cmd = commands.get(i); - - List v = cmd.hitTab(sender, chain.copy(), alias); - if(v != null) - { - return v; - } - } - } - } - - return super.onTabComplete(sender, command, alias, args); - } - - @Override - public boolean onCommand(CommandSender sender, org.bukkit.command.Command command, String label, String[] args) - { - if(bad) - { - return false; - } - - KList chain = new KList(); - chain.add(args); - - for(KList i : commands.k()) - { - for(String j : i) - { - if(j.equalsIgnoreCase(label)) - { - VirtualCommand cmd = commands.get(i); - - if(cmd.hit(sender, chain.copy(), label)) - { - return true; - } - } - } - } - - return false; - } - - public void registerCommand(ICommand cmd) - { - registerCommand(cmd, ""); - } - - public void registerCommand(ICommand cmd, String subTag) - { - if(bad) - { - return; - } - - commands.put(cmd.getAllNodes(), new VirtualCommand(cmd, subTag.trim().isEmpty() ? getTag() : getTag(subTag.trim()))); - PluginCommand cc = getCommand(cmd.getNode().toLowerCase()); - - if(cc != null) - { - cc.setExecutor(this); - cc.setUsage(getName() + ":" + getClass().toString() + ":" + cmd.getNode()); - } - - else - { - RouterCommand r = new RouterCommand(cmd, this); - r.setUsage(getName() + ":" + getClass().toString()); - ((CommandMap) new com.volmit.iris.util.V(Bukkit.getServer()).get("commandMap")).register("", r); - } - } - - public void unregisterCommand(ICommand cmd) - { - if(bad) - { - return; - } - try - { - SimpleCommandMap m = new com.volmit.iris.util.V(Bukkit.getServer()).get("commandMap"); - - Map k = new com.volmit.iris.util.V(m).get("knownCommands"); - - for(Iterator> it = k.entrySet().iterator(); it.hasNext();) - { - Map.Entry entry = it.next(); - if(entry.getValue() instanceof Command) - { - org.bukkit.command.Command c = (org.bukkit.command.Command) entry.getValue(); - String u = c.getUsage(); - - if(u != null && u.equals(getName() + ":" + getClass().toString() + ":" + cmd.getNode())) - { - if(c.unregister(m)) - { - it.remove(); - v("Unregistered Command /" + cmd.getNode()); - } - - else - { - Bukkit.getConsoleSender().sendMessage(getTag() + "Failed to unregister command " + c.getName()); - } - } - } - } - } - - catch(Throwable e) - { - e.printStackTrace(); - } - } - - public String getTag() - { - if(bad) - { - return ""; - } - return getTag(""); - } - - public void registerListener(Listener l) - { - if(bad) - { - return; - } - Bukkit.getPluginManager().registerEvents(l, this); - } - - public void unregisterListener(Listener l) - { - if(bad) - { - return; - } - HandlerList.unregisterAll(l); - } - - public void unregisterListeners() - { - if(bad) - { - return; - } - HandlerList.unregisterAll((Listener) this); - } - - public void unregisterCommands() - { - if(bad) - { - return; - } - for(VirtualCommand i : commands.v()) - { - try - { - unregisterCommand(i.getCommand()); - } - - catch(Throwable e) - { - - } - } - } - - private void unregisterPermissions() - { - if(bad) - { - return; - } - for(org.bukkit.permissions.Permission i : computePermissions()) - { - Bukkit.getPluginManager().removePermission(i); - v("Unregistered Permission " + i.getName()); - } - } - - private void stopControllers() - { - if(bad) - { - return; - } - for(IController i : controllers.v()) - { - try - { - unregisterListener(i); - i.stop(); - v("Stopped " + i.getName()); - } - - catch(Throwable e) - { - w("Failed to stop controller " + i.getName()); - e.printStackTrace(); - } - } - } - - public File getDataFile(String... strings) - { - File f = new File(getDataFolder(), new KList(strings).toString(File.separator)); - f.getParentFile().mkdirs(); - return f; - } - - public File getDataFileList(String pre, String[] strings) - { - KList v = new KList(strings); - v.add(0, pre); - File f = new File(getDataFolder(), v.toString(File.separator)); - f.getParentFile().mkdirs(); - return f; - } - - public File getDataFolder(String... strings) - { - if(strings.length == 0) - { - return super.getDataFolder(); - } - - File f = new File(getDataFolder(), new KList(strings).toString(File.separator)); - f.mkdirs(); - - return f; - } - - public File getDataFolderList(String pre, String[] strings) - { - KList v = new KList<>(strings); - v.add(0, pre); - if(v.size() == 0) - { - return super.getDataFolder(); - } - File f = new File(getDataFolder(), v.toString(File.separator)); - f.mkdirs(); - - return f; - } - - public abstract void start(); - - public abstract void stop(); - - public abstract String getTag(String subTag); +public abstract class VolmitPlugin extends JavaPlugin implements Listener { + public static boolean bad = false; + private KMap, VirtualCommand> commands; + private KList commandCache; + private KList permissionCache; + private KMap controllers; + private KList cachedControllers; + private KMap, IController> cachedClassControllers; + + public void selfDistruct() { + HandlerList.unregisterAll((Plugin) this); + getServer().getScheduler().cancelTasks(this); + File me = getFile(); + Plugin plugin = this; + String name = plugin.getName(); + SimpleCommandMap commandMap = null; + List plugins = null; + Map names = null; + Map commands = null; + Map> listeners = null; + + try { + + Field pluginsField = Bukkit.getPluginManager().getClass().getDeclaredField("plugins"); + pluginsField.setAccessible(true); + plugins = (List) pluginsField.get(getServer().getPluginManager()); + Field lookupNamesField = Bukkit.getPluginManager().getClass().getDeclaredField("lookupNames"); + lookupNamesField.setAccessible(true); + names = (Map) lookupNamesField.get(getServer().getPluginManager()); + + try { + Field listenersField = Bukkit.getPluginManager().getClass().getDeclaredField("listeners"); + listenersField.setAccessible(true); + listeners = (Map>) listenersField.get(getServer().getPluginManager()); + } catch (Throwable ignored) { + + } + + Field commandMapField = Bukkit.getPluginManager().getClass().getDeclaredField("commandMap"); + commandMapField.setAccessible(true); + commandMap = (SimpleCommandMap) commandMapField.get(getServer().getPluginManager()); + Field knownCommandsField = SimpleCommandMap.class.getDeclaredField("knownCommands"); + knownCommandsField.setAccessible(true); + commands = (Map) knownCommandsField.get(commandMap); + + } catch (Throwable e) { + + } + + getServer().getPluginManager().disablePlugin(plugin); + plugins.remove(plugin); + names.remove(name); + + if (listeners != null) { + for (SortedSet set : listeners.values()) { + set.removeIf(value -> value.getPlugin().equals(plugin)); + } + } + + for (Iterator> it = commands.entrySet().iterator(); it.hasNext(); ) { + Map.Entry entry = it.next(); + if (entry.getValue() instanceof PluginCommand) { + PluginCommand c = (PluginCommand) entry.getValue(); + if (c.getPlugin() == plugin) { + c.unregister(commandMap); + it.remove(); + } + } + } + + new Thread(() -> { + // Attempt to close the classloader to unlock any handles on the + // plugin's + // jar file. + ClassLoader cl = plugin.getClass().getClassLoader(); + + if (cl instanceof URLClassLoader) { + try { + ((URLClassLoader) cl).close(); + } catch (IOException ignored) { + + } + } + + // Will not work on processes started with the -XX:+DisableExplicitGC + // flag, + // but lets try it anyway. This tries to get around the issue where + // Windows + // refuses to unlock jar files that were previously loaded into the JVM. + System.gc(); + if (!me.delete()) { + me.deleteOnExit(); + } + }).start(); + } + + public void l(Object l) { + Iris.info("[" + getName() + "]: " + l); + } + + public void w(Object l) { + Iris.warn("[" + getName() + "]: " + l); + } + + public void f(Object l) { + Iris.error("[" + getName() + "]: " + l); + } + + public void v(Object l) { + Iris.verbose("[" + getName() + "]: " + l); + } + + public void onEnable() { + registerInstance(); + registerPermissions(); + registerCommands(); + registerControllers(); + Bukkit.getScheduler().scheduleSyncRepeatingTask(this, this::tickControllers, 0, 0); + J.a(() -> outputInfo()); + registerListener(this); + start(); + } + + public void unregisterAll() { + stopControllers(); + unregisterListeners(); + unregisterCommands(); + unregisterPermissions(); + unregisterInstance(); + } + + private void outputInfo() { + try { + IO.delete(getDataFolder("info")); + getDataFolder("info").mkdirs(); + outputPluginInfo(); + outputCommandInfo(); + outputPermissionInfo(); + } catch (Throwable e) { + + } + } + + private void outputPermissionInfo() throws IOException { + FileConfiguration fc = new YamlConfiguration(); + + for (MortarPermission i : permissionCache) { + chain(i, fc); + } + + fc.save(getDataFile("info", "permissions.yml")); + } + + private void chain(MortarPermission i, FileConfiguration fc) { + KList ff = new KList(); + + for (MortarPermission j : i.getChildren()) { + ff.add(j.getFullNode()); + } + + fc.set(i.getFullNode().replaceAll("\\Q.\\E", ",") + "." + "description", i.getDescription()); + fc.set(i.getFullNode().replaceAll("\\Q.\\E", ",") + "." + "default", i.isDefault()); + fc.set(i.getFullNode().replaceAll("\\Q.\\E", ",") + "." + "children", ff); + + for (MortarPermission j : i.getChildren()) { + chain(j, fc); + } + } + + private void outputCommandInfo() throws IOException { + FileConfiguration fc = new YamlConfiguration(); + + for (MortarCommand i : commandCache) { + chain(i, "/", fc); + } + + fc.save(getDataFile("info", "commands.yml")); + } + + private void chain(MortarCommand i, String c, FileConfiguration fc) { + String n = c + (c.length() == 1 ? "" : " ") + i.getNode(); + fc.set(n + "." + "description", i.getDescription()); + fc.set(n + "." + "required-permissions", i.getRequiredPermissions()); + fc.set(n + "." + "aliases", i.getAllNodes()); + + for (MortarCommand j : i.getChildren()) { + chain(j, n, fc); + } + } + + private void outputPluginInfo() throws IOException { + FileConfiguration fc = new YamlConfiguration(); + fc.set("version", getDescription().getVersion()); + fc.set("name", getDescription().getName()); + fc.save(getDataFile("info", "plugin.yml")); + } + + private void registerPermissions() { + permissionCache = new KList<>(); + + for (Field i : getClass().getDeclaredFields()) { + if (i.isAnnotationPresent(Permission.class)) { + try { + i.setAccessible(true); + MortarPermission pc = (MortarPermission) i.getType().getConstructor().newInstance(); + i.set(Modifier.isStatic(i.getModifiers()) ? null : this, pc); + registerPermission(pc); + permissionCache.add(pc); + v("Registered Permissions " + pc.getFullNode() + " (" + i.getName() + ")"); + } catch (IllegalArgumentException | IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException | SecurityException e) { + w("Failed to register permission (field " + i.getName() + ")"); + e.printStackTrace(); + } + } + } + + for (org.bukkit.permissions.Permission i : computePermissions()) { + try { + Bukkit.getPluginManager().addPermission(i); + } catch (Throwable e) { + + } + } + } + + private KList computePermissions() { + KList g = new KList<>(); + for (Field i : getClass().getDeclaredFields()) { + if (i.isAnnotationPresent(Permission.class)) { + try { + MortarPermission x = (MortarPermission) i.get(Modifier.isStatic(i.getModifiers()) ? null : this); + g.add(toPermission(x)); + g.addAll(computePermissions(x)); + } catch (IllegalArgumentException | IllegalAccessException | SecurityException e) { + e.printStackTrace(); + } + } + } + + return g.removeDuplicates(); + } + + private KList computePermissions(MortarPermission p) { + KList g = new KList<>(); + + if (p == null) { + return g; + } + + for (MortarPermission i : p.getChildren()) { + if (i == null) { + continue; + } + + g.add(toPermission(i)); + g.addAll(computePermissions(i)); + } + + return g; + } + + private org.bukkit.permissions.Permission toPermission(MortarPermission p) { + if (p == null) { + return null; + } + + org.bukkit.permissions.Permission perm = new org.bukkit.permissions.Permission(p.getFullNode() + (p.hasParent() ? "" : ".*")); + perm.setDescription(p.getDescription() == null ? "" : p.getDescription()); + perm.setDefault(p.isDefault() ? PermissionDefault.TRUE : PermissionDefault.OP); + + for (MortarPermission i : p.getChildren()) { + perm.getChildren().put(i.getFullNode(), true); + } + + return perm; + } + + private void registerPermission(MortarPermission pc) { + + } + + @Override + public void onDisable() { + stop(); + Bukkit.getScheduler().cancelTasks(this); + unregisterListener(this); + unregisterAll(); + } + + private void tickControllers() { + if (bad) { + return; + } + + for (IController i : getControllers()) { + tickController(i); + } + } + + private void tickController(IController i) { + if (bad) { + return; + } + + if (i.getTickInterval() < 0) { + return; + } + + M.tick++; + if (M.interval(i.getTickInterval())) { + try { + i.tick(); + } catch (Throwable e) { + w("Failed to tick controller " + i.getName()); + e.printStackTrace(); + } + } + } + + public KList getControllers() { + if (bad) { + return new KList<>(); + } + + return cachedControllers; + } + + private void registerControllers() { + if (bad) { + return; + } + controllers = new KMap<>(); + cachedClassControllers = new KMap<>(); + + for (Field i : getClass().getDeclaredFields()) { + if (i.isAnnotationPresent(Control.class)) { + try { + i.setAccessible(true); + IController pc = (IController) i.getType().getConstructor().newInstance(); + registerController(pc); + i.set(this, pc); + v("Registered " + pc.getName() + " (" + i.getName() + ")"); + } catch (IllegalArgumentException | IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException | SecurityException e) { + w("Failed to register controller (field " + i.getName() + ")"); + e.printStackTrace(); + } + } + } + + cachedControllers = controllers.v(); + } + + public IController getController(Class c) { + return cachedClassControllers.get(c); + } + + private void registerController(IController pc) { + if (bad) { + return; + } + controllers.put(pc.getName(), pc); + cachedClassControllers.put(pc.getClass(), pc); + registerListener(pc); + + try { + pc.start(); + v("Started " + pc.getName()); + } catch (Throwable e) { + w("Failed to start controller " + pc.getName()); + e.printStackTrace(); + } + } + + private void registerInstance() { + if (bad) { + return; + } + for (Field i : getClass().getDeclaredFields()) { + if (i.isAnnotationPresent(Instance.class)) { + try { + i.setAccessible(true); + i.set(Modifier.isStatic(i.getModifiers()) ? null : this, this); + v("Registered Instance " + i.getName()); + } catch (IllegalArgumentException | IllegalAccessException | SecurityException e) { + w("Failed to register instance (field " + i.getName() + ")"); + e.printStackTrace(); + } + } + } + } + + private void unregisterInstance() { + if (bad) { + return; + } + for (Field i : getClass().getDeclaredFields()) { + if (i.isAnnotationPresent(Instance.class)) { + try { + i.setAccessible(true); + i.set(Modifier.isStatic(i.getModifiers()) ? null : this, null); + v("Unregistered Instance " + i.getName()); + } catch (IllegalArgumentException | IllegalAccessException | SecurityException e) { + w("Failed to unregister instance (field " + i.getName() + ")"); + e.printStackTrace(); + } + } + } + } + + private void registerCommands() { + if (bad) { + return; + } + commands = new KMap<>(); + commandCache = new KList<>(); + + for (Field i : getClass().getDeclaredFields()) { + if (i.isAnnotationPresent(com.volmit.iris.util.Command.class)) { + try { + i.setAccessible(true); + MortarCommand pc = (MortarCommand) i.getType().getConstructor().newInstance(); + com.volmit.iris.util.Command c = i.getAnnotation(com.volmit.iris.util.Command.class); + registerCommand(pc, c.value()); + commandCache.add(pc); + v("Registered Commands /" + pc.getNode() + " (" + i.getName() + ")"); + } catch (IllegalArgumentException | IllegalAccessException | InstantiationException | InvocationTargetException | NoSuchMethodException | SecurityException e) { + w("Failed to register command (field " + i.getName() + ")"); + e.printStackTrace(); + } + } + } + } + + @Nullable + @Override + public List onTabComplete(@NotNull CommandSender sender, @NotNull Command command, + @NotNull String alias, @NotNull String[] args) { + KList chain = new KList(); + + for (String i : args) { + if (i.trim().isEmpty()) { + continue; + } + + chain.add(i.trim()); + } + + for (KList i : commands.k()) { + for (String j : i) { + if (j.equalsIgnoreCase(alias)) { + VirtualCommand cmd = commands.get(i); + + List v = cmd.hitTab(sender, chain.copy(), alias); + if (v != null) { + return v; + } + } + } + } + + return super.onTabComplete(sender, command, alias, args); + } + + @Override + public boolean onCommand(CommandSender sender, org.bukkit.command.Command command, String label, String[] args) { + if (bad) { + return false; + } + + KList chain = new KList(); + chain.add(args); + + for (KList i : commands.k()) { + for (String j : i) { + if (j.equalsIgnoreCase(label)) { + VirtualCommand cmd = commands.get(i); + + if (cmd.hit(sender, chain.copy(), label)) { + return true; + } + } + } + } + + return false; + } + + public void registerCommand(ICommand cmd) { + registerCommand(cmd, ""); + } + + public void registerCommand(ICommand cmd, String subTag) { + if (bad) { + return; + } + + commands.put(cmd.getAllNodes(), new VirtualCommand(cmd, subTag.trim().isEmpty() ? getTag() : getTag(subTag.trim()))); + PluginCommand cc = getCommand(cmd.getNode().toLowerCase()); + + if (cc != null) { + cc.setExecutor(this); + cc.setUsage(getName() + ":" + getClass().toString() + ":" + cmd.getNode()); + } else { + RouterCommand r = new RouterCommand(cmd, this); + r.setUsage(getName() + ":" + getClass().toString()); + ((CommandMap) new com.volmit.iris.util.V(Bukkit.getServer()).get("commandMap")).register("", r); + } + } + + public void unregisterCommand(ICommand cmd) { + if (bad) { + return; + } + try { + SimpleCommandMap m = new com.volmit.iris.util.V(Bukkit.getServer()).get("commandMap"); + + Map k = new com.volmit.iris.util.V(m).get("knownCommands"); + + for (Iterator> it = k.entrySet().iterator(); it.hasNext(); ) { + Map.Entry entry = it.next(); + if (entry.getValue() instanceof Command) { + org.bukkit.command.Command c = entry.getValue(); + String u = c.getUsage(); + + if (u != null && u.equals(getName() + ":" + getClass().toString() + ":" + cmd.getNode())) { + if (c.unregister(m)) { + it.remove(); + v("Unregistered Command /" + cmd.getNode()); + } else { + Bukkit.getConsoleSender().sendMessage(getTag() + "Failed to unregister command " + c.getName()); + } + } + } + } + } catch (Throwable e) { + e.printStackTrace(); + } + } + + public String getTag() { + if (bad) { + return ""; + } + return getTag(""); + } + + public void registerListener(Listener l) { + if (bad) { + return; + } + Bukkit.getPluginManager().registerEvents(l, this); + } + + public void unregisterListener(Listener l) { + if (bad) { + return; + } + HandlerList.unregisterAll(l); + } + + public void unregisterListeners() { + if (bad) { + return; + } + HandlerList.unregisterAll((Listener) this); + } + + public void unregisterCommands() { + if (bad) { + return; + } + for (VirtualCommand i : commands.v()) { + try { + unregisterCommand(i.getCommand()); + } catch (Throwable e) { + + } + } + } + + private void unregisterPermissions() { + if (bad) { + return; + } + for (org.bukkit.permissions.Permission i : computePermissions()) { + Bukkit.getPluginManager().removePermission(i); + v("Unregistered Permission " + i.getName()); + } + } + + private void stopControllers() { + if (bad) { + return; + } + for (IController i : controllers.v()) { + try { + unregisterListener(i); + i.stop(); + v("Stopped " + i.getName()); + } catch (Throwable e) { + w("Failed to stop controller " + i.getName()); + e.printStackTrace(); + } + } + } + + public File getDataFile(String... strings) { + File f = new File(getDataFolder(), new KList(strings).toString(File.separator)); + f.getParentFile().mkdirs(); + return f; + } + + public File getDataFileList(String pre, String[] strings) { + KList v = new KList(strings); + v.add(0, pre); + File f = new File(getDataFolder(), v.toString(File.separator)); + f.getParentFile().mkdirs(); + return f; + } + + public File getDataFolder(String... strings) { + if (strings.length == 0) { + return super.getDataFolder(); + } + + File f = new File(getDataFolder(), new KList(strings).toString(File.separator)); + f.mkdirs(); + + return f; + } + + public File getDataFolderList(String pre, String[] strings) { + KList v = new KList<>(strings); + v.add(0, pre); + if (v.size() == 0) { + return super.getDataFolder(); + } + File f = new File(getDataFolder(), v.toString(File.separator)); + f.mkdirs(); + + return f; + } + + public abstract void start(); + + public abstract void stop(); + + public abstract String getTag(String subTag); } diff --git a/src/main/java/com/volmit/iris/util/WeightMap.java b/src/main/java/com/volmit/iris/util/WeightMap.java index 2a1556a09..13964f2dc 100644 --- a/src/main/java/com/volmit/iris/util/WeightMap.java +++ b/src/main/java/com/volmit/iris/util/WeightMap.java @@ -1,51 +1,43 @@ package com.volmit.iris.util; -public class WeightMap extends KMap -{ - private static final long serialVersionUID = 87558033900969389L; - private boolean modified = false; - private double lastWeight = 0; +public class WeightMap extends KMap { + private static final long serialVersionUID = 87558033900969389L; + private boolean modified = false; + private double lastWeight = 0; - public double getPercentChance(T t) - { - if(totalWeight() <= 0) - { - return 0; - } + public double getPercentChance(T t) { + if (totalWeight() <= 0) { + return 0; + } - return getWeight(t) / totalWeight(); - } + return getWeight(t) / totalWeight(); + } - public void clear() - { - modified = true; - } + public void clear() { + modified = true; + } - public WeightMap setWeight(T t, double weight) - { - modified = true; - put(t, weight); + public WeightMap setWeight(T t, double weight) { + modified = true; + put(t, weight); - return this; - } + return this; + } - public double getWeight(T t) - { - return get(t); - } + public double getWeight(T t) { + return get(t); + } - public double totalWeight() - { - if(!modified) - { - return lastWeight; - } + public double totalWeight() { + if (!modified) { + return lastWeight; + } - modified = false; - Shrinkwrap s = new Shrinkwrap(0D); - forEachKey(Integer.MAX_VALUE, (d) -> s.set(s.get() + 1)); - lastWeight = s.get(); + modified = false; + Shrinkwrap s = new Shrinkwrap(0D); + forEachKey(Integer.MAX_VALUE, (d) -> s.set(s.get() + 1)); + lastWeight = s.get(); - return lastWeight; - } + return lastWeight; + } } diff --git a/src/main/java/com/volmit/iris/util/WeightedRandom.java b/src/main/java/com/volmit/iris/util/WeightedRandom.java index 5b3219e2e..ed6a8a312 100644 --- a/src/main/java/com/volmit/iris/util/WeightedRandom.java +++ b/src/main/java/com/volmit/iris/util/WeightedRandom.java @@ -4,8 +4,8 @@ import java.util.Random; public class WeightedRandom { - private KList> weightedObjects = new KList<>(); - private Random random; + private final KList> weightedObjects = new KList<>(); + private final Random random; private int totalWeight = 0; public WeightedRandom(Random random) { diff --git a/src/main/java/com/volmit/iris/util/Window.java b/src/main/java/com/volmit/iris/util/Window.java index c283e2071..f31741dfe 100644 --- a/src/main/java/com/volmit/iris/util/Window.java +++ b/src/main/java/com/volmit/iris/util/Window.java @@ -3,71 +3,70 @@ package com.volmit.iris.util; import org.bukkit.entity.Player; import org.bukkit.inventory.ItemStack; -public interface Window -{ - public Window setDecorator(WindowDecorator decorator); +public interface Window { + Window setDecorator(WindowDecorator decorator); - public WindowDecorator getDecorator(); + WindowDecorator getDecorator(); - public WindowResolution getResolution(); + WindowResolution getResolution(); - public Window setResolution(WindowResolution resolution); + Window setResolution(WindowResolution resolution); - public Window clearElements(); + Window clearElements(); - public Window close(); + Window close(); - public Window open(); + Window open(); - public Window callClosed(); + Window callClosed(); - public Window updateInventory(); + Window updateInventory(); - public Window setVisible(boolean visible); + Window setVisible(boolean visible); - public ItemStack computeItemStack(int viewportSlot); + ItemStack computeItemStack(int viewportSlot); - public int getLayoutRow(int viewportSlottedPosition); + int getLayoutRow(int viewportSlottedPosition); - public int getLayoutPosition(int viewportSlottedPosition); + int getLayoutPosition(int viewportSlottedPosition); - public int getRealLayoutPosition(int viewportSlottedPosition); + int getRealLayoutPosition(int viewportSlottedPosition); - public int getRealPosition(int position, int row); + int getRealPosition(int position, int row); - public int getRow(int realPosition); + int getRow(int realPosition); - public int getPosition(int realPosition); + int getPosition(int realPosition); - public boolean isVisible(); + boolean isVisible(); - public int getViewportPosition(); + int getViewportPosition(); - public int getViewportSlots(); + int getViewportSlots(); - public Window setViewportPosition(int position); + Window setViewportPosition(int position); - public int getMaxViewportPosition(); + int getMaxViewportPosition(); - public Window scroll(int direction); + Window scroll(int direction); - public int getViewportHeight(); + int getViewportHeight(); - public Window setViewportHeight(int height); + Window setViewportHeight(int height); - public String getTitle(); + String getTitle(); - public Window setTitle(String title); + Window setTitle(String title); - public boolean hasElement(int position, int row); + boolean hasElement(int position, int row); - public Window setElement(int position, int row, Element e); + Window setElement(int position, int row, Element e); - public Element getElement(int position, int row); + Element getElement(int position, int row); - public Player getViewer(); + Player getViewer(); - public Window reopen(); + Window reopen(); - public Window onClosed(Callback window); + Window onClosed(Callback window); } diff --git a/src/main/java/com/volmit/iris/util/WindowDecorator.java b/src/main/java/com/volmit/iris/util/WindowDecorator.java index 5b4af9301..cd56a8979 100644 --- a/src/main/java/com/volmit/iris/util/WindowDecorator.java +++ b/src/main/java/com/volmit/iris/util/WindowDecorator.java @@ -1,6 +1,5 @@ package com.volmit.iris.util; -public interface WindowDecorator -{ - public Element onDecorateBackground(Window window, int position, int row); +public interface WindowDecorator { + Element onDecorateBackground(Window window, int position, int row); } diff --git a/src/main/java/com/volmit/iris/util/WindowResolution.java b/src/main/java/com/volmit/iris/util/WindowResolution.java index 581454721..dc1ed50bd 100644 --- a/src/main/java/com/volmit/iris/util/WindowResolution.java +++ b/src/main/java/com/volmit/iris/util/WindowResolution.java @@ -2,40 +2,34 @@ package com.volmit.iris.util; import org.bukkit.event.inventory.InventoryType; -public enum WindowResolution -{ - W9_H6(9, 6, InventoryType.CHEST), - W5_H1(5, 1, InventoryType.HOPPER), - W3_H3(3, 3, InventoryType.DROPPER); +public enum WindowResolution { + W9_H6(9, 6, InventoryType.CHEST), + W5_H1(5, 1, InventoryType.HOPPER), + W3_H3(3, 3, InventoryType.DROPPER); - private int width; - private int maxHeight; - private InventoryType type; + private final int width; + private final int maxHeight; + private final InventoryType type; - private WindowResolution(int w, int h, InventoryType type) - { - this.width = w; - this.maxHeight = h; - this.type = type; - } + WindowResolution(int w, int h, InventoryType type) { + this.width = w; + this.maxHeight = h; + this.type = type; + } - public int getMaxWidthOffset() - { - return (getWidth() - 1) / 2; - } + public int getMaxWidthOffset() { + return (getWidth() - 1) / 2; + } - public int getWidth() - { - return width; - } + public int getWidth() { + return width; + } - public int getMaxHeight() - { - return maxHeight; - } + public int getMaxHeight() { + return maxHeight; + } - public InventoryType getType() - { - return type; - } + public InventoryType getType() { + return type; + } } diff --git a/src/main/java/com/volmit/iris/util/Wrapper.java b/src/main/java/com/volmit/iris/util/Wrapper.java index 53353ed5a..9bf532a2c 100644 --- a/src/main/java/com/volmit/iris/util/Wrapper.java +++ b/src/main/java/com/volmit/iris/util/Wrapper.java @@ -1,72 +1,52 @@ package com.volmit.iris.util; -public class Wrapper -{ - private T t; +public class Wrapper { + private T t; - public Wrapper(T t) - { - set(t); - } + public Wrapper(T t) { + set(t); + } - public void set(T t) - { - this.t = t; - } + public void set(T t) { + this.t = t; + } - public T get() - { - return t; - } + public T get() { + return t; + } - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + ((t == null) ? 0 : t.hashCode()); - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + ((t == null) ? 0 : t.hashCode()); + return result; + } - @Override - public boolean equals(Object obj) - { - if(this == obj) - { - return true; - } - if(obj == null) - { - return false; - } - if(!(obj instanceof Wrapper)) - { - return false; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (obj == null) { + return false; + } + if (!(obj instanceof Wrapper)) { + return false; + } - Wrapper other = (Wrapper) obj; - if(t == null) - { - if(other.t != null) - { - return false; - } - } - else if(!t.equals(other.t)) - { - return false; - } - return true; - } + Wrapper other = (Wrapper) obj; + if (t == null) { + return other.t == null; + } else return t.equals(other.t); + } - @Override - public String toString() - { - if(t != null) - { - return get().toString(); - } + @Override + public String toString() { + if (t != null) { + return get().toString(); + } - return super.toString() + " (null)"; - } + return super.toString() + " (null)"; + } } diff --git a/src/main/java/com/volmit/iris/util/Writable.java b/src/main/java/com/volmit/iris/util/Writable.java index 2c02046f1..79d550b43 100644 --- a/src/main/java/com/volmit/iris/util/Writable.java +++ b/src/main/java/com/volmit/iris/util/Writable.java @@ -4,9 +4,8 @@ import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; -public interface Writable -{ - public void write(DataOutputStream o) throws IOException; +public interface Writable { + void write(DataOutputStream o) throws IOException; - public void read(DataInputStream i) throws IOException; + void read(DataInputStream i) throws IOException; } diff --git a/src/main/java/com/volmit/iris/util/XML.java b/src/main/java/com/volmit/iris/util/XML.java index d3feaacc0..167635284 100644 --- a/src/main/java/com/volmit/iris/util/XML.java +++ b/src/main/java/com/volmit/iris/util/XML.java @@ -30,555 +30,478 @@ import java.util.Iterator; /** * This provides static methods to convert an XML text into a JSONObject, and to * covert a JSONObject into an XML text. - * + * * @author JSON.org * @version 2014-05-03 */ -public class XML -{ - - /** The Character '&'. */ - public static final Character AMP = '&'; - - /** The Character '''. */ - public static final Character APOS = '\''; - - /** The Character '!'. */ - public static final Character BANG = '!'; - - /** The Character '='. */ - public static final Character EQ = '='; - - /** The Character '>'. */ - public static final Character GT = '>'; - - /** The Character '<'. */ - public static final Character LT = '<'; - - /** The Character '?'. */ - public static final Character QUEST = '?'; - - /** The Character '"'. */ - public static final Character QUOT = '"'; - - /** The Character '/'. */ - public static final Character SLASH = '/'; - - /** - * Replace special characters with XML escapes: - * - *

-	 * & (ampersand) is replaced by &amp;
-	 * < (less than) is replaced by &lt;
-	 * > (greater than) is replaced by &gt;
-	 * " (double quote) is replaced by &quot;
-	 * 
- * - * @param string - * The string to be escaped. - * @return The escaped string. - */ - public static String escape(String string) - { - StringBuilder sb = new StringBuilder(string.length()); - for(int i = 0, length = string.length(); i < length; i++) - { - char c = string.charAt(i); - switch(c) - { - case '&': - sb.append("&"); - break; - case '<': - sb.append("<"); - break; - case '>': - sb.append(">"); - break; - case '"': - sb.append("""); - break; - case '\'': - sb.append("'"); - break; - default: - sb.append(c); - } - } - return sb.toString(); - } - - /** - * Throw an exception if the string contains whitespace. Whitespace is not - * allowed in tagNames and attributes. - * - * @param string - * A string. - * @throws JSONException - */ - public static void noSpace(String string) throws JSONException - { - int i, length = string.length(); - if(length == 0) - { - throw new JSONException("Empty string."); - } - for(i = 0; i < length; i += 1) - { - if(Character.isWhitespace(string.charAt(i))) - { - throw new JSONException("'" + string + "' contains a space character."); - } - } - } - - /** - * Scan the content following the named tag, attaching it to the context. - * - * @param x - * The XMLTokener containing the source string. - * @param context - * The JSONObject that will include the new material. - * @param name - * The tag name. - * @return true if the close tag is processed. - * @throws JSONException - */ - private static boolean parse(XMLTokener x, JSONObject context, String name) throws JSONException - { - char c; - int i; - JSONObject jsonobject = null; - String string; - String tagName; - Object token; - - // Test for and skip past these forms: - // - // - // - // - // Report errors for these forms: - // <> - // <= - // << - - token = x.nextToken(); - - // "); - return false; - } - x.back(); - } else if(c == '[') - { - token = x.nextToken(); - if("CDATA".equals(token)) - { - if(x.next() == '[') - { - string = x.nextCDATA(); - if(string.length() > 0) - { - context.accumulate("content", string); - } - return false; - } - } - throw x.syntaxError("Expected 'CDATA['"); - } - i = 1; - do - { - token = x.nextMeta(); - if(token == null) - { - throw x.syntaxError("Missing '>' after ' 0); - return false; - } else if(token == QUEST) - { - - // "); - return false; - } else if(token == SLASH) - { - - // Close tag - - } else if(token == SLASH) - { - if(x.nextToken() != GT) - { - throw x.syntaxError("Misshaped tag"); - } - if(jsonobject.length() > 0) - { - context.accumulate(tagName, jsonobject); - } else - { - context.accumulate(tagName, ""); - } - return false; - - // Content, between <...> and - - } else if(token == GT) - { - for(;;) - { - token = x.nextContent(); - if(token == null) - { - if(tagName != null) - { - throw x.syntaxError("Unclosed tag " + tagName); - } - return false; - } else if(token instanceof String) - { - string = (String) token; - if(string.length() > 0) - { - jsonobject.accumulate("content", XML.stringToValue(string)); - } - - // Nested element - - } else if(token == LT) - { - if(parse(x, jsonobject, tagName)) - { - if(jsonobject.length() == 0) - { - context.accumulate(tagName, ""); - } else if(jsonobject.length() == 1 && jsonobject.opt("content") != null) - { - context.accumulate(tagName, jsonobject.opt("content")); - } else - { - context.accumulate(tagName, jsonobject); - } - return false; - } - } - } - } else - { - throw x.syntaxError("Misshaped tag"); - } - } - } - } - - /** - * Try to convert a string into a number, boolean, or null. If the string - * can't be converted, return the string. This is much less ambitious than - * JSONObject.stringToValue, especially because it does not attempt to - * convert plus forms, octal forms, hex forms, or E forms lacking decimal - * points. - * - * @param string - * A String. - * @return A simple JSON value. - */ - public static Object stringToValue(String string) - { - if("true".equalsIgnoreCase(string)) - { - return Boolean.TRUE; - } - if("false".equalsIgnoreCase(string)) - { - return Boolean.FALSE; - } - if("null".equalsIgnoreCase(string)) - { - return JSONObject.NULL; - } - - // If it might be a number, try converting it, first as a Long, and then - // as a - // Double. If that doesn't work, return the string. - - try - { - char initial = string.charAt(0); - if(initial == '-' || (initial >= '0' && initial <= '9')) - { - Long value = new Long(string); - if(value.toString().equals(string)) - { - return value; - } - } - } catch(Exception ignore) - { - try - { - Double value = new Double(string); - if(value.toString().equals(string)) - { - return value; - } - } catch(Exception ignoreAlso) - { - } - } - return string; - } - - /** - * Convert a well-formed (but not necessarily valid) XML string into a - * JSONObject. Some information may be lost in this transformation because - * JSON is a data format and XML is a document format. XML uses elements, - * attributes, and content text, while JSON uses unordered collections of - * name/value pairs and arrays of values. JSON does not does not like to - * distinguish between elements and attributes. Sequences of similar - * elements are represented as JSONArrays. Content text may be placed in a - * "content" member. Comments, prologs, DTDs, and <[ [ ]]> - * are ignored. - * - * @param string - * The source string. - * @return A JSONObject containing the structured data from the XML string. - * @throws JSONException - */ - public static JSONObject toJSONObject(String string) throws JSONException - { - JSONObject jo = new JSONObject(); - XMLTokener x = new XMLTokener(string); - while(x.more() && x.skipPast("<")) - { - parse(x, jo, null); - } - return jo; - } - - /** - * Convert a JSONObject into a well-formed, element-normal XML string. - * - * @param object - * A JSONObject. - * @return A string. - * @throws JSONException - */ - public static String toString(Object object) throws JSONException - { - return toString(object, null); - } - - /** - * Convert a JSONObject into a well-formed, element-normal XML string. - * - * @param object - * A JSONObject. - * @param tagName - * The optional name of the enclosing tag. - * @return A string. - * @throws JSONException - */ - public static String toString(Object object, String tagName) throws JSONException - { - StringBuilder sb = new StringBuilder(); - int i; - JSONArray ja; - JSONObject jo; - String key; - Iterator keys; - int length; - String string; - Object value; - if(object instanceof JSONObject) - { - - // Emit - - if(tagName != null) - { - sb.append('<'); - sb.append(tagName); - sb.append('>'); - } - - // Loop thru the keys. - - jo = (JSONObject) object; - keys = jo.keys(); - while(keys.hasNext()) - { - key = keys.next(); - value = jo.opt(key); - if(value == null) - { - value = ""; - } - string = value instanceof String ? (String) value : null; - - // Emit content in body - - if("content".equals(key)) - { - if(value instanceof JSONArray) - { - ja = (JSONArray) value; - length = ja.length(); - for(i = 0; i < length; i += 1) - { - if(i > 0) - { - sb.append('\n'); - } - sb.append(escape(ja.get(i).toString())); - } - } else - { - sb.append(escape(value.toString())); - } - - // Emit an array of similar keys - - } else if(value instanceof JSONArray) - { - ja = (JSONArray) value; - length = ja.length(); - for(i = 0; i < length; i += 1) - { - value = ja.get(i); - if(value instanceof JSONArray) - { - sb.append('<'); - sb.append(key); - sb.append('>'); - sb.append(toString(value)); - sb.append("'); - } else - { - sb.append(toString(value, key)); - } - } - } else if("".equals(value)) - { - sb.append('<'); - sb.append(key); - sb.append("/>"); - - // Emit a new tag - - } else - { - sb.append(toString(value, key)); - } - } - if(tagName != null) - { - - // Emit the close tag - - sb.append("'); - } - return sb.toString(); - - // XML does not have good support for arrays. If an array appears in - // a place - // where XML is lacking, synthesize an element. - - } else - { - if(object.getClass().isArray()) - { - object = new JSONArray(object); - } - if(object instanceof JSONArray) - { - ja = (JSONArray) object; - length = ja.length(); - for(i = 0; i < length; i += 1) - { - sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName)); - } - return sb.toString(); - } else - { - string = (object == null) ? "null" : escape(object.toString()); - return (tagName == null) ? "\"" + string + "\"" : (string.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + string + ""; - } - } - } +public class XML { + + /** + * The Character '&'. + */ + public static final Character AMP = '&'; + + /** + * The Character '''. + */ + public static final Character APOS = '\''; + + /** + * The Character '!'. + */ + public static final Character BANG = '!'; + + /** + * The Character '='. + */ + public static final Character EQ = '='; + + /** + * The Character '>'. + */ + public static final Character GT = '>'; + + /** + * The Character '<'. + */ + public static final Character LT = '<'; + + /** + * The Character '?'. + */ + public static final Character QUEST = '?'; + + /** + * The Character '"'. + */ + public static final Character QUOT = '"'; + + /** + * The Character '/'. + */ + public static final Character SLASH = '/'; + + /** + * Replace special characters with XML escapes: + * + *
+     * & (ampersand) is replaced by &amp;
+     * < (less than) is replaced by &lt;
+     * > (greater than) is replaced by &gt;
+     * " (double quote) is replaced by &quot;
+     * 
+ * + * @param string The string to be escaped. + * @return The escaped string. + */ + public static String escape(String string) { + StringBuilder sb = new StringBuilder(string.length()); + for (int i = 0, length = string.length(); i < length; i++) { + char c = string.charAt(i); + switch (c) { + case '&': + sb.append("&"); + break; + case '<': + sb.append("<"); + break; + case '>': + sb.append(">"); + break; + case '"': + sb.append("""); + break; + case '\'': + sb.append("'"); + break; + default: + sb.append(c); + } + } + return sb.toString(); + } + + /** + * Throw an exception if the string contains whitespace. Whitespace is not + * allowed in tagNames and attributes. + * + * @param string A string. + * @throws JSONException + */ + public static void noSpace(String string) throws JSONException { + int i, length = string.length(); + if (length == 0) { + throw new JSONException("Empty string."); + } + for (i = 0; i < length; i += 1) { + if (Character.isWhitespace(string.charAt(i))) { + throw new JSONException("'" + string + "' contains a space character."); + } + } + } + + /** + * Scan the content following the named tag, attaching it to the context. + * + * @param x The XMLTokener containing the source string. + * @param context The JSONObject that will include the new material. + * @param name The tag name. + * @return true if the close tag is processed. + * @throws JSONException + */ + private static boolean parse(XMLTokener x, JSONObject context, String name) throws JSONException { + char c; + int i; + JSONObject jsonobject = null; + String string; + String tagName; + Object token; + + // Test for and skip past these forms: + // + // + // + // + // Report errors for these forms: + // <> + // <= + // << + + token = x.nextToken(); + + // "); + return false; + } + x.back(); + } else if (c == '[') { + token = x.nextToken(); + if ("CDATA".equals(token)) { + if (x.next() == '[') { + string = x.nextCDATA(); + if (string.length() > 0) { + context.accumulate("content", string); + } + return false; + } + } + throw x.syntaxError("Expected 'CDATA['"); + } + i = 1; + do { + token = x.nextMeta(); + if (token == null) { + throw x.syntaxError("Missing '>' after ' 0); + return false; + } else if (token == QUEST) { + + // "); + return false; + } else if (token == SLASH) { + + // Close tag + + } else if (token == SLASH) { + if (x.nextToken() != GT) { + throw x.syntaxError("Misshaped tag"); + } + if (jsonobject.length() > 0) { + context.accumulate(tagName, jsonobject); + } else { + context.accumulate(tagName, ""); + } + return false; + + // Content, between <...> and + + } else if (token == GT) { + for (; ; ) { + token = x.nextContent(); + if (token == null) { + if (tagName != null) { + throw x.syntaxError("Unclosed tag " + tagName); + } + return false; + } else if (token instanceof String) { + string = (String) token; + if (string.length() > 0) { + jsonobject.accumulate("content", XML.stringToValue(string)); + } + + // Nested element + + } else if (token == LT) { + if (parse(x, jsonobject, tagName)) { + if (jsonobject.length() == 0) { + context.accumulate(tagName, ""); + } else if (jsonobject.length() == 1 && jsonobject.opt("content") != null) { + context.accumulate(tagName, jsonobject.opt("content")); + } else { + context.accumulate(tagName, jsonobject); + } + return false; + } + } + } + } else { + throw x.syntaxError("Misshaped tag"); + } + } + } + } + + /** + * Try to convert a string into a number, boolean, or null. If the string + * can't be converted, return the string. This is much less ambitious than + * JSONObject.stringToValue, especially because it does not attempt to + * convert plus forms, octal forms, hex forms, or E forms lacking decimal + * points. + * + * @param string A String. + * @return A simple JSON value. + */ + public static Object stringToValue(String string) { + if ("true".equalsIgnoreCase(string)) { + return Boolean.TRUE; + } + if ("false".equalsIgnoreCase(string)) { + return Boolean.FALSE; + } + if ("null".equalsIgnoreCase(string)) { + return JSONObject.NULL; + } + + // If it might be a number, try converting it, first as a Long, and then + // as a + // Double. If that doesn't work, return the string. + + try { + char initial = string.charAt(0); + if (initial == '-' || (initial >= '0' && initial <= '9')) { + Long value = new Long(string); + if (value.toString().equals(string)) { + return value; + } + } + } catch (Exception ignore) { + try { + Double value = new Double(string); + if (value.toString().equals(string)) { + return value; + } + } catch (Exception ignoreAlso) { + } + } + return string; + } + + /** + * Convert a well-formed (but not necessarily valid) XML string into a + * JSONObject. Some information may be lost in this transformation because + * JSON is a data format and XML is a document format. XML uses elements, + * attributes, and content text, while JSON uses unordered collections of + * name/value pairs and arrays of values. JSON does not does not like to + * distinguish between elements and attributes. Sequences of similar + * elements are represented as JSONArrays. Content text may be placed in a + * "content" member. Comments, prologs, DTDs, and <[ [ ]]> + * are ignored. + * + * @param string The source string. + * @return A JSONObject containing the structured data from the XML string. + * @throws JSONException + */ + public static JSONObject toJSONObject(String string) throws JSONException { + JSONObject jo = new JSONObject(); + XMLTokener x = new XMLTokener(string); + while (x.more() && x.skipPast("<")) { + parse(x, jo, null); + } + return jo; + } + + /** + * Convert a JSONObject into a well-formed, element-normal XML string. + * + * @param object A JSONObject. + * @return A string. + * @throws JSONException + */ + public static String toString(Object object) throws JSONException { + return toString(object, null); + } + + /** + * Convert a JSONObject into a well-formed, element-normal XML string. + * + * @param object A JSONObject. + * @param tagName The optional name of the enclosing tag. + * @return A string. + * @throws JSONException + */ + public static String toString(Object object, String tagName) throws JSONException { + StringBuilder sb = new StringBuilder(); + int i; + JSONArray ja; + JSONObject jo; + String key; + Iterator keys; + int length; + String string; + Object value; + if (object instanceof JSONObject) { + + // Emit + + if (tagName != null) { + sb.append('<'); + sb.append(tagName); + sb.append('>'); + } + + // Loop thru the keys. + + jo = (JSONObject) object; + keys = jo.keys(); + while (keys.hasNext()) { + key = keys.next(); + value = jo.opt(key); + if (value == null) { + value = ""; + } + string = value instanceof String ? (String) value : null; + + // Emit content in body + + if ("content".equals(key)) { + if (value instanceof JSONArray) { + ja = (JSONArray) value; + length = ja.length(); + for (i = 0; i < length; i += 1) { + if (i > 0) { + sb.append('\n'); + } + sb.append(escape(ja.get(i).toString())); + } + } else { + sb.append(escape(value.toString())); + } + + // Emit an array of similar keys + + } else if (value instanceof JSONArray) { + ja = (JSONArray) value; + length = ja.length(); + for (i = 0; i < length; i += 1) { + value = ja.get(i); + if (value instanceof JSONArray) { + sb.append('<'); + sb.append(key); + sb.append('>'); + sb.append(toString(value)); + sb.append("'); + } else { + sb.append(toString(value, key)); + } + } + } else if ("".equals(value)) { + sb.append('<'); + sb.append(key); + sb.append("/>"); + + // Emit a new tag + + } else { + sb.append(toString(value, key)); + } + } + if (tagName != null) { + + // Emit the close tag + + sb.append("'); + } + return sb.toString(); + + // XML does not have good support for arrays. If an array appears in + // a place + // where XML is lacking, synthesize an element. + + } else { + if (object.getClass().isArray()) { + object = new JSONArray(object); + } + if (object instanceof JSONArray) { + ja = (JSONArray) object; + length = ja.length(); + for (i = 0; i < length; i += 1) { + sb.append(toString(ja.opt(i), tagName == null ? "array" : tagName)); + } + return sb.toString(); + } else { + string = (object == null) ? "null" : escape(object.toString()); + return (tagName == null) ? "\"" + string + "\"" : (string.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + string + ""; + } + } + } } diff --git a/src/main/java/com/volmit/iris/util/XMLTokener.java b/src/main/java/com/volmit/iris/util/XMLTokener.java index 562944f8f..0498bfc36 100644 --- a/src/main/java/com/volmit/iris/util/XMLTokener.java +++ b/src/main/java/com/volmit/iris/util/XMLTokener.java @@ -28,398 +28,341 @@ SOFTWARE. /** * The XMLTokener extends the JSONTokener to provide additional methods for the * parsing of XML texts. - * + * * @author JSON.org * @version 2014-05-03 */ -public class XMLTokener extends JSONTokener -{ - - /** - * The table of entity values. It initially contains Character values for - * amp, apos, gt, lt, quot. - */ - public static final java.util.HashMap entity; - - static - { - entity = new java.util.HashMap(8); - entity.put("amp", XML.AMP); - entity.put("apos", XML.APOS); - entity.put("gt", XML.GT); - entity.put("lt", XML.LT); - entity.put("quot", XML.QUOT); - } - - /** - * Construct an XMLTokener from a string. - * - * @param s - * A source string. - */ - public XMLTokener(String s) - { - super(s); - } - - /** - * Get the text in the CDATA block. - * - * @return The string up to the ]]>. - * @throws JSONException - * If the ]]> is not found. - */ - public String nextCDATA() throws JSONException - { - char c; - int i; - StringBuilder sb = new StringBuilder(); - for(;;) - { - c = next(); - if(end()) - { - throw syntaxError("Unclosed CDATA"); - } - sb.append(c); - i = sb.length() - 3; - if(i >= 0 && sb.charAt(i) == ']' && sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') - { - sb.setLength(i); - return sb.toString(); - } - } - } - - /** - * Get the next XML outer token, trimming whitespace. There are two kinds of - * tokens: the '<' character which begins a markup tag, and the content text - * between markup tags. - * - * @return A string, or a '<' Character, or null if there is no more source - * text. - * @throws JSONException - */ - public Object nextContent() throws JSONException - { - char c; - StringBuilder sb; - do - { - c = next(); - } while(Character.isWhitespace(c)); - if(c == 0) - { - return null; - } - if(c == '<') - { - return XML.LT; - } - sb = new StringBuilder(); - for(;;) - { - if(c == '<' || c == 0) - { - back(); - return sb.toString().trim(); - } - if(c == '&') - { - sb.append(nextEntity(c)); - } else - { - sb.append(c); - } - c = next(); - } - } - - /** - * Return the next entity. These entities are translated to Characters: - * & ' > < ". - * - * @param ampersand - * An ampersand character. - * @return A Character or an entity String if the entity is not recognized. - * @throws JSONException - * If missing ';' in XML entity. - */ - public Object nextEntity(char ampersand) throws JSONException - { - StringBuilder sb = new StringBuilder(); - for(;;) - { - char c = next(); - if(Character.isLetterOrDigit(c) || c == '#') - { - sb.append(Character.toLowerCase(c)); - } else if(c == ';') - { - break; - } else - { - throw syntaxError("Missing ';' in XML entity: &" + sb); - } - } - String string = sb.toString(); - Object object = entity.get(string); - return object != null ? object : ampersand + string + ";"; - } - - /** - * Returns the next XML meta token. This is used for skipping over - * and structures. - * - * @return Syntax characters (< > / = ! ?) are returned as - * Character, and strings and names are returned as Boolean. We - * don't care what the values actually are. - * @throws JSONException - * If a string is not properly closed or if the XML is badly - * structured. - */ - public Object nextMeta() throws JSONException - { - char c; - char q; - do - { - c = next(); - } while(Character.isWhitespace(c)); - switch(c) - { - case 0: - throw syntaxError("Misshaped meta tag"); - case '<': - return XML.LT; - case '>': - return XML.GT; - case '/': - return XML.SLASH; - case '=': - return XML.EQ; - case '!': - return XML.BANG; - case '?': - return XML.QUEST; - case '"': - case '\'': - q = c; - for(;;) - { - c = next(); - if(c == 0) - { - throw syntaxError("Unterminated string"); - } - if(c == q) - { - return Boolean.TRUE; - } - } - default: - for(;;) - { - c = next(); - if(Character.isWhitespace(c)) - { - return Boolean.TRUE; - } - switch(c) - { - case 0: - case '<': - case '>': - case '/': - case '=': - case '!': - case '?': - case '"': - case '\'': - back(); - return Boolean.TRUE; - } - } - } - } - - /** - * Get the next XML Token. These tokens are found inside of angle brackets. - * It may be one of these characters: / > = ! ? or it may be a - * string wrapped in single quotes or double quotes, or it may be a name. - * - * @return a String or a Character. - * @throws JSONException - * If the XML is not well formed. - */ - public Object nextToken() throws JSONException - { - char c; - char q; - StringBuilder sb; - do - { - c = next(); - } while(Character.isWhitespace(c)); - switch(c) - { - case 0: - throw syntaxError("Misshaped element"); - case '<': - throw syntaxError("Misplaced '<'"); - case '>': - return XML.GT; - case '/': - return XML.SLASH; - case '=': - return XML.EQ; - case '!': - return XML.BANG; - case '?': - return XML.QUEST; - - // Quoted string - - case '"': - case '\'': - q = c; - sb = new StringBuilder(); - for(;;) - { - c = next(); - if(c == 0) - { - throw syntaxError("Unterminated string"); - } - if(c == q) - { - return sb.toString(); - } - if(c == '&') - { - sb.append(nextEntity(c)); - } else - { - sb.append(c); - } - } - default: - - // Name - - sb = new StringBuilder(); - for(;;) - { - sb.append(c); - c = next(); - if(Character.isWhitespace(c)) - { - return sb.toString(); - } - switch(c) - { - case 0: - return sb.toString(); - case '>': - case '/': - case '=': - case '!': - case '?': - case '[': - case ']': - back(); - return sb.toString(); - case '<': - case '"': - case '\'': - throw syntaxError("Bad character in a name"); - } - } - } - } - - /** - * Skip characters until past the requested string. If it is not found, we - * are left at the end of the source with a result of false. - * - * @param to - * A string to skip past. - * @throws JSONException - */ - public boolean skipPast(String to) throws JSONException - { - boolean b; - char c; - int i; - int j; - int offset = 0; - int length = to.length(); - char[] circle = new char[length]; - - /* - * First fill the circle buffer with as many characters as are in the to - * string. If we reach an early end, bail. - */ - - for(i = 0; i < length; i += 1) - { - c = next(); - if(c == 0) - { - return false; - } - circle[i] = c; - } - - /* We will loop, possibly for all of the remaining characters. */ - - for(;;) - { - j = offset; - b = true; - - /* Compare the circle buffer with the to string. */ - - for(i = 0; i < length; i += 1) - { - if(circle[j] != to.charAt(i)) - { - b = false; - break; - } - j += 1; - if(j >= length) - { - j -= length; - } - } - - /* If we exit the loop with b intact, then victory is ours. */ - - if(b) - { - return true; - } - - /* - * Get the next character. If there isn't one, then defeat is ours. - */ - - c = next(); - if(c == 0) - { - return false; - } - /* - * Shove the character in the circle buffer and advance the circle - * offset. The offset is mod n. - */ - circle[offset] = c; - offset += 1; - if(offset >= length) - { - offset -= length; - } - } - } +public class XMLTokener extends JSONTokener { + + /** + * The table of entity values. It initially contains Character values for + * amp, apos, gt, lt, quot. + */ + public static final java.util.HashMap entity; + + static { + entity = new java.util.HashMap(8); + entity.put("amp", XML.AMP); + entity.put("apos", XML.APOS); + entity.put("gt", XML.GT); + entity.put("lt", XML.LT); + entity.put("quot", XML.QUOT); + } + + /** + * Construct an XMLTokener from a string. + * + * @param s A source string. + */ + public XMLTokener(String s) { + super(s); + } + + /** + * Get the text in the CDATA block. + * + * @return The string up to the ]]>. + * @throws JSONException If the ]]> is not found. + */ + public String nextCDATA() throws JSONException { + char c; + int i; + StringBuilder sb = new StringBuilder(); + for (; ; ) { + c = next(); + if (end()) { + throw syntaxError("Unclosed CDATA"); + } + sb.append(c); + i = sb.length() - 3; + if (i >= 0 && sb.charAt(i) == ']' && sb.charAt(i + 1) == ']' && sb.charAt(i + 2) == '>') { + sb.setLength(i); + return sb.toString(); + } + } + } + + /** + * Get the next XML outer token, trimming whitespace. There are two kinds of + * tokens: the '<' character which begins a markup tag, and the content text + * between markup tags. + * + * @return A string, or a '<' Character, or null if there is no more source + * text. + * @throws JSONException + */ + public Object nextContent() throws JSONException { + char c; + StringBuilder sb; + do { + c = next(); + } while (Character.isWhitespace(c)); + if (c == 0) { + return null; + } + if (c == '<') { + return XML.LT; + } + sb = new StringBuilder(); + for (; ; ) { + if (c == '<' || c == 0) { + back(); + return sb.toString().trim(); + } + if (c == '&') { + sb.append(nextEntity(c)); + } else { + sb.append(c); + } + c = next(); + } + } + + /** + * Return the next entity. These entities are translated to Characters: + * & ' > < ". + * + * @param ampersand An ampersand character. + * @return A Character or an entity String if the entity is not recognized. + * @throws JSONException If missing ';' in XML entity. + */ + public Object nextEntity(char ampersand) throws JSONException { + StringBuilder sb = new StringBuilder(); + for (; ; ) { + char c = next(); + if (Character.isLetterOrDigit(c) || c == '#') { + sb.append(Character.toLowerCase(c)); + } else if (c == ';') { + break; + } else { + throw syntaxError("Missing ';' in XML entity: &" + sb); + } + } + String string = sb.toString(); + Object object = entity.get(string); + return object != null ? object : ampersand + string + ";"; + } + + /** + * Returns the next XML meta token. This is used for skipping over + * and structures. + * + * @return Syntax characters (< > / = ! ?) are returned as + * Character, and strings and names are returned as Boolean. We + * don't care what the values actually are. + * @throws JSONException If a string is not properly closed or if the XML is badly + * structured. + */ + public Object nextMeta() throws JSONException { + char c; + char q; + do { + c = next(); + } while (Character.isWhitespace(c)); + switch (c) { + case 0: + throw syntaxError("Misshaped meta tag"); + case '<': + return XML.LT; + case '>': + return XML.GT; + case '/': + return XML.SLASH; + case '=': + return XML.EQ; + case '!': + return XML.BANG; + case '?': + return XML.QUEST; + case '"': + case '\'': + q = c; + for (; ; ) { + c = next(); + if (c == 0) { + throw syntaxError("Unterminated string"); + } + if (c == q) { + return Boolean.TRUE; + } + } + default: + for (; ; ) { + c = next(); + if (Character.isWhitespace(c)) { + return Boolean.TRUE; + } + switch (c) { + case 0: + case '<': + case '>': + case '/': + case '=': + case '!': + case '?': + case '"': + case '\'': + back(); + return Boolean.TRUE; + } + } + } + } + + /** + * Get the next XML Token. These tokens are found inside of angle brackets. + * It may be one of these characters: / > = ! ? or it may be a + * string wrapped in single quotes or double quotes, or it may be a name. + * + * @return a String or a Character. + * @throws JSONException If the XML is not well formed. + */ + public Object nextToken() throws JSONException { + char c; + char q; + StringBuilder sb; + do { + c = next(); + } while (Character.isWhitespace(c)); + switch (c) { + case 0: + throw syntaxError("Misshaped element"); + case '<': + throw syntaxError("Misplaced '<'"); + case '>': + return XML.GT; + case '/': + return XML.SLASH; + case '=': + return XML.EQ; + case '!': + return XML.BANG; + case '?': + return XML.QUEST; + + // Quoted string + + case '"': + case '\'': + q = c; + sb = new StringBuilder(); + for (; ; ) { + c = next(); + if (c == 0) { + throw syntaxError("Unterminated string"); + } + if (c == q) { + return sb.toString(); + } + if (c == '&') { + sb.append(nextEntity(c)); + } else { + sb.append(c); + } + } + default: + + // Name + + sb = new StringBuilder(); + for (; ; ) { + sb.append(c); + c = next(); + if (Character.isWhitespace(c)) { + return sb.toString(); + } + switch (c) { + case 0: + return sb.toString(); + case '>': + case '/': + case '=': + case '!': + case '?': + case '[': + case ']': + back(); + return sb.toString(); + case '<': + case '"': + case '\'': + throw syntaxError("Bad character in a name"); + } + } + } + } + + /** + * Skip characters until past the requested string. If it is not found, we + * are left at the end of the source with a result of false. + * + * @param to A string to skip past. + * @throws JSONException + */ + public boolean skipPast(String to) throws JSONException { + boolean b; + char c; + int i; + int j; + int offset = 0; + int length = to.length(); + char[] circle = new char[length]; + + /* + * First fill the circle buffer with as many characters as are in the to + * string. If we reach an early end, bail. + */ + + for (i = 0; i < length; i += 1) { + c = next(); + if (c == 0) { + return false; + } + circle[i] = c; + } + + /* We will loop, possibly for all of the remaining characters. */ + + for (; ; ) { + j = offset; + b = true; + + /* Compare the circle buffer with the to string. */ + + for (i = 0; i < length; i += 1) { + if (circle[j] != to.charAt(i)) { + b = false; + break; + } + j += 1; + if (j >= length) { + j -= length; + } + } + + /* If we exit the loop with b intact, then victory is ours. */ + + if (b) { + return true; + } + + /* + * Get the next character. If there isn't one, then defeat is ours. + */ + + c = next(); + if (c == 0) { + return false; + } + /* + * Shove the character in the circle buffer and advance the circle + * offset. The offset is mod n. + */ + circle[offset] = c; + offset += 1; + if (offset >= length) { + offset -= length; + } + } + } }

+ * hunk.set(ax, ?, az, NOISE.get(ax+hx, az+hz)); + * + * @param parallelism the target parallelism value or 0 to disable + * @param c the consumer hunkX, hunkZ, hunkOffsetX, hunkOffsetZ. + * @return this + */ + default Hunk iterate2DTop(int parallelism, Consumer5> c) { + compute2D(parallelism, (x, y, z, h) -> + { + for (int i = 0; i < h.getWidth(); i++) { + for (int k = 0; k < h.getDepth(); k++) { + c.accept(i, k, x, z, h); + } + } + }); + + return this; + } + + default Hunk iterate(Predicate p, Consumer3 c) { + return iterate(getIdeal3DParallelism(), p, c); + } + + default Hunk iterate(int parallelism, Predicate p, Consumer3 c) { + iterate(parallelism, (x, y, z, t) -> + { + if (p.test(t)) { + c.accept(x, y, z); + } + }); + + return this; + } + + default Hunk iterate(Predicate p, Consumer4 c) { + return iterate(getIdeal3DParallelism(), p, c); + } + + default Hunk iterate(int parallelism, Predicate p, Consumer4 c) { + iterate(parallelism, (x, y, z, t) -> + { + if (p.test(t)) { + c.accept(x, y, z, t); + } + }); + + return this; + } + + default Hunk iterate(Consumer3 c) { + return iterate(getIdeal3DParallelism(), c); + } + + default Hunk iterateSync(Consumer3 c) { + for (int i = 0; i < getWidth(); i++) { + for (int j = 0; j < getHeight(); j++) { + for (int k = 0; k < getDepth(); k++) { + c.accept(i, j, k); + } + } + } + + return this; + } + + default Hunk iterateSync(Consumer4 c) { + for (int i = 0; i < getWidth(); i++) { + for (int j = 0; j < getHeight(); j++) { + for (int k = 0; k < getDepth(); k++) { + c.accept(i, j, k, get(i, j, k)); + } + } + } + + return this; + } + + default Hunk iterate(int parallelism, Consumer3 c) { + compute3D(parallelism, (x, y, z, h) -> + { + for (int i = 0; i < h.getWidth(); i++) { + for (int j = 0; j < h.getHeight(); j++) { + for (int k = 0; k < h.getDepth(); k++) { + c.accept(i + x, j + y, k + z); + } + } + } + }); + + return this; + } + + default Hunk iterate(Consumer4 c) { + return iterate(getIdeal3DParallelism(), c); + } + + default Hunk iterate(int parallelism, Consumer4 c) { + compute3D(parallelism, (x, y, z, h) -> + { + for (int i = 0; i < h.getWidth(); i++) { + for (int j = 0; j < h.getHeight(); j++) { + for (int k = 0; k < h.getDepth(); k++) { + c.accept(i + x, j + y, k + z, h.get(i, j, k)); + } + } + } + }); + + return this; + } + + default Hunk compute2D(Consumer4> v) { + return compute2D(getIdeal2DParallelism(), v); + } + + static void computeDual2D(int parallelism, Hunk a, Hunk b, Consumer5, Hunk> v) { + if (a.getWidth() != b.getWidth() || a.getHeight() != b.getHeight() || a.getDepth() != b.getDepth()) { + throw new RuntimeException("Hunk sizes must match!"); + } + + if (a.get2DDimension(parallelism) == 1) { + v.accept(0, 0, 0, a, b); + return; + } + + BurstExecutor e = MultiBurst.burst.burst(parallelism); + KList rq = new KList(parallelism); + getDualSections2D(parallelism, a, b, (xx, yy, zz, ha, hr, r) -> e.queue(() -> + { + v.accept(xx, yy, zz, ha, hr); + + synchronized (rq) { + rq.add(r); + } + }), (x, y, z, hax, hbx) -> + { + a.insert(x, y, z, hax); + b.insert(x, y, z, hbx); + }); + e.complete(); + rq.forEach(Runnable::run); + return; + } + + static void getDualSections2D(int sections, Hunk a, Hunk b, Consumer6, Hunk, Runnable> v, Consumer5, Hunk> inserterAB) { + if (a.getWidth() != b.getWidth() || a.getHeight() != b.getHeight() || a.getDepth() != b.getDepth()) { + throw new RuntimeException("Hunk sizes must match!"); + } + + int dim = a.get2DDimension(sections); + + if (sections <= 1) { + getDualSection(0, 0, 0, a.getWidth(), a.getHeight(), a.getDepth(), a, b, (ha, hr, r) -> v.accept(0, 0, 0, ha, hr, r), inserterAB); + return; + } + + int w = a.getWidth() / dim; + int wr = a.getWidth() - (w * dim); + int d = a.getDepth() / dim; + int dr = a.getDepth() - (d * dim); + int i, j; + + for (i = 0; i < a.getWidth(); i += w) { + int ii = i; + + for (j = 0; j < a.getDepth(); j += d) { + int jj = j; + getDualSection(i, 0, j, i + w + (i == 0 ? wr : 0), a.getHeight(), j + d + (j == 0 ? dr : 0), a, b, (ha, hr, r) -> v.accept(ii, 0, jj, ha, hr, r), inserterAB); + i = i == 0 ? i + wr : i; + j = j == 0 ? j + dr : j; + } + } + } + + static void getDualSection(int x, int y, int z, int x1, int y1, int z1, Hunk a, Hunk b, Consumer3, Hunk, Runnable> v, Consumer5, Hunk> inserter) { + Hunk copya = a.crop(x, y, z, x1, y1, z1); + Hunk copyb = b.crop(x, y, z, x1, y1, z1); + v.accept(copya, copyb, () -> inserter.accept(x, y, z, copya, copyb)); + } + + default Hunk compute2D(int parallelism, Consumer4> v) { + if (get2DDimension(parallelism) == 1) { + v.accept(0, 0, 0, this); + return this; + } + + BurstExecutor e = MultiBurst.burst.burst(parallelism); + + if (isAtomic()) { + getSectionsAtomic2D(parallelism, (xx, yy, zz, h) -> e.queue(() -> + { + v.accept(xx, yy, zz, h); + })); + + e.complete(); + } else { + KList rq = new KList(parallelism); + + getSections2D(parallelism, (xx, yy, zz, h, r) -> e.queue(() -> + { + v.accept(xx, yy, zz, h); + + synchronized (rq) { + rq.add(r); + } + }), this::insert); + + e.complete(); + rq.forEach(Runnable::run); + } + + return this; + } + + default Hunk compute2DYRange(int parallelism, int ymin, int ymax, Consumer4> v) { + if (get2DDimension(parallelism) == 1) { + v.accept(0, 0, 0, this); + return this; + } + + BurstExecutor e = MultiBurst.burst.burst(parallelism); + KList rq = new KList(parallelism); + getSections2DYLimit(parallelism, ymin, ymax, (xx, yy, zz, h, r) -> e.queue(() -> + { + v.accept(xx, yy, zz, h); + + synchronized (rq) { + rq.add(r); + } + }), this::insert); + e.complete(); + rq.forEach(Runnable::run); + return this; + } + + default Hunk compute3D(Consumer4> v) { + return compute3D(getIdeal3DParallelism(), v); + } + + default Hunk compute3D(int parallelism, Consumer4> v) { + if (get3DDimension(parallelism) == 1) { + v.accept(0, 0, 0, this); + return this; + } + + BurstExecutor e = MultiBurst.burst.burst(parallelism); + KList rq = new KList(parallelism); + getSections3D(parallelism, (xx, yy, zz, h, r) -> e.queue(() -> + { + v.accept(xx, yy, zz, h); + synchronized (rq) { + rq.add(r); + } + }), this::insert); + e.complete(); + rq.forEach(Runnable::run); + return this; + } + + default Hunk getSections2D(int sections, Consumer5, Runnable> v) { + return getSections2D(sections, v, this::insert); + } + + default Hunk getSectionsAtomic2D(int sections, Consumer4> v) { + int dim = get2DDimension(sections); + + if (sections <= 1) { + getAtomicSection(0, 0, 0, getWidth(), getHeight(), getDepth(), (hh) -> v.accept(0, 0, 0, hh)); + return this; + } + + int w = getWidth() / dim; + int wr = getWidth() - (w * dim); + int d = getDepth() / dim; + int dr = getDepth() - (d * dim); + int i, j; + + for (i = 0; i < getWidth(); i += w) { + int ii = i; + + for (j = 0; j < getDepth(); j += d) { + int jj = j; + getAtomicSection(i, 0, j, i + w + (i == 0 ? wr : 0), getHeight(), j + d + (j == 0 ? dr : 0), (h) -> v.accept(ii, 0, jj, h)); + i = i == 0 ? i + wr : i; + j = j == 0 ? j + dr : j; + } + } + + return this; + } + + default Hunk getSections2D(int sections, Consumer5, Runnable> v, Consumer4> inserter) { + int dim = get2DDimension(sections); + + if (sections <= 1) { + getSection(0, 0, 0, getWidth(), getHeight(), getDepth(), (hh, r) -> v.accept(0, 0, 0, hh, r), inserter); + return this; + } + + int w = getWidth() / dim; + int wr = getWidth() - (w * dim); + int d = getDepth() / dim; + int dr = getDepth() - (d * dim); + int i, j; + + for (i = 0; i < getWidth(); i += w) { + int ii = i; + + for (j = 0; j < getDepth(); j += d) { + int jj = j; + getSection(i, 0, j, i + w + (i == 0 ? wr : 0), getHeight(), j + d + (j == 0 ? dr : 0), (h, r) -> v.accept(ii, 0, jj, h, r), inserter); + i = i == 0 ? i + wr : i; + j = j == 0 ? j + dr : j; + } + } + + return this; + } + + default Hunk getSections2DYLimit(int sections, int ymin, int ymax, Consumer5, Runnable> v, Consumer4> inserter) { + int dim = get2DDimension(sections); + + if (sections <= 1) { + getSection(0, 0, 0, getWidth(), getHeight(), getDepth(), (hh, r) -> v.accept(0, 0, 0, hh, r), inserter); + return this; + } + + int w = getWidth() / dim; + int wr = getWidth() - (w * dim); + int d = getDepth() / dim; + int dr = getDepth() - (d * dim); + int i, j; + + for (i = 0; i < getWidth(); i += w) { + int ii = i; + + for (j = 0; j < getDepth(); j += d) { + int jj = j; + getSection(i, ymin, j, i + w + (i == 0 ? wr : 0), ymax, j + d + (j == 0 ? dr : 0), (h, r) -> v.accept(ii, ymin, jj, h, r), inserter); + i = i == 0 ? i + wr : i; + j = j == 0 ? j + dr : j; + } + } + + return this; + } + + default Hunk getSections3D(int sections, Consumer5, Runnable> v) { + return getSections3D(sections, v, (xx, yy, zz, c) -> insert(xx, yy, zz, c)); + } + + default Hunk getSections3D(int sections, Consumer5, Runnable> v, Consumer4> inserter) { + int dim = get3DDimension(sections); + + if (sections <= 1) { + getSection(0, 0, 0, getWidth(), getHeight(), getDepth(), (hh, r) -> v.accept(0, 0, 0, hh, r), inserter); + return this; + } + + int w = getWidth() / dim; + int h = getHeight() / dim; + int d = getDepth() / dim; + int wr = getWidth() - (w * dim); + int hr = getHeight() - (h * dim); + int dr = getDepth() - (d * dim); + int i, j, k; + + for (i = 0; i < getWidth(); i += w) { + int ii = i; + + for (j = 0; j < getHeight(); j += d) { + int jj = j; + + for (k = 0; k < getDepth(); k += d) { + int kk = k; + getSection(ii, jj, kk, i + w + (i == 0 ? wr : 0), j + h + (j == 0 ? hr : 0), k + d + (k == 0 ? dr : 0), (hh, r) -> v.accept(ii, jj, kk, hh, r), inserter); + i = i == 0 ? i + wr : i; + j = j == 0 ? j + hr : j; + k = k == 0 ? k + dr : k; + } + } + } + + return this; + } + + default Hunk getSection(int x, int y, int z, int x1, int y1, int z1, Consumer2, Runnable> v) { + return getSection(x, y, z, x1, y1, z1, v, (xx, yy, zz, c) -> insert(xx, yy, zz, c)); + } + + default Hunk getSection(int x, int y, int z, int x1, int y1, int z1, Consumer2, Runnable> v, Consumer4> inserter) { + Hunk copy = crop(x, y, z, x1, y1, z1); + v.accept(copy, () -> inserter.accept(x, y, z, copy)); + return this; + } + + default Hunk getAtomicSection(int x, int y, int z, int x1, int y1, int z1, Consumer> v) { + Hunk copy = croppedView(x, y, z, x1, y1, z1); + v.accept(copy); + return this; + } + + default void enforceBounds(int x, int y, int z) { + if (x < 0 || x >= getWidth() || y < 0 || y >= getHeight() || z < 0 || z >= getDepth()) { + //Iris.warn(x + "," + y + "," + z + " does not fit within size " + getWidth() + "," + getHeight() + "," + getDepth() + " (0,0,0 to " + (getWidth() - 1) + "," + (getHeight() - 1) + "," + (getDepth() - 1) + ")"); + } + } + + default void enforceBounds(int x, int y, int z, int w, int h, int d) { + if (x < 0 || x >= getWidth() || y < 0 || y >= getHeight() || z < 0 || z >= getDepth() || x + w < 0 || x + w > getWidth() || y + h < 0 || y + h > getHeight() || z + d < 0 || z + d > getDepth()) { + //Iris.warn("The hunk " + w + "," + h + "," + d + " with an offset of " + x + "," + y + "," + z + " does not fit within the parent hunk " + getWidth() + "," + getHeight() + "," + getDepth() + " (0,0,0 to " + (getWidth() - 1) + "," + (getHeight() - 1) + "," + (getDepth() - 1) + ")"); + } + } + + /** + * Create a new hunk from a section of this hunk. + * + * @param x1 The min x (inclusive) + * @param y1 The min y (inclusive) + * @param z1 The min z (inclusive) + * @param x2 The max x (exclusive) + * @param y2 The max y (exclusive) + * @param z2 The max z (exclusive) + * @return the new hunk (x2-x1, y2-y1, z2-z1) + */ + default ArrayHunk crop(int x1, int y1, int z1, int x2, int y2, int z2) { + ArrayHunk h = new ArrayHunk(x2 - x1, y2 - y1, z2 - z1); + enforceBounds(x1, y1, z1, x2 - x1, y2 - y1, z2 - z1); + + for (int i = x1; i < x2; i++) { + for (int j = y1; j < y2; j++) { + for (int k = z1; k < z2; k++) { + h.setRaw(i - x1, j - y1, k - z1, getRaw(i, j, k)); + } + } + } + + return h; + } + + /** + * Create a new view of this same hunk from a section of this hunk. + * Modifications are routed to this hunk! + * + * @param x1 The min x (inclusive) + * @param y1 The min y (inclusive) + * @param z1 The min z (inclusive) + * @param x2 The max x (exclusive) + * @param y2 The max y (exclusive) + * @param z2 The max z (exclusive) + * @return the cropped view of this hunk (x2-x1, y2-y1, z2-z1) + */ + default Hunk croppedView(int x1, int y1, int z1, int x2, int y2, int z2) { + enforceBounds(x1, y1, z1, x2 - x1, y2 - y1, z2 - z1); + return new HunkView(this, x2 - x1, y2 - y1, z2 - z1, x1, y1, z1); + } + + /** + * @return The X length + */ + int getWidth(); + + /** + * @return The Z length + */ + int getDepth(); + + /** + * @return The Y length + */ + int getHeight(); + + /** + * Set a region + * + * @param x1 inclusive 1st x + * @param y1 inclusive 1st y + * @param z1 inclusive 1st z + * @param x2 inclusive 2nd x + * @param y2 inclusive 2nd y + * @param z2 inclusive 2nd z + * @param t the value to set + */ + default void set(int x1, int y1, int z1, int x2, int y2, int z2, T t) { + enforceBounds(x1, y1, z1, x2 - x1, y2 - y1, z2 - z1); + for (int i = x1; i <= x2; i++) { + for (int j = y1; j <= y2; j++) { + for (int k = z1; k <= z2; k++) { + setRaw(i, j, k, t); + } + } + } + } + + /** + * Get the value to the closest valid position + * + * @param x the x + * @param y the y + * @param z the z + * @return the value closest to the border of the hunk + */ + default T getClosest(int x, int y, int z) { + return getRaw(x >= getWidth() ? getWidth() - 1 : x < 0 ? 0 : x, y >= getHeight() ? getHeight() - 1 : y < 0 ? 0 : y, z >= getDepth() ? getDepth() - 1 : z < 0 ? 0 : z); + } + + default void fill(T t) { + set(0, 0, 0, getWidth() - 1, getHeight() - 1, getDepth() - 1, t); + } + + /** + * Get a 1 node thick hunk representing the face of this hunk + * + * @param f the face + * @return the hunk view of this hunk + */ + default Hunk viewFace(HunkFace f) { + switch (f) { + case BOTTOM: + return croppedView(0, 0, 0, getWidth() - 1, 0, getDepth() - 1); + case EAST: + return croppedView(getWidth() - 1, 0, 0, getWidth() - 1, getHeight() - 1, getDepth() - 1); + case NORTH: + return croppedView(0, 0, 0, getWidth() - 1, getHeight() - 1, 0); + case SOUTH: + return croppedView(0, 0, 0, 0, getHeight() - 1, getDepth() - 1); + case TOP: + return croppedView(0, getHeight() - 1, 0, getWidth() - 1, getHeight() - 1, getDepth() - 1); + case WEST: + return croppedView(0, 0, getDepth() - 1, getWidth() - 1, getHeight() - 1, getDepth() - 1); + default: + break; + } + + return null; + } + + /** + * Crop (copy) a 1 node thick hunk representing the face of this hunk + * + * @param f the face + * @return the hunk copy (face) of this hunk + */ + default Hunk cropFace(HunkFace f) { + switch (f) { + case BOTTOM: + return crop(0, 0, 0, getWidth() - 1, 0, getDepth() - 1); + case EAST: + return crop(getWidth() - 1, 0, 0, getWidth() - 1, getHeight() - 1, getDepth() - 1); + case NORTH: + return crop(0, 0, 0, getWidth() - 1, getHeight() - 1, 0); + case SOUTH: + return crop(0, 0, 0, 0, getHeight() - 1, getDepth() - 1); + case TOP: + return crop(0, getHeight() - 1, 0, getWidth() - 1, getHeight() - 1, getDepth() - 1); + case WEST: + return crop(0, 0, getDepth() - 1, getWidth() - 1, getHeight() - 1, getDepth() - 1); + default: + break; + } + + return null; + } + + /** + * Set a value at the given position + * + * @param x the x + * @param y the y + * @param z the z + * @param t the value + */ + default void set(int x, int y, int z, T t) { + enforceBounds(x, y, z); + setRaw(x, y, z, t); + } + + default void setIfExists(int x, int y, int z, T t) { + if (x < 0 || x >= getWidth() || y < 0 || y >= getHeight() || z < 0 || z >= getDepth()) { + return; + } + + setRaw(x, y, z, t); + } + + default T getIfExists(int x, int y, int z, T t) { + if (x < 0 || x >= getWidth() || y < 0 || y >= getHeight() || z < 0 || z >= getDepth()) { + return t; + } + + return getOr(x, y, z, t); + } + + default T getIfExists(int x, int y, int z) { + return getIfExists(x, y, z, null); + } + + /** + * Set a value at the given position without checking coordinate bounds + * + * @param x the x + * @param y the y + * @param z the z + * @param t the value + */ + void setRaw(int x, int y, int z, T t); + + /** + * Get a value at the given position without checking coordinate bounds + * + * @param x the x + * @param y the y + * @param z the z + * @return the value or null + */ + T getRaw(int x, int y, int z); + + /** + * Get a value at the given position + * + * @param x the x + * @param y the y + * @param z the z + * @return the value or null + */ + default T get(int x, int y, int z) { + enforceBounds(x, y, z); + return getRaw(x, y, z); + } + + default T getOr(int x, int y, int z, T t) { + enforceBounds(x, y, z); + T v = getRaw(x, y, z); + + if (v == null) { + return t; + } + + return v; + } + + /** + * Insert a hunk into this one with an offset the inserted hunk + * + * @param offX the offset from zero for x + * @param offY the offset from zero for y + * @param offZ the offset from zero for z + * @param hunk the hunk to insert + */ + default void insert(int offX, int offY, int offZ, Hunk hunk) { + insert(offX, offY, offZ, hunk, false); + } + + default void insertSoftly(int offX, int offY, int offZ, Hunk hunk, Predicate shouldOverwrite) { + insertSoftly(offX, offY, offZ, hunk, false, shouldOverwrite); + } + + /** + * Insert a hunk into this one + * + * @param hunk the hunk to insert + */ + default void insert(Hunk hunk) { + insert(0, 0, 0, hunk, false); + } + + /** + * Returns the source of this hunk view. This could return another hunk view, + * not an actual source, however it does return it's underlying data source. If + * this hunk is a data source and not a view, it will return null. + * + * @return the source or null if this is already the source + */ + default Hunk getSource() { + return null; + } + + /** + * Insert a hunk into this one + * + * @param hunk the hunk to insert + * @param inverted invert the inserted hunk or not + */ + default void insert(Hunk hunk, boolean inverted) { + insert(0, 0, 0, hunk, inverted); + } + + /** + * Insert a hunk into this one with an offset and possibly inverting the y of + * the inserted hunk + * + * @param offX the offset from zero for x + * @param offY the offset from zero for y + * @param offZ the offset from zero for z + * @param hunk the hunk to insert + * @param invertY should the inserted hunk be inverted + */ + default void insert(int offX, int offY, int offZ, Hunk hunk, boolean invertY) { + enforceBounds(offX, offY, offZ, hunk.getWidth(), hunk.getHeight(), hunk.getDepth()); + + for (int i = offX; i < offX + hunk.getWidth(); i++) { + for (int j = offY; j < offY + hunk.getHeight(); j++) { + for (int k = offZ; k < offZ + hunk.getDepth(); k++) { + setRaw(i, j, k, hunk.getRaw(i - offX, j - offY, k - offZ)); + } + } + } + } + + /** + * Insert a hunk into this one with an offset and possibly inverting the y of. Will never insert a node if its already used + * the inserted hunk + * + * @param offX the offset from zero for x + * @param offY the offset from zero for y + * @param offZ the offset from zero for z + * @param hunk the hunk to insert + * @param invertY should the inserted hunk be inverted + */ + default void insertSoftly(int offX, int offY, int offZ, Hunk hunk, boolean invertY, Predicate shouldOverwrite) { + enforceBounds(offX, offY, offZ, hunk.getWidth(), hunk.getHeight(), hunk.getDepth()); + + for (int i = offX; i < offX + hunk.getWidth(); i++) { + for (int j = offY; j < offY + hunk.getHeight(); j++) { + for (int k = offZ; k < offZ + hunk.getDepth(); k++) { + if (shouldOverwrite.test(getRaw(i, j, k))) { + setRaw(i, j, k, hunk.getRaw(i - offX, j - offY, k - offZ)); + } + } + } + } + } + + /** + * Acts like fill, however if used by a mapped hunk, will simply clear it + * + * @param b the data to use for fill + */ + default void empty(T b) { + fill(b); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/HunkFace.java b/src/main/java/com/volmit/iris/scaffold/hunk/HunkFace.java index 253ae27c5..99dd6abb9 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/HunkFace.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/HunkFace.java @@ -1,11 +1,10 @@ package com.volmit.iris.scaffold.hunk; -public enum HunkFace -{ - TOP, - BOTTOM, - EAST, - WEST, - NORTH, - SOUTH; +public enum HunkFace { + TOP, + BOTTOM, + EAST, + WEST, + NORTH, + SOUTH } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/io/BasicHunkIOAdapter.java b/src/main/java/com/volmit/iris/scaffold/hunk/io/BasicHunkIOAdapter.java index 518171c1e..744399fbc 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/io/BasicHunkIOAdapter.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/io/BasicHunkIOAdapter.java @@ -16,19 +16,14 @@ public abstract class BasicHunkIOAdapter implements HunkIOAdapter { dos.writeInt(t.getNonNullEntries() + Integer.MIN_VALUE); AtomicBoolean failure = new AtomicBoolean(false); - t.iterate(0, (x,y,z,w) -> { - if(w != null) - { - try - { + t.iterate(0, (x, y, z, w) -> { + if (w != null) { + try { dos.writeShort(x + Short.MIN_VALUE); dos.writeShort(y + Short.MIN_VALUE); dos.writeShort(z + Short.MIN_VALUE); write(w, dos); - } - - catch(Throwable e) - { + } catch (Throwable e) { e.printStackTrace(); failure.set(true); } @@ -39,7 +34,7 @@ public abstract class BasicHunkIOAdapter implements HunkIOAdapter { } @Override - public Hunk read(Function3> factory, InputStream in) throws IOException { + public Hunk read(Function3> factory, InputStream in) throws IOException { DataInputStream din = new DataInputStream(in); int w = din.readShort() - Short.MIN_VALUE; int h = din.readShort() - Short.MIN_VALUE; @@ -47,19 +42,17 @@ public abstract class BasicHunkIOAdapter implements HunkIOAdapter { int e = din.readInt() - Integer.MIN_VALUE; Hunk t = factory.apply(w, h, d); - for(int i = 0; i < e; i++) - { + for (int i = 0; i < e; i++) { int x = din.readShort() - Short.MIN_VALUE; int y = din.readShort() - Short.MIN_VALUE; int z = din.readShort() - Short.MIN_VALUE; T v = read(din); - if(v == null) - { + if (v == null) { throw new IOException("NULL VALUE AT " + x + " " + y + " " + z); } - t.setRaw(x,y,z, v); + t.setRaw(x, y, z, v); } in.close(); diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/io/HunkIOAdapter.java b/src/main/java/com/volmit/iris/scaffold/hunk/io/HunkIOAdapter.java index 024e92563..6c913150b 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/io/HunkIOAdapter.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/io/HunkIOAdapter.java @@ -10,32 +10,27 @@ import java.io.*; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; -public interface HunkIOAdapter extends IOAdapter -{ - public void write(Hunk t, OutputStream out) throws IOException; +public interface HunkIOAdapter extends IOAdapter { + void write(Hunk t, OutputStream out) throws IOException; - public Hunk read(Function3> factory, InputStream in) throws IOException; + Hunk read(Function3> factory, InputStream in) throws IOException; - default void write(Hunk t, File f) throws IOException - { + default void write(Hunk t, File f) throws IOException { f.getParentFile().mkdirs(); FileOutputStream fos = new FileOutputStream(f); GZIPOutputStream gzo = new CustomOutputStream(fos, 6); write(t, gzo); } - default Hunk read(Function3> factory, File f) throws IOException - { + default Hunk read(Function3> factory, File f) throws IOException { return read(factory, new GZIPInputStream(new FileInputStream(f))); } - default Hunk read(Function3> factory, ByteArrayTag f) throws IOException - { + default Hunk read(Function3> factory, ByteArrayTag f) throws IOException { return read(factory, new ByteArrayInputStream(f.getValue())); } - default ByteArrayTag writeByteArrayTag(Hunk tHunk, String name) throws IOException - { + default ByteArrayTag writeByteArrayTag(Hunk tHunk, String name) throws IOException { ByteArrayOutputStream boas = new ByteArrayOutputStream(); write(tHunk, boas); return new ByteArrayTag(name, boas.toByteArray()); diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/io/HunkRegion.java b/src/main/java/com/volmit/iris/scaffold/hunk/io/HunkRegion.java index d54eac281..60db695c3 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/io/HunkRegion.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/io/HunkRegion.java @@ -1,92 +1,76 @@ package com.volmit.iris.scaffold.hunk.io; +import com.volmit.iris.util.*; + import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Map; -import com.volmit.iris.util.CompoundTag; -import com.volmit.iris.util.KMap; -import com.volmit.iris.util.NBTInputStream; -import com.volmit.iris.util.NBTOutputStream; -import com.volmit.iris.util.Tag; +public class HunkRegion { + private final File folder; + private CompoundTag compound; + private final int x; + private final int z; -public class HunkRegion -{ - private final File folder; - private CompoundTag compound; - private final int x; - private final int z; + public HunkRegion(File folder, int x, int z, CompoundTag compound) { + this.compound = fix(compound); + this.folder = folder; + this.x = x; + this.z = z; + folder.mkdirs(); + } - public HunkRegion(File folder, int x, int z, CompoundTag compound) - { - this.compound = fix(compound); - this.folder = folder; - this.x = x; - this.z = z; - folder.mkdirs(); - } + public HunkRegion(File folder, int x, int z) { + this(folder, x, z, new CompoundTag(x + "." + z, new KMap<>())); + File f = getFile(); - public HunkRegion(File folder, int x, int z) - { - this(folder, x, z, new CompoundTag(x + "." + z, new KMap<>())); - File f = getFile(); + if (f.exists()) { + try { + NBTInputStream in = new NBTInputStream(new FileInputStream(f)); + compound = fix((CompoundTag) in.readTag()); + in.close(); + } catch (Throwable ignored) { - if(f.exists()) - { - try - { - NBTInputStream in = new NBTInputStream(new FileInputStream(f)); - compound = fix((CompoundTag) in.readTag()); - in.close(); - } + } + } + } - catch(Throwable ignored) - { + public CompoundTag getCompound() { + return compound; + } - } - } - } + private CompoundTag fix(CompoundTag readTag) { + Map v = readTag.getValue(); - public CompoundTag getCompound() { - return compound; - } + if (!(v instanceof KMap)) { + return new CompoundTag(readTag.getName(), new KMap(v)); + } - private CompoundTag fix(CompoundTag readTag) - { - Map v = readTag.getValue(); + return readTag; + } - if(!(v instanceof KMap)) - { - return new CompoundTag(readTag.getName(), new KMap(v)); - } + public File getFile() { + return new File(folder, x + "." + z + ".dat"); + } - return readTag; - } + public void save() throws IOException { + synchronized (compound) { + File f = getFile(); + FileOutputStream fos = new FileOutputStream(f); + NBTOutputStream out = new NBTOutputStream(fos); + out.writeTag(compound); + out.close(); + } + } - public File getFile() - { - return new File(folder, x + "." + z + ".dat"); - } + public int getX() { + return x; + } - public void save() throws IOException - { - synchronized(compound) - { - File f = getFile(); - FileOutputStream fos = new FileOutputStream(f); - NBTOutputStream out = new NBTOutputStream(fos); - out.writeTag(compound); - out.close(); - } - } - - public int getX() { - return x; - } - public int getZ() { - return z; - } + public int getZ() { + return z; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/io/HunkRegionSlice.java b/src/main/java/com/volmit/iris/scaffold/hunk/io/HunkRegionSlice.java index b0c23fa1d..79cae2ace 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/io/HunkRegionSlice.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/io/HunkRegionSlice.java @@ -13,287 +13,235 @@ import org.bukkit.block.data.BlockData; import java.io.IOException; import java.util.concurrent.atomic.AtomicReference; -public class HunkRegionSlice -{ - public static final Function2> BLOCKDATA = (h, c) -> new HunkRegionSlice<>(h, Hunk::newMappedHunkSynced, new BlockDataHunkIOAdapter(), c, "blockdata"); - public static final Function2>> TILE = (h, c) -> new HunkRegionSlice<>(h, Hunk::newMappedHunkSynced, new TileDataHunkIOAdapter(), c, "tile"); - public static final Function3> STRING = (h, c, t) -> new HunkRegionSlice<>(h, Hunk::newMappedHunkSynced, new StringHunkIOAdapter(), c, t); - public static final Function3> BOOLEAN = (h, c, t) -> new HunkRegionSlice<>(h, Hunk::newMappedHunkSynced, new BooleanHunkIOAdapter(), c, t); - private final Function3> factory; - private final GridLock lock; - private final HunkIOAdapter adapter; - private final CompoundTag compound; - private final String key; - private final KMap> loadedChunks; - private final KMap lastUse; - private final KList save; - private final int height; +public class HunkRegionSlice { + public static final Function2> BLOCKDATA = (h, c) -> new HunkRegionSlice<>(h, Hunk::newMappedHunkSynced, new BlockDataHunkIOAdapter(), c, "blockdata"); + public static final Function2>> TILE = (h, c) -> new HunkRegionSlice<>(h, Hunk::newMappedHunkSynced, new TileDataHunkIOAdapter(), c, "tile"); + public static final Function3> STRING = (h, c, t) -> new HunkRegionSlice<>(h, Hunk::newMappedHunkSynced, new StringHunkIOAdapter(), c, t); + public static final Function3> BOOLEAN = (h, c, t) -> new HunkRegionSlice<>(h, Hunk::newMappedHunkSynced, new BooleanHunkIOAdapter(), c, t); + private final Function3> factory; + private final GridLock lock; + private final HunkIOAdapter adapter; + private final CompoundTag compound; + private final String key; + private final KMap> loadedChunks; + private final KMap lastUse; + private final KList save; + private final int height; - public HunkRegionSlice(int height, Function3> factory, HunkIOAdapter adapter, CompoundTag compound, String key) - { - this.lock = new GridLock(32, 32); - this.height = height; - this.loadedChunks = new KMap<>(); - this.factory = factory; - this.adapter = adapter; - this.compound = compound; - this.save = new KList<>(); - this.key = key; - this.lastUse = new KMap<>(); - } + public HunkRegionSlice(int height, Function3> factory, HunkIOAdapter adapter, CompoundTag compound, String key) { + this.lock = new GridLock(32, 32); + this.height = height; + this.loadedChunks = new KMap<>(); + this.factory = factory; + this.adapter = adapter; + this.compound = compound; + this.save = new KList<>(); + this.key = key; + this.lastUse = new KMap<>(); + } - public synchronized int cleanup(long t) - { - int v = 0; - if(loadedChunks.size() != lastUse.size()) - { - Iris.warn("Incorrect chunk use counts in " + key); + public synchronized int cleanup(long t) { + int v = 0; + if (loadedChunks.size() != lastUse.size()) { + Iris.warn("Incorrect chunk use counts in " + key); - for(ChunkPosition i : lastUse.k()) - { - if(!loadedChunks.containsKey(i)) - { - Iris.warn(" Missing LoadChunkKey " + i); - } - } - } + for (ChunkPosition i : lastUse.k()) { + if (!loadedChunks.containsKey(i)) { + Iris.warn(" Missing LoadChunkKey " + i); + } + } + } - for(ChunkPosition i : lastUse.k()) - { - Long l = lastUse.get(i); - if(l == null || M.ms() - l > t) - { - v++; - unload(i.getX(), i.getZ()); - } - } + for (ChunkPosition i : lastUse.k()) { + Long l = lastUse.get(i); + if (l == null || M.ms() - l > t) { + v++; + unload(i.getX(), i.getZ()); + } + } - return v; - } + return v; + } - public synchronized void clear() - { - for(String i : new KList<>(compound.getValue().keySet())) - { - if(i.startsWith(key + ".")) - { - compound.getValue().remove(i); - } - } - } + public synchronized void clear() { + for (String i : new KList<>(compound.getValue().keySet())) { + if (i.startsWith(key + ".")) { + compound.getValue().remove(i); + } + } + } - public synchronized void save() - { - BurstExecutor e = MultiBurst.burst.burst(); - for(ChunkPosition i : save.copy()) - { - if(i == null) - { - continue; - } + public synchronized void save() { + BurstExecutor e = MultiBurst.burst.burst(); + for (ChunkPosition i : save.copy()) { + if (i == null) { + continue; + } - e.queue(() -> save(i.getX(), i.getZ())); + e.queue(() -> save(i.getX(), i.getZ())); - try - { - lock.withNasty(i.getX(), i.getZ(), () -> save.remove(i)); - } + try { + lock.withNasty(i.getX(), i.getZ(), () -> save.remove(i)); + } catch (Throwable ef) { - catch(Throwable ef) - { + } + } - } - } + e.complete(); + } - e.complete(); - } + public boolean contains(int x, int z) { + return compound.getValue().containsKey(key(x, z)); + } - public boolean contains(int x, int z) - { - return compound.getValue().containsKey(key(x, z)); - } + public void delete(int x, int z) { + lock.with(x, z, () -> compound.getValue().remove(key(x, z))); + } - public void delete(int x, int z) - { - lock.with(x, z, () -> compound.getValue().remove(key(x, z))); - } + public Hunk read(int x, int z) throws IOException { + AtomicReference e = new AtomicReference<>(); + Hunk xt = lock.withResult(x, z, () -> { + Tag t = compound.getValue().get(key(x, z)); - public Hunk read(int x, int z) throws IOException - { - AtomicReference e = new AtomicReference<>(); - Hunk xt = lock.withResult(x, z, () -> { - Tag t = compound.getValue().get(key(x, z)); + if (!(t instanceof ByteArrayTag)) { + Iris.verbose("NOT BYTE ARRAY!"); + return null; + } - if(!(t instanceof ByteArrayTag)) - { - Iris.verbose("NOT BYTE ARRAY!"); - return null; - } + try { + return adapter.read(factory, (ByteArrayTag) t); + } catch (IOException xe) { + e.set(xe); + } - try { - return adapter.read(factory, (ByteArrayTag) t); - } catch (IOException xe) { - e.set(xe); - } + return null; + }); - return null; - }); + if (xt != null) { + return xt; + } - if(xt != null) - { - return xt; - } + if (e.get() != null) { + throw e.get(); + } - if(e.get()!= null) - { - throw e.get(); - } + return null; + } - return null; - } + public void write(Hunk hunk, int x, int z) throws IOException { + lock.withIO(x, z, () -> compound.getValue().put(key(x, z), hunk.writeByteArrayTag(adapter, key(x, z)))); + } - public void write(Hunk hunk, int x, int z) throws IOException - { - lock.withIO(x, z, () -> compound.getValue().put(key(x, z), hunk.writeByteArrayTag(adapter, key(x, z)))); - } + public synchronized int unloadAll() { + int v = 0; + for (ChunkPosition i : loadedChunks.k()) { + unload(i.getX(), i.getZ()); + v++; + } - public synchronized int unloadAll() - { - int v = 0; - for(ChunkPosition i : loadedChunks.k()) - { - unload(i.getX(), i.getZ()); - v++; - } + save.clear(); + loadedChunks.clear(); + lastUse.clear(); + return v; + } - save.clear(); - loadedChunks.clear(); - lastUse.clear(); - return v; - } + public void save(Hunk region, int x, int z) { + try { + lock.withIO(x, z, () -> write(region, x, z)); + } catch (IOException e) { + e.printStackTrace(); + } + } - public void save(Hunk region, int x, int z) - { - try - { - lock.withIO(x, z, () -> write(region, x, z)); - } - catch(IOException e) - { - e.printStackTrace(); - } - } + public boolean isLoaded(int x, int z) { + return lock.withResult(x, z, () -> loadedChunks.containsKey(new ChunkPosition(x, z))); + } - public boolean isLoaded(int x, int z) - { - return lock.withResult(x, z, () -> loadedChunks.containsKey(new ChunkPosition(x, z))); - } + public void save(int x, int z) { + lock.with(x, z, () -> { + if (isLoaded(x, z)) { + save(get(x, z), x, z); + } + }); + } - public void save(int x, int z) - { - lock.with(x, z, () -> { - if(isLoaded(x, z)) - { - save(get(x, z), x, z); - } - }); - } + public void unload(int x, int z) { + lock.with(x, z, () -> { + ChunkPosition key = new ChunkPosition(x, z); + if (isLoaded(x, z)) { + if (save.contains(key)) { + save(x, z); + save.remove(key); + } - public void unload(int x, int z) - { - lock.with(x, z, () -> { - ChunkPosition key = new ChunkPosition(x, z); - if(isLoaded(x, z)) - { - if(save.contains(key)) - { - save(x, z); - save.remove(key); - } + lastUse.remove(key); + loadedChunks.remove(key); + } + }); + } - lastUse.remove(key); - loadedChunks.remove(key); - } - }); - } + public Hunk load(int x, int z) { + return lock.withResult(x, z, () -> { + if (isLoaded(x, z)) { + return loadedChunks.get(new ChunkPosition(x, z)); + } - public Hunk load(int x, int z) - { - return lock.withResult(x, z, () -> { - if(isLoaded(x, z)) - { - return loadedChunks.get(new ChunkPosition(x, z)); - } + Hunk v = null; - Hunk v = null; + if (contains(x, z)) { + try { + v = read(x, z); + } catch (IOException e) { + e.printStackTrace(); + } + } - if(contains(x, z)) - { - try - { - v = read(x, z); - } + if (v == null) { + v = factory.apply(16, height, 16); + } - catch(IOException e) - { - e.printStackTrace(); - } - } + loadedChunks.put(new ChunkPosition(x, z), v); - if(v == null) - { - v = factory.apply(16, height, 16); - } + return v; + }); + } - loadedChunks.put(new ChunkPosition(x, z), v); + public Hunk get(int x, int z) { + return lock.withResult(x, z, () -> { + ChunkPosition key = new ChunkPosition(x, z); - return v; - }); - } + Hunk c = loadedChunks.get(key); - public Hunk get(int x, int z) - { - return lock.withResult(x, z, () -> { - ChunkPosition key = new ChunkPosition(x, z); + if (c == null) { + c = load(x, z); + } - Hunk c = loadedChunks.get(key); + lastUse.put(new ChunkPosition(x, z), M.ms()); - if(c == null) - { - c = load(x, z); - } + return c; + }); + } - lastUse.put(new ChunkPosition(x, z), M.ms()); + public Hunk getR(int x, int z) { + return lock.withResult(x, z, () -> get(x, z).readOnly()); + } - return c; - }); - } + public Hunk getRW(int x, int z) { + return lock.withResult(x, z, () -> { + save.addIfMissing(new ChunkPosition(x, z)); + return get(x, z); + }); + } - public Hunk getR(int x, int z) - { - return lock.withResult(x, z, () -> get(x, z).readOnly()); - } + private String key(int x, int z) { + if (x < 0 || x >= 32 || z < 0 || z >= 32) { + throw new IndexOutOfBoundsException("The chunk " + x + " " + z + " is out of bounds max is 31x31"); + } - public Hunk getRW(int x, int z) - { - return lock.withResult(x, z, () -> { - save.addIfMissing(new ChunkPosition(x, z)); - return get(x, z); - }); - } + return key + "." + x + "." + z; + } - private String key(int x, int z) - { - if(x < 0 || x >= 32 || z < 0 || z >= 32) - { - throw new IndexOutOfBoundsException("The chunk " + x + " " + z + " is out of bounds max is 31x31"); - } - - return key + "." + x + "." + z; - } - - public int getLoadCount() - { - return loadedChunks.size(); - } + public int getLoadCount() { + return loadedChunks.size(); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/io/PaletteHunkIOAdapter.java b/src/main/java/com/volmit/iris/scaffold/hunk/io/PaletteHunkIOAdapter.java index 78dbe0c91..d774b5575 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/io/PaletteHunkIOAdapter.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/io/PaletteHunkIOAdapter.java @@ -18,9 +18,8 @@ public abstract class PaletteHunkIOAdapter implements HunkIOAdapter { AtomicInteger nonNull = new AtomicInteger(0); DataPalette palette = new DataPalette(); - t.iterateSync((x,y,z,w) -> { - if(w != null) - { + t.iterateSync((x, y, z, w) -> { + if (w != null) { palette.getIndex(w); nonNull.getAndAdd(1); } @@ -29,19 +28,14 @@ public abstract class PaletteHunkIOAdapter implements HunkIOAdapter { palette.write(this, dos); dos.writeInt(nonNull.get() + Integer.MIN_VALUE); AtomicBoolean failure = new AtomicBoolean(false); - t.iterateSync((x,y,z,w) -> { - if(w != null) - { - try - { + t.iterateSync((x, y, z, w) -> { + if (w != null) { + try { dos.writeShort(x + Short.MIN_VALUE); dos.writeShort(y + Short.MIN_VALUE); dos.writeShort(z + Short.MIN_VALUE); dos.writeShort(palette.getIndex(w) + Short.MIN_VALUE); - } - - catch(Throwable e) - { + } catch (Throwable e) { e.printStackTrace(); failure.set(true); } @@ -52,7 +46,7 @@ public abstract class PaletteHunkIOAdapter implements HunkIOAdapter { } @Override - public Hunk read(Function3> factory, InputStream in) throws IOException { + public Hunk read(Function3> factory, InputStream in) throws IOException { DataInputStream din = new DataInputStream(in); int w = din.readShort() - Short.MIN_VALUE; int h = din.readShort() - Short.MIN_VALUE; @@ -61,22 +55,19 @@ public abstract class PaletteHunkIOAdapter implements HunkIOAdapter { int e = din.readInt() - Integer.MIN_VALUE; Hunk t = factory.apply(w, h, d); - for(int i = 0; i < e; i++) - { + for (int i = 0; i < e; i++) { int x = din.readShort() - Short.MIN_VALUE; int y = din.readShort() - Short.MIN_VALUE; int z = din.readShort() - Short.MIN_VALUE; int vf = din.readShort() - Short.MIN_VALUE; T v = null; - if( palette.getPalette().hasIndex(vf)) - { + if (palette.getPalette().hasIndex(vf)) { v = palette.getPalette().get(vf); } - if(v != null) - { - t.setRaw(x,y,z, v); + if (v != null) { + t.setRaw(x, y, z, v); } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/storage/ArrayHunk.java b/src/main/java/com/volmit/iris/scaffold/hunk/storage/ArrayHunk.java index df56dc22a..f80022489 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/storage/ArrayHunk.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/storage/ArrayHunk.java @@ -1,7 +1,6 @@ package com.volmit.iris.scaffold.hunk.storage; import com.volmit.iris.scaffold.hunk.Hunk; - import lombok.Data; import lombok.EqualsAndHashCode; @@ -9,37 +8,31 @@ import java.util.Arrays; @Data @EqualsAndHashCode(callSuper = false) -public class ArrayHunk extends StorageHunk implements Hunk -{ - private final T[] data; +public class ArrayHunk extends StorageHunk implements Hunk { + private final T[] data; - @SuppressWarnings("unchecked") - public ArrayHunk(int w, int h, int d) - { - super(w, h, d); - data = (T[]) new Object[w * h * d]; - } + @SuppressWarnings("unchecked") + public ArrayHunk(int w, int h, int d) { + super(w, h, d); + data = (T[]) new Object[w * h * d]; + } - @Override - public void setRaw(int x, int y, int z, T t) - { - data[index(x, y, z)] = t; - } + @Override + public void setRaw(int x, int y, int z, T t) { + data[index(x, y, z)] = t; + } - @Override - public T getRaw(int x, int y, int z) - { - return data[index(x, y, z)]; - } + @Override + public T getRaw(int x, int y, int z) { + return data[index(x, y, z)]; + } - private int index(int x, int y, int z) - { - return (z * getWidth() * getHeight()) + (y * getWidth()) + x; - } + private int index(int x, int y, int z) { + return (z * getWidth() * getHeight()) + (y * getWidth()) + x; + } - @Override - public void fill(T t) - { - Arrays.fill(data, t); - } + @Override + public void fill(T t) { + Arrays.fill(data, t); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/storage/AtomicDoubleHunk.java b/src/main/java/com/volmit/iris/scaffold/hunk/storage/AtomicDoubleHunk.java index 19eb09ecd..53d2ea3a9 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/storage/AtomicDoubleHunk.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/storage/AtomicDoubleHunk.java @@ -1,43 +1,36 @@ package com.volmit.iris.scaffold.hunk.storage; import com.google.common.util.concurrent.AtomicDoubleArray; - import com.volmit.iris.scaffold.hunk.Hunk; import lombok.Data; import lombok.EqualsAndHashCode; @Data @EqualsAndHashCode(callSuper = false) -public class AtomicDoubleHunk extends StorageHunk implements Hunk -{ - private final AtomicDoubleArray data; +public class AtomicDoubleHunk extends StorageHunk implements Hunk { + private final AtomicDoubleArray data; - public AtomicDoubleHunk(int w, int h, int d) - { - super(w, h, d); - data = new AtomicDoubleArray(w * h * d); - } + public AtomicDoubleHunk(int w, int h, int d) { + super(w, h, d); + data = new AtomicDoubleArray(w * h * d); + } - @Override - public boolean isAtomic() - { - return true; - } + @Override + public boolean isAtomic() { + return true; + } - @Override - public void setRaw(int x, int y, int z, Double t) - { - data.set(index(x, y, z), t); - } + @Override + public void setRaw(int x, int y, int z, Double t) { + data.set(index(x, y, z), t); + } - @Override - public Double getRaw(int x, int y, int z) - { - return data.get(index(x, y, z)); - } + @Override + public Double getRaw(int x, int y, int z) { + return data.get(index(x, y, z)); + } - private int index(int x, int y, int z) - { - return (z * getWidth() * getHeight()) + (y * getWidth()) + x; - } + private int index(int x, int y, int z) { + return (z * getWidth() * getHeight()) + (y * getWidth()) + x; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/storage/AtomicHunk.java b/src/main/java/com/volmit/iris/scaffold/hunk/storage/AtomicHunk.java index 08c604b67..53ede25c8 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/storage/AtomicHunk.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/storage/AtomicHunk.java @@ -1,43 +1,37 @@ package com.volmit.iris.scaffold.hunk.storage; -import java.util.concurrent.atomic.AtomicReferenceArray; - import com.volmit.iris.scaffold.hunk.Hunk; import lombok.Data; import lombok.EqualsAndHashCode; +import java.util.concurrent.atomic.AtomicReferenceArray; + @Data @EqualsAndHashCode(callSuper = false) -public class AtomicHunk extends StorageHunk implements Hunk -{ - private final AtomicReferenceArray data; +public class AtomicHunk extends StorageHunk implements Hunk { + private final AtomicReferenceArray data; - public AtomicHunk(int w, int h, int d) - { - super(w, h, d); - data = new AtomicReferenceArray(w * h * d); - } - - @Override - public boolean isAtomic() - { - return true; - } + public AtomicHunk(int w, int h, int d) { + super(w, h, d); + data = new AtomicReferenceArray(w * h * d); + } - @Override - public void setRaw(int x, int y, int z, T t) - { - data.set(index(x, y, z), t); - } + @Override + public boolean isAtomic() { + return true; + } - @Override - public T getRaw(int x, int y, int z) - { - return data.get(index(x, y, z)); - } + @Override + public void setRaw(int x, int y, int z, T t) { + data.set(index(x, y, z), t); + } - private int index(int x, int y, int z) - { - return (z * getWidth() * getHeight()) + (y * getWidth()) + x; - } + @Override + public T getRaw(int x, int y, int z) { + return data.get(index(x, y, z)); + } + + private int index(int x, int y, int z) { + return (z * getWidth() * getHeight()) + (y * getWidth()) + x; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/storage/AtomicIntegerHunk.java b/src/main/java/com/volmit/iris/scaffold/hunk/storage/AtomicIntegerHunk.java index 348eb3456..b2c315bfb 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/storage/AtomicIntegerHunk.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/storage/AtomicIntegerHunk.java @@ -1,43 +1,37 @@ package com.volmit.iris.scaffold.hunk.storage; -import java.util.concurrent.atomic.AtomicIntegerArray; - import com.volmit.iris.scaffold.hunk.Hunk; import lombok.Data; import lombok.EqualsAndHashCode; +import java.util.concurrent.atomic.AtomicIntegerArray; + @Data @EqualsAndHashCode(callSuper = false) -public class AtomicIntegerHunk extends StorageHunk implements Hunk -{ - private final AtomicIntegerArray data; +public class AtomicIntegerHunk extends StorageHunk implements Hunk { + private final AtomicIntegerArray data; - public AtomicIntegerHunk(int w, int h, int d) - { - super(w, h, d); - data = new AtomicIntegerArray(w * h * d); - } + public AtomicIntegerHunk(int w, int h, int d) { + super(w, h, d); + data = new AtomicIntegerArray(w * h * d); + } - @Override - public boolean isAtomic() - { - return true; - } + @Override + public boolean isAtomic() { + return true; + } - @Override - public void setRaw(int x, int y, int z, Integer t) - { - data.set(index(x, y, z), t); - } + @Override + public void setRaw(int x, int y, int z, Integer t) { + data.set(index(x, y, z), t); + } - @Override - public Integer getRaw(int x, int y, int z) - { - return data.get(index(x, y, z)); - } + @Override + public Integer getRaw(int x, int y, int z) { + return data.get(index(x, y, z)); + } - private int index(int x, int y, int z) - { - return (z * getWidth() * getHeight()) + (y * getWidth()) + x; - } + private int index(int x, int y, int z) { + return (z * getWidth() * getHeight()) + (y * getWidth()) + x; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/storage/AtomicLongHunk.java b/src/main/java/com/volmit/iris/scaffold/hunk/storage/AtomicLongHunk.java index 84b540f8b..aee5c2a65 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/storage/AtomicLongHunk.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/storage/AtomicLongHunk.java @@ -1,43 +1,37 @@ package com.volmit.iris.scaffold.hunk.storage; -import java.util.concurrent.atomic.AtomicLongArray; - import com.volmit.iris.scaffold.hunk.Hunk; import lombok.Data; import lombok.EqualsAndHashCode; +import java.util.concurrent.atomic.AtomicLongArray; + @Data @EqualsAndHashCode(callSuper = false) -public class AtomicLongHunk extends StorageHunk implements Hunk -{ - private final AtomicLongArray data; +public class AtomicLongHunk extends StorageHunk implements Hunk { + private final AtomicLongArray data; - public AtomicLongHunk(int w, int h, int d) - { - super(w, h, d); - data = new AtomicLongArray(w * h * d); - } + public AtomicLongHunk(int w, int h, int d) { + super(w, h, d); + data = new AtomicLongArray(w * h * d); + } - @Override - public boolean isAtomic() - { - return true; - } + @Override + public boolean isAtomic() { + return true; + } - @Override - public void setRaw(int x, int y, int z, Long t) - { - data.set(index(x, y, z), t); - } + @Override + public void setRaw(int x, int y, int z, Long t) { + data.set(index(x, y, z), t); + } - @Override - public Long getRaw(int x, int y, int z) - { - return data.get(index(x, y, z)); - } + @Override + public Long getRaw(int x, int y, int z) { + return data.get(index(x, y, z)); + } - private int index(int x, int y, int z) - { - return (z * getWidth() * getHeight()) + (y * getWidth()) + x; - } + private int index(int x, int y, int z) { + return (z * getWidth() * getHeight()) + (y * getWidth()) + x; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/storage/MappedHunk.java b/src/main/java/com/volmit/iris/scaffold/hunk/storage/MappedHunk.java index 1cfd083ba..931aa7e7d 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/storage/MappedHunk.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/storage/MappedHunk.java @@ -10,58 +10,49 @@ import java.util.Map; @Data @EqualsAndHashCode(callSuper = false) -public class MappedHunk extends StorageHunk implements Hunk -{ - private final Map data; +public class MappedHunk extends StorageHunk implements Hunk { + private final Map data; - public MappedHunk(int w, int h, int d) - { - super(w, h, d); - data = new KMap<>(); - } + public MappedHunk(int w, int h, int d) { + super(w, h, d); + data = new KMap<>(); + } - @Override - public void setRaw(int x, int y, int z, T t) - { - if(t == null) - { - data.remove(index(x,y,z)); - return; - } + @Override + public void setRaw(int x, int y, int z, T t) { + if (t == null) { + data.remove(index(x, y, z)); + return; + } - data.put(index(x, y, z), t); - } + data.put(index(x, y, z), t); + } - private Integer index(int x, int y, int z) - { - return (z * getWidth() * getHeight()) + (y * getWidth()) + x; - } + private Integer index(int x, int y, int z) { + return (z * getWidth() * getHeight()) + (y * getWidth()) + x; + } - @Override - public synchronized Hunk iterateSync(Consumer4 c) - { - int idx, z; + @Override + public synchronized Hunk iterateSync(Consumer4 c) { + int idx, z; - for(Map.Entry g : data.entrySet()) - { - idx = g.getKey(); - z = idx / (getWidth() * getHeight()); - idx -= (z * getWidth() * getHeight()); - c.accept(idx % getWidth(), idx / getWidth(), z, g.getValue()); - } + for (Map.Entry g : data.entrySet()) { + idx = g.getKey(); + z = idx / (getWidth() * getHeight()); + idx -= (z * getWidth() * getHeight()); + c.accept(idx % getWidth(), idx / getWidth(), z, g.getValue()); + } - return this; - } + return this; + } - @Override - public void empty(T b) - { - data.clear(); - } + @Override + public void empty(T b) { + data.clear(); + } - @Override - public T getRaw(int x, int y, int z) - { - return data.get(index(x, y, z)); - } + @Override + public T getRaw(int x, int y, int z) { + return data.get(index(x, y, z)); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/storage/StorageHunk.java b/src/main/java/com/volmit/iris/scaffold/hunk/storage/StorageHunk.java index 0dd1ea73b..dfeeb242a 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/storage/StorageHunk.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/storage/StorageHunk.java @@ -4,27 +4,24 @@ import com.volmit.iris.scaffold.hunk.Hunk; import lombok.Data; @Data -public abstract class StorageHunk implements Hunk -{ - private final int width; - private final int height; - private final int depth; +public abstract class StorageHunk implements Hunk { + private final int width; + private final int height; + private final int depth; - public StorageHunk(int width, int height, int depth) - { - if(width <= 0 || height <= 0 || depth <= 0) - { - throw new RuntimeException("Unsupported size " + width + " " + height + " " + depth); - } + public StorageHunk(int width, int height, int depth) { + if (width <= 0 || height <= 0 || depth <= 0) { + throw new RuntimeException("Unsupported size " + width + " " + height + " " + depth); + } - this.width = width; - this.height = height; - this.depth = depth; - } + this.width = width; + this.height = height; + this.depth = depth; + } - @Override - public abstract void setRaw(int x, int y, int z, T t); + @Override + public abstract void setRaw(int x, int y, int z, T t); - @Override - public abstract T getRaw(int x, int y, int z); + @Override + public abstract T getRaw(int x, int y, int z); } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/storage/SynchronizedArrayHunk.java b/src/main/java/com/volmit/iris/scaffold/hunk/storage/SynchronizedArrayHunk.java index 733359d28..8bc5e6136 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/storage/SynchronizedArrayHunk.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/storage/SynchronizedArrayHunk.java @@ -1,7 +1,6 @@ package com.volmit.iris.scaffold.hunk.storage; import com.volmit.iris.scaffold.hunk.Hunk; - import lombok.Data; import lombok.EqualsAndHashCode; @@ -9,46 +8,37 @@ import java.util.Arrays; @Data @EqualsAndHashCode(callSuper = false) -public class SynchronizedArrayHunk extends StorageHunk implements Hunk -{ - private final T[] data; +public class SynchronizedArrayHunk extends StorageHunk implements Hunk { + private final T[] data; - @SuppressWarnings("unchecked") - public SynchronizedArrayHunk(int w, int h, int d) - { - super(w, h, d); - data = (T[]) new Object[w * h * d]; - } + @SuppressWarnings("unchecked") + public SynchronizedArrayHunk(int w, int h, int d) { + super(w, h, d); + data = (T[]) new Object[w * h * d]; + } - @Override - public void setRaw(int x, int y, int z, T t) - { - synchronized(data) - { - data[index(x, y, z)] = t; - } - } + @Override + public void setRaw(int x, int y, int z, T t) { + synchronized (data) { + data[index(x, y, z)] = t; + } + } - @Override - public T getRaw(int x, int y, int z) - { - synchronized(data) - { - return data[index(x, y, z)]; - } - } + @Override + public T getRaw(int x, int y, int z) { + synchronized (data) { + return data[index(x, y, z)]; + } + } - private int index(int x, int y, int z) - { - return (z * getWidth() * getHeight()) + (y * getWidth()) + x; - } + private int index(int x, int y, int z) { + return (z * getWidth() * getHeight()) + (y * getWidth()) + x; + } - @Override - public void fill(T t) - { - synchronized(data) - { - Arrays.fill(data, t); - } - } + @Override + public void fill(T t) { + synchronized (data) { + Arrays.fill(data, t); + } + } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/view/BiomeGridHunkView.java b/src/main/java/com/volmit/iris/scaffold/hunk/view/BiomeGridHunkView.java index 9ed424402..0ae2190fe 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/view/BiomeGridHunkView.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/view/BiomeGridHunkView.java @@ -4,43 +4,36 @@ import com.volmit.iris.scaffold.hunk.Hunk; import org.bukkit.block.Biome; import org.bukkit.generator.ChunkGenerator.BiomeGrid; -public class BiomeGridHunkView implements Hunk -{ - private final BiomeGrid chunk; +public class BiomeGridHunkView implements Hunk { + private final BiomeGrid chunk; - public BiomeGridHunkView(BiomeGrid chunk) - { - this.chunk = chunk; - } + public BiomeGridHunkView(BiomeGrid chunk) { + this.chunk = chunk; + } - @Override - public int getWidth() - { - return 16; - } + @Override + public int getWidth() { + return 16; + } - @Override - public int getDepth() - { - return 16; - } + @Override + public int getDepth() { + return 16; + } - @Override - public int getHeight() - { - // TODO: WARNING HEIGHT - return 256; - } + @Override + public int getHeight() { + // TODO: WARNING HEIGHT + return 256; + } - @Override - public void setRaw(int x, int y, int z, Biome t) - { - chunk.setBiome(x, y, z, t); - } + @Override + public void setRaw(int x, int y, int z, Biome t) { + chunk.setBiome(x, y, z, t); + } - @Override - public Biome getRaw(int x, int y, int z) - { - return chunk.getBiome(x, y, z); - } + @Override + public Biome getRaw(int x, int y, int z) { + return chunk.getBiome(x, y, z); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/view/ChunkBiomeHunkView.java b/src/main/java/com/volmit/iris/scaffold/hunk/view/ChunkBiomeHunkView.java index b88690551..a8e6fdd20 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/view/ChunkBiomeHunkView.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/view/ChunkBiomeHunkView.java @@ -1,52 +1,43 @@ package com.volmit.iris.scaffold.hunk.view; +import com.volmit.iris.Iris; import com.volmit.iris.scaffold.hunk.Hunk; import org.bukkit.Chunk; import org.bukkit.block.Biome; -import com.volmit.iris.Iris; +public class ChunkBiomeHunkView implements Hunk { + private final Chunk chunk; -public class ChunkBiomeHunkView implements Hunk -{ - private final Chunk chunk; + public ChunkBiomeHunkView(Chunk chunk) { + this.chunk = chunk; + } - public ChunkBiomeHunkView(Chunk chunk) - { - this.chunk = chunk; - } + @Override + public int getWidth() { + return 16; + } - @Override - public int getWidth() - { - return 16; - } + @Override + public int getDepth() { + return 16; + } - @Override - public int getDepth() - { - return 16; - } + @Override + public int getHeight() { + return chunk.getWorld().getMaxHeight(); + } - @Override - public int getHeight() - { - return chunk.getWorld().getMaxHeight(); - } + @Override + public void setRaw(int x, int y, int z, Biome t) { + if (t == null) { + return; + } - @Override - public void setRaw(int x, int y, int z, Biome t) - { - if(t == null) - { - return; - } + Iris.edit.setBiome(chunk.getWorld(), x + (chunk.getX() * 16), y, z + (chunk.getZ() * 16), t); + } - Iris.edit.setBiome(chunk.getWorld(), x + (chunk.getX() * 16), y, z + (chunk.getZ() * 16), t); - } - - @Override - public Biome getRaw(int x, int y, int z) - { - return Iris.edit.getBiome(chunk.getWorld(), x + (chunk.getX() * 16), y, z + (chunk.getZ() * 16)); - } + @Override + public Biome getRaw(int x, int y, int z) { + return Iris.edit.getBiome(chunk.getWorld(), x + (chunk.getX() * 16), y, z + (chunk.getZ() * 16)); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/view/ChunkDataHunkView.java b/src/main/java/com/volmit/iris/scaffold/hunk/view/ChunkDataHunkView.java index 1070250ff..96b9162e9 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/view/ChunkDataHunkView.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/view/ChunkDataHunkView.java @@ -4,59 +4,49 @@ import com.volmit.iris.scaffold.hunk.Hunk; import org.bukkit.block.data.BlockData; import org.bukkit.generator.ChunkGenerator.ChunkData; -public class ChunkDataHunkView implements Hunk -{ - private final ChunkData chunk; +public class ChunkDataHunkView implements Hunk { + private final ChunkData chunk; - public ChunkDataHunkView(ChunkData chunk) - { - this.chunk = chunk; - } + public ChunkDataHunkView(ChunkData chunk) { + this.chunk = chunk; + } - @Override - public int getWidth() - { - return 16; - } + @Override + public int getWidth() { + return 16; + } - @Override - public int getDepth() - { - return 16; - } + @Override + public int getDepth() { + return 16; + } - @Override - public int getHeight() - { - return chunk.getMaxHeight(); - } + @Override + public int getHeight() { + return chunk.getMaxHeight(); + } - @Override - public void set(int x1, int y1, int z1, int x2, int y2, int z2, BlockData t) - { - if(t == null) - { - return; - } + @Override + public void set(int x1, int y1, int z1, int x2, int y2, int z2, BlockData t) { + if (t == null) { + return; + } - enforceBounds(x1, y1, z1, x2 - x1, y2 - y1, z2 - z1); - chunk.setRegion(x1, y1, z1, x2, y2, z2, t); - } + enforceBounds(x1, y1, z1, x2 - x1, y2 - y1, z2 - z1); + chunk.setRegion(x1, y1, z1, x2, y2, z2, t); + } - @Override - public void setRaw(int x, int y, int z, BlockData t) - { - if(t == null) - { - return; - } + @Override + public void setRaw(int x, int y, int z, BlockData t) { + if (t == null) { + return; + } - chunk.setBlock(x, y, z, t); - } + chunk.setBlock(x, y, z, t); + } - @Override - public BlockData getRaw(int x, int y, int z) - { - return chunk.getBlockData(x, y, z); - } + @Override + public BlockData getRaw(int x, int y, int z) { + return chunk.getBlockData(x, y, z); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/view/ChunkHunkView.java b/src/main/java/com/volmit/iris/scaffold/hunk/view/ChunkHunkView.java index 9fa03fbf1..f520580d6 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/view/ChunkHunkView.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/view/ChunkHunkView.java @@ -1,52 +1,43 @@ package com.volmit.iris.scaffold.hunk.view; +import com.volmit.iris.Iris; import com.volmit.iris.scaffold.hunk.Hunk; import org.bukkit.Chunk; import org.bukkit.block.data.BlockData; -import com.volmit.iris.Iris; +public class ChunkHunkView implements Hunk { + private final Chunk chunk; -public class ChunkHunkView implements Hunk -{ - private final Chunk chunk; + public ChunkHunkView(Chunk chunk) { + this.chunk = chunk; + } - public ChunkHunkView(Chunk chunk) - { - this.chunk = chunk; - } + @Override + public int getWidth() { + return 16; + } - @Override - public int getWidth() - { - return 16; - } + @Override + public int getDepth() { + return 16; + } - @Override - public int getDepth() - { - return 16; - } + @Override + public int getHeight() { + return chunk.getWorld().getMaxHeight(); + } - @Override - public int getHeight() - { - return chunk.getWorld().getMaxHeight(); - } + @Override + public void setRaw(int x, int y, int z, BlockData t) { + if (t == null) { + return; + } - @Override - public void setRaw(int x, int y, int z, BlockData t) - { - if(t == null) - { - return; - } + Iris.edit.set(chunk.getWorld(), x + (chunk.getX() * 16), y, z + (chunk.getZ() * 16), t); + } - Iris.edit.set(chunk.getWorld(), x + (chunk.getX() * 16), y, z + (chunk.getZ() * 16), t); - } - - @Override - public BlockData getRaw(int x, int y, int z) - { - return Iris.edit.get(chunk.getWorld(), x + (chunk.getX() * 16), y, z + (chunk.getZ() * 16)); - } + @Override + public BlockData getRaw(int x, int y, int z) { + return Iris.edit.get(chunk.getWorld(), x + (chunk.getX() * 16), y, z + (chunk.getZ() * 16)); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/view/DriftHunkView.java b/src/main/java/com/volmit/iris/scaffold/hunk/view/DriftHunkView.java index b06901798..08d758b9b 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/view/DriftHunkView.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/view/DriftHunkView.java @@ -2,54 +2,46 @@ package com.volmit.iris.scaffold.hunk.view; import com.volmit.iris.scaffold.hunk.Hunk; -public class DriftHunkView implements Hunk -{ - private final int ox; - private final int oy; - private final int oz; - private final Hunk src; +public class DriftHunkView implements Hunk { + private final int ox; + private final int oy; + private final int oz; + private final Hunk src; - public DriftHunkView(Hunk src, int ox, int oy, int oz) - { - this.src = src; - this.ox = ox; - this.oy = oy; - this.oz = oz; - } + public DriftHunkView(Hunk src, int ox, int oy, int oz) { + this.src = src; + this.ox = ox; + this.oy = oy; + this.oz = oz; + } - @Override - public void setRaw(int x, int y, int z, T t) - { - src.setRaw(x + ox, y + oy, z + oz, t); - } + @Override + public void setRaw(int x, int y, int z, T t) { + src.setRaw(x + ox, y + oy, z + oz, t); + } - @Override - public T getRaw(int x, int y, int z) - { - return src.getRaw(x + ox, y + oy, z + oz); - } + @Override + public T getRaw(int x, int y, int z) { + return src.getRaw(x + ox, y + oy, z + oz); + } - @Override - public int getWidth() - { - return src.getWidth(); - } + @Override + public int getWidth() { + return src.getWidth(); + } - @Override - public int getHeight() - { - return src.getHeight(); - } + @Override + public int getHeight() { + return src.getHeight(); + } - @Override - public int getDepth() - { - return src.getDepth(); - } + @Override + public int getDepth() { + return src.getDepth(); + } - @Override - public Hunk getSource() - { - return src; - } + @Override + public Hunk getSource() { + return src; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/view/FringedHunkView.java b/src/main/java/com/volmit/iris/scaffold/hunk/view/FringedHunkView.java index f1628e6b9..06b31bf8c 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/view/FringedHunkView.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/view/FringedHunkView.java @@ -6,45 +6,38 @@ public class FringedHunkView implements Hunk { private final Hunk src; private final Hunk out; - public FringedHunkView(Hunk src, Hunk out) - { + public FringedHunkView(Hunk src, Hunk out) { this.src = src; this.out = out; } @Override - public void setRaw(int x, int y, int z, T t) - { - out.setRaw(x,y,z,t); + public void setRaw(int x, int y, int z, T t) { + out.setRaw(x, y, z, t); } @Override - public T getRaw(int x, int y, int z) - { + public T getRaw(int x, int y, int z) { return src.getRaw(x, y, z); } @Override - public int getWidth() - { + public int getWidth() { return src.getWidth(); } @Override - public int getHeight() - { + public int getHeight() { return src.getHeight(); } @Override - public int getDepth() - { + public int getDepth() { return src.getDepth(); } @Override - public Hunk getSource() - { + public Hunk getSource() { return src; } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/view/HunkView.java b/src/main/java/com/volmit/iris/scaffold/hunk/view/HunkView.java index 42fc095fa..1b7ee2fb2 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/view/HunkView.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/view/HunkView.java @@ -2,70 +2,60 @@ package com.volmit.iris.scaffold.hunk.view; import com.volmit.iris.scaffold.hunk.Hunk; -public class HunkView implements Hunk -{ - private final int ox; - private final int oy; - private final int oz; - private final int w; - private final int h; - private final int d; - private final Hunk src; +public class HunkView implements Hunk { + private final int ox; + private final int oy; + private final int oz; + private final int w; + private final int h; + private final int d; + private final Hunk src; - public HunkView(Hunk src) - { - this(src, src.getWidth(), src.getHeight(), src.getDepth()); - } + public HunkView(Hunk src) { + this(src, src.getWidth(), src.getHeight(), src.getDepth()); + } - public HunkView(Hunk src, int w, int h, int d) - { - this(src, w, h, d, 0, 0, 0); - } + public HunkView(Hunk src, int w, int h, int d) { + this(src, w, h, d, 0, 0, 0); + } - public HunkView(Hunk src, int w, int h, int d, int ox, int oy, int oz) - { - this.src = src; - this.w = w; - this.h = h; - this.d = d; - this.ox = ox; - this.oy = oy; - this.oz = oz; - } + public HunkView(Hunk src, int w, int h, int d, int ox, int oy, int oz) { + this.src = src; + this.w = w; + this.h = h; + this.d = d; + this.ox = ox; + this.oy = oy; + this.oz = oz; + } - @Override - public void setRaw(int x, int y, int z, T t) - { - src.setRaw(x + ox, y + oy, z + oz, t); - } + @Override + public void setRaw(int x, int y, int z, T t) { + src.setRaw(x + ox, y + oy, z + oz, t); + } - @Override - public T getRaw(int x, int y, int z) - { - return src.getRaw(x + ox, y + oy, z + oz); - } + @Override + public T getRaw(int x, int y, int z) { + return src.getRaw(x + ox, y + oy, z + oz); + } - @Override - public int getWidth() - { - return w; - } + @Override + public int getWidth() { + return w; + } - @Override - public int getDepth() - { - return d; - } + @Override + public int getDepth() { + return d; + } - @Override - public int getHeight() - { - return h; - } + @Override + public int getHeight() { + return h; + } - @Override - public Hunk getSource() - { - return src; - } + @Override + public Hunk getSource() { + return src; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/view/InvertedHunkView.java b/src/main/java/com/volmit/iris/scaffold/hunk/view/InvertedHunkView.java index d92ff289d..d2f98b28e 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/view/InvertedHunkView.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/view/InvertedHunkView.java @@ -2,48 +2,40 @@ package com.volmit.iris.scaffold.hunk.view; import com.volmit.iris.scaffold.hunk.Hunk; -public class InvertedHunkView implements Hunk -{ - private final Hunk src; +public class InvertedHunkView implements Hunk { + private final Hunk src; - public InvertedHunkView(Hunk src) - { - this.src = src; - } + public InvertedHunkView(Hunk src) { + this.src = src; + } - @Override - public void setRaw(int x, int y, int z, T t) - { - src.setRaw(x, (getHeight() -1) - y, z, t); - } + @Override + public void setRaw(int x, int y, int z, T t) { + src.setRaw(x, (getHeight() - 1) - y, z, t); + } - @Override - public T getRaw(int x, int y, int z) - { - return src.getRaw(x, y, z); - } + @Override + public T getRaw(int x, int y, int z) { + return src.getRaw(x, y, z); + } - @Override - public int getWidth() - { - return src.getWidth(); - } + @Override + public int getWidth() { + return src.getWidth(); + } - @Override - public int getDepth() - { - return src.getDepth(); - } + @Override + public int getDepth() { + return src.getDepth(); + } - @Override - public int getHeight() - { - return src.getHeight(); - } + @Override + public int getHeight() { + return src.getHeight(); + } - @Override - public Hunk getSource() - { - return src; - } + @Override + public Hunk getSource() { + return src; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/view/ListeningHunk.java b/src/main/java/com/volmit/iris/scaffold/hunk/view/ListeningHunk.java index 5b74d6b51..15cf86ecc 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/view/ListeningHunk.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/view/ListeningHunk.java @@ -1,52 +1,45 @@ package com.volmit.iris.scaffold.hunk.view; -import com.volmit.iris.util.Consumer4; import com.volmit.iris.scaffold.hunk.Hunk; +import com.volmit.iris.util.Consumer4; public class ListeningHunk implements Hunk { private final Hunk src; private final Consumer4 listener; - public ListeningHunk(Hunk src, Consumer4 listener) - { + public ListeningHunk(Hunk src, Consumer4 listener) { this.src = src; this.listener = listener; } @Override - public void setRaw(int x, int y, int z, T t) - { - listener.accept(x,y,z,t); - src.setRaw(x,y,z,t); + public void setRaw(int x, int y, int z, T t) { + listener.accept(x, y, z, t); + src.setRaw(x, y, z, t); } @Override - public T getRaw(int x, int y, int z) - { + public T getRaw(int x, int y, int z) { return src.getRaw(x, y, z); } @Override - public int getWidth() - { + public int getWidth() { return src.getWidth(); } @Override - public int getHeight() - { + public int getHeight() { return src.getHeight(); } @Override - public int getDepth() - { + public int getDepth() { return src.getDepth(); } @Override - public Hunk getSource() - { + public Hunk getSource() { return src; } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/view/ReadOnlyHunk.java b/src/main/java/com/volmit/iris/scaffold/hunk/view/ReadOnlyHunk.java index 4218877c1..a5347286d 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/view/ReadOnlyHunk.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/view/ReadOnlyHunk.java @@ -5,56 +5,47 @@ import com.volmit.iris.scaffold.hunk.Hunk; public class ReadOnlyHunk implements Hunk { private final Hunk src; - public ReadOnlyHunk(Hunk src) - { + public ReadOnlyHunk(Hunk src) { this.src = src; } @Override - public void setRaw(int x, int y, int z, T t) - { + public void setRaw(int x, int y, int z, T t) { throw new IllegalStateException("This hunk is read only!"); } @Override - public T getRaw(int x, int y, int z) - { + public T getRaw(int x, int y, int z) { return src.getRaw(x, y, z); } @Override - public void set(int x1, int y1, int z1, int x2, int y2, int z2, T t) - { + public void set(int x1, int y1, int z1, int x2, int y2, int z2, T t) { throw new IllegalStateException("This hunk is read only!"); } @Override - public void fill(T t) - { + public void fill(T t) { throw new IllegalStateException("This hunk is read only!"); } @Override - public int getWidth() - { + public int getWidth() { return src.getWidth(); } @Override - public int getHeight() - { + public int getHeight() { return src.getHeight(); } @Override - public int getDepth() - { + public int getDepth() { return src.getDepth(); } @Override - public Hunk getSource() - { + public Hunk getSource() { return src; } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/view/RotatedXHunkView.java b/src/main/java/com/volmit/iris/scaffold/hunk/view/RotatedXHunkView.java index af801eca0..3ae7c2f3d 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/view/RotatedXHunkView.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/view/RotatedXHunkView.java @@ -2,62 +2,54 @@ package com.volmit.iris.scaffold.hunk.view; import com.volmit.iris.scaffold.hunk.Hunk; -public class RotatedXHunkView implements Hunk -{ - private final Hunk src; - private final double sin; - private final double cos; +public class RotatedXHunkView implements Hunk { + private final Hunk src; + private final double sin; + private final double cos; - public RotatedXHunkView(Hunk src, double deg) - { - this.src = src; - this.sin = Math.sin(Math.toRadians(deg)); - this.cos = Math.cos(Math.toRadians(deg)); - } + public RotatedXHunkView(Hunk src, double deg) { + this.src = src; + this.sin = Math.sin(Math.toRadians(deg)); + this.cos = Math.cos(Math.toRadians(deg)); + } - @Override - public void setRaw(int x, int y, int z, T t) - { - int yc = (int) Math.round(cos * (getHeight() / 2) - sin * (getDepth() / 2)); - int zc = (int) Math.round(sin * (getHeight() / 2) + cos * (getDepth() / 2)); - src.setIfExists(x, - (int) Math.round(cos * (y-yc) - sin * (z-zc))-yc, - (int) Math.round(sin * y-yc + cos * (z-zc))-zc, - t); - } + @Override + public void setRaw(int x, int y, int z, T t) { + int yc = (int) Math.round(cos * (getHeight() / 2) - sin * (getDepth() / 2)); + int zc = (int) Math.round(sin * (getHeight() / 2) + cos * (getDepth() / 2)); + src.setIfExists(x, + (int) Math.round(cos * (y - yc) - sin * (z - zc)) - yc, + (int) Math.round(sin * y - yc + cos * (z - zc)) - zc, + t); + } - @Override - public T getRaw(int x, int y, int z) - { - int yc = (int) Math.round(cos * (getHeight() / 2) - sin * (getDepth() / 2)); - int zc = (int) Math.round(sin * (getHeight() / 2) + cos * (getDepth() / 2)); - return src.getIfExists(x, - (int) Math.round(cos * (y-yc) - sin * (z-zc))-yc, - (int) Math.round(sin * y-yc + cos * (z-zc))-zc - ); - } + @Override + public T getRaw(int x, int y, int z) { + int yc = (int) Math.round(cos * (getHeight() / 2) - sin * (getDepth() / 2)); + int zc = (int) Math.round(sin * (getHeight() / 2) + cos * (getDepth() / 2)); + return src.getIfExists(x, + (int) Math.round(cos * (y - yc) - sin * (z - zc)) - yc, + (int) Math.round(sin * y - yc + cos * (z - zc)) - zc + ); + } - @Override - public int getWidth() - { - return src.getWidth(); - } + @Override + public int getWidth() { + return src.getWidth(); + } - @Override - public int getDepth() - { - return src.getDepth(); - } + @Override + public int getDepth() { + return src.getDepth(); + } - @Override - public int getHeight() - { - return src.getHeight(); - } + @Override + public int getHeight() { + return src.getHeight(); + } - @Override - public Hunk getSource() - { - return src; - } + @Override + public Hunk getSource() { + return src; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/view/RotatedYHunkView.java b/src/main/java/com/volmit/iris/scaffold/hunk/view/RotatedYHunkView.java index a760096f2..22526d231 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/view/RotatedYHunkView.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/view/RotatedYHunkView.java @@ -2,63 +2,55 @@ package com.volmit.iris.scaffold.hunk.view; import com.volmit.iris.scaffold.hunk.Hunk; -public class RotatedYHunkView implements Hunk -{ - private final Hunk src; - private final double sin; - private final double cos; +public class RotatedYHunkView implements Hunk { + private final Hunk src; + private final double sin; + private final double cos; - public RotatedYHunkView(Hunk src, double deg) - { - this.src = src; - this.sin = Math.sin(Math.toRadians(deg)); - this.cos = Math.cos(Math.toRadians(deg)); - } + public RotatedYHunkView(Hunk src, double deg) { + this.src = src; + this.sin = Math.sin(Math.toRadians(deg)); + this.cos = Math.cos(Math.toRadians(deg)); + } - @Override - public void setRaw(int x, int y, int z, T t) - { - int xc = (int) Math.round(cos * (getWidth() / 2) + sin * (getDepth() / 2)); - int zc = (int) Math.round(-sin * (getWidth() / 2) + cos * (getDepth() / 2)); - src.setIfExists((int) - Math.round(cos * (x - xc) + sin * (z - zc)) - xc, - y, - (int) Math.round(-sin * (x - xc) + cos * (z - zc)) - zc, t); - } + @Override + public void setRaw(int x, int y, int z, T t) { + int xc = (int) Math.round(cos * (getWidth() / 2) + sin * (getDepth() / 2)); + int zc = (int) Math.round(-sin * (getWidth() / 2) + cos * (getDepth() / 2)); + src.setIfExists((int) + Math.round(cos * (x - xc) + sin * (z - zc)) - xc, + y, + (int) Math.round(-sin * (x - xc) + cos * (z - zc)) - zc, t); + } - @Override - public T getRaw(int x, int y, int z) - { - int xc = (int) Math.round(cos * (getWidth() / 2) + sin * (getDepth() / 2)); - int zc = (int) Math.round(-sin * (getWidth() / 2) + cos * (getDepth() / 2)); - return src.getIfExists( - (int) Math.round(cos * (x - xc) + sin * (z - zc)) - xc, - y, - (int) Math.round(-sin * (x - xc) + cos * (z - zc)) - zc - ); - } + @Override + public T getRaw(int x, int y, int z) { + int xc = (int) Math.round(cos * (getWidth() / 2) + sin * (getDepth() / 2)); + int zc = (int) Math.round(-sin * (getWidth() / 2) + cos * (getDepth() / 2)); + return src.getIfExists( + (int) Math.round(cos * (x - xc) + sin * (z - zc)) - xc, + y, + (int) Math.round(-sin * (x - xc) + cos * (z - zc)) - zc + ); + } - @Override - public int getWidth() - { - return src.getWidth(); - } + @Override + public int getWidth() { + return src.getWidth(); + } - @Override - public int getDepth() - { - return src.getDepth(); - } + @Override + public int getDepth() { + return src.getDepth(); + } - @Override - public int getHeight() - { - return src.getHeight(); - } + @Override + public int getHeight() { + return src.getHeight(); + } - @Override - public Hunk getSource() - { - return src; - } + @Override + public Hunk getSource() { + return src; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/view/RotatedZHunkView.java b/src/main/java/com/volmit/iris/scaffold/hunk/view/RotatedZHunkView.java index 5214599c6..62db555ef 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/view/RotatedZHunkView.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/view/RotatedZHunkView.java @@ -2,58 +2,50 @@ package com.volmit.iris.scaffold.hunk.view; import com.volmit.iris.scaffold.hunk.Hunk; -public class RotatedZHunkView implements Hunk -{ - private final Hunk src; - private final double sin; - private final double cos; +public class RotatedZHunkView implements Hunk { + private final Hunk src; + private final double sin; + private final double cos; - public RotatedZHunkView(Hunk src, double deg) - { - this.src = src; - this.sin = Math.sin(Math.toRadians(deg)); - this.cos = Math.cos(Math.toRadians(deg)); - } + public RotatedZHunkView(Hunk src, double deg) { + this.src = src; + this.sin = Math.sin(Math.toRadians(deg)); + this.cos = Math.cos(Math.toRadians(deg)); + } - @Override - public void setRaw(int x, int y, int z, T t) - { - int xc = (int) Math.round(cos * (getWidth() / 2) - sin * (getHeight() / 2)); - int yc = (int) Math.round(sin * (getWidth() / 2) + cos * (getHeight() / 2)); - src.setIfExists((int) Math.round(cos * (x - xc) - sin * (y - yc)) - xc, (int) Math.round(sin * (x - xc) + cos * (y - yc)) - yc, z, t); - } + @Override + public void setRaw(int x, int y, int z, T t) { + int xc = (int) Math.round(cos * (getWidth() / 2) - sin * (getHeight() / 2)); + int yc = (int) Math.round(sin * (getWidth() / 2) + cos * (getHeight() / 2)); + src.setIfExists((int) Math.round(cos * (x - xc) - sin * (y - yc)) - xc, (int) Math.round(sin * (x - xc) + cos * (y - yc)) - yc, z, t); + } - @Override - public T getRaw(int x, int y, int z) - { - int xc = (int) Math.round(cos * (getWidth() / 2) - sin * (getHeight() / 2)); - int yc = (int) Math.round(sin * (getWidth() / 2) + cos * (getHeight() / 2)); - return src.getIfExists((int) Math.round(cos * (x - xc) - sin * (y - yc)) - xc, - (int) Math.round(sin * (x - xc) + cos * (y - yc)) - yc - , z); - } + @Override + public T getRaw(int x, int y, int z) { + int xc = (int) Math.round(cos * (getWidth() / 2) - sin * (getHeight() / 2)); + int yc = (int) Math.round(sin * (getWidth() / 2) + cos * (getHeight() / 2)); + return src.getIfExists((int) Math.round(cos * (x - xc) - sin * (y - yc)) - xc, + (int) Math.round(sin * (x - xc) + cos * (y - yc)) - yc + , z); + } - @Override - public int getWidth() - { - return src.getWidth(); - } + @Override + public int getWidth() { + return src.getWidth(); + } - @Override - public int getDepth() - { - return src.getDepth(); - } + @Override + public int getDepth() { + return src.getDepth(); + } - @Override - public int getHeight() - { - return src.getHeight(); - } + @Override + public int getHeight() { + return src.getHeight(); + } - @Override - public Hunk getSource() - { - return src; - } + @Override + public Hunk getSource() { + return src; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/view/SynchronizedHunkView.java b/src/main/java/com/volmit/iris/scaffold/hunk/view/SynchronizedHunkView.java index 54461fb43..af983ebb2 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/view/SynchronizedHunkView.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/view/SynchronizedHunkView.java @@ -5,47 +5,39 @@ import com.volmit.iris.scaffold.hunk.Hunk; public class SynchronizedHunkView implements Hunk { private final Hunk src; - public SynchronizedHunkView(Hunk src) - { + public SynchronizedHunkView(Hunk src) { this.src = src; } @Override - public void setRaw(int x, int y, int z, T t) - { - synchronized (src) - { - src.setRaw(x,y,z,t); + public void setRaw(int x, int y, int z, T t) { + synchronized (src) { + src.setRaw(x, y, z, t); } } @Override - public T getRaw(int x, int y, int z) - { + public T getRaw(int x, int y, int z) { return src.getRaw(x, y, z); } @Override - public int getWidth() - { + public int getWidth() { return src.getWidth(); } @Override - public int getHeight() - { + public int getHeight() { return src.getHeight(); } @Override - public int getDepth() - { + public int getDepth() { return src.getDepth(); } @Override - public Hunk getSource() - { + public Hunk getSource() { return src; } } diff --git a/src/main/java/com/volmit/iris/scaffold/hunk/view/WriteTrackHunk.java b/src/main/java/com/volmit/iris/scaffold/hunk/view/WriteTrackHunk.java index 00fdc5d36..5b58401d8 100644 --- a/src/main/java/com/volmit/iris/scaffold/hunk/view/WriteTrackHunk.java +++ b/src/main/java/com/volmit/iris/scaffold/hunk/view/WriteTrackHunk.java @@ -8,50 +8,42 @@ public class WriteTrackHunk implements Hunk { private final Hunk src; private final AtomicBoolean b; - public WriteTrackHunk(Hunk src, AtomicBoolean b) - { + public WriteTrackHunk(Hunk src, AtomicBoolean b) { this.src = src; this.b = b; } @Override - public void setRaw(int x, int y, int z, T t) - { - if(!b.get()) - { + public void setRaw(int x, int y, int z, T t) { + if (!b.get()) { b.set(true); } - src.setRaw(x,y,z,t); + src.setRaw(x, y, z, t); } @Override - public T getRaw(int x, int y, int z) - { + public T getRaw(int x, int y, int z) { return src.getRaw(x, y, z); } @Override - public int getWidth() - { + public int getWidth() { return src.getWidth(); } @Override - public int getHeight() - { + public int getHeight() { return src.getHeight(); } @Override - public int getDepth() - { + public int getDepth() { return src.getDepth(); } @Override - public Hunk getSource() - { + public Hunk getSource() { return src; } } diff --git a/src/main/java/com/volmit/iris/scaffold/jigsaw/PlannedPiece.java b/src/main/java/com/volmit/iris/scaffold/jigsaw/PlannedPiece.java index 62759e9dd..09c29ebfb 100644 --- a/src/main/java/com/volmit/iris/scaffold/jigsaw/PlannedPiece.java +++ b/src/main/java/com/volmit/iris/scaffold/jigsaw/PlannedPiece.java @@ -1,18 +1,12 @@ package com.volmit.iris.scaffold.jigsaw; -import com.volmit.iris.Iris; -import com.volmit.iris.generator.IrisEngine; import com.volmit.iris.manager.IrisDataManager; import com.volmit.iris.object.*; import com.volmit.iris.object.tile.TileData; import com.volmit.iris.scaffold.IrisWorlds; import com.volmit.iris.scaffold.engine.Engine; import com.volmit.iris.scaffold.engine.IrisAccess; -import com.volmit.iris.util.AxisAlignedBB; -import com.volmit.iris.util.BlockPosition; -import com.volmit.iris.util.IObjectPlacer; -import com.volmit.iris.util.KList; -import com.volmit.iris.util.RNG; +import com.volmit.iris.util.*; import lombok.Data; import org.bukkit.Material; import org.bukkit.World; @@ -36,18 +30,16 @@ public class PlannedPiece { private AxisAlignedBB box; private PlannedStructure structure; - public PlannedPiece(PlannedStructure structure, IrisPosition position, IrisJigsawPiece piece) - { - this(structure, position, piece, 0,0,0); + public PlannedPiece(PlannedStructure structure, IrisPosition position, IrisJigsawPiece piece) { + this(structure, position, piece, 0, 0, 0); } - public PlannedPiece(PlannedStructure structure, IrisPosition position, IrisJigsawPiece piece, int rx, int ry, int rz) - { + public PlannedPiece(PlannedStructure structure, IrisPosition position, IrisJigsawPiece piece, int rx, int ry, int rz) { this.structure = structure; this.position = position; rotationKey = (rz * 100) + (rx * 10) + ry; this.data = piece.getLoader(); - this.rotation = IrisObjectRotation.of(rx*90D, ry*90D, rz*90D); + this.rotation = IrisObjectRotation.of(rx * 90D, ry * 90D, rz * 90D); this.object = structure.rotated(piece, rotation); this.piece = rotation.rotateCopy(piece); this.piece.setLoadKey(piece.getLoadKey()); @@ -55,21 +47,17 @@ public class PlannedPiece { this.connected = new KList<>(); } - public void setPosition(IrisPosition p) - { + public void setPosition(IrisPosition p) { this.position = p; box = null; } - public String toString() - { + public String toString() { return piece.getLoadKey() + "@(" + position.getX() + "," + position.getY() + "," + position.getZ() + ")[rot:" + rotationKey + "]"; } - public AxisAlignedBB getBox() - { - if(box != null) - { + public AxisAlignedBB getBox() { + if (box != null) { return box; } @@ -78,34 +66,27 @@ public class PlannedPiece { return box; } - public boolean contains(IrisPosition p) - { + public boolean contains(IrisPosition p) { return getBox().contains(p); } - public boolean collidesWith(PlannedPiece p) - { + public boolean collidesWith(PlannedPiece p) { return getBox().intersects(p.getBox()); } - public KList getAvailableConnectors() - { - if(connected.isEmpty()) - { + public KList getAvailableConnectors() { + if (connected.isEmpty()) { return piece.getConnectors().copy(); } - if(connected.size() == piece.getConnectors().size()) - { + if (connected.size() == piece.getConnectors().size()) { return new KList<>(); } KList c = new KList<>(); - for(IrisJigsawPieceConnector i : piece.getConnectors()) - { - if(!connected.contains(i)) - { + for (IrisJigsawPieceConnector i : piece.getConnectors()) { + if (!connected.contains(i)) { c.add(i); } } @@ -113,23 +94,19 @@ public class PlannedPiece { return c; } - public boolean connect(IrisJigsawPieceConnector c) - { - if(piece.getConnectors().contains(c)) - { + public boolean connect(IrisJigsawPieceConnector c) { + if (piece.getConnectors().contains(c)) { return connected.addIfMissing(c); } return false; } - public IrisPosition getWorldPosition(IrisJigsawPieceConnector c) - { + public IrisPosition getWorldPosition(IrisJigsawPieceConnector c) { return getWorldPosition(c.getPosition()); } - public IrisPosition getWorldPosition(IrisPosition position) - { + public IrisPosition getWorldPosition(IrisPosition position) { return this.position.add(position).add(new IrisPosition(object.getCenter())); } @@ -144,13 +121,14 @@ public class PlannedPiece { if (a != null) { minY = a.getCompound().getDefaultEngine().getMinHeight(); - if (!a.getCompound().getRootDimension().isBedrock()) minY--; //If the dimension has no bedrock, allow it to go a block lower + if (!a.getCompound().getRootDimension().isBedrock()) + minY--; //If the dimension has no bedrock, allow it to go a block lower } getPiece().getPlacementOptions().getRotation().setEnabled(false); int finalMinY = minY; RNG rng = getStructure().getRng().nextParallelRNG(37555); - getObject().place(position.getX()+getObject().getCenter().getBlockX(), position.getY()+getObject().getCenter().getBlockY(), position.getZ()+getObject().getCenter().getBlockZ(), new IObjectPlacer() { + getObject().place(position.getX() + getObject().getCenter().getBlockX(), position.getY() + getObject().getCenter().getBlockY(), position.getZ() + getObject().getCenter().getBlockZ(), new IObjectPlacer() { @Override public int getHighest(int x, int z) { return position.getY(); @@ -177,14 +155,14 @@ public class PlannedPiece { if (table == null) return; Engine engine = a.getCompound().getEngineForHeight(y); engine.addItems(false, ((InventoryHolder) block.getState()).getInventory(), - rng.nextParallelRNG(BlockPosition.toLong(x, y, z)), + rng.nextParallelRNG(BlockPosition.toLong(x, y, z)), new KList<>(table), InventorySlotType.STORAGE, x, y, z, 15); } } @Override public BlockData get(int x, int y, int z) { - return world.getBlockAt(x,y,z).getBlockData(); + return world.getBlockAt(x, y, z).getBlockData(); } @Override @@ -194,7 +172,7 @@ public class PlannedPiece { @Override public boolean isSolid(int x, int y, int z) { - return world.getBlockAt(x,y,z).getType().isSolid(); + return world.getBlockAt(x, y, z).getType().isSolid(); } @Override @@ -214,7 +192,7 @@ public class PlannedPiece { @Override public void setTile(int xx, int yy, int zz, TileData tile) { - BlockState state = world.getBlockAt(xx,yy,zz).getState(); + BlockState state = world.getBlockAt(xx, yy, zz).getState(); tile.toBukkitTry(state); state.update(); } diff --git a/src/main/java/com/volmit/iris/scaffold/jigsaw/PlannedStructure.java b/src/main/java/com/volmit/iris/scaffold/jigsaw/PlannedStructure.java index f4c3937de..fc08912c8 100644 --- a/src/main/java/com/volmit/iris/scaffold/jigsaw/PlannedStructure.java +++ b/src/main/java/com/volmit/iris/scaffold/jigsaw/PlannedStructure.java @@ -28,8 +28,7 @@ public class PlannedStructure { private boolean verbose; private boolean terminating; - public PlannedStructure(IrisJigsawStructure structure, IrisPosition position, RNG rng) - { + public PlannedStructure(IrisJigsawStructure structure, IrisPosition position, RNG rng) { terminating = false; objectRotationCache = new KMap<>(); verbose = true; @@ -40,30 +39,23 @@ public class PlannedStructure { this.data = structure.getLoader(); generateStartPiece(); - for(int i = 0; i < structure.getMaxDepth(); i++) - { + for (int i = 0; i < structure.getMaxDepth(); i++) { generateOutwards(); } generateTerminators(); } - public KList place(IObjectPlacer placer, EngineParallaxManager e) - { + public KList place(IObjectPlacer placer, EngineParallaxManager e) { KList after = new KList<>(); IrisObjectPlacement options = new IrisObjectPlacement(); options.getRotation().setEnabled(false); int startHeight = pieces.get(0).getPosition().getY(); - for(PlannedPiece i : pieces) - { - if(i.getPiece().getPlaceMode().equals(ObjectPlaceMode.VACUUM) ) - { + for (PlannedPiece i : pieces) { + if (i.getPiece().getPlaceMode().equals(ObjectPlaceMode.VACUUM)) { place(i, startHeight, options, placer, e); - } - - else - { + } else { after.add(() -> place(i, startHeight, options, placer, e)); } } @@ -71,30 +63,25 @@ public class PlannedStructure { return after; } - public void place(PlannedPiece i, int startHeight, IrisObjectPlacement o, IObjectPlacer placer, EngineParallaxManager e) - { + public void place(PlannedPiece i, int startHeight, IrisObjectPlacement o, IObjectPlacer placer, EngineParallaxManager e) { IrisObjectPlacement options = o; - if(i.getPiece().getPlacementOptions() != null) - { - options= i.getPiece().getPlacementOptions(); + if (i.getPiece().getPlacementOptions() != null) { + options = i.getPiece().getPlacementOptions(); options.getRotation().setEnabled(false); - } - else - { + } else { options.setMode(i.getPiece().getPlaceMode()); } IrisObject v = i.getObject(); - int sx = (v.getW()/2); - int sz = (v.getD()/2); + int sx = (v.getW() / 2); + int sz = (v.getD() / 2); int xx = i.getPosition().getX() + sx; int zz = i.getPosition().getZ() + sz; int offset = i.getPosition().getY() - startHeight; int height = placer.getHighest(xx, zz) + offset + (v.getH() / 2); - if(options.getMode().equals(ObjectPlaceMode.PAINT) || options.isVacuum()) - { + if (options.getMode().equals(ObjectPlaceMode.PAINT) || options.isVacuum()) { height = -1; } @@ -105,31 +92,26 @@ public class PlannedStructure { int yf = b.getY(); int zf = b.getZ(); e.getParallaxAccess().setObject(xf, yf, zf, v.getLoadKey() + "@" + id); - ParallaxChunkMeta meta = e.getParallaxAccess().getMetaRW(xf>>4, zf>>4); + ParallaxChunkMeta meta = e.getParallaxAccess().getMetaRW(xf >> 4, zf >> 4); meta.setObjects(true); meta.setMinObject(Math.min(Math.max(meta.getMinObject(), 0), yf)); meta.setMaxObject(Math.max(Math.max(meta.getMaxObject(), 0), yf)); }, null, getData()); - for(IrisJigsawPieceConnector j : i.getAvailableConnectors()) - { - if(j.getSpawnEntity() != null)// && h != -1) + for (IrisJigsawPieceConnector j : i.getAvailableConnectors()) { + if (j.getSpawnEntity() != null)// && h != -1) { IrisPosition p; - if (j.getEntityPosition() == null){ + if (j.getEntityPosition() == null) { p = i.getWorldPosition(j).add(new IrisPosition(j.getDirection().toVector().multiply(2))); } else { p = i.getWorldPosition(j).add(j.getEntityPosition()); } - if(options.getMode().equals(ObjectPlaceMode.PAINT) || options.isVacuum()) - { + if (options.getMode().equals(ObjectPlaceMode.PAINT) || options.isVacuum()) { p.setY(placer.getHighest(xx, zz) + offset + (v.getH() / 2)); - } - - else - { + } else { p.setY(height); } for (int k = 0; k < j.getEntityCount(); k++) { @@ -138,30 +120,25 @@ public class PlannedStructure { } } - if(options.isVacuum()) - { + if (options.isVacuum()) { double a = Math.max(v.getW(), v.getD()); IrisFeature f = new IrisFeature(); - f.setConvergeToHeight(h - (v.getH() >> 1)-1); + f.setConvergeToHeight(h - (v.getH() >> 1) - 1); f.setBlockRadius(a); - f.setInterpolationRadius(a/4); + f.setInterpolationRadius(a / 4); f.setInterpolator(InterpolationMethod.BILINEAR_STARCAST_9); f.setStrength(1D); - e.getParallaxAccess().getMetaRW(xx >>4, zz >>4) + e.getParallaxAccess().getMetaRW(xx >> 4, zz >> 4) .getFeatures() .add(new IrisFeaturePositional(xx, zz, f)); } } - public void place(World world) - { - for(PlannedPiece i : pieces) - { + public void place(World world) { + for (PlannedPiece i : pieces) { Iris.sq(() -> { - for(IrisJigsawPieceConnector j : i.getAvailableConnectors()) - { - if(j.getSpawnEntity() != null) - { + for (IrisJigsawPieceConnector j : i.getAvailableConnectors()) { + if (j.getSpawnEntity() != null) { IrisAccess a = IrisWorlds.access(world); if (a == null) { Iris.warn("Cannot spawn entities from jigsaw in non Iris world!"); @@ -170,8 +147,7 @@ public class PlannedStructure { IrisPosition p = i.getWorldPosition(j).add(new IrisPosition(j.getDirection().toVector().multiply(2))); IrisEntity e = getData().getEntityLoader().load(j.getSpawnEntity()); - if(a != null) - { + if (a != null) { Entity entity = e.spawn(a.getCompound().getEngineForHeight(p.getY()), new Location(world, p.getX() + 0.5, p.getY(), p.getZ() + 0.5), rng); if (j.isKeepEntity()) { entity.setPersistent(true); @@ -186,10 +162,8 @@ public class PlannedStructure { } private void generateOutwards() { - for(PlannedPiece i : getPiecesWithAvailableConnectors().shuffle(rng)) - { - if(!generatePieceOutwards(i)) - { + for (PlannedPiece i : getPiecesWithAvailableConnectors().shuffle(rng)) { + if (!generatePieceOutwards(i)) { i.setDead(true); } } @@ -198,10 +172,8 @@ public class PlannedStructure { private boolean generatePieceOutwards(PlannedPiece piece) { boolean b = false; - for(IrisJigsawPieceConnector i : piece.getAvailableConnectors().shuffleCopy(rng)) - { - if(generateConnectorOutwards(piece, i)) - { + for (IrisJigsawPieceConnector i : piece.getAvailableConnectors().shuffleCopy(rng)) { + if (generateConnectorOutwards(piece, i)) { b = true; } } @@ -210,10 +182,8 @@ public class PlannedStructure { } private boolean generateConnectorOutwards(PlannedPiece piece, IrisJigsawPieceConnector pieceConnector) { - for(IrisJigsawPiece i : getShuffledPiecesFor(pieceConnector)) - { - if(generateRotatedPiece(piece, pieceConnector, i)) - { + for (IrisJigsawPiece i : getShuffledPiecesFor(pieceConnector)) { + if (generateRotatedPiece(piece, pieceConnector, i)) { return true; } } @@ -225,9 +195,8 @@ public class PlannedStructure { KList forder1 = new KList().qadd(0).qadd(1).qadd(2).qadd(3).shuffle(rng); KList forder2 = new KList().qadd(0).qadd(1).qadd(2).qadd(3).shuffle(rng); - for(Integer i : forder1) - { - if(pieceConnector.isRotateConnector()) { + for (Integer i : forder1) { + if (pieceConnector.isRotateConnector()) { assert pieceConnector.getDirection().getAxis() != null; if (!pieceConnector.getDirection().getAxis().equals(Axis.Y)) { for (Integer j : forder2) { @@ -242,8 +211,7 @@ public class PlannedStructure { } } - if (generateRotatedPiece(piece, pieceConnector, idea, 0, i, 0)) - { + if (generateRotatedPiece(piece, pieceConnector, idea, 0, i, 0)) { return true; } } @@ -251,14 +219,11 @@ public class PlannedStructure { return false; } - private boolean generateRotatedPiece(PlannedPiece piece, IrisJigsawPieceConnector pieceConnector, IrisJigsawPiece idea, int x, int y, int z) - { + private boolean generateRotatedPiece(PlannedPiece piece, IrisJigsawPieceConnector pieceConnector, IrisJigsawPiece idea, int x, int y, int z) { PlannedPiece test = new PlannedPiece(this, piece.getPosition(), idea, x, y, z); - for(IrisJigsawPieceConnector j : test.getPiece().getConnectors().shuffleCopy(rng)) - { - if(generatePositionedPiece(piece, pieceConnector, test, j)) - { + for (IrisJigsawPieceConnector j : test.getPiece().getConnectors().shuffleCopy(rng)) { + if (generatePositionedPiece(piece, pieceConnector, test, j)) { return true; } } @@ -270,18 +235,16 @@ public class PlannedStructure { IrisJigsawPieceConnector pieceConnector, PlannedPiece test, IrisJigsawPieceConnector testConnector) { - test.setPosition(new IrisPosition(0,0,0)); + test.setPosition(new IrisPosition(0, 0, 0)); IrisPosition connector = piece.getWorldPosition(pieceConnector); IrisDirection desiredDirection = pieceConnector.getDirection().reverse(); IrisPosition desiredPosition = connector.sub(new IrisPosition(desiredDirection.toVector())); - if(!pieceConnector.getTargetName().equals("*") && !pieceConnector.getTargetName().equals(testConnector.getName())) - { + if (!pieceConnector.getTargetName().equals("*") && !pieceConnector.getTargetName().equals(testConnector.getName())) { return false; } - if(!testConnector.getDirection().equals(desiredDirection)) - { + if (!testConnector.getDirection().equals(desiredDirection)) { return false; } @@ -289,21 +252,15 @@ public class PlannedStructure { test.setPosition(desiredPosition.sub(shift)); KList collision = collidesWith(test); - if(pieceConnector.isInnerConnector() && collision.isNotEmpty()) - { - for(PlannedPiece i : collision) - { - if(i.equals(piece)) - { - continue; + if (pieceConnector.isInnerConnector() && collision.isNotEmpty()) { + for (PlannedPiece i : collision) { + if (i.equals(piece)) { + continue; } return false; } - } - - else if(collision.isNotEmpty()) - { + } else if (collision.isNotEmpty()) { return false; } @@ -314,18 +271,14 @@ public class PlannedStructure { return true; } - private KList getShuffledPiecesFor(IrisJigsawPieceConnector c) - { + private KList getShuffledPiecesFor(IrisJigsawPieceConnector c) { KList p = new KList<>(); - for(String i : c.getPools().shuffleCopy(rng)) - { - for(String j : getData().getJigsawPoolLoader().load(i).getPieces().shuffleCopy(rng)) - { + for (String i : c.getPools().shuffleCopy(rng)) { + for (String j : getData().getJigsawPoolLoader().load(i).getPieces().shuffleCopy(rng)) { IrisJigsawPiece pi = getData().getJigsawPieceLoader().load(j); - if (pi == null || (terminating && !pi.isTerminal())) - { + if (pi == null || (terminating && !pi.isTerminal())) { continue; } @@ -340,49 +293,40 @@ public class PlannedStructure { } private void generateTerminators() { - if(getStructure().isTerminate()) - { + if (getStructure().isTerminate()) { terminating = true; generateOutwards(); } } - public KList getPiecesWithAvailableConnectors() - { + public KList getPiecesWithAvailableConnectors() { return pieces.copy().removeWhere(PlannedPiece::isFull); } - public int getVolume() - { + public int getVolume() { int v = 0; - for(PlannedPiece i : pieces) - { + for (PlannedPiece i : pieces) { v += i.getObject().getH() * i.getObject().getW() * i.getObject().getD(); } return v; } - public int getMass() - { + public int getMass() { int v = 0; - for(PlannedPiece i : pieces) - { + for (PlannedPiece i : pieces) { v += i.getObject().getBlocks().size(); } return v; } - public KList collidesWith(PlannedPiece piece) - { + public KList collidesWith(PlannedPiece piece) { KList v = new KList<>(); - for(PlannedPiece i : pieces) - { - if(i.collidesWith(piece)) - { + for (PlannedPiece i : pieces) { + if (i.collidesWith(piece)) { v.add(i); } } @@ -390,17 +334,13 @@ public class PlannedStructure { return v; } - public boolean collidesWith(PlannedPiece piece, PlannedPiece ignore) - { - for(PlannedPiece i : pieces) - { - if(i.equals(ignore)) - { + public boolean collidesWith(PlannedPiece piece, PlannedPiece ignore) { + for (PlannedPiece i : pieces) { + if (i.equals(ignore)) { continue; } - if(i.collidesWith(piece)) - { + if (i.collidesWith(piece)) { return true; } } @@ -408,12 +348,9 @@ public class PlannedStructure { return false; } - public boolean contains(IrisPosition p) - { - for(PlannedPiece i : pieces) - { - if(i.contains(p)) - { + public boolean contains(IrisPosition p) { + for (PlannedPiece i : pieces) { + if (i.contains(p)) { return true; } } @@ -424,12 +361,10 @@ public class PlannedStructure { public synchronized IrisObject rotated(IrisJigsawPiece piece, IrisObjectRotation rotation) { String key = piece.getObject() + "-" + rotation.hashCode(); - if(objectRotationCache.containsKey(key)) - { + if (objectRotationCache.containsKey(key)) { IrisObject o = objectRotationCache.get(key); - if(o != null) - { + if (o != null) { return o; } } diff --git a/src/main/java/com/volmit/iris/scaffold/lighting/BlockFaceSetSection.java b/src/main/java/com/volmit/iris/scaffold/lighting/BlockFaceSetSection.java index 71496a0ad..b47e50b5e 100644 --- a/src/main/java/com/volmit/iris/scaffold/lighting/BlockFaceSetSection.java +++ b/src/main/java/com/volmit/iris/scaffold/lighting/BlockFaceSetSection.java @@ -13,6 +13,6 @@ public class BlockFaceSetSection { } public BlockFaceSet get(int x, int y, int z) { - return BlockFaceSet.byMask((int) _maskData[(y << 8) | (z << 4) | x]); + return BlockFaceSet.byMask(_maskData[(y << 8) | (z << 4) | x]); } } diff --git a/src/main/java/com/volmit/iris/scaffold/lighting/FlatRegionInfo.java b/src/main/java/com/volmit/iris/scaffold/lighting/FlatRegionInfo.java index 3a7a8fc9f..ffc34aa6f 100644 --- a/src/main/java/com/volmit/iris/scaffold/lighting/FlatRegionInfo.java +++ b/src/main/java/com/volmit/iris/scaffold/lighting/FlatRegionInfo.java @@ -1,19 +1,18 @@ package com.volmit.iris.scaffold.lighting; +import com.bergerkiller.bukkit.common.utils.WorldUtil; +import org.bukkit.World; + import java.util.Arrays; import java.util.BitSet; import java.util.stream.IntStream; -import org.bukkit.World; - -import com.bergerkiller.bukkit.common.utils.WorldUtil; - /** * Loads region information, storing whether or not * the 32x32 (1024) chunks are available. */ public class FlatRegionInfo { - private static final int[] DEFAULT_RY_0 = new int[] {0}; // Optimization + private static final int[] DEFAULT_RY_0 = new int[]{0}; // Optimization public final World world; public final int rx, rz; public final int[] ry; @@ -22,7 +21,7 @@ public class FlatRegionInfo { private boolean _loadedFromDisk; public FlatRegionInfo(World world, int rx, int ry, int rz) { - this(world, rx, (ry==0) ? DEFAULT_RY_0 : new int[] {ry}, rz); + this(world, rx, (ry == 0) ? DEFAULT_RY_0 : new int[]{ry}, rz); } public FlatRegionInfo(World world, int rx, int[] ry, int rz) { @@ -59,7 +58,7 @@ public class FlatRegionInfo { /** * Gets the number of chunks in this region. * If not loaded yet, the default 1024 is returned. - * + * * @return chunk count */ public int getChunkCount() { @@ -68,7 +67,7 @@ public class FlatRegionInfo { /** * Gets the region Y-coordinates as a sorted, immutable distinct stream - * + * * @return ry int stream */ public IntStream getRYStream() { @@ -97,7 +96,7 @@ public class FlatRegionInfo { /** * Gets whether the chunk coordinates specified are within the range * of coordinates of this region - * + * * @param cx - chunk coordinates (world coordinates) * @param cz - chunk coordinates (world coordinates) * @return True if in range @@ -110,7 +109,7 @@ public class FlatRegionInfo { /** * Gets whether a chunk is contained and exists inside this region - * + * * @param cx - chunk coordinates (world coordinates) * @param cz - chunk coordinates (world coordinates) * @return True if the chunk is contained @@ -132,7 +131,7 @@ public class FlatRegionInfo { /** * Adds another Region Y-coordinate to the list. * The set of chunks and other properties are copied. - * + * * @param ry * @return new flat region info object with updated ry */ @@ -147,7 +146,7 @@ public class FlatRegionInfo { int[] new_y_coordinates = new int[this.ry.length + 1]; System.arraycopy(this.ry, 0, new_y_coordinates, 0, index); new_y_coordinates[index] = ry; - System.arraycopy(this.ry, index, new_y_coordinates, index+1, this.ry.length - index); + System.arraycopy(this.ry, index, new_y_coordinates, index + 1, this.ry.length - index); return new FlatRegionInfo(this, new_y_coordinates); } } diff --git a/src/main/java/com/volmit/iris/scaffold/lighting/FlatRegionInfoMap.java b/src/main/java/com/volmit/iris/scaffold/lighting/FlatRegionInfoMap.java index c9bd28f7c..186cd760f 100644 --- a/src/main/java/com/volmit/iris/scaffold/lighting/FlatRegionInfoMap.java +++ b/src/main/java/com/volmit/iris/scaffold/lighting/FlatRegionInfoMap.java @@ -1,16 +1,15 @@ package com.volmit.iris.scaffold.lighting; -import java.util.Collection; -import java.util.Set; -import java.util.stream.IntStream; - -import org.bukkit.Chunk; -import org.bukkit.World; - import com.bergerkiller.bukkit.common.bases.IntVector3; import com.bergerkiller.bukkit.common.utils.MathUtil; import com.bergerkiller.bukkit.common.utils.WorldUtil; import com.bergerkiller.bukkit.common.wrappers.LongHashMap; +import org.bukkit.Chunk; +import org.bukkit.World; + +import java.util.Collection; +import java.util.Set; +import java.util.stream.IntStream; /** * A map of region information @@ -46,7 +45,7 @@ public class FlatRegionInfoMap { /** * Gets whether a chunk exists - * + * * @param cx * @param cz * @return True if the chunk exists @@ -58,7 +57,7 @@ public class FlatRegionInfoMap { /** * Gets whether a chunk, and all its 8 neighbours, exist - * + * * @param cx * @param cz * @return True if the chunk and all its neighbours exist @@ -89,7 +88,7 @@ public class FlatRegionInfoMap { /** * Computes all the region Y-coordinates used by a region and its neighbouring 8 regions. * The returned array is sorted in increasing order and is distinct (no duplicate values). - * + * * @param region * @return region and neighbouring regions' Y-coordinates */ @@ -116,7 +115,7 @@ public class FlatRegionInfoMap { /** * Creates a region information mapping of all existing chunks of a world * that are currently loaded. No further loading is required. - * + * * @param world * @return region info map */ @@ -151,7 +150,7 @@ public class FlatRegionInfoMap { /** * Creates a region information mapping of all existing chunks of a world - * + * * @param world * @return region info map */ diff --git a/src/main/java/com/volmit/iris/scaffold/lighting/LightingAutoClean.java b/src/main/java/com/volmit/iris/scaffold/lighting/LightingAutoClean.java index 37d610fad..01f879c07 100644 --- a/src/main/java/com/volmit/iris/scaffold/lighting/LightingAutoClean.java +++ b/src/main/java/com/volmit/iris/scaffold/lighting/LightingAutoClean.java @@ -1,26 +1,25 @@ package com.volmit.iris.scaffold.lighting; -import java.util.HashMap; - -import com.volmit.iris.Iris; -import org.bukkit.World; - import com.bergerkiller.bukkit.common.Task; import com.bergerkiller.bukkit.common.utils.WorldUtil; import com.bergerkiller.bukkit.common.wrappers.LongHashSet; +import com.volmit.iris.Iris; +import org.bukkit.World; + +import java.util.HashMap; /** * Handles the automatic cleanup of chunk lighting when chunks are generated */ public class LightingAutoClean { - private static HashMap queues = new HashMap(); + private static final HashMap queues = new HashMap(); private static Task autoCleanTask = null; /** * Checks all neighbouring chunks to see if they are fully surrounded by chunks (now), and * schedules lighting repairs. This function only does anything when automatic cleaning is activated. - * - * @param world the chunk is in + * + * @param world the chunk is in * @param chunkX coordinate * @param chunkZ coordinate */ diff --git a/src/main/java/com/volmit/iris/scaffold/lighting/LightingCategory.java b/src/main/java/com/volmit/iris/scaffold/lighting/LightingCategory.java index 7f6cfdfc7..765459e29 100644 --- a/src/main/java/com/volmit/iris/scaffold/lighting/LightingCategory.java +++ b/src/main/java/com/volmit/iris/scaffold/lighting/LightingCategory.java @@ -63,7 +63,7 @@ public enum LightingCategory { // Apply sky light to block cube.skyLight.set(x, y & 0xf, z, light); - + // If opaque at the bottom, reset light to 0 for next block // The block itself is lit if (opaqueFaces.down()) { @@ -141,21 +141,21 @@ public enum LightingCategory { /** * Gets the name of this type of light, used when logging - * + * * @return category name */ public abstract String getName(); /** * Initializes the lighting in the chunk for this category - * + * * @param chunk */ public abstract void initialize(LightingChunk chunk); /** * Gets the y-coordinate to start processing from when spreading light around - * + * * @param chunk * @param x * @param z @@ -166,7 +166,7 @@ public enum LightingCategory { /** * Sets whether this category of light is dirty, indicating this category of light is all good, * or that more work is needed spreading light around. - * + * * @param chunk * @param dirty */ @@ -175,7 +175,7 @@ public enum LightingCategory { /** * Gets the light level in a section at the coordinates specified. * No bounds checking is performed. - * + * * @param section * @param x * @param y @@ -187,7 +187,7 @@ public enum LightingCategory { /** * Sets the light level in a section at the coordinates specified. * No bounds checking is performed. - * + * * @param section * @param x * @param y diff --git a/src/main/java/com/volmit/iris/scaffold/lighting/LightingChunk.java b/src/main/java/com/volmit/iris/scaffold/lighting/LightingChunk.java index 3d5862bde..a11c4bd66 100644 --- a/src/main/java/com/volmit/iris/scaffold/lighting/LightingChunk.java +++ b/src/main/java/com/volmit/iris/scaffold/lighting/LightingChunk.java @@ -9,7 +9,6 @@ import com.bergerkiller.bukkit.common.wrappers.ChunkSection; import com.bergerkiller.bukkit.common.wrappers.HeightMap; import com.bergerkiller.bukkit.common.wrappers.IntHashMap; import com.bergerkiller.generated.net.minecraft.server.ChunkHandle; - import com.volmit.iris.Iris; import org.bukkit.Chunk; import org.bukkit.World; @@ -60,7 +59,7 @@ public class LightingChunk { /** * Gets all the sections inside this chunk. * Elements are never null. - * + * * @return sections */ public Collection getSections() { @@ -70,9 +69,9 @@ public class LightingChunk { /** * Efficiently iterates the vertical cubes of a chunk, only * querying the lookup table every 16 blocks - * + * * @param previous The previous cube we iterated - * @param y Block y-coordinate + * @param y Block y-coordinate * @return the cube at the Block y-coordinate, or null if this cube does not exist */ public LightingCube nextCube(LightingCube previous, int y) { @@ -118,13 +117,13 @@ public class LightingChunk { public void detectCubeNeighbors() { for (LightingCube cube : this.sections.values()) { // Neighbors above and below - cube.neighbors.set(0, 1, 0, this.sections.get(cube.cy + 1)); + cube.neighbors.set(0, 1, 0, this.sections.get(cube.cy + 1)); cube.neighbors.set(0, -1, 0, this.sections.get(cube.cy - 1)); // Neighbors in neighboring chunks - cube.neighbors.set(-1, 0, 0, this.neighbors.getCube(-1, 0, cube.cy)); - cube.neighbors.set( 1, 0, 0, this.neighbors.getCube( 1, 0, cube.cy)); - cube.neighbors.set( 0, 0, -1, this.neighbors.getCube( 0, -1, cube.cy)); - cube.neighbors.set( 0, 0, 1, this.neighbors.getCube( 0, 1, cube.cy)); + cube.neighbors.set(-1, 0, 0, this.neighbors.getCube(-1, 0, cube.cy)); + cube.neighbors.set(1, 0, 0, this.neighbors.getCube(1, 0, cube.cy)); + cube.neighbors.set(0, 0, -1, this.neighbors.getCube(0, -1, cube.cy)); + cube.neighbors.set(0, 0, 1, this.neighbors.getCube(0, 1, cube.cy)); } } @@ -162,7 +161,7 @@ public class LightingChunk { this.maxY = 0; if (!lightingChunkSectionList.isEmpty()) { this.minY = lightingChunkSectionList.get(0).cy << 4; - this.maxY = (lightingChunkSectionList.get(lightingChunkSectionList.size()-1).cy << 4) + 15; + this.maxY = (lightingChunkSectionList.get(lightingChunkSectionList.size() - 1).cy << 4) + 15; } // Initialize and then load sky light heightmap information @@ -273,8 +272,7 @@ public class LightingChunk { return isSkyLightDirty || isBlockLightDirty; } - public void forceSpreadBlocks() - { + public void forceSpreadBlocks() { spread(LightingCategory.BLOCK); } @@ -415,7 +413,7 @@ public class LightingChunk { * * @param chunk to save to * @return completable future completed when the chunk is saved, - * with value True passed when saving occurred, False otherwise + * with value True passed when saving occurred, False otherwise */ @SuppressWarnings("unchecked") public CompletableFuture saveToChunk(Chunk chunk) { diff --git a/src/main/java/com/volmit/iris/scaffold/lighting/LightingChunkNeighboring.java b/src/main/java/com/volmit/iris/scaffold/lighting/LightingChunkNeighboring.java index 8d3e60cea..e7a8939ef 100644 --- a/src/main/java/com/volmit/iris/scaffold/lighting/LightingChunkNeighboring.java +++ b/src/main/java/com/volmit/iris/scaffold/lighting/LightingChunkNeighboring.java @@ -24,7 +24,7 @@ public class LightingChunkNeighboring { /** * Gets whether all 4 chunk neighbors are accessible - * + * * @return True if all neighbors are accessible */ public boolean hasAll() { @@ -49,10 +49,10 @@ public class LightingChunkNeighboring { /** * Gets a relative neighboring chunk, and then a vertical cube in that chunk, if possible. - * + * * @param deltaChunkX * @param deltaChunkZ - * @param cy Cube absolute y-coordinate + * @param cy Cube absolute y-coordinate * @return cube, null if the chunk or cube is not available */ public LightingCube getCube(int deltaChunkX, int deltaChunkZ, int cy) { diff --git a/src/main/java/com/volmit/iris/scaffold/lighting/LightingCube.java b/src/main/java/com/volmit/iris/scaffold/lighting/LightingCube.java index d1adff8b8..e5a6a75f2 100644 --- a/src/main/java/com/volmit/iris/scaffold/lighting/LightingCube.java +++ b/src/main/java/com/volmit/iris/scaffold/lighting/LightingCube.java @@ -1,13 +1,13 @@ package com.volmit.iris.scaffold.lighting; -import java.util.concurrent.CompletableFuture; - import com.bergerkiller.bukkit.common.collections.BlockFaceSet; import com.bergerkiller.bukkit.common.utils.WorldUtil; import com.bergerkiller.bukkit.common.wrappers.BlockData; import com.bergerkiller.bukkit.common.wrappers.ChunkSection; import com.bergerkiller.generated.net.minecraft.server.NibbleArrayHandle; +import java.util.concurrent.CompletableFuture; + /** * A single 16x16x16 cube of stored block information */ @@ -79,7 +79,7 @@ public class LightingCube { for (y = 0; y < 16; y++) { info = chunkSection.getBlockData(x, y, z); blockEmission = info.getEmission(); - opacity = info.getOpacity(owner.world, worldX+x, worldY+y, worldZ+z); + opacity = info.getOpacity(owner.world, worldX + x, worldY + y, worldZ + z); if (opacity >= 0xf) { opacity = 0xf; opaqueFaces = BlockFaceSet.ALL; @@ -87,7 +87,7 @@ public class LightingCube { if (opacity < 0) { opacity = 0; } - opaqueFaces = info.getOpaqueFaces(owner.world, worldX+x, worldY+y, worldZ+z); + opaqueFaces = info.getOpaqueFaces(owner.world, worldX + x, worldY + y, worldZ + z); } this.opacity.set(x, y, z, opacity); @@ -101,10 +101,10 @@ public class LightingCube { /** * Gets the opaque faces of a block - * - * @param x - coordinate - * @param y - coordinate - * @param z - coordinate + * + * @param x - coordinate + * @param y - coordinate + * @param z - coordinate * @return opaque face set */ public BlockFaceSet getOpaqueFaces(int x, int y, int z) { @@ -116,20 +116,20 @@ public class LightingCube { * If possibly more, also check opaque faces, and then return the * higher light value if all these tests pass. * The x/y/z coordinates are allowed to check neighboring cubes. - * + * * @param category * @param old_light * @param faceMask - * @param x The X-coordinate of the block (-1 to 16) - * @param y The Y-coordinate of the block (-1 to 16) - * @param z The Z-coordinate of the block (-1 to 16) + * @param x The X-coordinate of the block (-1 to 16) + * @param y The Y-coordinate of the block (-1 to 16) + * @param z The Z-coordinate of the block (-1 to 16) * @return higher light level if propagated, otherwise the old light value */ public int getLightIfHigherNeighbor(LightingCategory category, int old_light, int faceMask, int x, int y, int z) { if ((x & OOC | y & OOC | z & OOC) == 0) { return this.getLightIfHigher(category, old_light, faceMask, x, y, z); } else { - LightingCube neigh = this.neighbors.get(x>>4, y>>4, z>>4); + LightingCube neigh = this.neighbors.get(x >> 4, y >> 4, z >> 4); if (neigh != null) { return neigh.getLightIfHigher(category, old_light, faceMask, x & 0xf, y & 0xf, z & 0xf); } else { @@ -143,13 +143,13 @@ public class LightingCube { * If possibly more, also check opaque faces, and then return the * higher light value if all these tests pass. * Requires the x/y/z coordinates to lay within this cube. - * - * @param category Category of light to check + * + * @param category Category of light to check * @param old_light Previous light value - * @param faceMask The BlockFaceSet mask indicating the light-traveling direction - * @param x The X-coordinate of the block (0 to 15) - * @param y The Y-coordinate of the block (0 to 15) - * @param z The Z-coordinate of the block (0 to 15) + * @param faceMask The BlockFaceSet mask indicating the light-traveling direction + * @param x The X-coordinate of the block (0 to 15) + * @param y The Y-coordinate of the block (0 to 15) + * @param z The Z-coordinate of the block (0 to 15) * @return higher light level if propagated, otherwise the old light value */ public int getLightIfHigher(LightingCategory category, int old_light, int faceMask, int x, int y, int z) { @@ -161,7 +161,7 @@ public class LightingCube { /** * Called during initialization of block light to spread the light emitted by a block * to all neighboring blocks. - * + * * @param x The X-coordinate of the block (0 to 15) * @param y The Y-coordinate of the block (0 to 15) * @param z The Z-coordinate of the block (0 to 15) @@ -172,22 +172,22 @@ public class LightingCube { return; // Skip if neighbouring blocks won't receive light from it } if (x >= 1 && z >= 1 && x <= 14 && z <= 14) { - trySpreadBlockLightWithin(emitted, BlockFaceSet.MASK_EAST, x-1, y, z); - trySpreadBlockLightWithin(emitted, BlockFaceSet.MASK_WEST, x+1, y, z); - trySpreadBlockLightWithin(emitted, BlockFaceSet.MASK_SOUTH, x, y, z-1); - trySpreadBlockLightWithin(emitted, BlockFaceSet.MASK_NORTH, x, y, z+1); + trySpreadBlockLightWithin(emitted, BlockFaceSet.MASK_EAST, x - 1, y, z); + trySpreadBlockLightWithin(emitted, BlockFaceSet.MASK_WEST, x + 1, y, z); + trySpreadBlockLightWithin(emitted, BlockFaceSet.MASK_SOUTH, x, y, z - 1); + trySpreadBlockLightWithin(emitted, BlockFaceSet.MASK_NORTH, x, y, z + 1); } else { - trySpreadBlockLight(emitted, BlockFaceSet.MASK_EAST, x-1, y, z); - trySpreadBlockLight(emitted, BlockFaceSet.MASK_WEST, x+1, y, z); - trySpreadBlockLight(emitted, BlockFaceSet.MASK_SOUTH, x, y, z-1); - trySpreadBlockLight(emitted, BlockFaceSet.MASK_NORTH, x, y, z+1); + trySpreadBlockLight(emitted, BlockFaceSet.MASK_EAST, x - 1, y, z); + trySpreadBlockLight(emitted, BlockFaceSet.MASK_WEST, x + 1, y, z); + trySpreadBlockLight(emitted, BlockFaceSet.MASK_SOUTH, x, y, z - 1); + trySpreadBlockLight(emitted, BlockFaceSet.MASK_NORTH, x, y, z + 1); } if (y >= 1 && y <= 14) { - trySpreadBlockLightWithin(emitted, BlockFaceSet.MASK_UP, x, y-1, z); - trySpreadBlockLightWithin(emitted, BlockFaceSet.MASK_DOWN, x, y+1, z); + trySpreadBlockLightWithin(emitted, BlockFaceSet.MASK_UP, x, y - 1, z); + trySpreadBlockLightWithin(emitted, BlockFaceSet.MASK_DOWN, x, y + 1, z); } else { - trySpreadBlockLight(emitted, BlockFaceSet.MASK_UP, x, y-1, z); - trySpreadBlockLight(emitted, BlockFaceSet.MASK_DOWN, x, y+1, z); + trySpreadBlockLight(emitted, BlockFaceSet.MASK_UP, x, y - 1, z); + trySpreadBlockLight(emitted, BlockFaceSet.MASK_DOWN, x, y + 1, z); } } @@ -195,18 +195,18 @@ public class LightingCube { * Tries to spread block light from an emitting block to one of the 6 sites. * The block being spread to is allowed to be outside of the bounds of this cube, * in which case neighboring cubes are spread to instead. - * - * @param emitted The light that is emitted by the block + * + * @param emitted The light that is emitted by the block * @param faceMask The BlockFaceSet mask indicating the light-traveling direction - * @param x The X-coordinate of the block to spread to (-1 to 16) - * @param y The Y-coordinate of the block to spread to (-1 to 16) - * @param z The Z-coordinate of the block to spread to (-1 to 16) + * @param x The X-coordinate of the block to spread to (-1 to 16) + * @param y The Y-coordinate of the block to spread to (-1 to 16) + * @param z The Z-coordinate of the block to spread to (-1 to 16) */ public void trySpreadBlockLight(int emitted, int faceMask, int x, int y, int z) { if ((x & OOC | y & OOC | z & OOC) == 0) { this.trySpreadBlockLightWithin(emitted, faceMask, x, y, z); } else { - LightingCube neigh = this.neighbors.get(x>>4, y>>4, z>>4); + LightingCube neigh = this.neighbors.get(x >> 4, y >> 4, z >> 4); if (neigh != null) { neigh.trySpreadBlockLightWithin(emitted, faceMask, x & 0xf, y & 0xf, z & 0xf); } @@ -216,16 +216,16 @@ public class LightingCube { /** * Tries to spread block light from an emitting block to one of the 6 sides. * Assumes that the block being spread to is within this cube. - * - * @param emitted The light that is emitted by the block + * + * @param emitted The light that is emitted by the block * @param faceMask The BlockFaceSet mask indicating the light-traveling direction - * @param x The X-coordinate of the block to spread to (0 to 15) - * @param y The Y-coordinate of the block to spread to (0 to 15) - * @param z The Z-coordinate of the block to spread to (0 to 15) + * @param x The X-coordinate of the block to spread to (0 to 15) + * @param y The Y-coordinate of the block to spread to (0 to 15) + * @param z The Z-coordinate of the block to spread to (0 to 15) */ public void trySpreadBlockLightWithin(int emitted, int faceMask, int x, int y, int z) { if (!this.getOpaqueFaces(x, y, z).get(faceMask)) { - int new_level = emitted - Math.max(1, this.opacity.get(x, y, z)); + int new_level = emitted - Math.max(1, this.opacity.get(x, y, z)); if (new_level > this.blockLight.get(x, y, z)) { this.blockLight.set(x, y, z, new_level); } diff --git a/src/main/java/com/volmit/iris/scaffold/lighting/LightingCubeNeighboring.java b/src/main/java/com/volmit/iris/scaffold/lighting/LightingCubeNeighboring.java index 95b3e5400..7b0ffebb1 100644 --- a/src/main/java/com/volmit/iris/scaffold/lighting/LightingCubeNeighboring.java +++ b/src/main/java/com/volmit/iris/scaffold/lighting/LightingCubeNeighboring.java @@ -26,7 +26,7 @@ public class LightingCubeNeighboring { /** * Gets whether all 6 cube neighbors are accessible - * + * * @return True if all neighbors are accessible */ public boolean hasAll() { @@ -56,7 +56,7 @@ public class LightingCubeNeighboring { * @param deltaCubeX * @param deltaCubeY * @param deltaCubeZ - * @param neighbor to set to, is allowed to be null to set to 'none' + * @param neighbor to set to, is allowed to be null to set to 'none' */ public void set(int deltaCubeX, int deltaCubeY, int deltaCubeZ, LightingCube neighbor) { values[getIndexByCube(deltaCubeX, deltaCubeY, deltaCubeZ)] = neighbor; diff --git a/src/main/java/com/volmit/iris/scaffold/lighting/LightingForcedChunkCache.java b/src/main/java/com/volmit/iris/scaffold/lighting/LightingForcedChunkCache.java index b9e0205f4..d1dd047b8 100644 --- a/src/main/java/com/volmit/iris/scaffold/lighting/LightingForcedChunkCache.java +++ b/src/main/java/com/volmit/iris/scaffold/lighting/LightingForcedChunkCache.java @@ -1,12 +1,11 @@ package com.volmit.iris.scaffold.lighting; -import java.util.HashMap; -import java.util.Map; - -import org.bukkit.World; - import com.bergerkiller.bukkit.common.chunk.ForcedChunk; import com.bergerkiller.bukkit.common.utils.WorldUtil; +import org.bukkit.World; + +import java.util.HashMap; +import java.util.Map; /** * Shortly remembers the forced chunks it has kept loaded from a previous operation. @@ -67,8 +66,8 @@ public class LightingForcedChunkCache { if (o instanceof Key) { Key other = (Key) o; return other.x == this.x && - other.z == this.z && - other.world == this.world; + other.z == this.z && + other.world == this.world; } else { return false; } diff --git a/src/main/java/com/volmit/iris/scaffold/lighting/LightingService.java b/src/main/java/com/volmit/iris/scaffold/lighting/LightingService.java index 54bec789e..4120d8aca 100644 --- a/src/main/java/com/volmit/iris/scaffold/lighting/LightingService.java +++ b/src/main/java/com/volmit/iris/scaffold/lighting/LightingService.java @@ -9,7 +9,10 @@ import com.bergerkiller.bukkit.common.utils.WorldUtil; import com.bergerkiller.bukkit.common.wrappers.LongHashSet; import com.bergerkiller.bukkit.common.wrappers.LongHashSet.LongIterator; import com.volmit.iris.Iris; -import org.bukkit.*; +import org.bukkit.Bukkit; +import org.bukkit.ChatColor; +import org.bukkit.Location; +import org.bukkit.World; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; @@ -25,7 +28,7 @@ public class LightingService extends AsyncTask { private static boolean pendingFileInUse = false; private static LightingTask currentTask; private static boolean paused = false; - private static boolean lowOnMemory = false; + private static final boolean lowOnMemory = false; /** * Gets whether this service is currently processing something @@ -57,7 +60,7 @@ public class LightingService extends AsyncTask { /** * Gets whether execution is paused, and pending tasks are not being processed - * + * * @return True if paused */ public static boolean isPaused() { @@ -66,7 +69,7 @@ public class LightingService extends AsyncTask { /** * Sets whether execution is paused. - * + * * @param pause state to set to */ public static void setPaused(boolean pause) { @@ -77,7 +80,7 @@ public class LightingService extends AsyncTask { /** * Gets the status of the currently processed task - * + * * @return current task status */ public static String getCurrentStatus() { @@ -94,7 +97,7 @@ public class LightingService extends AsyncTask { /** * Gets the time the currently processing task was started. If no task is being processed, * an empty result is returned. If processing didn't start yet, the value will be 0. - * + * * @return time when the current task was started */ public static java.util.OptionalLong getCurrentStartTime() { @@ -163,7 +166,7 @@ public class LightingService extends AsyncTask { // In that case, be sure to only schedule chunks that actually exist // This prevents generating new chunks as part of this command LongHashSet chunks = args.getChunks(); - if (chunks.size() <= (34*34)) { + if (chunks.size() <= (34 * 34)) { LongHashSet chunks_filtered = new LongHashSet(chunks.size()); Set region_coords_filtered = new HashSet(); @@ -501,7 +504,7 @@ public class LightingService extends AsyncTask { /** * Sets the world itself. Automatically updates the world name. - * + * * @param world * @return these arguments */ @@ -514,7 +517,7 @@ public class LightingService extends AsyncTask { /** * Sets the world name to perform operations on. * If the world by this name does not exist, the world is null. - * + * * @param worldName * @return these arguments */ @@ -546,13 +549,13 @@ public class LightingService extends AsyncTask { public ScheduleArguments setChunksAround(Location location, int radius) { this.setWorld(location.getWorld()); - return this.setChunksAround(location.getBlockX()>>4, location.getBlockZ()>>4, radius); + return this.setChunksAround(location.getBlockX() >> 4, location.getBlockZ() >> 4, radius); } public ScheduleArguments setChunksAround(int middleX, int middleZ, int radius) { this.setRadius(radius); - LongHashSet chunks_hashset = new LongHashSet((2*radius)*(2*radius)); + LongHashSet chunks_hashset = new LongHashSet((2 * radius) * (2 * radius)); for (int a = -radius; a <= radius; a++) { for (int b = -radius; b <= radius; b++) { int cx = middleX + a; @@ -567,7 +570,7 @@ public class LightingService extends AsyncTask { * Sets the chunks to a cuboid area of chunks. * Make sure the minimum chunk coordinates are less or equal to * the maximum chunk coordinates. - * + * * @param minChunkX Minimum chunk x-coordinate (inclusive) * @param minChunkZ Minimum chunk z-coordinate (inclusive) * @param maxChunkX Maximum chunk x-coordinate (inclusive) @@ -609,7 +612,7 @@ public class LightingService extends AsyncTask { /** * Parses the arguments specified in a command - * + * * @param sender * @return false if the input is incorrect and operations may not proceed * @throws NoPermissionException @@ -620,11 +623,10 @@ public class LightingService extends AsyncTask { /** * Creates a new ScheduleArguments instance ready to be configured - * + * * @return args */ - public static ScheduleArguments create() - { + public static ScheduleArguments create() { return new ScheduleArguments(); } } diff --git a/src/main/java/com/volmit/iris/scaffold/lighting/LightingTask.java b/src/main/java/com/volmit/iris/scaffold/lighting/LightingTask.java index 5935a60dc..389aa550e 100644 --- a/src/main/java/com/volmit/iris/scaffold/lighting/LightingTask.java +++ b/src/main/java/com/volmit/iris/scaffold/lighting/LightingTask.java @@ -24,7 +24,7 @@ public interface LightingTask { /** * Gets a descriptive status of the current task being processed - * + * * @return status */ String getStatus(); @@ -32,7 +32,7 @@ public interface LightingTask { /** * Gets the timestamp (milliseconds since epoch) when this task was first started. * If 0 is returned, then the task wasn't started yet. - * + * * @return time this task was started */ long getTimeStarted(); @@ -49,7 +49,7 @@ public interface LightingTask { /** * Whether this task can be saved to PendingLight.dat - * + * * @return True if it can be saved */ boolean canSave(); diff --git a/src/main/java/com/volmit/iris/scaffold/lighting/LightingTaskBatch.java b/src/main/java/com/volmit/iris/scaffold/lighting/LightingTaskBatch.java index 4643a953b..becf3ed01 100644 --- a/src/main/java/com/volmit/iris/scaffold/lighting/LightingTaskBatch.java +++ b/src/main/java/com/volmit/iris/scaffold/lighting/LightingTaskBatch.java @@ -6,6 +6,9 @@ import com.bergerkiller.bukkit.common.utils.LogicUtil; import com.bergerkiller.bukkit.common.utils.MathUtil; import com.bergerkiller.bukkit.common.utils.WorldUtil; import com.bergerkiller.bukkit.common.wrappers.LongHashSet; +import com.volmit.iris.Iris; +import org.bukkit.Chunk; +import org.bukkit.World; import java.util.Arrays; import java.util.concurrent.CompletableFuture; @@ -14,17 +17,13 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.stream.Stream; -import com.volmit.iris.Iris; -import org.bukkit.Chunk; -import org.bukkit.World; - /** * Contains all the chunk coordinates that have to be fixed, * and handles the full process of this fixing. * It is literally a batch of chunks being processed. */ public class LightingTaskBatch implements LightingTask { - private static boolean DEBUG_LOG = false; // logs performance stats + private static final boolean DEBUG_LOG = false; // logs performance stats public final World world; private final Object chunks_lock = new Object(); private final int[] region_y_coords; @@ -79,7 +78,7 @@ public class LightingTaskBatch implements LightingTask { * Gets the X and Z-coordinates of all the chunk columns to process. * The coordinates are combined into a single Long, which can be decoded * using {@link MathUtil#longHashMsw(long)} for X and {@link MathUtil#longHashLsw(long) for Z. - * + * * @return chunk coordinates */ public long[] getChunks() { @@ -102,7 +101,7 @@ public class LightingTaskBatch implements LightingTask { /** * Gets the Y-coordinates of all the regions to look for chunk data. A region stores 32 chunk * slices vertically, and goes up/down 512 blocks every coordinate increase/decrease. - * + * * @return region Y-coordinates */ public int[] getRegionYCoordinates() { @@ -176,7 +175,7 @@ public class LightingTaskBatch implements LightingTask { BatchChunkInfo chunk = this.getAverageChunk(); if (chunk != null) { String postfix = " chunks near " + - "x=" + (chunk.cx*16) + " z=" + (chunk.cz*16); + "x=" + (chunk.cx * 16) + " z=" + (chunk.cz * 16); if (this.stage == Stage.LOADING) { synchronized (this.chunks_lock) { if (this.chunks != null) { @@ -212,7 +211,7 @@ public class LightingTaskBatch implements LightingTask { private String getShortStatus() { BatchChunkInfo chunk = this.getAverageChunk(); if (chunk != null) { - return "[x=" + (chunk.cx*16) + " z=" + (chunk.cz*16) + " count=" + chunk.count + "]"; + return "[x=" + (chunk.cx * 16) + " z=" + (chunk.cz * 16) + " count=" + chunk.count + "]"; } else { return "[Unknown]"; } @@ -356,7 +355,7 @@ public class LightingTaskBatch implements LightingTask { int failed_chunk_count = 0; LightingChunk[] new_chunks = this.chunks; - for (int i = new_chunks.length-1; i >= 0; i--) { + for (int i = new_chunks.length - 1; i >= 0; i--) { LightingChunk lc = new_chunks[i]; if (lc.forcedChunk.getChunkAsync().isCompletedExceptionally()) { failed_chunk_avg_x += lc.chunkX; @@ -417,7 +416,7 @@ public class LightingTaskBatch implements LightingTask { this.stage = Stage.APPLYING; try { CompletableFuture future = apply(); - int max_num_of_waits = (5*120); + int max_num_of_waits = (5 * 120); while (true) { if (--max_num_of_waits == 0) { Iris.error("Failed to apply lighting data for " + getShortStatus() + ": Timeout"); @@ -558,7 +557,7 @@ public class LightingTaskBatch implements LightingTask { return !this.options.getLoadedChunksOnly() && !this.options.getDebugMakeCorrupted(); } - private static enum Stage { + private enum Stage { LOADING, FIXING, APPLYING } } diff --git a/src/main/java/com/volmit/iris/scaffold/lighting/LightingTaskWorld.java b/src/main/java/com/volmit/iris/scaffold/lighting/LightingTaskWorld.java index da242df7e..f90a22dca 100644 --- a/src/main/java/com/volmit/iris/scaffold/lighting/LightingTaskWorld.java +++ b/src/main/java/com/volmit/iris/scaffold/lighting/LightingTaskWorld.java @@ -2,12 +2,11 @@ package com.volmit.iris.scaffold.lighting; import com.bergerkiller.bukkit.common.utils.CommonUtil; import com.bergerkiller.bukkit.common.wrappers.LongHashSet; +import org.bukkit.World; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; -import org.bukkit.World; - public class LightingTaskWorld implements LightingTask { private static final int ASSUMED_CHUNKS_PER_REGION = 34 * 34; private final World world; @@ -46,7 +45,7 @@ public class LightingTaskWorld implements LightingTask { if (regions == null) { return "Reading available regions from world " + getWorld().getName(); } else { - return "Reading available chunks from world " + getWorld().getName() + " (region " + (regionCountLoaded+1) + "/" + regions.getRegionCount() + ")"; + return "Reading available chunks from world " + getWorld().getName() + " (region " + (regionCountLoaded + 1) + "/" + regions.getRegionCount() + ")"; } } @@ -123,7 +122,7 @@ public class LightingTaskWorld implements LightingTask { // Reduce count, schedule and clear the buffer // Put the coordinates that are available - final LongHashSet buffer = new LongHashSet(34*34); + final LongHashSet buffer = new LongHashSet(34 * 34); if (true) { int dx, dz; for (dx = -1; dx < 33; dx++) { diff --git a/src/main/java/com/volmit/iris/scaffold/lighting/LightingUtil.java b/src/main/java/com/volmit/iris/scaffold/lighting/LightingUtil.java index 6d35e943f..ae5bdb870 100644 --- a/src/main/java/com/volmit/iris/scaffold/lighting/LightingUtil.java +++ b/src/main/java/com/volmit/iris/scaffold/lighting/LightingUtil.java @@ -6,8 +6,8 @@ import com.bergerkiller.bukkit.common.utils.MathUtil; * Just some utilities used by Light Cleaner */ public class LightingUtil { - private static TimeDurationFormat timeFormat_hh_mm = new TimeDurationFormat("HH 'hours' mm 'minutes'"); - private static TimeDurationFormat timeFormat_mm_ss = new TimeDurationFormat("mm 'minutes' ss 'seconds'"); + private static final TimeDurationFormat timeFormat_hh_mm = new TimeDurationFormat("HH 'hours' mm 'minutes'"); + private static final TimeDurationFormat timeFormat_mm_ss = new TimeDurationFormat("mm 'minutes' ss 'seconds'"); private static final long SECOND_MILLIS = 1000L; private static final long MINUTE_MILLIS = 60L * SECOND_MILLIS; @@ -19,7 +19,7 @@ public class LightingUtil { return MathUtil.round((double) duration / (double) SECOND_MILLIS, 2) + " seconds"; } else if (duration < HOUR_MILLIS) { return timeFormat_mm_ss.format(duration); - } else if (duration < (2*DAY_MILLIS)) { + } else if (duration < (2 * DAY_MILLIS)) { return timeFormat_hh_mm.format(duration); } else { long num_days = duration / DAY_MILLIS; diff --git a/src/main/java/com/volmit/iris/scaffold/lighting/TimeDurationFormat.java b/src/main/java/com/volmit/iris/scaffold/lighting/TimeDurationFormat.java index 08c526588..e5b714565 100644 --- a/src/main/java/com/volmit/iris/scaffold/lighting/TimeDurationFormat.java +++ b/src/main/java/com/volmit/iris/scaffold/lighting/TimeDurationFormat.java @@ -19,7 +19,7 @@ public class TimeDurationFormat { /** * Creates a new time duration format. The format accepts the same formatting * tokens as the Date formatter does. - * + * * @param format * @throws IllegalArgumentException if the input format is invalid */ @@ -34,7 +34,7 @@ public class TimeDurationFormat { /** * Formats the duration - * + * * @param durationMillis * @return formatted string */ diff --git a/src/main/java/com/volmit/iris/scaffold/parallax/ParallaxAccess.java b/src/main/java/com/volmit/iris/scaffold/parallax/ParallaxAccess.java index aeb3f7ea6..108b084ac 100644 --- a/src/main/java/com/volmit/iris/scaffold/parallax/ParallaxAccess.java +++ b/src/main/java/com/volmit/iris/scaffold/parallax/ParallaxAccess.java @@ -81,18 +81,15 @@ public interface ParallaxAccess { default void maxMin(int x, int z, int value) { ParallaxChunkMeta meat = getMetaRW(x, z); - if(value > meat.getMaxObject()) - { + if (value > meat.getMaxObject()) { meat.setMaxObject(value); } - if(meat.getMinObject() <=-1) - { + if (meat.getMinObject() <= -1) { meat.setMinObject(value); } - if(value < meat.getMinObject()) - { + if (value < meat.getMinObject()) { meat.setMinObject(value); } } @@ -105,44 +102,43 @@ public interface ParallaxAccess { getMetaRW(x, z).setFeatureGenerated(v); } - public Hunk> getTilesR(int x, int z); + Hunk> getTilesR(int x, int z); - public Hunk> getTilesRW(int x, int z); + Hunk> getTilesRW(int x, int z); - public Hunk getBlocksR(int x, int z); + Hunk getBlocksR(int x, int z); - public Hunk getBlocksRW(int x, int z); + Hunk getBlocksRW(int x, int z); - public Hunk getObjectsR(int x, int z); + Hunk getObjectsR(int x, int z); - public Hunk getObjectsRW(int x, int z); + Hunk getObjectsRW(int x, int z); - public Hunk getEntitiesRW(int x, int z); + Hunk getEntitiesRW(int x, int z); - public Hunk getEntitiesR(int x, int z); + Hunk getEntitiesR(int x, int z); - public Hunk getUpdatesR(int x, int z); + Hunk getUpdatesR(int x, int z); - public Hunk getUpdatesRW(int x, int z); + Hunk getUpdatesRW(int x, int z); - public ParallaxChunkMeta getMetaR(int x, int z); + ParallaxChunkMeta getMetaR(int x, int z); - public ParallaxChunkMeta getMetaRW(int x, int z); + ParallaxChunkMeta getMetaRW(int x, int z); - public void cleanup(long regionIdle, long chunkIdle); + void cleanup(long regionIdle, long chunkIdle); - public void cleanup(); + void cleanup(); - public void saveAll(); + void saveAll(); - public void saveAllNOW(); + void saveAllNOW(); - public int getRegionCount(); + int getRegionCount(); - public int getChunkCount(); + int getChunkCount(); - public default void delete(int x, int z) - { + default void delete(int x, int z) { getUpdatesRW(x, z).empty(false); getBlocksRW(x, z).empty(null); getTilesRW(x, z).empty(null); diff --git a/src/main/java/com/volmit/iris/scaffold/parallax/ParallaxChunkMeta.java b/src/main/java/com/volmit/iris/scaffold/parallax/ParallaxChunkMeta.java index 41daabeba..faffa93c1 100644 --- a/src/main/java/com/volmit/iris/scaffold/parallax/ParallaxChunkMeta.java +++ b/src/main/java/com/volmit/iris/scaffold/parallax/ParallaxChunkMeta.java @@ -25,7 +25,7 @@ public class ParallaxChunkMeta { @Override public ParallaxChunkMeta read(DataInputStream din) throws IOException { - return new Gson().fromJson(din.readUTF(), ParallaxChunkMeta.class); + return new Gson().fromJson(din.readUTF(), ParallaxChunkMeta.class); } }; @@ -40,8 +40,7 @@ public class ParallaxChunkMeta { private int count; private CopyOnWriteArrayList features; - public ParallaxChunkMeta() - { + public ParallaxChunkMeta() { this(false, false, false, false, false, false, -1, -1, 0, new CopyOnWriteArrayList<>()); } } diff --git a/src/main/java/com/volmit/iris/scaffold/parallax/ParallaxRegion.java b/src/main/java/com/volmit/iris/scaffold/parallax/ParallaxRegion.java index 2e609ca4a..49d7de34a 100644 --- a/src/main/java/com/volmit/iris/scaffold/parallax/ParallaxRegion.java +++ b/src/main/java/com/volmit/iris/scaffold/parallax/ParallaxRegion.java @@ -16,195 +16,174 @@ import org.bukkit.block.data.BlockData; import java.io.File; import java.io.IOException; -public class ParallaxRegion extends HunkRegion -{ - private boolean dirtyMeta; - private Hunk meta; - private HunkIOAdapter metaAdapter; - private HunkRegionSlice blockSlice; - private HunkRegionSlice> tileSlice; - private HunkRegionSlice objectSlice; - private HunkRegionSlice entitySlice; - private HunkRegionSlice updateSlice; - private final GridLock lock; - private long lastUse; - private final int height; +public class ParallaxRegion extends HunkRegion { + private boolean dirtyMeta; + private Hunk meta; + private HunkIOAdapter metaAdapter; + private HunkRegionSlice blockSlice; + private HunkRegionSlice> tileSlice; + private HunkRegionSlice objectSlice; + private HunkRegionSlice entitySlice; + private HunkRegionSlice updateSlice; + private final GridLock lock; + private long lastUse; + private final int height; - public ParallaxRegion(int height, File folder, int x, int z, CompoundTag compound) - { - super(folder, x, z, compound); - this.height = height; - setupSlices(); - lock = new GridLock(32, 32); - } + public ParallaxRegion(int height, File folder, int x, int z, CompoundTag compound) { + super(folder, x, z, compound); + this.height = height; + setupSlices(); + lock = new GridLock(32, 32); + } - public ParallaxRegion(int height, File folder, int x, int z) - { - super(folder, x, z); - this.height = height; - setupSlices(); - lock = new GridLock(32, 32); - } + public ParallaxRegion(int height, File folder, int x, int z) { + super(folder, x, z); + this.height = height; + setupSlices(); + lock = new GridLock(32, 32); + } - private void setupSlices() - { - blockSlice = HunkRegionSlice.BLOCKDATA.apply(height, getCompound()); - tileSlice = HunkRegionSlice.TILE.apply(height, getCompound()); - objectSlice = HunkRegionSlice.STRING.apply(height, getCompound(), "objects"); - entitySlice = HunkRegionSlice.STRING.apply(height, getCompound(), "entities"); - updateSlice = HunkRegionSlice.BOOLEAN.apply(height, getCompound(), "updates"); - metaAdapter = ParallaxChunkMeta.adapter.apply(getCompound()); - dirtyMeta = false; - meta = null; - lastUse = M.ms(); - } + private void setupSlices() { + blockSlice = HunkRegionSlice.BLOCKDATA.apply(height, getCompound()); + tileSlice = HunkRegionSlice.TILE.apply(height, getCompound()); + objectSlice = HunkRegionSlice.STRING.apply(height, getCompound(), "objects"); + entitySlice = HunkRegionSlice.STRING.apply(height, getCompound(), "entities"); + updateSlice = HunkRegionSlice.BOOLEAN.apply(height, getCompound(), "updates"); + metaAdapter = ParallaxChunkMeta.adapter.apply(getCompound()); + dirtyMeta = false; + meta = null; + lastUse = M.ms(); + } - public boolean hasBeenIdleLongerThan(long time) - { - return M.ms() - lastUse > time; - } + public boolean hasBeenIdleLongerThan(long time) { + return M.ms() - lastUse > time; + } - public ParallaxChunkMeta getMetaR(int x, int z) - { - return lock.withResult(x, z, () -> getMetaHunkR().getOr(x, 0, z, new ParallaxChunkMeta())); - } + public ParallaxChunkMeta getMetaR(int x, int z) { + return lock.withResult(x, z, () -> getMetaHunkR().getOr(x, 0, z, new ParallaxChunkMeta())); + } - public ParallaxChunkMeta getMetaRW(int x, int z) - { - return lock.withResult(x, z, () -> { - lastUse = M.ms(); - dirtyMeta = true; - ParallaxChunkMeta p = getMetaHunkRW().get(x, 0, z); - if(p == null) - { - p = new ParallaxChunkMeta(); - getMetaHunkRW().set(x,0,z,p); - } + public ParallaxChunkMeta getMetaRW(int x, int z) { + return lock.withResult(x, z, () -> { + lastUse = M.ms(); + dirtyMeta = true; + ParallaxChunkMeta p = getMetaHunkRW().get(x, 0, z); + if (p == null) { + p = new ParallaxChunkMeta(); + getMetaHunkRW().set(x, 0, z, p); + } - return p; - }); - } + return p; + }); + } - private Hunk getMetaHunkR() - { - if(meta == null) - { - meta = loadMetaHunk(); - } + private Hunk getMetaHunkR() { + if (meta == null) { + meta = loadMetaHunk(); + } - return meta; - } + return meta; + } - private Hunk getMetaHunkRW() - { - dirtyMeta = true; - return getMetaHunkR(); - } + private Hunk getMetaHunkRW() { + dirtyMeta = true; + return getMetaHunkR(); + } - private Hunk loadMetaHunk() - { - lastUse = M.ms(); - if(meta == null) - { - Tag t = getCompound().getValue().get("meta"); + private Hunk loadMetaHunk() { + lastUse = M.ms(); + if (meta == null) { + Tag t = getCompound().getValue().get("meta"); - if((t instanceof ByteArrayTag)) - { - try { - meta = metaAdapter.read((x,y,z) -> Hunk.newArrayHunk(32, 1, 32), (ByteArrayTag)t); - } catch (IOException e) { - e.printStackTrace(); - } - } + if ((t instanceof ByteArrayTag)) { + try { + meta = metaAdapter.read((x, y, z) -> Hunk.newArrayHunk(32, 1, 32), (ByteArrayTag) t); + } catch (IOException e) { + e.printStackTrace(); + } + } - if(meta == null) - { - meta = Hunk.newArrayHunk(32, 1, 32); - } - } + if (meta == null) { + meta = Hunk.newArrayHunk(32, 1, 32); + } + } - return meta; - } + return meta; + } - public void unloadMetaHunk() - { - if(dirtyMeta) - { - saveMetaHunk(); - dirtyMeta = false; - } + public void unloadMetaHunk() { + if (dirtyMeta) { + saveMetaHunk(); + dirtyMeta = false; + } - meta = null; - } + meta = null; + } - public void saveMetaHunk() - { - if(meta != null && dirtyMeta) - { - try { - getCompound().getValue().put("meta", meta.writeByteArrayTag(metaAdapter, "meta")); - dirtyMeta = false; - } catch (IOException e) { - e.printStackTrace(); - } - } - } + public void saveMetaHunk() { + if (meta != null && dirtyMeta) { + try { + getCompound().getValue().put("meta", meta.writeByteArrayTag(metaAdapter, "meta")); + dirtyMeta = false; + } catch (IOException e) { + e.printStackTrace(); + } + } + } - public synchronized void save() throws IOException - { - blockSlice.save(); - objectSlice.save(); - entitySlice.save(); - tileSlice.save(); - updateSlice.save(); - saveMetaHunk(); - super.save(); - } + public synchronized void save() throws IOException { + blockSlice.save(); + objectSlice.save(); + entitySlice.save(); + tileSlice.save(); + updateSlice.save(); + saveMetaHunk(); + super.save(); + } - public int unload() - { - unloadMetaHunk(); - return blockSlice.unloadAll()+ - objectSlice.unloadAll()+ - entitySlice.unloadAll()+ - tileSlice.unloadAll()+ - updateSlice.unloadAll(); - } + public int unload() { + unloadMetaHunk(); + return blockSlice.unloadAll() + + objectSlice.unloadAll() + + entitySlice.unloadAll() + + tileSlice.unloadAll() + + updateSlice.unloadAll(); + } - public HunkRegionSlice getBlockSlice() { - lastUse = M.ms(); - return blockSlice; - } + public HunkRegionSlice getBlockSlice() { + lastUse = M.ms(); + return blockSlice; + } - public HunkRegionSlice getEntitySlice() { - lastUse = M.ms(); - return entitySlice; - } + public HunkRegionSlice getEntitySlice() { + lastUse = M.ms(); + return entitySlice; + } - public HunkRegionSlice> getTileSlice() { - lastUse = M.ms(); - return tileSlice; - } + public HunkRegionSlice> getTileSlice() { + lastUse = M.ms(); + return tileSlice; + } - public HunkRegionSlice getObjectSlice() { - lastUse = M.ms(); - return objectSlice; - } + public HunkRegionSlice getObjectSlice() { + lastUse = M.ms(); + return objectSlice; + } - public HunkRegionSlice getUpdateSlice() { - lastUse = M.ms(); - return updateSlice; - } + public HunkRegionSlice getUpdateSlice() { + lastUse = M.ms(); + return updateSlice; + } - public synchronized int cleanup(long c) { - return blockSlice.cleanup(c) + - objectSlice.cleanup(c) + - entitySlice.cleanup(c) + - tileSlice.cleanup(c) + - updateSlice.cleanup(c); - } + public synchronized int cleanup(long c) { + return blockSlice.cleanup(c) + + objectSlice.cleanup(c) + + entitySlice.cleanup(c) + + tileSlice.cleanup(c) + + updateSlice.cleanup(c); + } - public int getChunkCount() { - return blockSlice.getLoadCount() + objectSlice.getLoadCount() + entitySlice.getLoadCount() + tileSlice.getLoadCount() + updateSlice.getLoadCount(); - } + public int getChunkCount() { + return blockSlice.getLoadCount() + objectSlice.getLoadCount() + entitySlice.getLoadCount() + tileSlice.getLoadCount() + updateSlice.getLoadCount(); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/parallax/ParallaxWorld.java b/src/main/java/com/volmit/iris/scaffold/parallax/ParallaxWorld.java index ff97e1469..48a6a09d2 100644 --- a/src/main/java/com/volmit/iris/scaffold/parallax/ParallaxWorld.java +++ b/src/main/java/com/volmit/iris/scaffold/parallax/ParallaxWorld.java @@ -12,263 +12,212 @@ import org.bukkit.block.data.BlockData; import java.io.File; import java.io.IOException; -public class ParallaxWorld implements ParallaxAccess -{ - private final KMap loadedRegions; - private final KList save; - private final File folder; - private final int height; +public class ParallaxWorld implements ParallaxAccess { + private final KMap loadedRegions; + private final KList save; + private final File folder; + private final int height; - public ParallaxWorld(int height, File folder) - { - this.height = height; - this.folder = folder; - save = new KList<>(); - loadedRegions = new KMap<>(); - folder.mkdirs(); - } + public ParallaxWorld(int height, File folder) { + this.height = height; + this.folder = folder; + save = new KList<>(); + loadedRegions = new KMap<>(); + folder.mkdirs(); + } - public int getRegionCount() - { - return loadedRegions.size(); - } + public int getRegionCount() { + return loadedRegions.size(); + } - public int getChunkCount() - { - int m = 0; + public int getChunkCount() { + int m = 0; - try - { - for(ParallaxRegion i : loadedRegions.values()) - { - m+= i.getChunkCount(); - } - } + try { + for (ParallaxRegion i : loadedRegions.values()) { + m += i.getChunkCount(); + } + } catch (Throwable ignored) { - catch(Throwable ignored) - { + } - } + return m; + } - return m; - } + public void close() { + for (ParallaxRegion i : loadedRegions.v()) { + unload(i.getX(), i.getZ()); + } - public void close() - { - for(ParallaxRegion i : loadedRegions.v()) - { - unload(i.getX(), i.getZ()); - } + save.clear(); + loadedRegions.clear(); + } - save.clear(); - loadedRegions.clear(); - } + public void save(ParallaxRegion region) { + try { + region.save(); + } catch (IOException e) { + e.printStackTrace(); + } + } - public void save(ParallaxRegion region) - { - try - { - region.save(); - } + public boolean isLoaded(int x, int z) { + return loadedRegions.containsKey(key(x, z)); + } - catch(IOException e) - { - e.printStackTrace(); - } - } + public void save(int x, int z) { + if (isLoaded(x, z)) { + save(getR(x, z)); + } + } - public boolean isLoaded(int x, int z) - { - return loadedRegions.containsKey(key(x, z)); - } + public int unload(int x, int z) { + long key = key(x, z); + int v = 0; + if (isLoaded(x, z)) { + if (save.contains(key)) { + save(x, z); + save.remove(key); + } - public void save(int x, int z) - { - if(isLoaded(x, z)) - { - save(getR(x, z)); - } - } + ParallaxRegion lr = loadedRegions.remove(key); - public int unload(int x, int z) - { - long key = key(x, z); - int v = 0; - if(isLoaded(x, z)) - { - if(save.contains(key)) - { - save(x, z); - save.remove(key); - } + if (lr != null) { + v += lr.unload(); + } + } - ParallaxRegion lr = loadedRegions.remove(key); + return v; + } - if(lr != null) - { - v += lr.unload(); - } - } + public ParallaxRegion load(int x, int z) { + if (isLoaded(x, z)) { + return loadedRegions.get(key(x, z)); + } - return v; - } + ParallaxRegion v = new ParallaxRegion(height, folder, x, z); + loadedRegions.put(key(x, z), v); - public ParallaxRegion load(int x, int z) - { - if(isLoaded(x, z)) - { - return loadedRegions.get(key(x, z)); - } + return v; + } - ParallaxRegion v = new ParallaxRegion(height, folder, x, z); - loadedRegions.put(key(x, z), v); + public ParallaxRegion getR(int x, int z) { + long key = key(x, z); - return v; - } + ParallaxRegion region = loadedRegions.get(key); - public ParallaxRegion getR(int x, int z) - { - long key = key(x, z); + if (region == null) { + region = load(x, z); + } - ParallaxRegion region = loadedRegions.get(key); + return region; + } - if(region == null) - { - region = load(x, z); - } + public ParallaxRegion getRW(int x, int z) { + save.addIfMissing(key(x, z)); + return getR(x, z); + } - return region; - } + private long key(int x, int z) { + return (((long) x) << 32) | (((long) z) & 0xffffffffL); + } - public ParallaxRegion getRW(int x, int z) - { - save.addIfMissing(key(x, z)); - return getR(x, z); - } + @Override + public Hunk getBlocksR(int x, int z) { + return getR(x >> 5, z >> 5).getBlockSlice().getR(x & 31, z & 31); + } - private long key(int x, int z) - { - return (((long) x) << 32) | (((long) z) & 0xffffffffL); - } + @Override + public Hunk getBlocksRW(int x, int z) { + return getRW(x >> 5, z >> 5).getBlockSlice().getRW(x & 31, z & 31); + } - @Override - public Hunk getBlocksR(int x, int z) - { - return getR(x >> 5, z >> 5).getBlockSlice().getR(x & 31, z & 31); - } + @Override + public Hunk> getTilesR(int x, int z) { + return getR(x >> 5, z >> 5).getTileSlice().getR(x & 31, z & 31); + } - @Override - public Hunk getBlocksRW(int x, int z) - { - return getRW(x >> 5, z >> 5).getBlockSlice().getRW(x & 31, z & 31); - } + @Override + public Hunk> getTilesRW(int x, int z) { + return getRW(x >> 5, z >> 5).getTileSlice().getRW(x & 31, z & 31); + } - @Override - public Hunk> getTilesR(int x, int z) - { - return getR(x >> 5, z >> 5).getTileSlice().getR(x & 31, z & 31); - } + @Override + public Hunk getObjectsR(int x, int z) { + return getR(x >> 5, z >> 5).getObjectSlice().getR(x & 31, z & 31); + } - @Override - public Hunk> getTilesRW(int x, int z) - { - return getRW(x >> 5, z >> 5).getTileSlice().getRW(x & 31, z & 31); - } + @Override + public Hunk getObjectsRW(int x, int z) { + return getRW(x >> 5, z >> 5).getObjectSlice().getRW(x & 31, z & 31); + } - @Override - public Hunk getObjectsR(int x, int z) - { - return getR(x >> 5, z >> 5).getObjectSlice().getR(x & 31, z & 31); - } + @Override + public Hunk getEntitiesRW(int x, int z) { + return getRW(x >> 5, z >> 5).getEntitySlice().getRW(x & 31, z & 31); + } - @Override - public Hunk getObjectsRW(int x, int z) - { - return getRW(x >> 5, z >> 5).getObjectSlice().getRW(x & 31, z & 31); - } + @Override + public Hunk getEntitiesR(int x, int z) { + return getRW(x >> 5, z >> 5).getEntitySlice().getR(x & 31, z & 31); + } - @Override - public Hunk getEntitiesRW(int x, int z) { - return getRW(x >> 5, z >> 5).getEntitySlice().getRW(x & 31, z & 31); - } + @Override + public Hunk getUpdatesR(int x, int z) { + return getR(x >> 5, z >> 5).getUpdateSlice().getR(x & 31, z & 31); + } - @Override - public Hunk getEntitiesR(int x, int z) { - return getRW(x >> 5, z >> 5).getEntitySlice().getR(x & 31, z & 31); - } + @Override + public Hunk getUpdatesRW(int x, int z) { + return getRW(x >> 5, z >> 5).getUpdateSlice().getRW(x & 31, z & 31); + } - @Override - public Hunk getUpdatesR(int x, int z) - { - return getR(x >> 5, z >> 5).getUpdateSlice().getR(x & 31, z & 31); - } + @Override + public ParallaxChunkMeta getMetaR(int x, int z) { + return getR(x >> 5, z >> 5).getMetaR(x & 31, z & 31); + } - @Override - public Hunk getUpdatesRW(int x, int z) - { - return getRW(x >> 5, z >> 5).getUpdateSlice().getRW(x & 31, z & 31); - } + @Override + public ParallaxChunkMeta getMetaRW(int x, int z) { + return getRW(x >> 5, z >> 5).getMetaRW(x & 31, z & 31); + } - @Override - public ParallaxChunkMeta getMetaR(int x, int z) - { - return getR(x >> 5, z >> 5).getMetaR(x & 31, z & 31); - } + public void cleanup() { + cleanup(IrisSettings.get().getParallaxRegionEvictionMS(), IrisSettings.get().getParallax().getParallaxChunkEvictionMS()); + } - @Override - public ParallaxChunkMeta getMetaRW(int x, int z) - { - return getRW(x >> 5, z >> 5).getMetaRW(x & 31, z & 31); - } + @Override + public void cleanup(long r, long c) { + J.a(() -> { + try { + int rr = 0; + int cc = 0; - public void cleanup() - { - cleanup(IrisSettings.get().getParallaxRegionEvictionMS(), IrisSettings.get().getParallax().getParallaxChunkEvictionMS()); - } + for (ParallaxRegion i : loadedRegions.v()) { + if (i.hasBeenIdleLongerThan(r)) { + rr++; + unload(i.getX(), i.getZ()); + } else { + cc += i.cleanup(c); + } + } + } catch (Throwable e) { + e.printStackTrace(); + } + }); + } - @Override - public void cleanup(long r, long c) { - J.a(() -> { - try - { - int rr = 0; - int cc = 0; + @Override + public void saveAll() { + J.a(this::saveAllNOW); + } - for(ParallaxRegion i : loadedRegions.v()) - { - if(i.hasBeenIdleLongerThan(r)) - { - rr++; - unload(i.getX(), i.getZ()); - } - - else - { - cc+= i.cleanup(c); - } - } - } - - catch(Throwable e) - { - e.printStackTrace(); - } - }); - } - - @Override - public void saveAll() { - J.a(this::saveAllNOW); - } - - @Override - public void saveAllNOW() { - for(ParallaxRegion i : loadedRegions.v()) - { - if(save.contains(key(i.getX(), i.getZ()))) - { - save(i.getX(), i.getZ()); - } - } - } + @Override + public void saveAllNOW() { + for (ParallaxRegion i : loadedRegions.v()) { + if (save.contains(key(i.getX(), i.getZ()))) { + save(i.getX(), i.getZ()); + } + } + } } diff --git a/src/main/java/com/volmit/iris/scaffold/parallel/BurstExecutor.java b/src/main/java/com/volmit/iris/scaffold/parallel/BurstExecutor.java index 8e755309d..8d987d105 100644 --- a/src/main/java/com/volmit/iris/scaffold/parallel/BurstExecutor.java +++ b/src/main/java/com/volmit/iris/scaffold/parallel/BurstExecutor.java @@ -6,73 +6,57 @@ import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; -public class BurstExecutor -{ - private ExecutorService executor; - private KList> futures; +public class BurstExecutor { + private final ExecutorService executor; + private final KList> futures; - public BurstExecutor(ExecutorService executor, int burstSizeEstimate) - { - this.executor = executor; - futures = new KList>(burstSizeEstimate); - } + public BurstExecutor(ExecutorService executor, int burstSizeEstimate) { + this.executor = executor; + futures = new KList>(burstSizeEstimate); + } - public CompletableFuture queue(Runnable r) - { - synchronized(futures) - { - CompletableFuture c = CompletableFuture.runAsync(r, executor); - futures.add(c); - return c; - } - } + public CompletableFuture queue(Runnable r) { + synchronized (futures) { + CompletableFuture c = CompletableFuture.runAsync(r, executor); + futures.add(c); + return c; + } + } - public BurstExecutor queue(KList r) { - synchronized(futures) - { - for(Runnable i : r) - { - CompletableFuture c = CompletableFuture.runAsync(i, executor); - futures.add(c); - } - } + public BurstExecutor queue(KList r) { + synchronized (futures) { + for (Runnable i : r) { + CompletableFuture c = CompletableFuture.runAsync(i, executor); + futures.add(c); + } + } - return this; - } + return this; + } - public BurstExecutor queue(Runnable[] r) - { - synchronized(futures) - { - for(Runnable i : r) - { - CompletableFuture c = CompletableFuture.runAsync(i, executor); - futures.add(c); - } - } + public BurstExecutor queue(Runnable[] r) { + synchronized (futures) { + for (Runnable i : r) { + CompletableFuture c = CompletableFuture.runAsync(i, executor); + futures.add(c); + } + } - return this; - } + return this; + } - public void complete() - { - synchronized(futures) - { - if(futures.isEmpty()) - { - return; - } + public void complete() { + synchronized (futures) { + if (futures.isEmpty()) { + return; + } - try - { - CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).get(); - futures.clear(); - } - - catch(InterruptedException | ExecutionException e) - { - e.printStackTrace(); - } - } - } + try { + CompletableFuture.allOf(futures.toArray(new CompletableFuture[futures.size()])).get(); + futures.clear(); + } catch (InterruptedException | ExecutionException e) { + e.printStackTrace(); + } + } + } } diff --git a/src/main/java/com/volmit/iris/scaffold/parallel/BurstedHunk.java b/src/main/java/com/volmit/iris/scaffold/parallel/BurstedHunk.java index 32c83a514..a1f1ced4e 100644 --- a/src/main/java/com/volmit/iris/scaffold/parallel/BurstedHunk.java +++ b/src/main/java/com/volmit/iris/scaffold/parallel/BurstedHunk.java @@ -2,11 +2,10 @@ package com.volmit.iris.scaffold.parallel; import com.volmit.iris.scaffold.hunk.Hunk; -public interface BurstedHunk extends Hunk -{ - public int getOffsetX(); +public interface BurstedHunk extends Hunk { + int getOffsetX(); - public int getOffsetY(); + int getOffsetY(); - public int getOffsetZ(); + int getOffsetZ(); } diff --git a/src/main/java/com/volmit/iris/scaffold/parallel/GridLock.java b/src/main/java/com/volmit/iris/scaffold/parallel/GridLock.java index 4163861dd..0f471da34 100644 --- a/src/main/java/com/volmit/iris/scaffold/parallel/GridLock.java +++ b/src/main/java/com/volmit/iris/scaffold/parallel/GridLock.java @@ -9,18 +9,15 @@ import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import java.util.function.Supplier; -public class GridLock -{ - private Hunk locks; +public class GridLock { + private final Hunk locks; - public GridLock(int x, int z) - { + public GridLock(int x, int z) { this.locks = Hunk.newAtomicHunk(x, 1, z); - locks.iterateSync((a,b,c) -> locks.set(a,b,c,new ReentrantLock())); + locks.iterateSync((a, b, c) -> locks.set(a, b, c, new ReentrantLock())); } - public void with(int x, int z, Runnable r) - { + public void with(int x, int z, Runnable r) { lock(x, z); r.run(); unlock(x, z); @@ -38,52 +35,45 @@ public class GridLock unlock(x, z); } - public T withResult(int x, int z, Supplier r) - { + public T withResult(int x, int z, Supplier r) { lock(x, z); T t = r.get(); unlock(x, z); return t; } - public void withAll(Runnable r) - { - locks.iterateSync((a,b,c,d) -> d.lock()); + public void withAll(Runnable r) { + locks.iterateSync((a, b, c, d) -> d.lock()); r.run(); - locks.iterateSync((a,b,c,d) -> d.unlock()); + locks.iterateSync((a, b, c, d) -> d.unlock()); } - public T withAllResult(Supplier r) - { - locks.iterateSync((a,b,c,d) -> d.lock()); + public T withAllResult(Supplier r) { + locks.iterateSync((a, b, c, d) -> d.lock()); T t = r.get(); - locks.iterateSync((a,b,c,d) -> d.unlock()); + locks.iterateSync((a, b, c, d) -> d.unlock()); return t; } - public boolean tryLock(int x, int z) - { - return locks.get(x,0,z).tryLock(); + public boolean tryLock(int x, int z) { + return locks.get(x, 0, z).tryLock(); } - public boolean tryLock(int x, int z, long timeout) - { + public boolean tryLock(int x, int z, long timeout) { try { - return locks.get(x,0,z).tryLock(timeout, TimeUnit.MILLISECONDS); + return locks.get(x, 0, z).tryLock(timeout, TimeUnit.MILLISECONDS); } catch (InterruptedException ignored) { } return false; } - public void lock(int x, int z) - { - locks.get(x,0,z).lock(); + public void lock(int x, int z) { + locks.get(x, 0, z).lock(); } - public void unlock(int x, int z) - { - locks.get(x,0,z).unlock(); + public void unlock(int x, int z) { + locks.get(x, 0, z).unlock(); } } diff --git a/src/main/java/com/volmit/iris/scaffold/parallel/MultiBurst.java b/src/main/java/com/volmit/iris/scaffold/parallel/MultiBurst.java index 0d233e36d..3aad2c506 100644 --- a/src/main/java/com/volmit/iris/scaffold/parallel/MultiBurst.java +++ b/src/main/java/com/volmit/iris/scaffold/parallel/MultiBurst.java @@ -7,71 +7,62 @@ import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; -public class MultiBurst -{ - public static MultiBurst burst = new MultiBurst(Runtime.getRuntime().availableProcessors()); - private final ExecutorService service; - private ExecutorService syncService; - private int tid; +public class MultiBurst { + public static MultiBurst burst = new MultiBurst(Runtime.getRuntime().availableProcessors()); + private final ExecutorService service; + private ExecutorService syncService; + private int tid; - public MultiBurst(int tc) - { - service = Executors.newFixedThreadPool(tc, new ThreadFactory() - { - @Override - public Thread newThread(Runnable r) - { - tid++; - Thread t = new Thread(r); - t.setName("Iris Generator " + tid); - t.setPriority(6); - t.setUncaughtExceptionHandler((et, e) -> - { - Iris.info("Exception encountered in " + et.getName()); - e.printStackTrace(); - }); + public MultiBurst(int tc) { + service = Executors.newFixedThreadPool(tc, new ThreadFactory() { + @Override + public Thread newThread(Runnable r) { + tid++; + Thread t = new Thread(r); + t.setName("Iris Generator " + tid); + t.setPriority(6); + t.setUncaughtExceptionHandler((et, e) -> + { + Iris.info("Exception encountered in " + et.getName()); + e.printStackTrace(); + }); - return t; - } - }); - } + return t; + } + }); + } - public void burst(Runnable... r) - { - burst(r.length).queue(r).complete(); - } + public void burst(Runnable... r) { + burst(r.length).queue(r).complete(); + } - public void burst(KList r) { - burst(r.size()).queue(r).complete(); - } + public void burst(KList r) { + burst(r.size()).queue(r).complete(); + } - public void sync(Runnable... r) - { - for(Runnable i : r) - { - i.run(); - } - } + public void sync(Runnable... r) { + for (Runnable i : r) { + i.run(); + } + } - public BurstExecutor burst(int estimate) - { - return new BurstExecutor(service, estimate); - } + public BurstExecutor burst(int estimate) { + return new BurstExecutor(service, estimate); + } - public BurstExecutor burst() - { - return burst(16); - } + public BurstExecutor burst() { + return burst(16); + } - public void lazy(Runnable o) { - service.execute(o); - } + public void lazy(Runnable o) { + service.execute(o); + } - public void shutdownNow() { - service.shutdownNow().forEach(Runnable::run); - } + public void shutdownNow() { + service.shutdownNow().forEach(Runnable::run); + } - public void shutdown() { - service.shutdown(); - } + public void shutdown() { + service.shutdown(); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/ArraySignificance.java b/src/main/java/com/volmit/iris/scaffold/stream/ArraySignificance.java index 609d0c067..f209f5c15 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/ArraySignificance.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/ArraySignificance.java @@ -2,60 +2,50 @@ package com.volmit.iris.scaffold.stream; import com.volmit.iris.util.KList; -public class ArraySignificance implements Significance -{ - private final KList types; - private final KList significance; - private final T significant; +public class ArraySignificance implements Significance { + private final KList types; + private final KList significance; + private final T significant; - public ArraySignificance(KList types, KList significance, T significant) - { - this.types = types; - this.significance = significance; - this.significant = significant; - } + public ArraySignificance(KList types, KList significance, T significant) { + this.types = types; + this.significance = significance; + this.significant = significant; + } - public ArraySignificance(KList types, KList significance) - { - this.types = types; - this.significance = significance; - double s = 0; - int v = 0; - for(int i = 0; i < significance.size(); i++) - { - if(significance.get(i) > s) - { - s = significance.get(i); - v = i; - } - } + public ArraySignificance(KList types, KList significance) { + this.types = types; + this.significance = significance; + double s = 0; + int v = 0; + for (int i = 0; i < significance.size(); i++) { + if (significance.get(i) > s) { + s = significance.get(i); + v = i; + } + } - significant = types.get(v); - } + significant = types.get(v); + } - @Override - public KList getFactorTypes() - { - return types; - } + @Override + public KList getFactorTypes() { + return types; + } - @Override - public double getSignificance(T t) - { - for(int i = 0; i < types.size(); i++) - { - if(types.get(i).equals(t)) - { - return significance.get(i); - } - } + @Override + public double getSignificance(T t) { + for (int i = 0; i < types.size(); i++) { + if (types.get(i).equals(t)) { + return significance.get(i); + } + } - return 0; - } + return 0; + } - @Override - public T getMostSignificantType() - { - return significant; - } + @Override + public T getMostSignificantType() { + return significant; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/BasicLayer.java b/src/main/java/com/volmit/iris/scaffold/stream/BasicLayer.java index 587ec9ae5..f3f6b71a2 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/BasicLayer.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/BasicLayer.java @@ -5,26 +5,22 @@ import lombok.Data; @Data @AllArgsConstructor -public class BasicLayer implements ProceduralLayer -{ - private final long seed; - private final double zoom; - private final double offsetX; - private final double offsetY; - private final double offsetZ; +public class BasicLayer implements ProceduralLayer { + private final long seed; + private final double zoom; + private final double offsetX; + private final double offsetY; + private final double offsetZ; - public BasicLayer(long seed, double zoom) - { - this(seed, zoom, 0D, 0D, 0D); - } + public BasicLayer(long seed, double zoom) { + this(seed, zoom, 0D, 0D, 0D); + } - public BasicLayer(long seed) - { - this(seed, 1D); - } + public BasicLayer(long seed) { + this(seed, 1D); + } - public BasicLayer() - { - this(1337); - } + public BasicLayer() { + this(1337); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/BasicStream.java b/src/main/java/com/volmit/iris/scaffold/stream/BasicStream.java index 78b557fe4..3d489ed79 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/BasicStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/BasicStream.java @@ -1,17 +1,14 @@ package com.volmit.iris.scaffold.stream; -public abstract class BasicStream extends BasicLayer implements ProceduralStream -{ +public abstract class BasicStream extends BasicLayer implements ProceduralStream { private final ProceduralStream source; - public BasicStream(ProceduralStream source) - { + public BasicStream(ProceduralStream source) { super(); this.source = source; } - public BasicStream() - { + public BasicStream() { this(null); } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/ProceduralLayer.java b/src/main/java/com/volmit/iris/scaffold/stream/ProceduralLayer.java index 6fcd4f1f0..1ea581be9 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/ProceduralLayer.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/ProceduralLayer.java @@ -1,14 +1,13 @@ package com.volmit.iris.scaffold.stream; -public interface ProceduralLayer -{ - public long getSeed(); +public interface ProceduralLayer { + long getSeed(); - public double getOffsetX(); + double getOffsetX(); - public double getOffsetY(); + double getOffsetY(); - public double getOffsetZ(); + double getOffsetZ(); - public double getZoom(); + double getZoom(); } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/ProceduralStream.java b/src/main/java/com/volmit/iris/scaffold/stream/ProceduralStream.java index d65fad7fe..bc11d6f61 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/ProceduralStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/ProceduralStream.java @@ -12,517 +12,417 @@ import com.volmit.iris.util.*; import java.util.List; import java.util.function.Function; -public interface ProceduralStream extends ProceduralLayer, Interpolated -{ - public static ProceduralStream ofDouble(Function2 f) - { - try { - return of(f, Interpolated.DOUBLE); - } catch (IncompatibleClassChangeError e){ - Iris.warn(f.toString()); - e.printStackTrace(); - return null; - } - } - - public static ProceduralStream ofDouble(Function3 f) - { - return of(f, Interpolated.DOUBLE); - } - - public static ProceduralStream of(Function2 f, Interpolated helper) - { - return of(f, (x, y, z) -> f.apply(x, z), helper); - } - - public static ProceduralStream of(Function3 f, Interpolated helper) - { - return of((x, z) -> f.apply(x, 0D, z), f, helper); - } - - public static ProceduralStream of(Function2 f, Function3 f2, Interpolated helper) - { - return new FunctionStream<>(f, f2, helper); - } - - default ProceduralStream profile() - { - return profile(10); - } - - default ProceduralStream profile(int memory) - { - return new ProfiledStream<>(this, memory); - } - - default ProceduralStream onNull(T v) - { - return new NullSafeStream<>(this, v); - } - - default ProceduralStream add(Function3 a) - { - return new AddingStream<>(this, a); - } - - default ProceduralStream add(Function2 a) - { - return new AddingStream<>(this, a); - } - - default ProceduralStream add2D(Function2 a) - { - return new AddingStream<>(this, a); - } - - default ProceduralStream add(double a) - { - return new AddingStream<>(this, a); - } - - default ProceduralStream blockToChunkCoords() - { - return bitShiftCoordsRight(4); - } - - default ProceduralStream chunkToRegionCoords() - { - return bitShiftCoordsRight(5); - } - - default ProceduralStream blockToRegionCoords() - { - return blockToChunkCoords().chunkToRegionCoords(); - } - - default ProceduralStream regionToBlockCoords() - { - return regionToChunkCoords().chunkToBlockCoords(); - } - - default ProceduralStream regionToChunkCoords() - { - return bitShiftCoordsLeft(5); - } - - default ProceduralStream chunkToBlockCoords() - { - return bitShiftCoordsLeft(4); - } - - default ProceduralStream bitShiftCoordsRight(int a) - { - return new CoordinateBitShiftRightStream<>(this, a); - } - - default ProceduralStream synchronize() - { - return new SynchronizedStream<>(this); - } - - default ProceduralStream semaphore(int permits) - { - return new SemaphoreStream<>(this, permits); - } - - default ProceduralStream bitShiftCoordsLeft(int a) - { - return new CoordinateBitShiftLeftStream<>(this, a); - } - - default ProceduralStream max(Function3 a) - { - return new MaxingStream<>(this, a); - } - - default ProceduralStream max(Function2 a) - { - return new MaxingStream<>(this, a); - } - - default ProceduralStream slope() - { - return slope(1); - } - - default ProceduralStream slope(int range) - { - return new SlopeStream<>(this, range); - } - - default ProceduralStream max(double a) - { - return new MaxingStream<>(this, a); - } - - default ProceduralStream min(Function3 a) - { - return new MinningStream<>(this, a); - } - - default ProceduralStream min(Function2 a) - { - return new MinningStream<>(this, a); - } - - default ProceduralStream min(double a) - { - return new MinningStream<>(this, a); - } - - default ProceduralStream subtract(Function3 a) - { - return new SubtractingStream<>(this, a); - } - - default ProceduralStream subtract(Function2 a) - { - return new SubtractingStream<>(this, a); - } - - default ProceduralStream subtract(double a) - { - return new SubtractingStream<>(this, a); - } - - default ProceduralStream multiply(Function3 a) - { - return new MultiplyingStream<>(this, a); - } - - default ProceduralStream multiply(Function2 a) - { - return new MultiplyingStream<>(this, a); - } - - default ProceduralStream multiply(double a) - { - return new MultiplyingStream<>(this, a); - } - - default ProceduralStream divide(Function3 a) - { - return new DividingStream<>(this, a); - } - - default ProceduralStream divide(Function2 a) - { - return new DividingStream<>(this, a); - } - - default ProceduralStream divide(double a) - { - return new DividingStream<>(this, a); - } - - default ProceduralStream modulo(Function3 a) - { - return new ModuloStream<>(this, a); - } - - default ProceduralStream modulo(Function2 a) - { - return new ModuloStream<>(this, a); - } - - default ProceduralStream modulo(double a) - { - return new ModuloStream<>(this, a); - } - - default ProceduralStream round() - { - return new RoundingStream(this); - } - - default ProceduralStream roundDouble() - { - return new RoundingDoubleStream(this); - } - - default ProceduralStream forceDouble() - { - return new ForceDoubleStream(this); - } - - default ProceduralStream> significance(double radius, int checks) - { - return new SignificanceStream, T>(this, radius, checks); - } - - default ProceduralStream to3D() - { - return new To3DStream(this); - } - - default ProceduralStream cache2D(int maxSize) - { - return new CachedStream2D(this, maxSize); - } - - default ProceduralStream convert(Function converter) - { - return new ConversionStream(this, converter); - } - - default ProceduralStream convertAware2D(Function3 converter) - { - return new AwareConversionStream2D(this, converter); - } - - default ProceduralStream convertAware3D(Function4 converter) - { - return new AwareConversionStream3D(this, converter); - } - - default ProceduralStream convertCached(Function converter) - { - return new CachedConversionStream(this, converter); - } - - default ProceduralStream offset(double x, double y, double z) - { - return new OffsetStream(this, x, y, z); - } - - default ProceduralStream offset(double x, double z) - { - return new OffsetStream(this, x, 0, z); - } - - default ProceduralStream zoom(double x, double y, double z) - { - return new ZoomStream(this, x, y, z); - } - - default ProceduralStream zoom(double x, double z) - { - return new ZoomStream(this, x, 1, z); - } - - default ProceduralStream zoom(double all) - { - return new ZoomStream(this, all, all, all); - } - - default ProceduralStream radial(double scale) - { - return new RadialStream<>(this, scale); - } - - default ProceduralStream radial() - { - return radial(1D); - } - - default ProceduralStream select(V... types) - { - return new SelectionStream(this, types); - } - - default ProceduralStream select(List types) - { - return new SelectionStream(this, types); - } - - @SuppressWarnings("unchecked") - default ProceduralStream selectRarity(V... types) - { - KList rarityTypes = new KList<>(); - - for(V i : types) - { - rarityTypes.addMultiple(i, IRare.get(i)); - } - - return new SelectionStream(this, rarityTypes); - } - - default ProceduralStream selectRarity(List types) - { - KList rarityTypes = new KList<>(); - int totalRarity = 0; - for(V i : types) - { - totalRarity += IRare.get(i); - } - - for(V i : types) - { - rarityTypes.addMultiple(i, Math.max(1, (IRare.get(i) / totalRarity))); - } - - return new SelectionStream(this, rarityTypes); - } - - default ProceduralStream clamp(double min, double max) - { - return new ClampedStream(this, min, max); - } - - default ProceduralStream fit(double min, double max) - { - return new FittedStream(this, min, max); - } - - default ProceduralStream fit(double inMin, double inMax, double min, double max) - { - return new FittedStream(this, inMin, inMax, min, max); - } - - default void fill(Hunk h, double x, double y, double z, int parallelism) - { - h.compute3D(parallelism, (xx, yy, zz, hh) -> hh.iterate((xv, yv, zv) -> hh.set(xv, yv, zv, get(xx + xv + x, yy + yv + y, zz + zv + z)))); - } - - default void fill2D(Hunk h, double x, double z, V v, int parallelism) - { - h.compute2D(parallelism, (xx, __, zz, hh) -> - { - for(int i = 0; i < hh.getWidth(); i++) - { - for(int k = 0; k < hh.getDepth(); k++) - { - double n = getDouble(i + x + xx, k + z + zz); - - for(int j = 0; j < Math.min(h.getHeight(), n); j++) - { - hh.set(i, j, k, v); - } - } - } - }); - } - - default void fill2D(Hunk h, double x, double z, ProceduralStream v, int parallelism) - { - h.compute2D(parallelism, (xx, yy, zz, hh) -> - { - for(int i = 0; i < hh.getWidth(); i++) - { - for(int k = 0; k < hh.getDepth(); k++) - { - double n = getDouble(i + x + xx, k + z + zz); - - for(int j = 0; j < Math.min(h.getHeight(), n); j++) - { - hh.set(i, j, k, v.get(i + x + xx, j + yy, k + z + zz)); - } - } - } - }); - } - - default void fill2DYLocked(Hunk h, double x, double z, V v, int parallelism) - { - h.compute2D(parallelism, (xx, yy, zz, hh) -> - { - for(int i = 0; i < hh.getWidth(); i++) - { - for(int k = 0; k < hh.getDepth(); k++) - { - double n = getDouble(i + x + xx, k + z + zz); - - for(int j = 0; j < Math.min(h.getHeight(), n); j++) - { - hh.set(i, j, k, v); - } - } - } - }); - } - - default void fill2DYLocked(Hunk h, double x, double z, ProceduralStream v, int parallelism) - { - h.compute2D(parallelism, (xx, yy, zz, hh) -> - { - for(int i = 0; i < hh.getWidth(); i++) - { - for(int k = 0; k < hh.getDepth(); k++) - { - double n = getDouble(i + x + xx, k + z + zz); - - for(int j = 0; j < Math.min(h.getHeight(), n); j++) - { - hh.set(i, j, k, v.get(i + x + xx, k + z + zz)); - } - } - } - }); - } - - default void fill3D(Hunk h, double x, int y, double z, V v, int parallelism) - { - h.compute3D(parallelism, (xx, yy, zz, hh) -> hh.iterate((xv, yv, zv) -> - { - if(getDouble(xx + xv + x, yy + yv + y, zz + zv + z) > 0.5) - { - hh.set(xv, yv, zv, v); - } - })); - } - - default void fill3D(Hunk h, double x, int y, double z, ProceduralStream v, int parallelism) - { - h.compute3D(parallelism, (xx, yy, zz, hh) -> hh.iterate((xv, yv, zv) -> - { - if(getDouble(xx + xv + x, yy + yv + y, zz + zv + z) > 0.5) - { - hh.set(xv, yv, zv, v.get(xx + xv + x, yy + yv + y, zz + zv + z)); - } - })); - } - - default void fill(Hunk h, double x, double y, double z) - { - fill(h, x, z, 4); - } - - default void fill2D(Hunk h, double x, double z, V v) - { - fill2D(h, x, z, v, 4); - } - - default void fill2D(Hunk h, double x, double z, ProceduralStream v) - { - fill2D(h, x, z, v, 4); - } - - default void fill2DYLocked(Hunk h, double x, double z, V v) - { - fill2DYLocked(h, x, z, v, 4); - } - - default void fill2DYLocked(Hunk h, double x, double z, ProceduralStream v) - { - fill2DYLocked(h, x, z, v, 4); - } - - default void fill3D(Hunk h, double x, int y, double z, V v) - { - fill3D(h, x, y, z, v, 4); - } - - default void fill3D(Hunk h, double x, int y, double z, ProceduralStream v) - { - fill3D(h, x, y, z, v, 4); - } - - default double getDouble(double x, double z) - { - return toDouble(get(x, z)); - } - - default double getDouble(double x, double y, double z) - { - return toDouble(get(x, y, z)); - } - - public ProceduralStream getTypedSource(); - - public ProceduralStream getSource(); - - public T get(double x, double z); - - public T get(double x, double y, double z); +public interface ProceduralStream extends ProceduralLayer, Interpolated { + static ProceduralStream ofDouble(Function2 f) { + try { + return of(f, Interpolated.DOUBLE); + } catch (IncompatibleClassChangeError e) { + Iris.warn(f.toString()); + e.printStackTrace(); + return null; + } + } + + static ProceduralStream ofDouble(Function3 f) { + return of(f, Interpolated.DOUBLE); + } + + static ProceduralStream of(Function2 f, Interpolated helper) { + return of(f, (x, y, z) -> f.apply(x, z), helper); + } + + static ProceduralStream of(Function3 f, Interpolated helper) { + return of((x, z) -> f.apply(x, 0D, z), f, helper); + } + + static ProceduralStream of(Function2 f, Function3 f2, Interpolated helper) { + return new FunctionStream<>(f, f2, helper); + } + + default ProceduralStream profile() { + return profile(10); + } + + default ProceduralStream profile(int memory) { + return new ProfiledStream<>(this, memory); + } + + default ProceduralStream onNull(T v) { + return new NullSafeStream<>(this, v); + } + + default ProceduralStream add(Function3 a) { + return new AddingStream<>(this, a); + } + + default ProceduralStream add(Function2 a) { + return new AddingStream<>(this, a); + } + + default ProceduralStream add2D(Function2 a) { + return new AddingStream<>(this, a); + } + + default ProceduralStream add(double a) { + return new AddingStream<>(this, a); + } + + default ProceduralStream blockToChunkCoords() { + return bitShiftCoordsRight(4); + } + + default ProceduralStream chunkToRegionCoords() { + return bitShiftCoordsRight(5); + } + + default ProceduralStream blockToRegionCoords() { + return blockToChunkCoords().chunkToRegionCoords(); + } + + default ProceduralStream regionToBlockCoords() { + return regionToChunkCoords().chunkToBlockCoords(); + } + + default ProceduralStream regionToChunkCoords() { + return bitShiftCoordsLeft(5); + } + + default ProceduralStream chunkToBlockCoords() { + return bitShiftCoordsLeft(4); + } + + default ProceduralStream bitShiftCoordsRight(int a) { + return new CoordinateBitShiftRightStream<>(this, a); + } + + default ProceduralStream synchronize() { + return new SynchronizedStream<>(this); + } + + default ProceduralStream semaphore(int permits) { + return new SemaphoreStream<>(this, permits); + } + + default ProceduralStream bitShiftCoordsLeft(int a) { + return new CoordinateBitShiftLeftStream<>(this, a); + } + + default ProceduralStream max(Function3 a) { + return new MaxingStream<>(this, a); + } + + default ProceduralStream max(Function2 a) { + return new MaxingStream<>(this, a); + } + + default ProceduralStream slope() { + return slope(1); + } + + default ProceduralStream slope(int range) { + return new SlopeStream<>(this, range); + } + + default ProceduralStream max(double a) { + return new MaxingStream<>(this, a); + } + + default ProceduralStream min(Function3 a) { + return new MinningStream<>(this, a); + } + + default ProceduralStream min(Function2 a) { + return new MinningStream<>(this, a); + } + + default ProceduralStream min(double a) { + return new MinningStream<>(this, a); + } + + default ProceduralStream subtract(Function3 a) { + return new SubtractingStream<>(this, a); + } + + default ProceduralStream subtract(Function2 a) { + return new SubtractingStream<>(this, a); + } + + default ProceduralStream subtract(double a) { + return new SubtractingStream<>(this, a); + } + + default ProceduralStream multiply(Function3 a) { + return new MultiplyingStream<>(this, a); + } + + default ProceduralStream multiply(Function2 a) { + return new MultiplyingStream<>(this, a); + } + + default ProceduralStream multiply(double a) { + return new MultiplyingStream<>(this, a); + } + + default ProceduralStream divide(Function3 a) { + return new DividingStream<>(this, a); + } + + default ProceduralStream divide(Function2 a) { + return new DividingStream<>(this, a); + } + + default ProceduralStream divide(double a) { + return new DividingStream<>(this, a); + } + + default ProceduralStream modulo(Function3 a) { + return new ModuloStream<>(this, a); + } + + default ProceduralStream modulo(Function2 a) { + return new ModuloStream<>(this, a); + } + + default ProceduralStream modulo(double a) { + return new ModuloStream<>(this, a); + } + + default ProceduralStream round() { + return new RoundingStream(this); + } + + default ProceduralStream roundDouble() { + return new RoundingDoubleStream(this); + } + + default ProceduralStream forceDouble() { + return new ForceDoubleStream(this); + } + + default ProceduralStream> significance(double radius, int checks) { + return new SignificanceStream, T>(this, radius, checks); + } + + default ProceduralStream to3D() { + return new To3DStream(this); + } + + default ProceduralStream cache2D(int maxSize) { + return new CachedStream2D(this, maxSize); + } + + default ProceduralStream convert(Function converter) { + return new ConversionStream(this, converter); + } + + default ProceduralStream convertAware2D(Function3 converter) { + return new AwareConversionStream2D(this, converter); + } + + default ProceduralStream convertAware3D(Function4 converter) { + return new AwareConversionStream3D(this, converter); + } + + default ProceduralStream convertCached(Function converter) { + return new CachedConversionStream(this, converter); + } + + default ProceduralStream offset(double x, double y, double z) { + return new OffsetStream(this, x, y, z); + } + + default ProceduralStream offset(double x, double z) { + return new OffsetStream(this, x, 0, z); + } + + default ProceduralStream zoom(double x, double y, double z) { + return new ZoomStream(this, x, y, z); + } + + default ProceduralStream zoom(double x, double z) { + return new ZoomStream(this, x, 1, z); + } + + default ProceduralStream zoom(double all) { + return new ZoomStream(this, all, all, all); + } + + default ProceduralStream radial(double scale) { + return new RadialStream<>(this, scale); + } + + default ProceduralStream radial() { + return radial(1D); + } + + default ProceduralStream select(V... types) { + return new SelectionStream(this, types); + } + + default ProceduralStream select(List types) { + return new SelectionStream(this, types); + } + + @SuppressWarnings("unchecked") + default ProceduralStream selectRarity(V... types) { + KList rarityTypes = new KList<>(); + + for (V i : types) { + rarityTypes.addMultiple(i, IRare.get(i)); + } + + return new SelectionStream(this, rarityTypes); + } + + default ProceduralStream selectRarity(List types) { + KList rarityTypes = new KList<>(); + int totalRarity = 0; + for (V i : types) { + totalRarity += IRare.get(i); + } + + for (V i : types) { + rarityTypes.addMultiple(i, Math.max(1, (IRare.get(i) / totalRarity))); + } + + return new SelectionStream(this, rarityTypes); + } + + default ProceduralStream clamp(double min, double max) { + return new ClampedStream(this, min, max); + } + + default ProceduralStream fit(double min, double max) { + return new FittedStream(this, min, max); + } + + default ProceduralStream fit(double inMin, double inMax, double min, double max) { + return new FittedStream(this, inMin, inMax, min, max); + } + + default void fill(Hunk h, double x, double y, double z, int parallelism) { + h.compute3D(parallelism, (xx, yy, zz, hh) -> hh.iterate((xv, yv, zv) -> hh.set(xv, yv, zv, get(xx + xv + x, yy + yv + y, zz + zv + z)))); + } + + default void fill2D(Hunk h, double x, double z, V v, int parallelism) { + h.compute2D(parallelism, (xx, __, zz, hh) -> + { + for (int i = 0; i < hh.getWidth(); i++) { + for (int k = 0; k < hh.getDepth(); k++) { + double n = getDouble(i + x + xx, k + z + zz); + + for (int j = 0; j < Math.min(h.getHeight(), n); j++) { + hh.set(i, j, k, v); + } + } + } + }); + } + + default void fill2D(Hunk h, double x, double z, ProceduralStream v, int parallelism) { + h.compute2D(parallelism, (xx, yy, zz, hh) -> + { + for (int i = 0; i < hh.getWidth(); i++) { + for (int k = 0; k < hh.getDepth(); k++) { + double n = getDouble(i + x + xx, k + z + zz); + + for (int j = 0; j < Math.min(h.getHeight(), n); j++) { + hh.set(i, j, k, v.get(i + x + xx, j + yy, k + z + zz)); + } + } + } + }); + } + + default void fill2DYLocked(Hunk h, double x, double z, V v, int parallelism) { + h.compute2D(parallelism, (xx, yy, zz, hh) -> + { + for (int i = 0; i < hh.getWidth(); i++) { + for (int k = 0; k < hh.getDepth(); k++) { + double n = getDouble(i + x + xx, k + z + zz); + + for (int j = 0; j < Math.min(h.getHeight(), n); j++) { + hh.set(i, j, k, v); + } + } + } + }); + } + + default void fill2DYLocked(Hunk h, double x, double z, ProceduralStream v, int parallelism) { + h.compute2D(parallelism, (xx, yy, zz, hh) -> + { + for (int i = 0; i < hh.getWidth(); i++) { + for (int k = 0; k < hh.getDepth(); k++) { + double n = getDouble(i + x + xx, k + z + zz); + + for (int j = 0; j < Math.min(h.getHeight(), n); j++) { + hh.set(i, j, k, v.get(i + x + xx, k + z + zz)); + } + } + } + }); + } + + default void fill3D(Hunk h, double x, int y, double z, V v, int parallelism) { + h.compute3D(parallelism, (xx, yy, zz, hh) -> hh.iterate((xv, yv, zv) -> + { + if (getDouble(xx + xv + x, yy + yv + y, zz + zv + z) > 0.5) { + hh.set(xv, yv, zv, v); + } + })); + } + + default void fill3D(Hunk h, double x, int y, double z, ProceduralStream v, int parallelism) { + h.compute3D(parallelism, (xx, yy, zz, hh) -> hh.iterate((xv, yv, zv) -> + { + if (getDouble(xx + xv + x, yy + yv + y, zz + zv + z) > 0.5) { + hh.set(xv, yv, zv, v.get(xx + xv + x, yy + yv + y, zz + zv + z)); + } + })); + } + + default void fill(Hunk h, double x, double y, double z) { + fill(h, x, z, 4); + } + + default void fill2D(Hunk h, double x, double z, V v) { + fill2D(h, x, z, v, 4); + } + + default void fill2D(Hunk h, double x, double z, ProceduralStream v) { + fill2D(h, x, z, v, 4); + } + + default void fill2DYLocked(Hunk h, double x, double z, V v) { + fill2DYLocked(h, x, z, v, 4); + } + + default void fill2DYLocked(Hunk h, double x, double z, ProceduralStream v) { + fill2DYLocked(h, x, z, v, 4); + } + + default void fill3D(Hunk h, double x, int y, double z, V v) { + fill3D(h, x, y, z, v, 4); + } + + default void fill3D(Hunk h, double x, int y, double z, ProceduralStream v) { + fill3D(h, x, y, z, v, 4); + } + + default double getDouble(double x, double z) { + return toDouble(get(x, z)); + } + + default double getDouble(double x, double y, double z) { + return toDouble(get(x, y, z)); + } + + ProceduralStream getTypedSource(); + + ProceduralStream getSource(); + + T get(double x, double z); + + T get(double x, double y, double z); } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/Significance.java b/src/main/java/com/volmit/iris/scaffold/stream/Significance.java index f91c9f1ee..6794f776d 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/Significance.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/Significance.java @@ -2,11 +2,10 @@ package com.volmit.iris.scaffold.stream; import com.volmit.iris.util.KList; -public interface Significance -{ - public KList getFactorTypes(); +public interface Significance { + KList getFactorTypes(); - public double getSignificance(T t); + double getSignificance(T t); - public T getMostSignificantType(); + T getMostSignificantType(); } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/AddingStream.java b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/AddingStream.java index 032b58430..1d8aa2ee3 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/AddingStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/AddingStream.java @@ -5,48 +5,40 @@ import com.volmit.iris.scaffold.stream.ProceduralStream; import com.volmit.iris.util.Function2; import com.volmit.iris.util.Function3; -public class AddingStream extends BasicStream -{ - private final Function3 add; +public class AddingStream extends BasicStream { + private final Function3 add; - public AddingStream(ProceduralStream stream, Function3 add) - { - super(stream); - this.add = add; - } + public AddingStream(ProceduralStream stream, Function3 add) { + super(stream); + this.add = add; + } - public AddingStream(ProceduralStream stream, Function2 add) - { - this(stream, (x, y, z) -> add.apply(x, z)); - } + public AddingStream(ProceduralStream stream, Function2 add) { + this(stream, (x, y, z) -> add.apply(x, z)); + } - public AddingStream(ProceduralStream stream, double add) - { - this(stream, (x, y, z) -> add); - } + public AddingStream(ProceduralStream stream, double add) { + this(stream, (x, y, z) -> add); + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - return fromDouble(add.apply(x, 0D, z) + getTypedSource().getDouble(x, z)); - } + @Override + public T get(double x, double z) { + return fromDouble(add.apply(x, 0D, z) + getTypedSource().getDouble(x, z)); + } - @Override - public T get(double x, double y, double z) - { - return fromDouble(add.apply(x, y, z) + getTypedSource().getDouble(x, y, z)); - } + @Override + public T get(double x, double y, double z) { + return fromDouble(add.apply(x, y, z) + getTypedSource().getDouble(x, y, z)); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/ClampedStream.java b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/ClampedStream.java index 694662069..855ac0a7b 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/ClampedStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/ClampedStream.java @@ -3,45 +3,38 @@ package com.volmit.iris.scaffold.stream.arithmetic; import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; -public class ClampedStream extends BasicStream implements ProceduralStream -{ - private final double min; - private final double max; +public class ClampedStream extends BasicStream implements ProceduralStream { + private final double min; + private final double max; - public ClampedStream(ProceduralStream stream, double min, double max) - { - super(stream); - this.min = min; - this.max = max; - } + public ClampedStream(ProceduralStream stream, double min, double max) { + super(stream); + this.min = min; + this.max = max; + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - private double clamp(double v) - { - return Math.max(Math.min(v, max), min); - } + private double clamp(double v) { + return Math.max(Math.min(v, max), min); + } - @Override - public T get(double x, double z) - { - return fromDouble(clamp(getTypedSource().getDouble(x, z))); - } + @Override + public T get(double x, double z) { + return fromDouble(clamp(getTypedSource().getDouble(x, z))); + } - @Override - public T get(double x, double y, double z) - { - return fromDouble(clamp(getTypedSource().getDouble(x, y, z))); - } + @Override + public T get(double x, double y, double z) { + return fromDouble(clamp(getTypedSource().getDouble(x, y, z))); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/CoordinateBitShiftLeftStream.java b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/CoordinateBitShiftLeftStream.java index dee0c9325..98d10d8d6 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/CoordinateBitShiftLeftStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/CoordinateBitShiftLeftStream.java @@ -3,38 +3,32 @@ package com.volmit.iris.scaffold.stream.arithmetic; import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; -public class CoordinateBitShiftLeftStream extends BasicStream implements ProceduralStream -{ - private final int amount; +public class CoordinateBitShiftLeftStream extends BasicStream implements ProceduralStream { + private final int amount; - public CoordinateBitShiftLeftStream(ProceduralStream stream, int amount) - { - super(stream); - this.amount = amount; - } + public CoordinateBitShiftLeftStream(ProceduralStream stream, int amount) { + super(stream); + this.amount = amount; + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - return getTypedSource().get((int) x << amount, (int) z << amount); - } + @Override + public T get(double x, double z) { + return getTypedSource().get((int) x << amount, (int) z << amount); + } - @Override - public T get(double x, double y, double z) - { - return getTypedSource().get((int) x << amount, (int) y << amount, (int) z << amount); - } + @Override + public T get(double x, double y, double z) { + return getTypedSource().get((int) x << amount, (int) y << amount, (int) z << amount); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/CoordinateBitShiftRightStream.java b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/CoordinateBitShiftRightStream.java index 11234970a..8ea7bac4d 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/CoordinateBitShiftRightStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/CoordinateBitShiftRightStream.java @@ -3,38 +3,32 @@ package com.volmit.iris.scaffold.stream.arithmetic; import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; -public class CoordinateBitShiftRightStream extends BasicStream implements ProceduralStream -{ - private final int amount; +public class CoordinateBitShiftRightStream extends BasicStream implements ProceduralStream { + private final int amount; - public CoordinateBitShiftRightStream(ProceduralStream stream, int amount) - { - super(stream); - this.amount = amount; - } + public CoordinateBitShiftRightStream(ProceduralStream stream, int amount) { + super(stream); + this.amount = amount; + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - return getTypedSource().get((int) x >> amount, (int) z >> amount); - } + @Override + public T get(double x, double z) { + return getTypedSource().get((int) x >> amount, (int) z >> amount); + } - @Override - public T get(double x, double y, double z) - { - return getTypedSource().get((int) x >> amount, (int) y >> amount, (int) z >> amount); - } + @Override + public T get(double x, double y, double z) { + return getTypedSource().get((int) x >> amount, (int) y >> amount, (int) z >> amount); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/DividingStream.java b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/DividingStream.java index ca0da2836..7f4bc887a 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/DividingStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/DividingStream.java @@ -5,47 +5,39 @@ import com.volmit.iris.scaffold.stream.ProceduralStream; import com.volmit.iris.util.Function2; import com.volmit.iris.util.Function3; -public class DividingStream extends BasicStream implements ProceduralStream -{ - private final Function3 add; +public class DividingStream extends BasicStream implements ProceduralStream { + private final Function3 add; - public DividingStream(ProceduralStream stream, Function3 add) - { - super(stream); - this.add = add; - } + public DividingStream(ProceduralStream stream, Function3 add) { + super(stream); + this.add = add; + } - public DividingStream(ProceduralStream stream, Function2 add) - { - this(stream, (x, y, z) -> add.apply(x, z)); - } + public DividingStream(ProceduralStream stream, Function2 add) { + this(stream, (x, y, z) -> add.apply(x, z)); + } - public DividingStream(ProceduralStream stream, double add) - { - this(stream, (x, y, z) -> add); - } + public DividingStream(ProceduralStream stream, double add) { + this(stream, (x, y, z) -> add); + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - return fromDouble(getTypedSource().getDouble(x, z) / add.apply(x, 0D, z)); - } + @Override + public T get(double x, double z) { + return fromDouble(getTypedSource().getDouble(x, z) / add.apply(x, 0D, z)); + } - @Override - public T get(double x, double y, double z) - { - return fromDouble(getTypedSource().getDouble(x, y, z) / add.apply(x, y, z)); - } + @Override + public T get(double x, double y, double z) { + return fromDouble(getTypedSource().getDouble(x, y, z) / add.apply(x, y, z)); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/FittedStream.java b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/FittedStream.java index 67fc89346..efd7006a1 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/FittedStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/FittedStream.java @@ -3,54 +3,46 @@ package com.volmit.iris.scaffold.stream.arithmetic; import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; -public class FittedStream extends BasicStream implements ProceduralStream -{ - private final double min; - private final double max; - private final double inMin; - private final double inMax; +public class FittedStream extends BasicStream implements ProceduralStream { + private final double min; + private final double max; + private final double inMin; + private final double inMax; - public FittedStream(ProceduralStream stream, double inMin, double inMax, double min, double max) - { - super(stream); - this.inMin = inMin; - this.inMax = inMax; - this.min = min; - this.max = max; - } + public FittedStream(ProceduralStream stream, double inMin, double inMax, double min, double max) { + super(stream); + this.inMin = inMin; + this.inMax = inMax; + this.min = min; + this.max = max; + } - public FittedStream(ProceduralStream stream, double min, double max) - { - this(stream, 0, 1, min, max); - } + public FittedStream(ProceduralStream stream, double min, double max) { + this(stream, 0, 1, min, max); + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - private double dlerp(double v) - { - return min + ((max - min) * ((v - inMin) / (inMax - inMin))); - } + private double dlerp(double v) { + return min + ((max - min) * ((v - inMin) / (inMax - inMin))); + } - @Override - public T get(double x, double z) - { - return fromDouble(dlerp(getTypedSource().getDouble(x, z))); - } + @Override + public T get(double x, double z) { + return fromDouble(dlerp(getTypedSource().getDouble(x, z))); + } - @Override - public T get(double x, double y, double z) - { - return fromDouble(dlerp(getTypedSource().getDouble(x, y, z))); - } + @Override + public T get(double x, double y, double z) { + return fromDouble(dlerp(getTypedSource().getDouble(x, y, z))); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/MaxingStream.java b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/MaxingStream.java index 1777718bc..fa70e71e4 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/MaxingStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/MaxingStream.java @@ -5,48 +5,40 @@ import com.volmit.iris.scaffold.stream.ProceduralStream; import com.volmit.iris.util.Function2; import com.volmit.iris.util.Function3; -public class MaxingStream extends BasicStream -{ - private final Function3 add; +public class MaxingStream extends BasicStream { + private final Function3 add; - public MaxingStream(ProceduralStream stream, Function3 add) - { - super(stream); - this.add = add; - } + public MaxingStream(ProceduralStream stream, Function3 add) { + super(stream); + this.add = add; + } - public MaxingStream(ProceduralStream stream, Function2 add) - { - this(stream, (x, y, z) -> add.apply(x, z)); - } + public MaxingStream(ProceduralStream stream, Function2 add) { + this(stream, (x, y, z) -> add.apply(x, z)); + } - public MaxingStream(ProceduralStream stream, double add) - { - this(stream, (x, y, z) -> add); - } + public MaxingStream(ProceduralStream stream, double add) { + this(stream, (x, y, z) -> add); + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - return fromDouble(Math.max(add.apply(x, 0D, z), getTypedSource().getDouble(x, z))); - } + @Override + public T get(double x, double z) { + return fromDouble(Math.max(add.apply(x, 0D, z), getTypedSource().getDouble(x, z))); + } - @Override - public T get(double x, double y, double z) - { - return fromDouble(Math.max(add.apply(x, y, z), getTypedSource().getDouble(x, y, z))); - } + @Override + public T get(double x, double y, double z) { + return fromDouble(Math.max(add.apply(x, y, z), getTypedSource().getDouble(x, y, z))); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/MinningStream.java b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/MinningStream.java index 594444590..4e5b9a540 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/MinningStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/MinningStream.java @@ -5,48 +5,40 @@ import com.volmit.iris.scaffold.stream.ProceduralStream; import com.volmit.iris.util.Function2; import com.volmit.iris.util.Function3; -public class MinningStream extends BasicStream -{ - private final Function3 add; +public class MinningStream extends BasicStream { + private final Function3 add; - public MinningStream(ProceduralStream stream, Function3 add) - { - super(stream); - this.add = add; - } + public MinningStream(ProceduralStream stream, Function3 add) { + super(stream); + this.add = add; + } - public MinningStream(ProceduralStream stream, Function2 add) - { - this(stream, (x, y, z) -> add.apply(x, z)); - } + public MinningStream(ProceduralStream stream, Function2 add) { + this(stream, (x, y, z) -> add.apply(x, z)); + } - public MinningStream(ProceduralStream stream, double add) - { - this(stream, (x, y, z) -> add); - } + public MinningStream(ProceduralStream stream, double add) { + this(stream, (x, y, z) -> add); + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - return fromDouble(Math.min(add.apply(x, 0D, z), getTypedSource().getDouble(x, z))); - } + @Override + public T get(double x, double z) { + return fromDouble(Math.min(add.apply(x, 0D, z), getTypedSource().getDouble(x, z))); + } - @Override - public T get(double x, double y, double z) - { - return fromDouble(Math.min(add.apply(x, y, z), getTypedSource().getDouble(x, y, z))); - } + @Override + public T get(double x, double y, double z) { + return fromDouble(Math.min(add.apply(x, y, z), getTypedSource().getDouble(x, y, z))); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/ModuloStream.java b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/ModuloStream.java index 268f1e5a7..f3f9aa51c 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/ModuloStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/ModuloStream.java @@ -5,47 +5,39 @@ import com.volmit.iris.scaffold.stream.ProceduralStream; import com.volmit.iris.util.Function2; import com.volmit.iris.util.Function3; -public class ModuloStream extends BasicStream -{ - private final Function3 add; +public class ModuloStream extends BasicStream { + private final Function3 add; - public ModuloStream(ProceduralStream stream, Function3 add) - { - super(stream); - this.add = add; - } + public ModuloStream(ProceduralStream stream, Function3 add) { + super(stream); + this.add = add; + } - public ModuloStream(ProceduralStream stream, Function2 add) - { - this(stream, (x, y, z) -> add.apply(x, z)); - } + public ModuloStream(ProceduralStream stream, Function2 add) { + this(stream, (x, y, z) -> add.apply(x, z)); + } - public ModuloStream(ProceduralStream stream, double add) - { - this(stream, (x, y, z) -> add); - } + public ModuloStream(ProceduralStream stream, double add) { + this(stream, (x, y, z) -> add); + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - return fromDouble(getTypedSource().getDouble(x, z) % add.apply(x, 0D, z)); - } + @Override + public T get(double x, double z) { + return fromDouble(getTypedSource().getDouble(x, z) % add.apply(x, 0D, z)); + } - @Override - public T get(double x, double y, double z) - { - return fromDouble(getTypedSource().getDouble(x, y, z) % add.apply(x, y, z)); - } + @Override + public T get(double x, double y, double z) { + return fromDouble(getTypedSource().getDouble(x, y, z) % add.apply(x, y, z)); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/MultiplyingStream.java b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/MultiplyingStream.java index 71f4cda0e..7d6f5596b 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/MultiplyingStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/MultiplyingStream.java @@ -5,47 +5,39 @@ import com.volmit.iris.scaffold.stream.ProceduralStream; import com.volmit.iris.util.Function2; import com.volmit.iris.util.Function3; -public class MultiplyingStream extends BasicStream -{ - private final Function3 add; +public class MultiplyingStream extends BasicStream { + private final Function3 add; - public MultiplyingStream(ProceduralStream stream, Function3 add) - { - super(stream); - this.add = add; - } + public MultiplyingStream(ProceduralStream stream, Function3 add) { + super(stream); + this.add = add; + } - public MultiplyingStream(ProceduralStream stream, Function2 add) - { - this(stream, (x, y, z) -> add.apply(x, z)); - } + public MultiplyingStream(ProceduralStream stream, Function2 add) { + this(stream, (x, y, z) -> add.apply(x, z)); + } - public MultiplyingStream(ProceduralStream stream, double add) - { - this(stream, (x, y, z) -> add); - } + public MultiplyingStream(ProceduralStream stream, double add) { + this(stream, (x, y, z) -> add); + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - return fromDouble(getTypedSource().getDouble(x, z) * add.apply(x, 0D, z)); - } + @Override + public T get(double x, double z) { + return fromDouble(getTypedSource().getDouble(x, z) * add.apply(x, 0D, z)); + } - @Override - public T get(double x, double y, double z) - { - return fromDouble(getTypedSource().getDouble(x, y, z) * add.apply(x, y, z)); - } + @Override + public T get(double x, double y, double z) { + return fromDouble(getTypedSource().getDouble(x, y, z) * add.apply(x, y, z)); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/OffsetStream.java b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/OffsetStream.java index 532a200f1..09dc64513 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/OffsetStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/OffsetStream.java @@ -3,42 +3,36 @@ package com.volmit.iris.scaffold.stream.arithmetic; import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; -public class OffsetStream extends BasicStream implements ProceduralStream -{ - private final double ox; - private final double oy; - private final double oz; +public class OffsetStream extends BasicStream implements ProceduralStream { + private final double ox; + private final double oy; + private final double oz; - public OffsetStream(ProceduralStream stream, double x, double y, double z) - { - super(stream); - this.ox = x; - this.oy = y; - this.oz = z; - } + public OffsetStream(ProceduralStream stream, double x, double y, double z) { + super(stream); + this.ox = x; + this.oy = y; + this.oz = z; + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - return getTypedSource().get(x + ox, z + oz); - } + @Override + public T get(double x, double z) { + return getTypedSource().get(x + ox, z + oz); + } - @Override - public T get(double x, double y, double z) - { - return getTypedSource().get(x + ox, y + oy, z + oz); - } + @Override + public T get(double x, double y, double z) { + return getTypedSource().get(x + ox, y + oy, z + oz); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/RadialStream.java b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/RadialStream.java index c46bb2ad5..1f403c483 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/RadialStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/RadialStream.java @@ -3,48 +3,40 @@ package com.volmit.iris.scaffold.stream.arithmetic; import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; -public class RadialStream extends BasicStream implements ProceduralStream -{ - private final double scale; +public class RadialStream extends BasicStream implements ProceduralStream { + private final double scale; - public RadialStream(ProceduralStream stream) - { - this(stream, 1D); - } + public RadialStream(ProceduralStream stream) { + this(stream, 1D); + } - public RadialStream(ProceduralStream stream, double scale) - { - super(stream); - this.scale = scale; - } + public RadialStream(ProceduralStream stream, double scale) { + super(stream); + this.scale = scale; + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - private double radii(double v) - { - return (v / (360D * scale)) % 360D; - } + private double radii(double v) { + return (v / (360D * scale)) % 360D; + } - @Override - public T get(double x, double z) - { - return fromDouble(radii(getTypedSource().getDouble(x, z))); - } + @Override + public T get(double x, double z) { + return fromDouble(radii(getTypedSource().getDouble(x, z))); + } - @Override - public T get(double x, double y, double z) - { - return fromDouble(radii(getTypedSource().getDouble(x, y, z))); - } + @Override + public T get(double x, double y, double z) { + return fromDouble(radii(getTypedSource().getDouble(x, y, z))); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/RoundingDoubleStream.java b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/RoundingDoubleStream.java index e3154c529..5550b6b12 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/RoundingDoubleStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/RoundingDoubleStream.java @@ -3,43 +3,36 @@ package com.volmit.iris.scaffold.stream.arithmetic; import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; -public class RoundingDoubleStream extends BasicStream -{ - private final ProceduralStream stream; +public class RoundingDoubleStream extends BasicStream { + private final ProceduralStream stream; - public RoundingDoubleStream(ProceduralStream stream) - { - super(); - this.stream = stream; - } + public RoundingDoubleStream(ProceduralStream stream) { + super(); + this.stream = stream; + } - @Override - public double toDouble(Double t) - { - return t; - } + @Override + public double toDouble(Double t) { + return t; + } - @Override - public Double fromDouble(double d) - { - return (double) Math.round(d); - } + @Override + public Double fromDouble(double d) { + return (double) Math.round(d); + } - private double round(double v) - { - return Math.round(v); - } + private double round(double v) { + return Math.round(v); + } - @Override - public Double get(double x, double z) - { - return round(stream.getDouble(x, z)); - } + @Override + public Double get(double x, double z) { + return round(stream.getDouble(x, z)); + } - @Override - public Double get(double x, double y, double z) - { - return round(stream.getDouble(x, y, z)); - } + @Override + public Double get(double x, double y, double z) { + return round(stream.getDouble(x, y, z)); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/SlopeStream.java b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/SlopeStream.java index 81d59f60d..450b4ecfd 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/SlopeStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/SlopeStream.java @@ -3,47 +3,41 @@ package com.volmit.iris.scaffold.stream.arithmetic; import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; -public class SlopeStream extends BasicStream -{ - private final int range; +public class SlopeStream extends BasicStream { + private final int range; - public SlopeStream(ProceduralStream stream, int range) - { - super(stream); - this.range = range; - } + public SlopeStream(ProceduralStream stream, int range) { + super(stream); + this.range = range; + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - double height = getTypedSource().getDouble(x, z); - double dx = getTypedSource().getDouble(x + range, z) - height; - double dy = getTypedSource().getDouble(x, z + range) - height; + @Override + public T get(double x, double z) { + double height = getTypedSource().getDouble(x, z); + double dx = getTypedSource().getDouble(x + range, z) - height; + double dy = getTypedSource().getDouble(x, z + range) - height; - return fromDouble(Math.sqrt(dx * dx + dy * dy)); - } + return fromDouble(Math.sqrt(dx * dx + dy * dy)); + } - @Override - public T get(double x, double y, double z) - { - double height = getTypedSource().getDouble(x, y, z); - double dx = getTypedSource().getDouble(x + range,y, z) - height; - double dy = getTypedSource().getDouble(x,y+range, z) - height; - double dz = getTypedSource().getDouble(x,y, z + range) - height; + @Override + public T get(double x, double y, double z) { + double height = getTypedSource().getDouble(x, y, z); + double dx = getTypedSource().getDouble(x + range, y, z) - height; + double dy = getTypedSource().getDouble(x, y + range, z) - height; + double dz = getTypedSource().getDouble(x, y, z + range) - height; - return fromDouble(Math.cbrt((dx * dx) + (dy * dy) + (dz * dz))); - } + return fromDouble(Math.cbrt((dx * dx) + (dy * dy) + (dz * dz))); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/SubtractingStream.java b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/SubtractingStream.java index acb639d9e..3770f805f 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/SubtractingStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/SubtractingStream.java @@ -5,47 +5,39 @@ import com.volmit.iris.scaffold.stream.ProceduralStream; import com.volmit.iris.util.Function2; import com.volmit.iris.util.Function3; -public class SubtractingStream extends BasicStream -{ - private final Function3 add; +public class SubtractingStream extends BasicStream { + private final Function3 add; - public SubtractingStream(ProceduralStream stream, Function3 add) - { - super(stream); - this.add = add; - } + public SubtractingStream(ProceduralStream stream, Function3 add) { + super(stream); + this.add = add; + } - public SubtractingStream(ProceduralStream stream, Function2 add) - { - this(stream, (x, y, z) -> add.apply(x, z)); - } + public SubtractingStream(ProceduralStream stream, Function2 add) { + this(stream, (x, y, z) -> add.apply(x, z)); + } - public SubtractingStream(ProceduralStream stream, double add) - { - this(stream, (x, y, z) -> add); - } + public SubtractingStream(ProceduralStream stream, double add) { + this(stream, (x, y, z) -> add); + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - return fromDouble(getTypedSource().getDouble(x, z) - add.apply(x, 0D, z)); - } + @Override + public T get(double x, double z) { + return fromDouble(getTypedSource().getDouble(x, z) - add.apply(x, 0D, z)); + } - @Override - public T get(double x, double y, double z) - { - return fromDouble(getTypedSource().getDouble(x, y, z) - add.apply(x, y, z)); - } + @Override + public T get(double x, double y, double z) { + return fromDouble(getTypedSource().getDouble(x, y, z) - add.apply(x, y, z)); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/ZoomStream.java b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/ZoomStream.java index 350176300..3ff7aaec6 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/ZoomStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/arithmetic/ZoomStream.java @@ -3,42 +3,36 @@ package com.volmit.iris.scaffold.stream.arithmetic; import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; -public class ZoomStream extends BasicStream -{ - private final double ox; - private final double oy; - private final double oz; +public class ZoomStream extends BasicStream { + private final double ox; + private final double oy; + private final double oz; - public ZoomStream(ProceduralStream stream, double x, double y, double z) - { - super(stream); - this.ox = x; - this.oy = y; - this.oz = z; - } + public ZoomStream(ProceduralStream stream, double x, double y, double z) { + super(stream); + this.ox = x; + this.oy = y; + this.oz = z; + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - return getTypedSource().get(x / ox, z / oz); - } + @Override + public T get(double x, double z) { + return getTypedSource().get(x / ox, z / oz); + } - @Override - public T get(double x, double y, double z) - { - return getTypedSource().get(x / ox, y / oy, z / oz); - } + @Override + public T get(double x, double y, double z) { + return getTypedSource().get(x / ox, y / oy, z / oz); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/convert/AwareConversionStream2D.java b/src/main/java/com/volmit/iris/scaffold/stream/convert/AwareConversionStream2D.java index 8950d94fa..4b2e4a42d 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/convert/AwareConversionStream2D.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/convert/AwareConversionStream2D.java @@ -4,49 +4,42 @@ import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; import com.volmit.iris.util.Function3; -public class AwareConversionStream2D extends BasicStream -{ - private final ProceduralStream stream; - private final Function3 converter; +public class AwareConversionStream2D extends BasicStream { + private final ProceduralStream stream; + private final Function3 converter; - public AwareConversionStream2D(ProceduralStream stream, Function3 converter) - { - super(null); - this.stream = stream; - this.converter = converter; - } + public AwareConversionStream2D(ProceduralStream stream, Function3 converter) { + super(null); + this.stream = stream; + this.converter = converter; + } - @Override - public double toDouble(V t) - { - if(t instanceof Double) - { - return (Double) t; - } + @Override + public double toDouble(V t) { + if (t instanceof Double) { + return (Double) t; + } - return 0; - } + return 0; + } - @Override - public V fromDouble(double d) - { - return null; - } + @Override + public V fromDouble(double d) { + return null; + } - @Override - public ProceduralStream getSource() { - return stream; - } + @Override + public ProceduralStream getSource() { + return stream; + } - @Override - public V get(double x, double z) - { - return converter.apply(stream.get(x, z), x, z); - } + @Override + public V get(double x, double z) { + return converter.apply(stream.get(x, z), x, z); + } - @Override - public V get(double x, double y, double z) - { - return converter.apply(stream.get(x, y, z), x, z); - } + @Override + public V get(double x, double y, double z) { + return converter.apply(stream.get(x, y, z), x, z); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/convert/AwareConversionStream3D.java b/src/main/java/com/volmit/iris/scaffold/stream/convert/AwareConversionStream3D.java index 5146bc0d0..9fdf0d5ed 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/convert/AwareConversionStream3D.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/convert/AwareConversionStream3D.java @@ -4,49 +4,44 @@ import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; import com.volmit.iris.util.Function4; -public class AwareConversionStream3D extends BasicStream -{ - private final ProceduralStream stream; - private final Function4 converter; +public class AwareConversionStream3D extends BasicStream { + private final ProceduralStream stream; + private final Function4 converter; - public AwareConversionStream3D(ProceduralStream stream, Function4 converter) - { - super(null); - this.stream = stream; - this.converter = converter; - } + public AwareConversionStream3D(ProceduralStream stream, Function4 converter) { + super(null); + this.stream = stream; + this.converter = converter; + } - @Override - public double toDouble(V t) - { - if(t instanceof Double) - { - return (Double) t; - } + @Override + public double toDouble(V t) { + if (t instanceof Double) { + return (Double) t; + } - return 0; - } + return 0; + } - @Override - public V fromDouble(double d) - { - return null; + @Override + public V fromDouble(double d) { + return null; - }@Override - public ProceduralStream getSource() { - return stream; - } + } - @Override - public V get(double x, double z) - { - return converter.apply(stream.get(x, z), x, 0D, z); - } + @Override + public ProceduralStream getSource() { + return stream; + } - @Override - public V get(double x, double y, double z) - { - return converter.apply(stream.get(x, y, z), x, y, z); - } + @Override + public V get(double x, double z) { + return converter.apply(stream.get(x, z), x, 0D, z); + } + + @Override + public V get(double x, double y, double z) { + return converter.apply(stream.get(x, y, z), x, y, z); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/convert/CachedConversionStream.java b/src/main/java/com/volmit/iris/scaffold/stream/convert/CachedConversionStream.java index 448b016cd..da74da1f1 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/convert/CachedConversionStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/convert/CachedConversionStream.java @@ -1,56 +1,50 @@ package com.volmit.iris.scaffold.stream.convert; -import java.util.function.Function; - import com.volmit.iris.scaffold.stream.BasicLayer; import com.volmit.iris.scaffold.stream.ProceduralStream; import com.volmit.iris.util.KMap; -public class CachedConversionStream extends BasicLayer implements ProceduralStream -{ - private final ProceduralStream stream; - private final Function converter; - private final KMap cache; +import java.util.function.Function; - public CachedConversionStream(ProceduralStream stream, Function converter) - { - super(); - this.stream = stream; - this.converter = converter; - cache = new KMap<>(); - } +public class CachedConversionStream extends BasicLayer implements ProceduralStream { + private final ProceduralStream stream; + private final Function converter; + private final KMap cache; - @Override - public double toDouble(V t) - { - return 0; - } + public CachedConversionStream(ProceduralStream stream, Function converter) { + super(); + this.stream = stream; + this.converter = converter; + cache = new KMap<>(); + } - @Override - public V fromDouble(double d) - { - return null; - } + @Override + public double toDouble(V t) { + return 0; + } - @Override - public ProceduralStream getTypedSource() { - return null; - } + @Override + public V fromDouble(double d) { + return null; + } - @Override - public ProceduralStream getSource() { - return stream; - } + @Override + public ProceduralStream getTypedSource() { + return null; + } - @Override - public V get(double x, double z) - { - return cache.compute(stream.get(x, z), (k, v) -> v != null ? v : converter.apply(k)); - } + @Override + public ProceduralStream getSource() { + return stream; + } - @Override - public V get(double x, double y, double z) - { - return cache.compute(stream.get(x, y, z), (k, v) -> v != null ? v : converter.apply(k)); - } + @Override + public V get(double x, double z) { + return cache.compute(stream.get(x, z), (k, v) -> v != null ? v : converter.apply(k)); + } + + @Override + public V get(double x, double y, double z) { + return cache.compute(stream.get(x, y, z), (k, v) -> v != null ? v : converter.apply(k)); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/convert/ConversionStream.java b/src/main/java/com/volmit/iris/scaffold/stream/convert/ConversionStream.java index 0991971ec..80d0bbdb7 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/convert/ConversionStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/convert/ConversionStream.java @@ -1,58 +1,51 @@ package com.volmit.iris.scaffold.stream.convert; -import java.util.function.Function; - import com.volmit.iris.scaffold.stream.BasicLayer; import com.volmit.iris.scaffold.stream.ProceduralStream; -public class ConversionStream extends BasicLayer implements ProceduralStream -{ - private final ProceduralStream stream; - private final Function converter; +import java.util.function.Function; - public ConversionStream(ProceduralStream stream, Function converter) - { - super(); - this.stream = stream; - this.converter = converter; - } +public class ConversionStream extends BasicLayer implements ProceduralStream { + private final ProceduralStream stream; + private final Function converter; - @Override - public double toDouble(V t) - { - if(t instanceof Double) - { - return (Double) t; - } - - return 0; - } + public ConversionStream(ProceduralStream stream, Function converter) { + super(); + this.stream = stream; + this.converter = converter; + } - @Override - public V fromDouble(double d) - { - return null; - } + @Override + public double toDouble(V t) { + if (t instanceof Double) { + return (Double) t; + } - @Override - public ProceduralStream getTypedSource() { - return null; - } + return 0; + } - @Override - public ProceduralStream getSource() { - return null; - } + @Override + public V fromDouble(double d) { + return null; + } - @Override - public V get(double x, double z) - { - return converter.apply(stream.get(x, z)); - } + @Override + public ProceduralStream getTypedSource() { + return null; + } - @Override - public V get(double x, double y, double z) - { - return converter.apply(stream.get(x, y, z)); - } + @Override + public ProceduralStream getSource() { + return null; + } + + @Override + public V get(double x, double z) { + return converter.apply(stream.get(x, z)); + } + + @Override + public V get(double x, double y, double z) { + return converter.apply(stream.get(x, y, z)); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/convert/ForceDoubleStream.java b/src/main/java/com/volmit/iris/scaffold/stream/convert/ForceDoubleStream.java index b563bb512..d5171ff2e 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/convert/ForceDoubleStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/convert/ForceDoubleStream.java @@ -3,38 +3,32 @@ package com.volmit.iris.scaffold.stream.convert; import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; -public class ForceDoubleStream extends BasicStream -{ - private ProceduralStream stream; +public class ForceDoubleStream extends BasicStream { + private ProceduralStream stream; - public ForceDoubleStream(ProceduralStream stream) - { - super(null); - } + public ForceDoubleStream(ProceduralStream stream) { + super(null); + } - @Override - public double toDouble(Double t) - { - return t; - } + @Override + public double toDouble(Double t) { + return t; + } - @SuppressWarnings("unchecked") - @Override - public Double fromDouble(double d) - { - return d; - } + @SuppressWarnings("unchecked") + @Override + public Double fromDouble(double d) { + return d; + } - @Override - public Double get(double x, double z) - { - return stream.getDouble(x, z); - } + @Override + public Double get(double x, double z) { + return stream.getDouble(x, z); + } - @Override - public Double get(double x, double y, double z) - { - return stream.getDouble(x, y, z); - } + @Override + public Double get(double x, double y, double z) { + return stream.getDouble(x, y, z); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/convert/RoundingStream.java b/src/main/java/com/volmit/iris/scaffold/stream/convert/RoundingStream.java index 7ae21f2d6..2ce110f61 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/convert/RoundingStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/convert/RoundingStream.java @@ -3,42 +3,35 @@ package com.volmit.iris.scaffold.stream.convert; import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; -public class RoundingStream extends BasicStream -{ - private final ProceduralStream stream; +public class RoundingStream extends BasicStream { + private final ProceduralStream stream; - public RoundingStream(ProceduralStream stream) - { - super(); - this.stream = stream; - } + public RoundingStream(ProceduralStream stream) { + super(); + this.stream = stream; + } - @Override - public double toDouble(Integer t) - { - return t.doubleValue(); - } + @Override + public double toDouble(Integer t) { + return t.doubleValue(); + } - @Override - public Integer fromDouble(double d) - { - return (int) Math.round(d); - } + @Override + public Integer fromDouble(double d) { + return (int) Math.round(d); + } - private int round(double v) - { - return (int) Math.round(v); - } + private int round(double v) { + return (int) Math.round(v); + } - @Override - public Integer get(double x, double z) - { - return round(stream.getDouble(x, z)); - } + @Override + public Integer get(double x, double z) { + return round(stream.getDouble(x, z)); + } - @Override - public Integer get(double x, double y, double z) - { - return round(stream.getDouble(x, y, z)); - } + @Override + public Integer get(double x, double y, double z) { + return round(stream.getDouble(x, y, z)); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/convert/SelectionStream.java b/src/main/java/com/volmit/iris/scaffold/stream/convert/SelectionStream.java index f6c83418b..6f9d51e0e 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/convert/SelectionStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/convert/SelectionStream.java @@ -1,60 +1,51 @@ package com.volmit.iris.scaffold.stream.convert; -import java.util.List; - import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; -public class SelectionStream extends BasicStream -{ - private final ProceduralStream stream; - private final T[] options; +import java.util.List; - public SelectionStream(ProceduralStream stream, T[] options) - { - super(); - this.stream = stream.fit(0, options.length - 1).round(); - this.options = options; - } +public class SelectionStream extends BasicStream { + private final ProceduralStream stream; + private final T[] options; - @SuppressWarnings("unchecked") - public SelectionStream(ProceduralStream stream, List options) - { - this(stream, (T[]) options.toArray()); - } + public SelectionStream(ProceduralStream stream, T[] options) { + super(); + this.stream = stream.fit(0, options.length - 1).round(); + this.options = options; + } - @Override - public double toDouble(T t) - { - throw new UnsupportedOperationException(); - } + @SuppressWarnings("unchecked") + public SelectionStream(ProceduralStream stream, List options) { + this(stream, (T[]) options.toArray()); + } - @Override - public T fromDouble(double d) - { - throw new UnsupportedOperationException(); - } + @Override + public double toDouble(T t) { + throw new UnsupportedOperationException(); + } - @Override - public T get(double x, double z) - { - if(options.length == 0) - { - return null; - } + @Override + public T fromDouble(double d) { + throw new UnsupportedOperationException(); + } - return options[stream.get(x, z)]; - } + @Override + public T get(double x, double z) { + if (options.length == 0) { + return null; + } - @Override - public T get(double x, double y, double z) - { - if(options.length == 0) - { - return null; - } + return options[stream.get(x, z)]; + } - return options[stream.get(x, y, z)]; - } + @Override + public T get(double x, double y, double z) { + if (options.length == 0) { + return null; + } + + return options[stream.get(x, y, z)]; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/convert/SignificanceStream.java b/src/main/java/com/volmit/iris/scaffold/stream/convert/SignificanceStream.java index 323009a55..26dbebe66 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/convert/SignificanceStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/convert/SignificanceStream.java @@ -1,79 +1,67 @@ package com.volmit.iris.scaffold.stream.convert; import com.volmit.iris.scaffold.stream.ArraySignificance; -import com.volmit.iris.scaffold.stream.Significance; import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; +import com.volmit.iris.scaffold.stream.Significance; import com.volmit.iris.util.KList; -public class SignificanceStream, T> extends BasicStream -{ - private final ProceduralStream stream; - private final double radius; - private final int checks; +public class SignificanceStream, T> extends BasicStream { + private final ProceduralStream stream; + private final double radius; + private final int checks; - public SignificanceStream(ProceduralStream stream, double radius, int checks) - { - super(); - this.stream = stream; - this.radius = radius; - this.checks = checks; - } + public SignificanceStream(ProceduralStream stream, double radius, int checks) { + super(); + this.stream = stream; + this.radius = radius; + this.checks = checks; + } - @Override - public double toDouble(K t) - { - return 0; - } + @Override + public double toDouble(K t) { + return 0; + } - @Override - public K fromDouble(double d) - { - return null; - } + @Override + public K fromDouble(double d) { + return null; + } - @SuppressWarnings("unchecked") - @Override - public K get(double x, double z) - { - KList ke = new KList<>(8); - KList va = new KList(8); + @SuppressWarnings("unchecked") + @Override + public K get(double x, double z) { + KList ke = new KList<>(8); + KList va = new KList(8); - double m = (360 / checks); - double v = 0; + double m = (360 / checks); + double v = 0; - for(int i = 0; i < 360; i += m) - { - double sin = Math.sin(Math.toRadians(i)); - double cos = Math.cos(Math.toRadians(i)); - double cx = x + ((radius * cos) - (radius * sin)); - double cz = z + ((radius * sin) + (radius * cos)); - T t = stream.get(cx, cz); + for (int i = 0; i < 360; i += m) { + double sin = Math.sin(Math.toRadians(i)); + double cos = Math.cos(Math.toRadians(i)); + double cx = x + ((radius * cos) - (radius * sin)); + double cz = z + ((radius * sin) + (radius * cos)); + T t = stream.get(cx, cz); - if(ke.addIfMissing(t)) - { - va.add(1D); - v++; - } + if (ke.addIfMissing(t)) { + va.add(1D); + v++; + } else { + int ind = ke.indexOf(t); + va.set(ind, va.get(ind) + 1D); + } + } - else - { - int ind = ke.indexOf(t); - va.set(ind, va.get(ind) + 1D); - } - } + for (int i = 0; i < va.size(); i++) { + va.set(i, va.get(i) / v); + } - for(int i = 0; i < va.size(); i++) - { - va.set(i, va.get(i) / (double) v); - } + return (K) new ArraySignificance(ke, va); + } - return (K) new ArraySignificance(ke, va); - } - - @Override - public K get(double x, double y, double z) - { - return get(x, z); - } + @Override + public K get(double x, double y, double z) { + return get(x, z); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/convert/To3DStream.java b/src/main/java/com/volmit/iris/scaffold/stream/convert/To3DStream.java index a04c1084b..c38160e89 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/convert/To3DStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/convert/To3DStream.java @@ -3,34 +3,28 @@ package com.volmit.iris.scaffold.stream.convert; import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; -public class To3DStream extends BasicStream -{ - public To3DStream(ProceduralStream stream) - { - super(stream); - } +public class To3DStream extends BasicStream { + public To3DStream(ProceduralStream stream) { + super(stream); + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - return getTypedSource().get(x, z); - } + @Override + public T get(double x, double z) { + return getTypedSource().get(x, z); + } - @Override - public T get(double x, double y, double z) - { - return getTypedSource().fromDouble(getTypedSource().getDouble(x, z) >= y ? 1D : 0D); - } + @Override + public T get(double x, double y, double z) { + return getTypedSource().fromDouble(getTypedSource().getDouble(x, z) >= y ? 1D : 0D); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/BiHermiteStream.java b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/BiHermiteStream.java index 16bcd8b73..24970842b 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/BiHermiteStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/BiHermiteStream.java @@ -4,85 +4,77 @@ import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; import com.volmit.iris.util.IrisInterpolation; -public class BiHermiteStream extends BasicStream implements Interpolator -{ - private final int rx; - private final int ry; - private final double tension; - private final double bias; +public class BiHermiteStream extends BasicStream implements Interpolator { + private final int rx; + private final int ry; + private final double tension; + private final double bias; - public BiHermiteStream(ProceduralStream stream, int rx, int ry, double tension, double bias) - { - super(stream); - this.rx = rx; - this.ry = ry; - this.tension = tension; - this.bias = bias; - } + public BiHermiteStream(ProceduralStream stream, int rx, int ry, double tension, double bias) { + super(stream); + this.rx = rx; + this.ry = ry; + this.tension = tension; + this.bias = bias; + } - public BiHermiteStream(ProceduralStream stream, int rx, int ry) - { - this(stream, rx, ry, 0.5, 0); - } + public BiHermiteStream(ProceduralStream stream, int rx, int ry) { + this(stream, rx, ry, 0.5, 0); + } - public T interpolate(double x, double y) - { - int fx = (int) Math.floor(x / rx); - int fz = (int) Math.floor(y / ry); - int x0 = (int) Math.round((fx - 1) * rx); - int z0 = (int) Math.round((fz - 1) * ry); - int x1 = (int) Math.round(fx * rx); - int z1 = (int) Math.round(fz * ry); - int x2 = (int) Math.round((fx + 1) * rx); - int z2 = (int) Math.round((fz + 1) * ry); - int x3 = (int) Math.round((fx + 2) * rx); - int z3 = (int) Math.round((fz + 2) * ry); - double px = IrisInterpolation.rangeScale(0, 1, x1, x2, x); - double pz = IrisInterpolation.rangeScale(0, 1, z1, z2, y); + public T interpolate(double x, double y) { + int fx = (int) Math.floor(x / rx); + int fz = (int) Math.floor(y / ry); + int x0 = Math.round((fx - 1) * rx); + int z0 = Math.round((fz - 1) * ry); + int x1 = Math.round(fx * rx); + int z1 = Math.round(fz * ry); + int x2 = Math.round((fx + 1) * rx); + int z2 = Math.round((fz + 1) * ry); + int x3 = Math.round((fx + 2) * rx); + int z3 = Math.round((fz + 2) * ry); + double px = IrisInterpolation.rangeScale(0, 1, x1, x2, x); + double pz = IrisInterpolation.rangeScale(0, 1, z1, z2, y); - //@builder - return getTypedSource().fromDouble(IrisInterpolation.bihermite( - getTypedSource().getDouble(x0, z0), - getTypedSource().getDouble(x0, z1), - getTypedSource().getDouble(x0, z2), - getTypedSource().getDouble(x0, z3), - getTypedSource().getDouble(x1, z0), - getTypedSource().getDouble(x1, z1), - getTypedSource().getDouble(x1, z2), - getTypedSource().getDouble(x1, z3), - getTypedSource().getDouble(x2, z0), - getTypedSource().getDouble(x2, z1), - getTypedSource().getDouble(x2, z2), - getTypedSource().getDouble(x2, z3), - getTypedSource().getDouble(x3, z0), - getTypedSource().getDouble(x3, z1), - getTypedSource().getDouble(x3, z2), - getTypedSource().getDouble(x3, z3), - px, pz, tension, bias)); - //@done - } + //@builder + return getTypedSource().fromDouble(IrisInterpolation.bihermite( + getTypedSource().getDouble(x0, z0), + getTypedSource().getDouble(x0, z1), + getTypedSource().getDouble(x0, z2), + getTypedSource().getDouble(x0, z3), + getTypedSource().getDouble(x1, z0), + getTypedSource().getDouble(x1, z1), + getTypedSource().getDouble(x1, z2), + getTypedSource().getDouble(x1, z3), + getTypedSource().getDouble(x2, z0), + getTypedSource().getDouble(x2, z1), + getTypedSource().getDouble(x2, z2), + getTypedSource().getDouble(x2, z3), + getTypedSource().getDouble(x3, z0), + getTypedSource().getDouble(x3, z1), + getTypedSource().getDouble(x3, z2), + getTypedSource().getDouble(x3, z3), + px, pz, tension, bias)); + //@done + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - return interpolate(x, z); - } + @Override + public T get(double x, double z) { + return interpolate(x, z); + } - @Override - public T get(double x, double y, double z) - { - return interpolate(x, z); - } + @Override + public T get(double x, double y, double z) { + return interpolate(x, z); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/BiStarcastStream.java b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/BiStarcastStream.java index 63e7d5018..8f9ab720e 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/BiStarcastStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/BiStarcastStream.java @@ -3,56 +3,48 @@ package com.volmit.iris.scaffold.stream.interpolation; import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; -public class BiStarcastStream extends BasicStream implements Interpolator -{ - private int rad; - private int checks; +public class BiStarcastStream extends BasicStream implements Interpolator { + private final int rad; + private final int checks; - public BiStarcastStream(ProceduralStream stream, int rad, int checks) - { - super(stream); - this.rad = rad; - this.checks = checks; - } + public BiStarcastStream(ProceduralStream stream, int rad, int checks) { + super(stream); + this.rad = rad; + this.checks = checks; + } - public T interpolate(double x, double y) - { - double m = (360D / checks); - double v = 0; + public T interpolate(double x, double y) { + double m = (360D / checks); + double v = 0; - for(int i = 0; i < 360; i += m) - { - double sin = Math.sin(Math.toRadians(i)); - double cos = Math.cos(Math.toRadians(i)); - double cx = x + ((rad * cos) - (rad * sin)); - double cz = y + ((rad * sin) + (rad * cos)); - v += getTypedSource().getDouble(cx, cz); - } + for (int i = 0; i < 360; i += m) { + double sin = Math.sin(Math.toRadians(i)); + double cos = Math.cos(Math.toRadians(i)); + double cx = x + ((rad * cos) - (rad * sin)); + double cz = y + ((rad * sin) + (rad * cos)); + v += getTypedSource().getDouble(cx, cz); + } - return getTypedSource().fromDouble(v / checks); - } + return getTypedSource().fromDouble(v / checks); + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - return interpolate(x, z); - } + @Override + public T get(double x, double z) { + return interpolate(x, z); + } - @Override - public T get(double x, double y, double z) - { - return interpolate(x, z); - } + @Override + public T get(double x, double y, double z) { + return interpolate(x, z); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/BicubicStream.java b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/BicubicStream.java index 894230f7b..29a8f5cef 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/BicubicStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/BicubicStream.java @@ -4,76 +4,69 @@ import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; import com.volmit.iris.util.IrisInterpolation; -public class BicubicStream extends BasicStream implements Interpolator -{ - private final int rx; - private final int ry; +public class BicubicStream extends BasicStream implements Interpolator { + private final int rx; + private final int ry; - public BicubicStream(ProceduralStream stream, int rx, int ry) - { - super(stream); - this.rx = rx; - this.ry = ry; - } + public BicubicStream(ProceduralStream stream, int rx, int ry) { + super(stream); + this.rx = rx; + this.ry = ry; + } - public T interpolate(double x, double y) - { - int fx = (int) Math.floor(x / rx); - int fz = (int) Math.floor(y / ry); - int x0 = (int) Math.round((fx - 1) * rx); - int z0 = (int) Math.round((fz - 1) * ry); - int x1 = (int) Math.round(fx * rx); - int z1 = (int) Math.round(fz * ry); - int x2 = (int) Math.round((fx + 1) * rx); - int z2 = (int) Math.round((fz + 1) * ry); - int x3 = (int) Math.round((fx + 2) * rx); - int z3 = (int) Math.round((fz + 2) * ry); - double px = IrisInterpolation.rangeScale(0, 1, x1, x2, x); - double pz = IrisInterpolation.rangeScale(0, 1, z1, z2, y); + public T interpolate(double x, double y) { + int fx = (int) Math.floor(x / rx); + int fz = (int) Math.floor(y / ry); + int x0 = Math.round((fx - 1) * rx); + int z0 = Math.round((fz - 1) * ry); + int x1 = Math.round(fx * rx); + int z1 = Math.round(fz * ry); + int x2 = Math.round((fx + 1) * rx); + int z2 = Math.round((fz + 1) * ry); + int x3 = Math.round((fx + 2) * rx); + int z3 = Math.round((fz + 2) * ry); + double px = IrisInterpolation.rangeScale(0, 1, x1, x2, x); + double pz = IrisInterpolation.rangeScale(0, 1, z1, z2, y); - //@builder - return getTypedSource().fromDouble(IrisInterpolation.bicubic( - getTypedSource().getDouble(x0, z0), - getTypedSource().getDouble(x0, z1), - getTypedSource().getDouble(x0, z2), - getTypedSource().getDouble(x0, z3), - getTypedSource().getDouble(x1, z0), - getTypedSource().getDouble(x1, z1), - getTypedSource().getDouble(x1, z2), - getTypedSource().getDouble(x1, z3), - getTypedSource().getDouble(x2, z0), - getTypedSource().getDouble(x2, z1), - getTypedSource().getDouble(x2, z2), - getTypedSource().getDouble(x2, z3), - getTypedSource().getDouble(x3, z0), - getTypedSource().getDouble(x3, z1), - getTypedSource().getDouble(x3, z2), - getTypedSource().getDouble(x3, z3), - px, pz)); - //@done - } + //@builder + return getTypedSource().fromDouble(IrisInterpolation.bicubic( + getTypedSource().getDouble(x0, z0), + getTypedSource().getDouble(x0, z1), + getTypedSource().getDouble(x0, z2), + getTypedSource().getDouble(x0, z3), + getTypedSource().getDouble(x1, z0), + getTypedSource().getDouble(x1, z1), + getTypedSource().getDouble(x1, z2), + getTypedSource().getDouble(x1, z3), + getTypedSource().getDouble(x2, z0), + getTypedSource().getDouble(x2, z1), + getTypedSource().getDouble(x2, z2), + getTypedSource().getDouble(x2, z3), + getTypedSource().getDouble(x3, z0), + getTypedSource().getDouble(x3, z1), + getTypedSource().getDouble(x3, z2), + getTypedSource().getDouble(x3, z3), + px, pz)); + //@done + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - return interpolate(x, z); - } + @Override + public T get(double x, double z) { + return interpolate(x, z); + } - @Override - public T get(double x, double y, double z) - { - return interpolate(x, z); - } + @Override + public T get(double x, double y, double z) { + return interpolate(x, z); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/BilinearStream.java b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/BilinearStream.java index 8eb508c27..391819d82 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/BilinearStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/BilinearStream.java @@ -4,60 +4,53 @@ import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; import com.volmit.iris.util.IrisInterpolation; -public class BilinearStream extends BasicStream implements Interpolator -{ - private final int rx; - private final int ry; +public class BilinearStream extends BasicStream implements Interpolator { + private final int rx; + private final int ry; - public BilinearStream(ProceduralStream stream, int rx, int ry) - { - super(stream); - this.rx = rx; - this.ry = ry; - } + public BilinearStream(ProceduralStream stream, int rx, int ry) { + super(stream); + this.rx = rx; + this.ry = ry; + } - public T interpolate(double x, double y) - { - int fx = (int) Math.floor(x / rx); - int fz = (int) Math.floor(y / ry); - int x1 = (int) Math.round(fx * rx); - int z1 = (int) Math.round(fz * ry); - int x2 = (int) Math.round((fx + 1) * rx); - int z2 = (int) Math.round((fz + 1) * ry); - double px = IrisInterpolation.rangeScale(0, 1, x1, x2, x); - double pz = IrisInterpolation.rangeScale(0, 1, z1, z2, y); + public T interpolate(double x, double y) { + int fx = (int) Math.floor(x / rx); + int fz = (int) Math.floor(y / ry); + int x1 = Math.round(fx * rx); + int z1 = Math.round(fz * ry); + int x2 = Math.round((fx + 1) * rx); + int z2 = Math.round((fz + 1) * ry); + double px = IrisInterpolation.rangeScale(0, 1, x1, x2, x); + double pz = IrisInterpolation.rangeScale(0, 1, z1, z2, y); - //@builder - return getTypedSource().fromDouble(IrisInterpolation.blerp( - getTypedSource().getDouble(x1, z1), - getTypedSource().getDouble(x2, z1), - getTypedSource().getDouble(x1, z2), - getTypedSource().getDouble(x2, z2), - px, pz)); - //@done - } + //@builder + return getTypedSource().fromDouble(IrisInterpolation.blerp( + getTypedSource().getDouble(x1, z1), + getTypedSource().getDouble(x2, z1), + getTypedSource().getDouble(x1, z2), + getTypedSource().getDouble(x2, z2), + px, pz)); + //@done + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - return interpolate(x, z); - } + @Override + public T get(double x, double z) { + return interpolate(x, z); + } - @Override - public T get(double x, double y, double z) - { - return interpolate(x, z); - } + @Override + public T get(double x, double y, double z) { + return interpolate(x, z); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/Interpolated.java b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/Interpolated.java index a24bf2c0c..8bd102f78 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/Interpolated.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/Interpolated.java @@ -8,44 +8,37 @@ import org.bukkit.block.data.BlockData; import java.util.function.Function; -public interface Interpolated -{ - Interpolated BLOCK_DATA = of((t) -> 0D, (t) -> null); - Interpolated> CAVE_RESULTS = of((t) -> 0D, (t) -> null); - Interpolated RNG = of((t) -> 0D, (t) -> null); - Interpolated DOUBLE = of((t) -> t, (t) -> t); - Interpolated INT = of(Double::valueOf, Double::intValue); - Interpolated LONG = of(Double::valueOf, Double::longValue); +public interface Interpolated { + Interpolated BLOCK_DATA = of((t) -> 0D, (t) -> null); + Interpolated> CAVE_RESULTS = of((t) -> 0D, (t) -> null); + Interpolated RNG = of((t) -> 0D, (t) -> null); + Interpolated DOUBLE = of((t) -> t, (t) -> t); + Interpolated INT = of(Double::valueOf, Double::intValue); + Interpolated LONG = of(Double::valueOf, Double::longValue); - double toDouble(T t); + double toDouble(T t); - T fromDouble(double d); + T fromDouble(double d); - default InterpolatorFactory interpolate() - { - if(this instanceof ProceduralStream) - { - return new InterpolatorFactory((ProceduralStream) this); - } + default InterpolatorFactory interpolate() { + if (this instanceof ProceduralStream) { + return new InterpolatorFactory((ProceduralStream) this); + } - return null; - } + return null; + } - static Interpolated of(Function a, Function b) - { - return new Interpolated() - { - @Override - public double toDouble(T t) - { - return a.apply(t); - } + static Interpolated of(Function a, Function b) { + return new Interpolated() { + @Override + public double toDouble(T t) { + return a.apply(t); + } - @Override - public T fromDouble(double d) - { - return b.apply(d); - } - }; - } + @Override + public T fromDouble(double d) { + return b.apply(d); + } + }; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/InterpolatingStream.java b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/InterpolatingStream.java index b4562cb71..94ddebeda 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/InterpolatingStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/InterpolatingStream.java @@ -1,51 +1,44 @@ package com.volmit.iris.scaffold.stream.interpolation; +import com.volmit.iris.object.InterpolationMethod; import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; -import com.volmit.iris.object.InterpolationMethod; import com.volmit.iris.util.IrisInterpolation; import com.volmit.iris.util.NoiseProvider; -public class InterpolatingStream extends BasicStream implements Interpolator -{ - private final InterpolationMethod type; - private final NoiseProvider np; - private final int rx; +public class InterpolatingStream extends BasicStream implements Interpolator { + private final InterpolationMethod type; + private final NoiseProvider np; + private final int rx; - public InterpolatingStream(ProceduralStream stream, int rx, InterpolationMethod type) - { - super(stream); - this.type = type; - this.rx = rx; - this.np = (xf, zf) -> getTypedSource().getDouble(xf, zf); - } + public InterpolatingStream(ProceduralStream stream, int rx, InterpolationMethod type) { + super(stream); + this.type = type; + this.rx = rx; + this.np = (xf, zf) -> getTypedSource().getDouble(xf, zf); + } - public T interpolate(double x, double y) - { - return fromDouble(IrisInterpolation.getNoise(type, (int) x, (int) y, (double) rx, np)); - } + public T interpolate(double x, double y) { + return fromDouble(IrisInterpolation.getNoise(type, (int) x, (int) y, rx, np)); + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - return interpolate(x, z); - } + @Override + public T get(double x, double z) { + return interpolate(x, z); + } - @Override - public T get(double x, double y, double z) - { - return interpolate(x, z); - } + @Override + public T get(double x, double y, double z) { + return interpolate(x, z); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/Interpolator.java b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/Interpolator.java index 06a857a08..96cad3cfc 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/Interpolator.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/Interpolator.java @@ -2,16 +2,13 @@ package com.volmit.iris.scaffold.stream.interpolation; import com.volmit.iris.scaffold.stream.ProceduralStream; -public interface Interpolator -{ - @SuppressWarnings("unchecked") - default InterpolatorFactory into() - { - if(this instanceof ProceduralStream) - { - return new InterpolatorFactory((ProceduralStream) this); - } +public interface Interpolator { + @SuppressWarnings("unchecked") + default InterpolatorFactory into() { + if (this instanceof ProceduralStream) { + return new InterpolatorFactory((ProceduralStream) this); + } - return null; - } + return null; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/InterpolatorFactory.java b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/InterpolatorFactory.java index e79688e11..75c90b42e 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/InterpolatorFactory.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/InterpolatorFactory.java @@ -1,109 +1,88 @@ package com.volmit.iris.scaffold.stream.interpolation; -import com.volmit.iris.scaffold.stream.ProceduralStream; import com.volmit.iris.object.InterpolationMethod; +import com.volmit.iris.scaffold.stream.ProceduralStream; -public class InterpolatorFactory -{ - private final ProceduralStream stream; +public class InterpolatorFactory { + private final ProceduralStream stream; - public InterpolatorFactory(ProceduralStream stream) - { - this.stream = stream; - } + public InterpolatorFactory(ProceduralStream stream) { + this.stream = stream; + } - public InterpolatingStream with(InterpolationMethod t, int rx) - { - return new InterpolatingStream(stream, rx, t); - } + public InterpolatingStream with(InterpolationMethod t, int rx) { + return new InterpolatingStream(stream, rx, t); + } - public TrilinearStream trilinear(int rx, int ry, int rz) - { - return new TrilinearStream<>(stream, rx, ry, rz); - } + public TrilinearStream trilinear(int rx, int ry, int rz) { + return new TrilinearStream<>(stream, rx, ry, rz); + } - public TricubicStream tricubic(int rx, int ry, int rz) - { - return new TricubicStream<>(stream, rx, ry, rz); - } + public TricubicStream tricubic(int rx, int ry, int rz) { + return new TricubicStream<>(stream, rx, ry, rz); + } - public BicubicStream bicubic(int rx, int ry) - { - return new BicubicStream<>(stream, rx, ry); - } + public BicubicStream bicubic(int rx, int ry) { + return new BicubicStream<>(stream, rx, ry); + } - public BicubicStream bicubic(int r) - { - return bicubic(r, r); - } + public BicubicStream bicubic(int r) { + return bicubic(r, r); + } - public BilinearStream bilinear(int rx, int ry) - { - return new BilinearStream<>(stream, rx, ry); - } + public BilinearStream bilinear(int rx, int ry) { + return new BilinearStream<>(stream, rx, ry); + } - public BilinearStream bilinear(int r) - { - return bilinear(r, r); - } + public BilinearStream bilinear(int r) { + return bilinear(r, r); + } - public TriStarcastStream tristarcast(int radius, int checks) - { - return new TriStarcastStream<>(stream, radius, checks); - } + public TriStarcastStream tristarcast(int radius, int checks) { + return new TriStarcastStream<>(stream, radius, checks); + } - public TriStarcastStream tristarcast3(int radius) - { - return tristarcast(radius, 3); - } + public TriStarcastStream tristarcast3(int radius) { + return tristarcast(radius, 3); + } - public TriStarcastStream tristarcast6(int radius) - { - return tristarcast(radius, 6); - } + public TriStarcastStream tristarcast6(int radius) { + return tristarcast(radius, 6); + } - public TriStarcastStream tristarcast9(int radius) - { - return tristarcast(radius, 9); - } + public TriStarcastStream tristarcast9(int radius) { + return tristarcast(radius, 9); + } - public BiStarcastStream bistarcast(int radius, int checks) - { - return new BiStarcastStream<>(stream, radius, checks); - } + public BiStarcastStream bistarcast(int radius, int checks) { + return new BiStarcastStream<>(stream, radius, checks); + } - public BiStarcastStream bistarcast3(int radius) - { - return bistarcast(radius, 3); - } + public BiStarcastStream bistarcast3(int radius) { + return bistarcast(radius, 3); + } - public BiStarcastStream bistarcast6(int radius) - { - return bistarcast(radius, 6); - } + public BiStarcastStream bistarcast6(int radius) { + return bistarcast(radius, 6); + } - public BiStarcastStream bistarcast9(int radius) - { - return bistarcast(radius, 9); - } + public BiStarcastStream bistarcast9(int radius) { + return bistarcast(radius, 9); + } - public BiHermiteStream bihermite(int rx, int ry, double tension, double bias) - { - return new BiHermiteStream<>(stream, rx, ry, tension, bias); - } + public BiHermiteStream bihermite(int rx, int ry, double tension, double bias) { + return new BiHermiteStream<>(stream, rx, ry, tension, bias); + } - public BiHermiteStream bihermite(int rx, int ry) - { - return new BiHermiteStream<>(stream, rx, ry); - } + public BiHermiteStream bihermite(int rx, int ry) { + return new BiHermiteStream<>(stream, rx, ry); + } - public BiHermiteStream bihermite(int r) - { - return bihermite(r, r); - } + public BiHermiteStream bihermite(int r) { + return bihermite(r, r); + } - public BiHermiteStream bihermite(int r, double tension, double bias) - { - return bihermite(r, r, tension, bias); - } + public BiHermiteStream bihermite(int r, double tension, double bias) { + return bihermite(r, r, tension, bias); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/TriHermiteStream.java b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/TriHermiteStream.java index 6e69de26a..5936e176a 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/TriHermiteStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/TriHermiteStream.java @@ -4,136 +4,129 @@ import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; import com.volmit.iris.util.IrisInterpolation; -public class TriHermiteStream extends BasicStream implements Interpolator -{ - private final int rx; - private final int ry; - private final int rz; - private final double tension; - private final double bias; +public class TriHermiteStream extends BasicStream implements Interpolator { + private final int rx; + private final int ry; + private final int rz; + private final double tension; + private final double bias; - public TriHermiteStream(ProceduralStream stream, int rx, int ry, int rz, double tension, double bias) - { - super(stream); - this.rx = rx; - this.ry = ry; - this.rz = rz; - this.tension = tension; - this.bias = bias; - } + public TriHermiteStream(ProceduralStream stream, int rx, int ry, int rz, double tension, double bias) { + super(stream); + this.rx = rx; + this.ry = ry; + this.rz = rz; + this.tension = tension; + this.bias = bias; + } - public T interpolate(double x, double y, double z) - { - int fx = (int) Math.floor(x / rx); - int fy = (int) Math.floor(y / ry); - int fz = (int) Math.floor(z / rz); - int x0 = (int) Math.round((fx - 1) * rx); - int y0 = (int) Math.round((fy - 1) * ry); - int z0 = (int) Math.round((fz - 1) * rz); - int x1 = (int) Math.round(fx * rx); - int y1 = (int) Math.round(fy * ry); - int z1 = (int) Math.round(fz * rz); - int x2 = (int) Math.round((fx + 1) * rx); - int y2 = (int) Math.round((fy + 1) * ry); - int z2 = (int) Math.round((fz + 1) * rz); - int x3 = (int) Math.round((fx + 2) * rx); - int y3 = (int) Math.round((fy + 2) * ry); - int z3 = (int) Math.round((fz + 2) * rz); - double px = IrisInterpolation.rangeScale(0, 1, x1, x2, x); - double py = IrisInterpolation.rangeScale(0, 1, y1, y2, y); - double pz = IrisInterpolation.rangeScale(0, 1, z1, z2, z); + public T interpolate(double x, double y, double z) { + int fx = (int) Math.floor(x / rx); + int fy = (int) Math.floor(y / ry); + int fz = (int) Math.floor(z / rz); + int x0 = Math.round((fx - 1) * rx); + int y0 = Math.round((fy - 1) * ry); + int z0 = Math.round((fz - 1) * rz); + int x1 = Math.round(fx * rx); + int y1 = Math.round(fy * ry); + int z1 = Math.round(fz * rz); + int x2 = Math.round((fx + 1) * rx); + int y2 = Math.round((fy + 1) * ry); + int z2 = Math.round((fz + 1) * rz); + int x3 = Math.round((fx + 2) * rx); + int y3 = Math.round((fy + 2) * ry); + int z3 = Math.round((fz + 2) * rz); + double px = IrisInterpolation.rangeScale(0, 1, x1, x2, x); + double py = IrisInterpolation.rangeScale(0, 1, y1, y2, y); + double pz = IrisInterpolation.rangeScale(0, 1, z1, z2, z); - //@builder - return getTypedSource().fromDouble(IrisInterpolation.trihermite( - getTypedSource().getDouble(x0, y0, z0), - getTypedSource().getDouble(x0, y0,z1), - getTypedSource().getDouble(x0, y0,z2), - getTypedSource().getDouble(x0, y0,z3), - getTypedSource().getDouble(x1, y0,z0), - getTypedSource().getDouble(x1, y0,z1), - getTypedSource().getDouble(x1, y0,z2), - getTypedSource().getDouble(x1, y0,z3), - getTypedSource().getDouble(x2, y0,z0), - getTypedSource().getDouble(x2, y0,z1), - getTypedSource().getDouble(x2, y0,z2), - getTypedSource().getDouble(x2, y0,z3), - getTypedSource().getDouble(x3, y0,z0), - getTypedSource().getDouble(x3, y0,z1), - getTypedSource().getDouble(x3, y0,z2), - getTypedSource().getDouble(x3, y0,z3), - getTypedSource().getDouble(x0, y1, z0), - getTypedSource().getDouble(x0, y1,z1), - getTypedSource().getDouble(x0, y1,z2), - getTypedSource().getDouble(x0, y1,z3), - getTypedSource().getDouble(x1, y1,z0), - getTypedSource().getDouble(x1, y1,z1), - getTypedSource().getDouble(x1, y1,z2), - getTypedSource().getDouble(x1, y1,z3), - getTypedSource().getDouble(x2, y1,z0), - getTypedSource().getDouble(x2, y1,z1), - getTypedSource().getDouble(x2, y1,z2), - getTypedSource().getDouble(x2, y1,z3), - getTypedSource().getDouble(x3, y1,z0), - getTypedSource().getDouble(x3, y1,z1), - getTypedSource().getDouble(x3, y1,z2), - getTypedSource().getDouble(x3, y1,z3), - getTypedSource().getDouble(x0, y2, z0), - getTypedSource().getDouble(x0, y2,z1), - getTypedSource().getDouble(x0, y2,z2), - getTypedSource().getDouble(x0, y2,z3), - getTypedSource().getDouble(x1, y2,z0), - getTypedSource().getDouble(x1, y2,z1), - getTypedSource().getDouble(x1, y2,z2), - getTypedSource().getDouble(x1, y2,z3), - getTypedSource().getDouble(x2, y2,z0), - getTypedSource().getDouble(x2, y2,z1), - getTypedSource().getDouble(x2, y2,z2), - getTypedSource().getDouble(x2, y2,z3), - getTypedSource().getDouble(x3, y2,z0), - getTypedSource().getDouble(x3, y2,z1), - getTypedSource().getDouble(x3, y2,z2), - getTypedSource().getDouble(x3, y2,z3), - getTypedSource().getDouble(x0, y3, z0), - getTypedSource().getDouble(x0, y3,z1), - getTypedSource().getDouble(x0, y3,z2), - getTypedSource().getDouble(x0, y3,z3), - getTypedSource().getDouble(x1, y3,z0), - getTypedSource().getDouble(x1, y3,z1), - getTypedSource().getDouble(x1, y3,z2), - getTypedSource().getDouble(x1, y3,z3), - getTypedSource().getDouble(x2, y3,z0), - getTypedSource().getDouble(x2, y3,z1), - getTypedSource().getDouble(x2, y3,z2), - getTypedSource().getDouble(x2, y3,z3), - getTypedSource().getDouble(x3, y3,z0), - getTypedSource().getDouble(x3, y3,z1), - getTypedSource().getDouble(x3, y3,z2), - getTypedSource().getDouble(x3, y3,z3), - px, pz, py, tension, bias)); - //@done - } + //@builder + return getTypedSource().fromDouble(IrisInterpolation.trihermite( + getTypedSource().getDouble(x0, y0, z0), + getTypedSource().getDouble(x0, y0, z1), + getTypedSource().getDouble(x0, y0, z2), + getTypedSource().getDouble(x0, y0, z3), + getTypedSource().getDouble(x1, y0, z0), + getTypedSource().getDouble(x1, y0, z1), + getTypedSource().getDouble(x1, y0, z2), + getTypedSource().getDouble(x1, y0, z3), + getTypedSource().getDouble(x2, y0, z0), + getTypedSource().getDouble(x2, y0, z1), + getTypedSource().getDouble(x2, y0, z2), + getTypedSource().getDouble(x2, y0, z3), + getTypedSource().getDouble(x3, y0, z0), + getTypedSource().getDouble(x3, y0, z1), + getTypedSource().getDouble(x3, y0, z2), + getTypedSource().getDouble(x3, y0, z3), + getTypedSource().getDouble(x0, y1, z0), + getTypedSource().getDouble(x0, y1, z1), + getTypedSource().getDouble(x0, y1, z2), + getTypedSource().getDouble(x0, y1, z3), + getTypedSource().getDouble(x1, y1, z0), + getTypedSource().getDouble(x1, y1, z1), + getTypedSource().getDouble(x1, y1, z2), + getTypedSource().getDouble(x1, y1, z3), + getTypedSource().getDouble(x2, y1, z0), + getTypedSource().getDouble(x2, y1, z1), + getTypedSource().getDouble(x2, y1, z2), + getTypedSource().getDouble(x2, y1, z3), + getTypedSource().getDouble(x3, y1, z0), + getTypedSource().getDouble(x3, y1, z1), + getTypedSource().getDouble(x3, y1, z2), + getTypedSource().getDouble(x3, y1, z3), + getTypedSource().getDouble(x0, y2, z0), + getTypedSource().getDouble(x0, y2, z1), + getTypedSource().getDouble(x0, y2, z2), + getTypedSource().getDouble(x0, y2, z3), + getTypedSource().getDouble(x1, y2, z0), + getTypedSource().getDouble(x1, y2, z1), + getTypedSource().getDouble(x1, y2, z2), + getTypedSource().getDouble(x1, y2, z3), + getTypedSource().getDouble(x2, y2, z0), + getTypedSource().getDouble(x2, y2, z1), + getTypedSource().getDouble(x2, y2, z2), + getTypedSource().getDouble(x2, y2, z3), + getTypedSource().getDouble(x3, y2, z0), + getTypedSource().getDouble(x3, y2, z1), + getTypedSource().getDouble(x3, y2, z2), + getTypedSource().getDouble(x3, y2, z3), + getTypedSource().getDouble(x0, y3, z0), + getTypedSource().getDouble(x0, y3, z1), + getTypedSource().getDouble(x0, y3, z2), + getTypedSource().getDouble(x0, y3, z3), + getTypedSource().getDouble(x1, y3, z0), + getTypedSource().getDouble(x1, y3, z1), + getTypedSource().getDouble(x1, y3, z2), + getTypedSource().getDouble(x1, y3, z3), + getTypedSource().getDouble(x2, y3, z0), + getTypedSource().getDouble(x2, y3, z1), + getTypedSource().getDouble(x2, y3, z2), + getTypedSource().getDouble(x2, y3, z3), + getTypedSource().getDouble(x3, y3, z0), + getTypedSource().getDouble(x3, y3, z1), + getTypedSource().getDouble(x3, y3, z2), + getTypedSource().getDouble(x3, y3, z3), + px, pz, py, tension, bias)); + //@done + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - return interpolate(x, 0, z); - } + @Override + public T get(double x, double z) { + return interpolate(x, 0, z); + } - @Override - public T get(double x, double y, double z) - { - return interpolate(x, y, z); - } + @Override + public T get(double x, double y, double z) { + return interpolate(x, y, z); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/TriStarcastStream.java b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/TriStarcastStream.java index 85ad988cc..9a1c47a46 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/TriStarcastStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/TriStarcastStream.java @@ -3,57 +3,49 @@ package com.volmit.iris.scaffold.stream.interpolation; import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; -public class TriStarcastStream extends BasicStream implements Interpolator -{ - private final int rad; - private final int checks; +public class TriStarcastStream extends BasicStream implements Interpolator { + private final int rad; + private final int checks; - public TriStarcastStream(ProceduralStream stream, int rad, int checks) - { - super(stream); - this.rad = rad; - this.checks = checks; - } + public TriStarcastStream(ProceduralStream stream, int rad, int checks) { + super(stream); + this.rad = rad; + this.checks = checks; + } - public T interpolate(double x, double y, double z) - { - double m = (360D / checks); - double v = 0; + public T interpolate(double x, double y, double z) { + double m = (360D / checks); + double v = 0; - for(int i = 0; i < 360; i += m) - { - double sin = Math.sin(Math.toRadians(i)); - double cos = Math.cos(Math.toRadians(i)); - double cx = x + ((rad * cos) - (rad * sin)); - double cy = y + ((rad * sin) + (rad * cos)); - double cz = z + ((rad * cos) - (rad * sin)); - v += getTypedSource().getDouble(cx, cy, cz); - } + for (int i = 0; i < 360; i += m) { + double sin = Math.sin(Math.toRadians(i)); + double cos = Math.cos(Math.toRadians(i)); + double cx = x + ((rad * cos) - (rad * sin)); + double cy = y + ((rad * sin) + (rad * cos)); + double cz = z + ((rad * cos) - (rad * sin)); + v += getTypedSource().getDouble(cx, cy, cz); + } - return getTypedSource().fromDouble(v / checks); - } + return getTypedSource().fromDouble(v / checks); + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - return interpolate(x, 0, z); - } + @Override + public T get(double x, double z) { + return interpolate(x, 0, z); + } - @Override - public T get(double x, double y, double z) - { - return interpolate(x, y, z); - } + @Override + public T get(double x, double y, double z) { + return interpolate(x, y, z); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/TricubicStream.java b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/TricubicStream.java index 640b9a051..12acbb2e2 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/TricubicStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/TricubicStream.java @@ -4,135 +4,128 @@ import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; import com.volmit.iris.util.IrisInterpolation; -public class TricubicStream extends BasicStream implements Interpolator -{ - private final int rx; - private final int ry; - private final int rz; +public class TricubicStream extends BasicStream implements Interpolator { + private final int rx; + private final int ry; + private final int rz; - public TricubicStream(ProceduralStream stream, int rx, int ry, int rz) - { - super(stream); - this.rx = rx; - this.ry = ry; - this.rz = rz; - } + public TricubicStream(ProceduralStream stream, int rx, int ry, int rz) { + super(stream); + this.rx = rx; + this.ry = ry; + this.rz = rz; + } - public T interpolate(double x, double y, double z) - { - int fx = (int) Math.floor(x / rx); - int fy = (int) Math.floor(y / ry); - int fz = (int) Math.floor(z / rz); - int x0 = (int) Math.round((fx - 1) * rx); - int y0 = (int) Math.round((fy - 1) * ry); - int z0 = (int) Math.round((fz - 1) * rz); - int x1 = (int) Math.round(fx * rx); - int y1 = (int) Math.round(fy * ry); - int z1 = (int) Math.round(fz * rz); - int x2 = (int) Math.round((fx + 1) * rx); - int y2 = (int) Math.round((fy + 1) * ry); - int z2 = (int) Math.round((fz + 1) * rz); - int x3 = (int) Math.round((fx + 2) * rx); - int y3 = (int) Math.round((fy + 2) * ry); - int z3 = (int) Math.round((fz + 2) * rz); - double px = IrisInterpolation.rangeScale(0, 1, x1, x2, x); - double py = IrisInterpolation.rangeScale(0, 1, y1, y2, y); - double pz = IrisInterpolation.rangeScale(0, 1, z1, z2, z); + public T interpolate(double x, double y, double z) { + int fx = (int) Math.floor(x / rx); + int fy = (int) Math.floor(y / ry); + int fz = (int) Math.floor(z / rz); + int x0 = Math.round((fx - 1) * rx); + int y0 = Math.round((fy - 1) * ry); + int z0 = Math.round((fz - 1) * rz); + int x1 = Math.round(fx * rx); + int y1 = Math.round(fy * ry); + int z1 = Math.round(fz * rz); + int x2 = Math.round((fx + 1) * rx); + int y2 = Math.round((fy + 1) * ry); + int z2 = Math.round((fz + 1) * rz); + int x3 = Math.round((fx + 2) * rx); + int y3 = Math.round((fy + 2) * ry); + int z3 = Math.round((fz + 2) * rz); + double px = IrisInterpolation.rangeScale(0, 1, x1, x2, x); + double py = IrisInterpolation.rangeScale(0, 1, y1, y2, y); + double pz = IrisInterpolation.rangeScale(0, 1, z1, z2, z); - //@builder - return getTypedSource().fromDouble(IrisInterpolation.tricubic( - getTypedSource().getDouble(x0, y0, z0), - getTypedSource().getDouble(x0, y0,z1), - getTypedSource().getDouble(x0, y0,z2), - getTypedSource().getDouble(x0, y0,z3), - getTypedSource().getDouble(x1, y0,z0), - getTypedSource().getDouble(x1, y0,z1), - getTypedSource().getDouble(x1, y0,z2), - getTypedSource().getDouble(x1, y0,z3), - getTypedSource().getDouble(x2, y0,z0), - getTypedSource().getDouble(x2, y0,z1), - getTypedSource().getDouble(x2, y0,z2), - getTypedSource().getDouble(x2, y0,z3), - getTypedSource().getDouble(x3, y0,z0), - getTypedSource().getDouble(x3, y0,z1), - getTypedSource().getDouble(x3, y0,z2), - getTypedSource().getDouble(x3, y0,z3), - - getTypedSource().getDouble(x0, y1, z0), - getTypedSource().getDouble(x0, y1,z1), - getTypedSource().getDouble(x0, y1,z2), - getTypedSource().getDouble(x0, y1,z3), - getTypedSource().getDouble(x1, y1,z0), - getTypedSource().getDouble(x1, y1,z1), - getTypedSource().getDouble(x1, y1,z2), - getTypedSource().getDouble(x1, y1,z3), - getTypedSource().getDouble(x2, y1,z0), - getTypedSource().getDouble(x2, y1,z1), - getTypedSource().getDouble(x2, y1,z2), - getTypedSource().getDouble(x2, y1,z3), - getTypedSource().getDouble(x3, y1,z0), - getTypedSource().getDouble(x3, y1,z1), - getTypedSource().getDouble(x3, y1,z2), - getTypedSource().getDouble(x3, y1,z3), - - getTypedSource().getDouble(x0, y2, z0), - getTypedSource().getDouble(x0, y2,z1), - getTypedSource().getDouble(x0, y2,z2), - getTypedSource().getDouble(x0, y2,z3), - getTypedSource().getDouble(x1, y2,z0), - getTypedSource().getDouble(x1, y2,z1), - getTypedSource().getDouble(x1, y2,z2), - getTypedSource().getDouble(x1, y2,z3), - getTypedSource().getDouble(x2, y2,z0), - getTypedSource().getDouble(x2, y2,z1), - getTypedSource().getDouble(x2, y2,z2), - getTypedSource().getDouble(x2, y2,z3), - getTypedSource().getDouble(x3, y2,z0), - getTypedSource().getDouble(x3, y2,z1), - getTypedSource().getDouble(x3, y2,z2), - getTypedSource().getDouble(x3, y2,z3), - - getTypedSource().getDouble(x0, y3, z0), - getTypedSource().getDouble(x0, y3,z1), - getTypedSource().getDouble(x0, y3,z2), - getTypedSource().getDouble(x0, y3,z3), - getTypedSource().getDouble(x1, y3,z0), - getTypedSource().getDouble(x1, y3,z1), - getTypedSource().getDouble(x1, y3,z2), - getTypedSource().getDouble(x1, y3,z3), - getTypedSource().getDouble(x2, y3,z0), - getTypedSource().getDouble(x2, y3,z1), - getTypedSource().getDouble(x2, y3,z2), - getTypedSource().getDouble(x2, y3,z3), - getTypedSource().getDouble(x3, y3,z0), - getTypedSource().getDouble(x3, y3,z1), - getTypedSource().getDouble(x3, y3,z2), - getTypedSource().getDouble(x3, y3,z3), - px, pz, py)); - //@done - } + //@builder + return getTypedSource().fromDouble(IrisInterpolation.tricubic( + getTypedSource().getDouble(x0, y0, z0), + getTypedSource().getDouble(x0, y0, z1), + getTypedSource().getDouble(x0, y0, z2), + getTypedSource().getDouble(x0, y0, z3), + getTypedSource().getDouble(x1, y0, z0), + getTypedSource().getDouble(x1, y0, z1), + getTypedSource().getDouble(x1, y0, z2), + getTypedSource().getDouble(x1, y0, z3), + getTypedSource().getDouble(x2, y0, z0), + getTypedSource().getDouble(x2, y0, z1), + getTypedSource().getDouble(x2, y0, z2), + getTypedSource().getDouble(x2, y0, z3), + getTypedSource().getDouble(x3, y0, z0), + getTypedSource().getDouble(x3, y0, z1), + getTypedSource().getDouble(x3, y0, z2), + getTypedSource().getDouble(x3, y0, z3), - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + getTypedSource().getDouble(x0, y1, z0), + getTypedSource().getDouble(x0, y1, z1), + getTypedSource().getDouble(x0, y1, z2), + getTypedSource().getDouble(x0, y1, z3), + getTypedSource().getDouble(x1, y1, z0), + getTypedSource().getDouble(x1, y1, z1), + getTypedSource().getDouble(x1, y1, z2), + getTypedSource().getDouble(x1, y1, z3), + getTypedSource().getDouble(x2, y1, z0), + getTypedSource().getDouble(x2, y1, z1), + getTypedSource().getDouble(x2, y1, z2), + getTypedSource().getDouble(x2, y1, z3), + getTypedSource().getDouble(x3, y1, z0), + getTypedSource().getDouble(x3, y1, z1), + getTypedSource().getDouble(x3, y1, z2), + getTypedSource().getDouble(x3, y1, z3), - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + getTypedSource().getDouble(x0, y2, z0), + getTypedSource().getDouble(x0, y2, z1), + getTypedSource().getDouble(x0, y2, z2), + getTypedSource().getDouble(x0, y2, z3), + getTypedSource().getDouble(x1, y2, z0), + getTypedSource().getDouble(x1, y2, z1), + getTypedSource().getDouble(x1, y2, z2), + getTypedSource().getDouble(x1, y2, z3), + getTypedSource().getDouble(x2, y2, z0), + getTypedSource().getDouble(x2, y2, z1), + getTypedSource().getDouble(x2, y2, z2), + getTypedSource().getDouble(x2, y2, z3), + getTypedSource().getDouble(x3, y2, z0), + getTypedSource().getDouble(x3, y2, z1), + getTypedSource().getDouble(x3, y2, z2), + getTypedSource().getDouble(x3, y2, z3), - @Override - public T get(double x, double z) - { - return interpolate(x, 0, z); - } + getTypedSource().getDouble(x0, y3, z0), + getTypedSource().getDouble(x0, y3, z1), + getTypedSource().getDouble(x0, y3, z2), + getTypedSource().getDouble(x0, y3, z3), + getTypedSource().getDouble(x1, y3, z0), + getTypedSource().getDouble(x1, y3, z1), + getTypedSource().getDouble(x1, y3, z2), + getTypedSource().getDouble(x1, y3, z3), + getTypedSource().getDouble(x2, y3, z0), + getTypedSource().getDouble(x2, y3, z1), + getTypedSource().getDouble(x2, y3, z2), + getTypedSource().getDouble(x2, y3, z3), + getTypedSource().getDouble(x3, y3, z0), + getTypedSource().getDouble(x3, y3, z1), + getTypedSource().getDouble(x3, y3, z2), + getTypedSource().getDouble(x3, y3, z3), + px, pz, py)); + //@done + } - @Override - public T get(double x, double y, double z) - { - return interpolate(x, y, z); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } + + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } + + @Override + public T get(double x, double z) { + return interpolate(x, 0, z); + } + + @Override + public T get(double x, double y, double z) { + return interpolate(x, y, z); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/TrilinearStream.java b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/TrilinearStream.java index 4c5b64a4c..276521eec 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/interpolation/TrilinearStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/interpolation/TrilinearStream.java @@ -4,70 +4,63 @@ import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; import com.volmit.iris.util.IrisInterpolation; -public class TrilinearStream extends BasicStream implements Interpolator -{ - private final int rx; - private final int ry; - private final int rz; +public class TrilinearStream extends BasicStream implements Interpolator { + private final int rx; + private final int ry; + private final int rz; - public TrilinearStream(ProceduralStream stream, int rx, int ry, int rz) - { - super(stream); - this.rx = rx; - this.ry = ry; - this.rz = rz; - } + public TrilinearStream(ProceduralStream stream, int rx, int ry, int rz) { + super(stream); + this.rx = rx; + this.ry = ry; + this.rz = rz; + } - public T interpolate(double x, double y, double z) - { - int fx = (int) Math.floor(x / rx); - int fy = (int) Math.floor(y / ry); - int fz = (int) Math.floor(z / rz); - int x1 = (int) Math.round(fx * rx); - int y1 = (int) Math.round(fy * ry); - int z1 = (int) Math.round(fz * rz); - int x2 = (int) Math.round((fx + 1) * rx); - int y2 = (int) Math.round((fy + 1) * ry); - int z2 = (int) Math.round((fz + 1) * rz); - double px = IrisInterpolation.rangeScale(0, 1, x1, x2, x); - double py = IrisInterpolation.rangeScale(0, 1, y1, y2, y); - double pz = IrisInterpolation.rangeScale(0, 1, z1, z2, z); + public T interpolate(double x, double y, double z) { + int fx = (int) Math.floor(x / rx); + int fy = (int) Math.floor(y / ry); + int fz = (int) Math.floor(z / rz); + int x1 = Math.round(fx * rx); + int y1 = Math.round(fy * ry); + int z1 = Math.round(fz * rz); + int x2 = Math.round((fx + 1) * rx); + int y2 = Math.round((fy + 1) * ry); + int z2 = Math.round((fz + 1) * rz); + double px = IrisInterpolation.rangeScale(0, 1, x1, x2, x); + double py = IrisInterpolation.rangeScale(0, 1, y1, y2, y); + double pz = IrisInterpolation.rangeScale(0, 1, z1, z2, z); - //@builder - return getTypedSource().fromDouble(IrisInterpolation.trilerp( - getTypedSource().getDouble(x1, y1, z1), - getTypedSource().getDouble(x2, y1, z1), - getTypedSource().getDouble(x1, y1, z2), - getTypedSource().getDouble(x2, y1, z2), - getTypedSource().getDouble(x1, y2, z1), - getTypedSource().getDouble(x2, y2, z1), - getTypedSource().getDouble(x1, y2, z2), - getTypedSource().getDouble(x2, y2, z2), - px, pz, py)); - //@done - } + //@builder + return getTypedSource().fromDouble(IrisInterpolation.trilerp( + getTypedSource().getDouble(x1, y1, z1), + getTypedSource().getDouble(x2, y1, z1), + getTypedSource().getDouble(x1, y1, z2), + getTypedSource().getDouble(x2, y1, z2), + getTypedSource().getDouble(x1, y2, z1), + getTypedSource().getDouble(x2, y2, z1), + getTypedSource().getDouble(x1, y2, z2), + getTypedSource().getDouble(x2, y2, z2), + px, pz, py)); + //@done + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - return interpolate(x, 0, z); - } + @Override + public T get(double x, double z) { + return interpolate(x, 0, z); + } - @Override - public T get(double x, double y, double z) - { - return interpolate(x, y, z); - } + @Override + public T get(double x, double y, double z) { + return interpolate(x, y, z); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/sources/CNGStream.java b/src/main/java/com/volmit/iris/scaffold/stream/sources/CNGStream.java index fcfe000da..38116dea2 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/sources/CNGStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/sources/CNGStream.java @@ -1,62 +1,54 @@ package com.volmit.iris.scaffold.stream.sources; +import com.volmit.iris.generator.noise.CNG; import com.volmit.iris.scaffold.stream.BasicLayer; import com.volmit.iris.scaffold.stream.ProceduralStream; -import com.volmit.iris.generator.noise.CNG; -public class CNGStream extends BasicLayer implements ProceduralStream -{ - private final CNG cng; +public class CNGStream extends BasicLayer implements ProceduralStream { + private final CNG cng; - public CNGStream(CNG cng) - { - this.cng = cng; - } + public CNGStream(CNG cng) { + this.cng = cng; + } - public CNGStream(CNG cng, double zoom, double offsetX, double offsetY, double offsetZ) - { - super(1337, zoom, offsetX, offsetY, offsetZ); - this.cng = cng; - } + public CNGStream(CNG cng, double zoom, double offsetX, double offsetY, double offsetZ) { + super(1337, zoom, offsetX, offsetY, offsetZ); + this.cng = cng; + } - public CNGStream(CNG cng, double zoom) - { - super(1337, zoom); - this.cng = cng; - } + public CNGStream(CNG cng, double zoom) { + super(1337, zoom); + this.cng = cng; + } - @Override - public double toDouble(Double t) - { - return t; - } + @Override + public double toDouble(Double t) { + return t; + } - @Override - public Double fromDouble(double d) - { - return d; - } + @Override + public Double fromDouble(double d) { + return d; + } - @Override - public ProceduralStream getTypedSource() { - return null; - } + @Override + public ProceduralStream getTypedSource() { + return null; + } - @Override - public ProceduralStream getSource() { - return null; - } + @Override + public ProceduralStream getSource() { + return null; + } - @Override - public Double get(double x, double z) - { - return cng.noise((x + getOffsetX()) / getZoom(), (z + getOffsetZ()) / getZoom()); - } + @Override + public Double get(double x, double z) { + return cng.noise((x + getOffsetX()) / getZoom(), (z + getOffsetZ()) / getZoom()); + } - @Override - public Double get(double x, double y, double z) - { - return cng.noise((x + getOffsetX()) / getZoom(), (y + getOffsetY()) / getZoom(), (z + getOffsetZ()) * getZoom()); - } + @Override + public Double get(double x, double y, double z) { + return cng.noise((x + getOffsetX()) / getZoom(), (y + getOffsetY()) / getZoom(), (z + getOffsetZ()) * getZoom()); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/sources/FunctionStream.java b/src/main/java/com/volmit/iris/scaffold/stream/sources/FunctionStream.java index 26b54a82a..ffdf63b6a 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/sources/FunctionStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/sources/FunctionStream.java @@ -5,41 +5,35 @@ import com.volmit.iris.scaffold.stream.interpolation.Interpolated; import com.volmit.iris.util.Function2; import com.volmit.iris.util.Function3; -public class FunctionStream extends BasicStream -{ - private Function2 f2; - private Function3 f3; - private Interpolated helper; +public class FunctionStream extends BasicStream { + private final Function2 f2; + private final Function3 f3; + private final Interpolated helper; - public FunctionStream(Function2 f2, Function3 f3, Interpolated helper) - { - super(); - this.f2 = f2; - this.f3 = f3; - this.helper = helper; - } + public FunctionStream(Function2 f2, Function3 f3, Interpolated helper) { + super(); + this.f2 = f2; + this.f3 = f3; + this.helper = helper; + } - @Override - public double toDouble(T t) - { - return helper.toDouble(t); - } + @Override + public double toDouble(T t) { + return helper.toDouble(t); + } - @Override - public T fromDouble(double d) - { - return helper.fromDouble(d); - } + @Override + public T fromDouble(double d) { + return helper.fromDouble(d); + } - @Override - public T get(double x, double z) - { - return f2.apply(x, z); - } + @Override + public T get(double x, double z) { + return f2.apply(x, z); + } - @Override - public T get(double x, double y, double z) - { - return f3.apply(x, y, z); - } + @Override + public T get(double x, double y, double z) { + return f3.apply(x, y, z); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/utility/CachedStream2D.java b/src/main/java/com/volmit/iris/scaffold/stream/utility/CachedStream2D.java index 3767eaf4a..28ad81a98 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/utility/CachedStream2D.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/utility/CachedStream2D.java @@ -1,50 +1,41 @@ package com.volmit.iris.scaffold.stream.utility; import com.googlecode.concurrentlinkedhashmap.ConcurrentLinkedHashMap; -import com.volmit.iris.Iris; import com.volmit.iris.scaffold.cache.Cache; import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; -import java.util.concurrent.ConcurrentHashMap; +public class CachedStream2D extends BasicStream implements ProceduralStream { + private final ProceduralStream stream; + private final ConcurrentLinkedHashMap cache; -public class CachedStream2D extends BasicStream implements ProceduralStream -{ - private final ProceduralStream stream; - private final ConcurrentLinkedHashMap cache; + public CachedStream2D(ProceduralStream stream, int size) { + super(); + this.stream = stream; + cache = new ConcurrentLinkedHashMap.Builder() + .initialCapacity(size) + .maximumWeightedCapacity(size) + .concurrencyLevel(32) + .build(); + } - public CachedStream2D(ProceduralStream stream, int size) - { - super(); - this.stream = stream; - cache = new ConcurrentLinkedHashMap.Builder() - .initialCapacity(size) - .maximumWeightedCapacity(size) - .concurrencyLevel(32) - .build(); - } + @Override + public double toDouble(T t) { + return stream.toDouble(t); + } - @Override - public double toDouble(T t) - { - return stream.toDouble(t); - } + @Override + public T fromDouble(double d) { + return stream.fromDouble(d); + } - @Override - public T fromDouble(double d) - { - return stream.fromDouble(d); - } + @Override + public T get(double x, double z) { + return cache.compute(Cache.key((int) x, (int) z), (k, v) -> v != null ? v : stream.get((int) x, (int) z)); + } - @Override - public T get(double x, double z) - { - return cache.compute(Cache.key((int) x, (int) z), (k, v) -> v != null ? v : stream.get((int)x, (int)z)); - } - - @Override - public T get(double x, double y, double z) - { - return stream.get(x, y, z); - } + @Override + public T get(double x, double y, double z) { + return stream.get(x, y, z); + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/utility/NullSafeStream.java b/src/main/java/com/volmit/iris/scaffold/stream/utility/NullSafeStream.java index 14ab5ba97..7c7dce361 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/utility/NullSafeStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/utility/NullSafeStream.java @@ -3,53 +3,45 @@ package com.volmit.iris.scaffold.stream.utility; import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; -public class NullSafeStream extends BasicStream implements ProceduralStream -{ - private final ProceduralStream stream; - private final T ifNull; +public class NullSafeStream extends BasicStream implements ProceduralStream { + private final ProceduralStream stream; + private final T ifNull; - public NullSafeStream(ProceduralStream stream, T ifNull) - { - super(); - this.stream = stream; - this.ifNull = ifNull; - } + public NullSafeStream(ProceduralStream stream, T ifNull) { + super(); + this.stream = stream; + this.ifNull = ifNull; + } - @Override - public double toDouble(T t) - { - return stream.toDouble(t); - } + @Override + public double toDouble(T t) { + return stream.toDouble(t); + } - @Override - public T fromDouble(double d) - { - return stream.fromDouble(d); - } + @Override + public T fromDouble(double d) { + return stream.fromDouble(d); + } - @Override - public T get(double x, double z) - { - T t = stream.get(x, z); + @Override + public T get(double x, double z) { + T t = stream.get(x, z); - if(t == null) - { - return ifNull; - } + if (t == null) { + return ifNull; + } - return t; - } + return t; + } - @Override - public T get(double x, double y, double z) - { - T t = stream.get(x, y, z); + @Override + public T get(double x, double y, double z) { + T t = stream.get(x, y, z); - if(t == null) - { - return ifNull; - } + if (t == null) { + return ifNull; + } - return t; - } + return t; + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/utility/ProfiledStream.java b/src/main/java/com/volmit/iris/scaffold/stream/utility/ProfiledStream.java index 7080b29c0..40f11a5fb 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/utility/ProfiledStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/utility/ProfiledStream.java @@ -11,169 +11,144 @@ import lombok.Data; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Consumer; -public class ProfiledStream extends BasicStream -{ - public static final AtomicInteger ids = new AtomicInteger(); - private final int id; - private final RollingSequence metrics; +public class ProfiledStream extends BasicStream { + public static final AtomicInteger ids = new AtomicInteger(); + private final int id; + private final RollingSequence metrics; - public ProfiledStream(ProceduralStream stream, int memory) - { - super(stream); - this.metrics = new RollingSequence(memory); - this.id = ids.getAndAdd(1); - } + public ProfiledStream(ProceduralStream stream, int memory) { + super(stream); + this.metrics = new RollingSequence(memory); + this.id = ids.getAndAdd(1); + } - public int getId() - { - return id; - } + public int getId() { + return id; + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - PrecisionStopwatch p = PrecisionStopwatch.start(); - T t = getTypedSource().get(x, z); - try - { - metrics.put(p.getMilliseconds()); - } + @Override + public T get(double x, double z) { + PrecisionStopwatch p = PrecisionStopwatch.start(); + T t = getTypedSource().get(x, z); + try { + metrics.put(p.getMilliseconds()); + } catch (Throwable e) { + } - catch(Throwable e) - {} + return t; + } - return t; - } + @Override + public T get(double x, double y, double z) { + PrecisionStopwatch p = PrecisionStopwatch.start(); + T t = getTypedSource().get(x, y, z); + try { + metrics.put(p.getMilliseconds()); + } catch (Throwable e) { + } - @Override - public T get(double x, double y, double z) - { - PrecisionStopwatch p = PrecisionStopwatch.start(); - T t = getTypedSource().get(x, y, z); - try - { - metrics.put(p.getMilliseconds()); - } + return t; + } - catch(Throwable e) - {} + public RollingSequence getMetrics() { + return metrics; + } - return t; - } + public static void print(Consumer printer, ProceduralStream stream) { + KList tails = getTails(stream); + int ind = tails.size(); + for (ProfiledTail i : tails) { + printer.accept(Form.repeat(" ", ind) + i); + ind--; + } + } - public RollingSequence getMetrics() - { - return metrics; - } + private static KList> getAllChildren(ProceduralStream s) { + KList> v = new KList<>(); + ProceduralStream cursor = s; - public static void print(Consumer printer, ProceduralStream stream) { - KList tails = getTails(stream); - int ind = tails.size(); - for(ProfiledTail i : tails) - { - printer.accept(Form.repeat(" ", ind) + i); - ind--; - } - } + for (int i = 0; i < 32; i++) { + v.add(cursor); + cursor = nextChuld(cursor); - private static KList> getAllChildren(ProceduralStream s) - { - KList> v = new KList<>(); - ProceduralStream cursor = s; + if (cursor == null) { + break; + } + } - for(int i = 0; i < 32; i++) - { - v.add(cursor); - cursor = nextChuld(cursor); + return v; + } - if(cursor == null) - { - break; - } - } + private static ProceduralStream nextChuld(ProceduralStream s) { + ProceduralStream v = s.getTypedSource(); + return v == null ? s.getSource() : v; + } - return v; - } + private static ProfiledTail getTail(ProceduralStream t) { + if (t instanceof ProfiledStream) { + ProfiledStream s = ((ProfiledStream) t); - private static ProceduralStream nextChuld(ProceduralStream s) - { - ProceduralStream v = s.getTypedSource(); - return v == null ? s.getSource() : v; - } + return new ProfiledTail(s.getId(), s.getMetrics(), s.getClass().getSimpleName().replaceAll("\\QStream\\E", "")); + } - private static ProfiledTail getTail(ProceduralStream t) - { - if(t instanceof ProfiledStream) - { - ProfiledStream s = ((ProfiledStream)t); + return null; + } - return new ProfiledTail(s.getId(), s.getMetrics(), s.getClass().getSimpleName().replaceAll("\\QStream\\E", "")); - } + private static KList getTails(ProceduralStream t) { + KList tails = new KList<>(); - return null; - } + for (ProceduralStream v : getAllChildren(t)) { + ProfiledTail p = getTail(v); - private static KList getTails(ProceduralStream t) { - KList tails = new KList<>(); + if (p != null) { + tails.add(p); + } + } - for (ProceduralStream v : getAllChildren(t)) { - ProfiledTail p = getTail(v); + if (tails.isEmpty()) { + return null; + } - if (p != null) { - tails.add(p); - } - } + ProfiledTail cursor = tails.popLast(); + KList tailx = new KList<>(); + tailx.add(cursor); - if (tails.isEmpty()) - { - return null; - } + while (tails.isNotEmpty()) { + tailx.add(cursor); + ProfiledTail parent = tails.popLast(); + parent.setChild(cursor); + cursor = parent; + tailx.add(cursor); + } - ProfiledTail cursor = tails.popLast(); - KList tailx = new KList<>(); - tailx.add(cursor); + return tailx; + } - while(tails.isNotEmpty()) - { - tailx.add(cursor); - ProfiledTail parent = tails.popLast(); - parent.setChild(cursor); - cursor = parent; - tailx.add(cursor); - } + @Data + private static class ProfiledTail { + private final int id; + private final RollingSequence metrics; + private ProfiledTail child; + private final String name; - return tailx; - } + public ProfiledTail(int id, RollingSequence metrics, String name) { + this.id = id; + this.metrics = metrics; + this.name = name; + } - @Data - private static class ProfiledTail - { - private final int id; - private final RollingSequence metrics; - private ProfiledTail child; - private final String name; - - public ProfiledTail(int id, RollingSequence metrics, String name) { - this.id = id; - this.metrics = metrics; - this.name = name; - } - - public String toString() - { - return id + "-" + name + ": " + Form.duration(metrics.getAverage(), 2); - } - } + public String toString() { + return id + "-" + name + ": " + Form.duration(metrics.getAverage(), 2); + } + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/utility/SemaphoreStream.java b/src/main/java/com/volmit/iris/scaffold/stream/utility/SemaphoreStream.java index 5ea800960..1db48c933 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/utility/SemaphoreStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/utility/SemaphoreStream.java @@ -5,43 +5,35 @@ import com.volmit.iris.scaffold.stream.ProceduralStream; import java.util.concurrent.Semaphore; -public class SemaphoreStream extends BasicStream -{ - private final Semaphore semaphore; +public class SemaphoreStream extends BasicStream { + private final Semaphore semaphore; - public SemaphoreStream(ProceduralStream stream, int permits) - { - super(stream); - this.semaphore = new Semaphore(permits); - } + public SemaphoreStream(ProceduralStream stream, int permits) { + super(stream); + this.semaphore = new Semaphore(permits); + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - synchronized (getTypedSource()) - { - return getTypedSource().get(x, z); - } - } + @Override + public T get(double x, double z) { + synchronized (getTypedSource()) { + return getTypedSource().get(x, z); + } + } - @Override - public T get(double x, double y, double z) - { - synchronized (getTypedSource()) - { - return getTypedSource().get(x, y, z); - } - } + @Override + public T get(double x, double y, double z) { + synchronized (getTypedSource()) { + return getTypedSource().get(x, y, z); + } + } } diff --git a/src/main/java/com/volmit/iris/scaffold/stream/utility/SynchronizedStream.java b/src/main/java/com/volmit/iris/scaffold/stream/utility/SynchronizedStream.java index 7843bcd7f..da830f79b 100644 --- a/src/main/java/com/volmit/iris/scaffold/stream/utility/SynchronizedStream.java +++ b/src/main/java/com/volmit/iris/scaffold/stream/utility/SynchronizedStream.java @@ -3,40 +3,32 @@ package com.volmit.iris.scaffold.stream.utility; import com.volmit.iris.scaffold.stream.BasicStream; import com.volmit.iris.scaffold.stream.ProceduralStream; -public class SynchronizedStream extends BasicStream -{ - public SynchronizedStream(ProceduralStream stream) - { - super(stream); - } +public class SynchronizedStream extends BasicStream { + public SynchronizedStream(ProceduralStream stream) { + super(stream); + } - @Override - public double toDouble(T t) - { - return getTypedSource().toDouble(t); - } + @Override + public double toDouble(T t) { + return getTypedSource().toDouble(t); + } - @Override - public T fromDouble(double d) - { - return getTypedSource().fromDouble(d); - } + @Override + public T fromDouble(double d) { + return getTypedSource().fromDouble(d); + } - @Override - public T get(double x, double z) - { - synchronized (getTypedSource()) - { - return getTypedSource().get(x, z); - } - } + @Override + public T get(double x, double z) { + synchronized (getTypedSource()) { + return getTypedSource().get(x, z); + } + } - @Override - public T get(double x, double y, double z) - { - synchronized (getTypedSource()) - { - return getTypedSource().get(x, y, z); - } - } + @Override + public T get(double x, double y, double z) { + synchronized (getTypedSource()) { + return getTypedSource().get(x, y, z); + } + } } diff --git a/src/main/java/com/volmit/iris/util/AR.java b/src/main/java/com/volmit/iris/util/AR.java index 74bb12d6a..f156e2ec4 100644 --- a/src/main/java/com/volmit/iris/util/AR.java +++ b/src/main/java/com/volmit/iris/util/AR.java @@ -1,27 +1,22 @@ package com.volmit.iris.util; -public abstract class AR implements Runnable, CancellableTask -{ - private int id = 0; +public abstract class AR implements Runnable, CancellableTask { + private int id = 0; - public AR() - { - this(0); - } + public AR() { + this(0); + } - public AR(int interval) - { - id = J.ar(this, interval); - } + public AR(int interval) { + id = J.ar(this, interval); + } - @Override - public void cancel() - { - J.car(id); - } + @Override + public void cancel() { + J.car(id); + } - public int getId() - { - return id; - } + public int getId() { + return id; + } } diff --git a/src/main/java/com/volmit/iris/util/AlignedPoint.java b/src/main/java/com/volmit/iris/util/AlignedPoint.java index ce9b86fd3..61373533d 100644 --- a/src/main/java/com/volmit/iris/util/AlignedPoint.java +++ b/src/main/java/com/volmit/iris/util/AlignedPoint.java @@ -1,46 +1,38 @@ package com.volmit.iris.util; -public class AlignedPoint -{ - private double x; - private double y; - private double z; +public class AlignedPoint { + private double x; + private double y; + private double z; - public AlignedPoint(double x, double y, double z) - { - this.x = x; - this.y = y; - this.z = z; - } + public AlignedPoint(double x, double y, double z) { + this.x = x; + this.y = y; + this.z = z; + } - public double getX() - { - return x; - } + public double getX() { + return x; + } - public void setX(double x) - { - this.x = x; - } + public void setX(double x) { + this.x = x; + } - public double getY() - { - return y; - } + public double getY() { + return y; + } - public void setY(double y) - { - this.y = y; - } + public void setY(double y) { + this.y = y; + } - public double getZ() - { - return z; - } + public double getZ() { + return z; + } - public void setZ(double z) - { - this.z = z; - } + public void setZ(double z) { + this.z = z; + } } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/ArrayType.java b/src/main/java/com/volmit/iris/util/ArrayType.java index d8ea3686c..441f29168 100644 --- a/src/main/java/com/volmit/iris/util/ArrayType.java +++ b/src/main/java/com/volmit/iris/util/ArrayType.java @@ -1,16 +1,15 @@ package com.volmit.iris.util; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - import java.lang.annotation.Retention; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + @Retention(RUNTIME) @Target({PARAMETER, TYPE, FIELD}) -public @interface ArrayType -{ - Class type(); +public @interface ArrayType { + Class type(); - int min() default 0; + int min() default 0; } diff --git a/src/main/java/com/volmit/iris/util/AtomicAverage.java b/src/main/java/com/volmit/iris/util/AtomicAverage.java index 2ec248a5e..e3d95ba06 100644 --- a/src/main/java/com/volmit/iris/util/AtomicAverage.java +++ b/src/main/java/com/volmit/iris/util/AtomicAverage.java @@ -6,90 +6,82 @@ import com.google.common.util.concurrent.AtomicDoubleArray; * Provides an incredibly fast averaging object. It swaps values from a sum * using an array. Averages do not use any form of looping. An average of 10,000 * entries is the same speed as an average with 5 entries. - * - * @author cyberpwn * + * @author cyberpwn */ public class AtomicAverage { - protected AtomicDoubleArray values; - private double average; - private double lastSum; - private boolean dirty; - protected int cursor; - private boolean brandNew; + protected AtomicDoubleArray values; + private double average; + private double lastSum; + private boolean dirty; + protected int cursor; + private boolean brandNew; - /** - * Create an average holder - * - * @param size the size of entries to keep - */ - public AtomicAverage(int size) { - values = new AtomicDoubleArray(size); - DoubleArrayUtils.fill(values, 0); - brandNew = true; - average = 0; - cursor = 0; - lastSum = 0; - dirty = false; - } + /** + * Create an average holder + * + * @param size the size of entries to keep + */ + public AtomicAverage(int size) { + values = new AtomicDoubleArray(size); + DoubleArrayUtils.fill(values, 0); + brandNew = true; + average = 0; + cursor = 0; + lastSum = 0; + dirty = false; + } - /** - * Put a value into the average (rolls over if full) - * - * @param i the value - */ - public void put(double i) { + /** + * Put a value into the average (rolls over if full) + * + * @param i the value + */ + public void put(double i) { - try - { - dirty = true; + try { + dirty = true; - if(brandNew) - { - DoubleArrayUtils.fill(values, i); - lastSum = size() * i; - brandNew = false; - return; - } + if (brandNew) { + DoubleArrayUtils.fill(values, i); + lastSum = size() * i; + brandNew = false; + return; + } - double current = values.get(cursor); - lastSum = (lastSum - current) + i; - values.set(cursor, i); - cursor = cursor + 1 < size() ? cursor + 1 : 0; - } + double current = values.get(cursor); + lastSum = (lastSum - current) + i; + values.set(cursor, i); + cursor = cursor + 1 < size() ? cursor + 1 : 0; + } catch (Throwable e) { - catch(Throwable e) - { + } + } - } - } + /** + * Get the current average + * + * @return the average + */ + public double getAverage() { + if (dirty) { + calculateAverage(); + return getAverage(); + } - /** - * Get the current average - * - * @return the average - */ - public double getAverage() { - if (dirty) { - calculateAverage(); - return getAverage(); - } + return average; + } - return average; - } + private void calculateAverage() { + average = lastSum / (double) size(); + dirty = false; + } - private void calculateAverage() { - average = lastSum / (double) size(); - dirty = false; - } - - public int size() - { - return values.length(); - } - - public boolean isDirty() - { - return dirty; - } + public int size() { + return values.length(); + } + + public boolean isDirty() { + return dirty; + } } diff --git a/src/main/java/com/volmit/iris/util/AtomicRollingSequence.java b/src/main/java/com/volmit/iris/util/AtomicRollingSequence.java index de71cc6cb..5660fe7f5 100644 --- a/src/main/java/com/volmit/iris/util/AtomicRollingSequence.java +++ b/src/main/java/com/volmit/iris/util/AtomicRollingSequence.java @@ -1,102 +1,86 @@ package com.volmit.iris.util; -public class AtomicRollingSequence extends AtomicAverage -{ - private double median; - private double max; - private double min; - private boolean dirtyMedian; - private int dirtyExtremes; - private boolean precision; +public class AtomicRollingSequence extends AtomicAverage { + private double median; + private double max; + private double min; + private boolean dirtyMedian; + private int dirtyExtremes; + private boolean precision; - public AtomicRollingSequence(int size) - { - super(size); - median = 0; - min = 0; - max = 0; - setPrecision(false); - } + public AtomicRollingSequence(int size) { + super(size); + median = 0; + min = 0; + max = 0; + setPrecision(false); + } - public double addLast(int amt) - { - double f = 0; + public double addLast(int amt) { + double f = 0; - for(int i = 0; i < Math.min(values.length(), amt); i++) - { - f += values.get(i); - } + for (int i = 0; i < Math.min(values.length(), amt); i++) { + f += values.get(i); + } - return f; - } + return f; + } - public void setPrecision(boolean p) - { - this.precision = p; - } + public void setPrecision(boolean p) { + this.precision = p; + } - public boolean isPrecision() - { - return precision; - } + public boolean isPrecision() { + return precision; + } - public double getMin() - { - if(dirtyExtremes > (isPrecision() ? 0 : values.length())) - { - resetExtremes(); - } + public double getMin() { + if (dirtyExtremes > (isPrecision() ? 0 : values.length())) { + resetExtremes(); + } - return min; - } + return min; + } - public double getMax() - { - if(dirtyExtremes > (isPrecision() ? 0 : values.length())) - { - resetExtremes(); - } + public double getMax() { + if (dirtyExtremes > (isPrecision() ? 0 : values.length())) { + resetExtremes(); + } - return max; - } + return max; + } - public double getMedian() - { - if(dirtyMedian) - { - recalculateMedian(); - } + public double getMedian() { + if (dirtyMedian) { + recalculateMedian(); + } - return median; - } + return median; + } - private void recalculateMedian() - { - median = new KList().forceAdd(values).sort().middleValue(); - dirtyMedian = false; - } + private void recalculateMedian() { + median = new KList().forceAdd(values).sort().middleValue(); + dirtyMedian = false; + } - public void resetExtremes() - { - max = Integer.MIN_VALUE; - min = Integer.MAX_VALUE; + public void resetExtremes() { + max = Integer.MIN_VALUE; + min = Integer.MAX_VALUE; - for(int i = 0; i < values.length(); i++) - { - double v = values.get(i); - max = M.max(max, v); - min = M.min(min, v); - } + for (int i = 0; i < values.length(); i++) { + double v = values.get(i); + max = M.max(max, v); + min = M.min(min, v); + } - dirtyExtremes = 0; - } + dirtyExtremes = 0; + } - public void put(double i) - { - super.put(i); - dirtyMedian = true; - dirtyExtremes++; - max = M.max(max, i); - min = M.min(min, i); - } + public void put(double i) { + super.put(i); + dirtyMedian = true; + dirtyExtremes++; + max = M.max(max, i); + min = M.min(min, i); + } } diff --git a/src/main/java/com/volmit/iris/util/Average.java b/src/main/java/com/volmit/iris/util/Average.java index 427a86b61..8cf8dcccb 100644 --- a/src/main/java/com/volmit/iris/util/Average.java +++ b/src/main/java/com/volmit/iris/util/Average.java @@ -4,82 +4,78 @@ package com.volmit.iris.util; * Provides an incredibly fast averaging object. It swaps values from a sum * using an array. Averages do not use any form of looping. An average of 10,000 * entries is the same speed as an average with 5 entries. - * - * @author cyberpwn * + * @author cyberpwn */ public class Average { - protected double[] values; - private double average; - private double lastSum; - private boolean dirty; - protected int cursor; - private boolean brandNew; + protected double[] values; + private double average; + private double lastSum; + private boolean dirty; + protected int cursor; + private boolean brandNew; - /** - * Create an average holder - * - * @param size the size of entries to keep - */ - public Average(int size) { - values = new double[size]; - DoubleArrayUtils.fill(values, 0); - brandNew = true; - average = 0; - cursor = 0; - lastSum = 0; - dirty = false; - } + /** + * Create an average holder + * + * @param size the size of entries to keep + */ + public Average(int size) { + values = new double[size]; + DoubleArrayUtils.fill(values, 0); + brandNew = true; + average = 0; + cursor = 0; + lastSum = 0; + dirty = false; + } - /** - * Put a value into the average (rolls over if full) - * - * @param i the value - */ - public void put(double i) { + /** + * Put a value into the average (rolls over if full) + * + * @param i the value + */ + public void put(double i) { - dirty = true; - - if(brandNew) - { - DoubleArrayUtils.fill(values, i); - lastSum = size() * i; - brandNew = false; - return; - } - - double current = values[cursor]; - lastSum = (lastSum - current) + i; - values[cursor] = i; - cursor = cursor + 1 < size() ? cursor + 1 : 0; - } + dirty = true; - /** - * Get the current average - * - * @return the average - */ - public double getAverage() { - if (dirty) { - calculateAverage(); - return getAverage(); - } + if (brandNew) { + DoubleArrayUtils.fill(values, i); + lastSum = size() * i; + brandNew = false; + return; + } - return average; - } + double current = values[cursor]; + lastSum = (lastSum - current) + i; + values[cursor] = i; + cursor = cursor + 1 < size() ? cursor + 1 : 0; + } - private void calculateAverage() { - average = lastSum / (double) size(); - dirty = false; - } - - public int size() - { - return values.length; - } - - public boolean isDirty() - { - return dirty; - } + /** + * Get the current average + * + * @return the average + */ + public double getAverage() { + if (dirty) { + calculateAverage(); + return getAverage(); + } + + return average; + } + + private void calculateAverage() { + average = lastSum / (double) size(); + dirty = false; + } + + public int size() { + return values.length; + } + + public boolean isDirty() { + return dirty; + } } diff --git a/src/main/java/com/volmit/iris/util/AxisAlignedBB.java b/src/main/java/com/volmit/iris/util/AxisAlignedBB.java index b4396c276..605468023 100644 --- a/src/main/java/com/volmit/iris/util/AxisAlignedBB.java +++ b/src/main/java/com/volmit/iris/util/AxisAlignedBB.java @@ -4,82 +4,69 @@ import com.volmit.iris.object.IrisPosition; import org.bukkit.World; import org.bukkit.util.BlockVector; -public class AxisAlignedBB -{ - private double xa; - private double xb; - private double ya; - private double yb; - private double za; - private double zb; +public class AxisAlignedBB { + private final double xa; + private final double xb; + private final double ya; + private final double yb; + private final double za; + private final double zb; - public AxisAlignedBB(double xa, double xb, double ya, double yb, double za, double zb) - { - this.xa = xa; - this.xb = xb; - this.ya = ya; - this.yb = yb; - this.za = za; - this.zb = zb; - } + public AxisAlignedBB(double xa, double xb, double ya, double yb, double za, double zb) { + this.xa = xa; + this.xb = xb; + this.ya = ya; + this.yb = yb; + this.za = za; + this.zb = zb; + } - public AxisAlignedBB shifted(IrisPosition p) - { - return shifted(p.getX(), p.getY(), p.getZ()); - } + public AxisAlignedBB shifted(IrisPosition p) { + return shifted(p.getX(), p.getY(), p.getZ()); + } - public AxisAlignedBB shifted(double x, double y, double z) - { - return new AxisAlignedBB(min().add(new IrisPosition((int)x,(int)y,(int)z)), max().add(new IrisPosition((int)x,(int)y,(int)z))); - } + public AxisAlignedBB shifted(double x, double y, double z) { + return new AxisAlignedBB(min().add(new IrisPosition((int) x, (int) y, (int) z)), max().add(new IrisPosition((int) x, (int) y, (int) z))); + } - public AxisAlignedBB(AlignedPoint a, AlignedPoint b) - { - this(a.getX(), b.getX(), a.getY(), b.getY(), a.getZ(), b.getZ()); - } + public AxisAlignedBB(AlignedPoint a, AlignedPoint b) { + this(a.getX(), b.getX(), a.getY(), b.getY(), a.getZ(), b.getZ()); + } - public AxisAlignedBB(IrisPosition a, IrisPosition b) - { - this(a.getX(), b.getX(), a.getY(), b.getY(), a.getZ(), b.getZ()); - } + public AxisAlignedBB(IrisPosition a, IrisPosition b) { + this(a.getX(), b.getX(), a.getY(), b.getY(), a.getZ(), b.getZ()); + } - public boolean contains(AlignedPoint p) - { - return p.getX() >= xa && p.getX() <= xb && p.getY() >= ya && p.getZ() <= yb && p.getZ() >= za && p.getZ() <= zb; - } + public boolean contains(AlignedPoint p) { + return p.getX() >= xa && p.getX() <= xb && p.getY() >= ya && p.getZ() <= yb && p.getZ() >= za && p.getZ() <= zb; + } - public boolean contains(IrisPosition p) - { - return p.getX() >= xa && p.getX() <= xb && p.getY() >= ya && p.getZ() <= yb && p.getZ() >= za && p.getZ() <= zb; - } + public boolean contains(IrisPosition p) { + return p.getX() >= xa && p.getX() <= xb && p.getY() >= ya && p.getZ() <= yb && p.getZ() >= za && p.getZ() <= zb; + } - public boolean intersects(AxisAlignedBB s) - { - return this.xb >= s.xa && this.yb >= s.ya && this.zb >= s.za && s.xb >= this.xa && s.yb >= this.ya && s.zb >= this.za; - } + public boolean intersects(AxisAlignedBB s) { + return this.xb >= s.xa && this.yb >= s.ya && this.zb >= s.za && s.xb >= this.xa && s.yb >= this.ya && s.zb >= this.za; + } - public IrisPosition max() - { - return new IrisPosition((int)xb, (int)yb, (int)zb); - } + public IrisPosition max() { + return new IrisPosition((int) xb, (int) yb, (int) zb); + } - public BlockVector maxbv() - { - return new BlockVector((int)xb, (int)yb, (int)zb); - } + public BlockVector maxbv() { + return new BlockVector((int) xb, (int) yb, (int) zb); + } - public IrisPosition min() - { - return new IrisPosition((int)xa, (int)ya, (int)za); - } + public IrisPosition min() { + return new IrisPosition((int) xa, (int) ya, (int) za); + } - public BlockVector minbv() - { - return new BlockVector((int)xa, (int)ya, (int)za); - } + public BlockVector minbv() { + return new BlockVector((int) xa, (int) ya, (int) za); + } - public Cuboid toCuboid(World world) { - return new Cuboid(min().toLocation(world), max().toLocation(world)); - } + public Cuboid toCuboid(World world) { + return new Cuboid(min().toLocation(world), max().toLocation(world)); + } } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/B.java b/src/main/java/com/volmit/iris/util/B.java index 25037b64c..d9adca2cb 100644 --- a/src/main/java/com/volmit/iris/util/B.java +++ b/src/main/java/com/volmit/iris/util/B.java @@ -5,576 +5,497 @@ import org.bukkit.Bukkit; import org.bukkit.Material; import org.bukkit.block.data.BlockData; -public class B -{ - private static final Material AIR_MATERIAL = Material.AIR; - private static final BlockData AIR = AIR_MATERIAL.createBlockData(); - private static final KSet nullBlockDataCache = new KSet<>(); - private static final KSet nullMaterialCache = new KSet<>(); - private static final KMap solidCache = new KMap<>(); - private static final KMap updatableCache = new KMap<>(); - private static final KMap foliageCache = new KMap<>(); - private static final KMap litCache = new KMap<>(); - private static final KMap decorantCache = new KMap<>(); - private static final KMap storageCache = new KMap<>(); - private static final KMap storageChestCache = new KMap<>(); - private static final KMap blockDataCache = new KMap<>(); - private static final KMap materialCache = new KMap<>(); - - public static boolean isWater(BlockData b) - { - return b.getMaterial().equals(Material.WATER); - } - - public static BlockData getAir() - { - return AIR; - } - - public static Material getMaterial(String bdx) - { - Material mat = getMaterialOrNull(bdx); - - if(mat != null) - { - return mat; - } - - return AIR_MATERIAL; - } - - public static Material getMaterialOrNull(String bdxx) - { - String bx = bdxx.trim().toUpperCase(); - - if(nullMaterialCache.contains(bx)) - { - return null; - } - - Material mat = materialCache.get(bx); - - if(mat != null) - { - return mat; - } - - try - { - Material mm = Material.valueOf(bx); - materialCache.put(bx, mm); - return mm; - } - - catch(Throwable e) - { - nullMaterialCache.add(bx); - return null; - } - } - - public static boolean isSolid(BlockData mat) - { - return isSolid(mat.getMaterial()); - } - - public static boolean isSolid(Material mat) - { - Boolean solid = solidCache.get(mat); - - if(solid != null) - { - return solid; - } - - solid = mat.isSolid(); - solidCache.put(mat, solid); - - return solid; - } - - public static BlockData getOrNull(String bdxf) - { - try - { - String bd = bdxf.trim(); - - BlockData bdx = parseBlockData(bd); - - if(bdx == null) - { - Iris.warn("Unknown Block Data '" + bd + "'"); - return AIR; - } - - return bdx; - } - - catch(Throwable e) - { - Iris.warn("Unknown Block Data '" + bdxf + "'"); - } - - return null; - } - - public static BlockData get(String bdxf) - { - BlockData bd = getOrNull(bdxf); - - if(bd != null) - { - return bd; - } - - return AIR; - } - - private static BlockData parseBlockDataOrNull(String ix) - { - if(nullBlockDataCache.contains(ix)) - { - return null; - } - - try - { - BlockData bb = blockDataCache.get(ix); - - if(bb != null) - { - return bb; - } - - BlockData bx = Bukkit.createBlockData(ix); - blockDataCache.put(ix, bx); - return bx; - } - - catch(Throwable e) - { - - } - - String i = ix.toUpperCase().trim(); - i = i.equals("WOOL") ? "WHITE_WOOL" : i; - i = i.equals("CONCRETE") ? "WHITE_CONCRETE" : i; - - try - { - BlockData bd = Material.valueOf(i).createBlockData(); - blockDataCache.put(ix, bd); - } - - catch(Throwable e) - { - - } - - nullBlockDataCache.add(ix); - return null; - } - - private static BlockData parseBlockData(String ix) - { - BlockData bd = parseBlockDataOrNull(ix); - - if(bd != null) - { - return bd; - } - - return AIR; - } - - public static boolean isStorage(BlockData mat) - { - Material mm = mat.getMaterial(); - Boolean f = storageCache.get(mm); - - if(f != null) - { - return f; - } - - f = mm.equals(B.getMaterial("CHEST")) - || mm.equals(B.getMaterial("TRAPPED_CHEST")) - || mm.equals(B.getMaterial("SHULKER_BOX")) - || mm.equals(B.getMaterial("WHITE_SHULKER_BOX")) - || mm.equals(B.getMaterial("ORANGE_SHULKER_BOX")) - || mm.equals(B.getMaterial("MAGENTA_SHULKER_BOX")) - || mm.equals(B.getMaterial("LIGHT_BLUE_SHULKER_BOX")) - || mm.equals(B.getMaterial("YELLOW_SHULKER_BOX")) - || mm.equals(B.getMaterial("LIME_SHULKER_BOX")) - || mm.equals(B.getMaterial("PINK_SHULKER_BOX")) - || mm.equals(B.getMaterial("GRAY_SHULKER_BOX")) - || mm.equals(B.getMaterial("LIGHT_GRAY_SHULKER_BOX")) - || mm.equals(B.getMaterial("CYAN_SHULKER_BOX")) - || mm.equals(B.getMaterial("PURPLE_SHULKER_BOX")) - || mm.equals(B.getMaterial("BLUE_SHULKER_BOX")) - || mm.equals(B.getMaterial("BROWN_SHULKER_BOX")) - || mm.equals(B.getMaterial("GREEN_SHULKER_BOX")) - || mm.equals(B.getMaterial("RED_SHULKER_BOX")) - || mm.equals(B.getMaterial("BLACK_SHULKER_BOX")) - || mm.equals(B.getMaterial("BARREL")) - || mm.equals(B.getMaterial("DISPENSER")) - || mm.equals(B.getMaterial("DROPPER")) - || mm.equals(B.getMaterial("HOPPER")) - || mm.equals(B.getMaterial("FURNACE")) - || mm.equals(B.getMaterial("BLAST_FURNACE")) - || mm.equals(B.getMaterial("SMOKER")); - storageCache.put(mm, f); - return f; - } - - public static boolean isStorageChest(BlockData mat) - { - if(!isStorage(mat)) - { - return false; - } - - Material mm = mat.getMaterial(); - Boolean f = storageChestCache.get(mm); - - if(f != null) - { - return f; - } - - f = mm.equals(B.getMaterial("CHEST")) - || mm.equals(B.getMaterial("TRAPPED_CHEST")) - || mm.equals(B.getMaterial("SHULKER_BOX")) - || mm.equals(B.getMaterial("WHITE_SHULKER_BOX")) - || mm.equals(B.getMaterial("ORANGE_SHULKER_BOX")) - || mm.equals(B.getMaterial("MAGENTA_SHULKER_BOX")) - || mm.equals(B.getMaterial("LIGHT_BLUE_SHULKER_BOX")) - || mm.equals(B.getMaterial("YELLOW_SHULKER_BOX")) - || mm.equals(B.getMaterial("LIME_SHULKER_BOX")) - || mm.equals(B.getMaterial("PINK_SHULKER_BOX")) - || mm.equals(B.getMaterial("GRAY_SHULKER_BOX")) - || mm.equals(B.getMaterial("LIGHT_GRAY_SHULKER_BOX")) - || mm.equals(B.getMaterial("CYAN_SHULKER_BOX")) - || mm.equals(B.getMaterial("PURPLE_SHULKER_BOX")) - || mm.equals(B.getMaterial("BLUE_SHULKER_BOX")) - || mm.equals(B.getMaterial("BROWN_SHULKER_BOX")) - || mm.equals(B.getMaterial("GREEN_SHULKER_BOX")) - || mm.equals(B.getMaterial("RED_SHULKER_BOX")) - || mm.equals(B.getMaterial("BLACK_SHULKER_BOX")) - || mm.equals(B.getMaterial("BARREL")) - || mm.equals(B.getMaterial("DISPENSER")) - || mm.equals(B.getMaterial("DROPPER")) - || mm.equals(B.getMaterial("HOPPER")); - storageChestCache.put(mm, f); - return f; - } - - public static boolean isLit(BlockData mat) - { - Material mm = mat.getMaterial(); - Boolean f = litCache.get(mm); - - if(f != null) - { - return f; - } - - f = mm.equals(B.getMaterial("GLOWSTONE")) - || mm.equals(B.getMaterial("END_ROD")) - || mm.equals(B.getMaterial("SOUL_SAND")) - || mm.equals(B.getMaterial("TORCH")) - || mm.equals(Material.REDSTONE_TORCH) - || mm.equals(B.getMaterial("SOUL_TORCH")) - || mm.equals(Material.REDSTONE_WALL_TORCH) - || mm.equals(Material.WALL_TORCH) - || mm.equals(B.getMaterial("SOUL_WALL_TORCH")) - || mm.equals(B.getMaterial("LANTERN")) - || mm.equals(Material.JACK_O_LANTERN) - || mm.equals(Material.REDSTONE_LAMP) - || mm.equals(Material.MAGMA_BLOCK) - || mm.equals(B.getMaterial("SHROOMLIGHT")) - || mm.equals(B.getMaterial("SEA_LANTERN")) - || mm.equals(B.getMaterial("SOUL_LANTERN")) - || mm.equals(Material.FIRE) - || mm.equals(B.getMaterial("SOUL_FIRE")) - || mm.equals(B.getMaterial("SEA_PICKLE")) - || mm.equals(Material.BREWING_STAND) - || mm.equals(Material.REDSTONE_ORE); - litCache.put(mm, f); - return f; - } - - public static boolean isUpdatable(BlockData mat) - { - Boolean u = updatableCache.get(mat.getMaterial()); - - if(u != null) - { - return u; - } - - u = isLit(mat) || isStorage(mat); - updatableCache.put(mat.getMaterial(), u); - return u; - } - - public static boolean isFoliage(Material d) - { - return isFoliage(d.createBlockData()); - } - - public static boolean isFoliage(BlockData d) - { - Boolean f = foliageCache.get(d.getMaterial()); - if(f != null) - { - return f; - } - - if(isFluid(d) || isAir(d) || isSolid(d)) - { - foliageCache.put(d.getMaterial(), false); - return false; - } - - Material mat = d.getMaterial(); - f = mat.equals(Material.POPPY) - || mat.equals(Material.DANDELION) - || mat.equals(B.getMaterial("CORNFLOWER")) - || mat.equals(B.getMaterial("SWEET_BERRY_BUSH")) - || mat.equals(B.getMaterial("CRIMSON_ROOTS")) - || mat.equals(B.getMaterial("WARPED_ROOTS")) - || mat.equals(B.getMaterial("NETHER_SPROUTS")) - || mat.equals(B.getMaterial("ALLIUM")) - || mat.equals(B.getMaterial("AZURE_BLUET")) - || mat.equals(B.getMaterial("BLUE_ORCHID")) - || mat.equals(B.getMaterial("POPPY")) - || mat.equals(B.getMaterial("DANDELION")) - || mat.equals(B.getMaterial("OXEYE_DAISY")) - || mat.equals(B.getMaterial("LILY_OF_THE_VALLEY")) - || mat.equals(B.getMaterial("WITHER_ROSE")) - || mat.equals(Material.DARK_OAK_SAPLING) - || mat.equals(Material.ACACIA_SAPLING) - || mat.equals(Material.JUNGLE_SAPLING) - || mat.equals(Material.BIRCH_SAPLING) - || mat.equals(Material.SPRUCE_SAPLING) - || mat.equals(Material.OAK_SAPLING) - || mat.equals(Material.ORANGE_TULIP) - || mat.equals(Material.PINK_TULIP) - || mat.equals(Material.RED_TULIP) - || mat.equals(Material.WHITE_TULIP) - || mat.equals(Material.FERN) - || mat.equals(Material.LARGE_FERN) - || mat.equals(Material.GRASS) - || mat.equals(Material.TALL_GRASS); - foliageCache.put(d.getMaterial(), f); - return f; - } - - public static boolean canPlaceOnto(Material mat, Material onto) - { - String key = mat.name() + "" + onto.name(); - - if(isFoliage(mat)) - { - if(!isFoliagePlantable(onto)) - { - return false; - } - } - - if(onto.equals(Material.AIR) || onto.equals(B.getMaterial("CAVE_AIR")) || onto.equals(B.getMaterial("VOID_AIR"))) - { - return false; - } - - if(onto.equals(Material.GRASS_BLOCK) && mat.equals(Material.DEAD_BUSH)) - { - return false; - } - - if(onto.equals(Material.DIRT_PATH)) - { - if(!mat.isSolid()) - { - return false; - } - } - - if(onto.equals(Material.ACACIA_LEAVES) - || onto.equals(Material.BIRCH_LEAVES) - || onto.equals(Material.DARK_OAK_LEAVES) - || onto.equals(Material.JUNGLE_LEAVES) - || onto.equals(Material.OAK_LEAVES) - || onto.equals(Material.SPRUCE_LEAVES)) - { - if(!mat.isSolid()) - { - return false; - } - } - - return true; - } - - public static boolean isDecorant(BlockData m) - { - Material mm = m.getMaterial(); - Boolean f = decorantCache.get(mm); - - if(f != null) - { - return f; - } - - f = mm.equals(Material.GRASS) - || mm.equals(Material.TALL_GRASS) - || mm.equals(B.getMaterial("CORNFLOWER")) - || mm.equals(Material.SUNFLOWER) - || mm.equals(Material.CHORUS_FLOWER) - || mm.equals(Material.POPPY) - || mm.equals(Material.DANDELION) - || mm.equals(Material.OXEYE_DAISY) - || mm.equals(Material.ORANGE_TULIP) - || mm.equals(Material.PINK_TULIP) - || mm.equals(Material.RED_TULIP) - || mm.equals(Material.WHITE_TULIP) - || mm.equals(Material.LILAC) - || mm.equals(Material.DEAD_BUSH) - || mm.equals(B.getMaterial("SWEET_BERRY_BUSH")) - || mm.equals(Material.ROSE_BUSH) - || mm.equals(B.getMaterial("WITHER_ROSE")) - || mm.equals(Material.ALLIUM) - || mm.equals(Material.BLUE_ORCHID) - || mm.equals(B.getMaterial("LILY_OF_THE_VALLEY")) - || mm.equals(B.getMaterial("CRIMSON_FUNGUS")) - || mm.equals(B.getMaterial("WARPED_FUNGUS")) - || mm.equals(Material.RED_MUSHROOM) - || mm.equals(Material.BROWN_MUSHROOM) - || mm.equals(B.getMaterial("CRIMSON_ROOTS")) - || mm.equals(B.getMaterial("AZURE_BLUET")) - || mm.equals(B.getMaterial("WEEPING_VINES")) - || mm.equals(B.getMaterial("WEEPING_VINES_PLANT")) - || mm.equals(B.getMaterial("WARPED_ROOTS")) - || mm.equals(B.getMaterial("NETHER_SPROUTS")) - || mm.equals(B.getMaterial("TWISTING_VINES")) - || mm.equals(B.getMaterial("TWISTING_VINES_PLANT")) - || mm.equals(Material.SUGAR_CANE) - || mm.equals(Material.WHEAT) - || mm.equals(Material.POTATOES) - || mm.equals(Material.CARROTS) - || mm.equals(Material.BEETROOTS) - || mm.equals(Material.NETHER_WART) - || mm.equals(B.getMaterial("SEA_PICKLE")) - || mm.equals(B.getMaterial("SEAGRASS")) - || mm.equals(B.getMaterial("ACACIA_BUTTON")) - || mm.equals(B.getMaterial("BIRCH_BUTTON")) - || mm.equals(B.getMaterial("CRIMSON_BUTTON")) - || mm.equals(B.getMaterial("DARK_OAK_BUTTON")) - || mm.equals(B.getMaterial("JUNGLE_BUTTON")) - || mm.equals(B.getMaterial("OAK_BUTTON")) - || mm.equals(B.getMaterial("POLISHED_BLACKSTONE_BUTTON")) - || mm.equals(B.getMaterial("SPRUCE_BUTTON")) - || mm.equals(B.getMaterial("STONE_BUTTON")) - || mm.equals(B.getMaterial("WARPED_BUTTON")) - || mm.equals(Material.TORCH) - || mm.equals(B.getMaterial("SOUL_TORCH")); - decorantCache.put(mm, f); - return f; - } - - public static KList get(KList find) - { - KList b = new KList<>(); - - for(String i : find) - { - BlockData bd = get(i); - - if(bd != null) - { - b.add(bd); - } - } - - return b; - } - - public static boolean isFoliagePlantable(BlockData d) - { - return d.getMaterial().equals(Material.GRASS_BLOCK) - || d.getMaterial().equals(Material.DIRT) - || d.getMaterial().equals(Material.COARSE_DIRT) - || d.getMaterial().equals(Material.PODZOL); - } - - public static boolean isFoliagePlantable(Material d) - { - return d.equals(Material.GRASS_BLOCK) - || d.equals(Material.DIRT) - || d.equals(Material.COARSE_DIRT) - || d.equals(Material.PODZOL); - } - - public static boolean isFluid(BlockData d) - { - return d.getMaterial().equals(Material.WATER) || d.getMaterial().equals(Material.LAVA); - } - - public static boolean isAirOrFluid(BlockData d) - { - return isAir(d) || isFluid(d); - } - - public static boolean isAir(BlockData d) - { - if(d == null) - { - return true; - } - - return d.getMaterial().equals(Material.AIR) || d.getMaterial().equals(Material.CAVE_AIR) || d.getMaterial().equals(Material.VOID_AIR); - } - - - - public static String[] getBlockTypes() - { - KList bt = new KList(); - - for(Material i : Material.values()) - { - if(i.isBlock()) - { - String v = i.createBlockData().getAsString(true); - - if(v.contains("[")) - { - v = v.split("\\Q[\\E")[0]; - } - - if(v.contains(":")) - { - v = v.split("\\Q:\\E")[1]; - } - - bt.add(v); - } - } - - return bt.toArray(new String[bt.size()]); - } - - public static String[] getItemTypes() - { - KList bt = new KList(); - - for(Material i : Material.values()) - { - String v = i.name().toLowerCase().trim(); - bt.add(v); - } - - return bt.toArray(new String[bt.size()]); - } +public class B { + private static final Material AIR_MATERIAL = Material.AIR; + private static final BlockData AIR = AIR_MATERIAL.createBlockData(); + private static final KSet nullBlockDataCache = new KSet<>(); + private static final KSet nullMaterialCache = new KSet<>(); + private static final KMap solidCache = new KMap<>(); + private static final KMap updatableCache = new KMap<>(); + private static final KMap foliageCache = new KMap<>(); + private static final KMap litCache = new KMap<>(); + private static final KMap decorantCache = new KMap<>(); + private static final KMap storageCache = new KMap<>(); + private static final KMap storageChestCache = new KMap<>(); + private static final KMap blockDataCache = new KMap<>(); + private static final KMap materialCache = new KMap<>(); + + public static boolean isWater(BlockData b) { + return b.getMaterial().equals(Material.WATER); + } + + public static BlockData getAir() { + return AIR; + } + + public static Material getMaterial(String bdx) { + Material mat = getMaterialOrNull(bdx); + + if (mat != null) { + return mat; + } + + return AIR_MATERIAL; + } + + public static Material getMaterialOrNull(String bdxx) { + String bx = bdxx.trim().toUpperCase(); + + if (nullMaterialCache.contains(bx)) { + return null; + } + + Material mat = materialCache.get(bx); + + if (mat != null) { + return mat; + } + + try { + Material mm = Material.valueOf(bx); + materialCache.put(bx, mm); + return mm; + } catch (Throwable e) { + nullMaterialCache.add(bx); + return null; + } + } + + public static boolean isSolid(BlockData mat) { + return isSolid(mat.getMaterial()); + } + + public static boolean isSolid(Material mat) { + Boolean solid = solidCache.get(mat); + + if (solid != null) { + return solid; + } + + solid = mat.isSolid(); + solidCache.put(mat, solid); + + return solid; + } + + public static BlockData getOrNull(String bdxf) { + try { + String bd = bdxf.trim(); + + BlockData bdx = parseBlockData(bd); + + if (bdx == null) { + Iris.warn("Unknown Block Data '" + bd + "'"); + return AIR; + } + + return bdx; + } catch (Throwable e) { + Iris.warn("Unknown Block Data '" + bdxf + "'"); + } + + return null; + } + + public static BlockData get(String bdxf) { + BlockData bd = getOrNull(bdxf); + + if (bd != null) { + return bd; + } + + return AIR; + } + + private static BlockData parseBlockDataOrNull(String ix) { + if (nullBlockDataCache.contains(ix)) { + return null; + } + + try { + BlockData bb = blockDataCache.get(ix); + + if (bb != null) { + return bb; + } + + BlockData bx = Bukkit.createBlockData(ix); + blockDataCache.put(ix, bx); + return bx; + } catch (Throwable e) { + + } + + String i = ix.toUpperCase().trim(); + i = i.equals("WOOL") ? "WHITE_WOOL" : i; + i = i.equals("CONCRETE") ? "WHITE_CONCRETE" : i; + + try { + BlockData bd = Material.valueOf(i).createBlockData(); + blockDataCache.put(ix, bd); + } catch (Throwable e) { + + } + + nullBlockDataCache.add(ix); + return null; + } + + private static BlockData parseBlockData(String ix) { + BlockData bd = parseBlockDataOrNull(ix); + + if (bd != null) { + return bd; + } + + return AIR; + } + + public static boolean isStorage(BlockData mat) { + Material mm = mat.getMaterial(); + Boolean f = storageCache.get(mm); + + if (f != null) { + return f; + } + + f = mm.equals(B.getMaterial("CHEST")) + || mm.equals(B.getMaterial("TRAPPED_CHEST")) + || mm.equals(B.getMaterial("SHULKER_BOX")) + || mm.equals(B.getMaterial("WHITE_SHULKER_BOX")) + || mm.equals(B.getMaterial("ORANGE_SHULKER_BOX")) + || mm.equals(B.getMaterial("MAGENTA_SHULKER_BOX")) + || mm.equals(B.getMaterial("LIGHT_BLUE_SHULKER_BOX")) + || mm.equals(B.getMaterial("YELLOW_SHULKER_BOX")) + || mm.equals(B.getMaterial("LIME_SHULKER_BOX")) + || mm.equals(B.getMaterial("PINK_SHULKER_BOX")) + || mm.equals(B.getMaterial("GRAY_SHULKER_BOX")) + || mm.equals(B.getMaterial("LIGHT_GRAY_SHULKER_BOX")) + || mm.equals(B.getMaterial("CYAN_SHULKER_BOX")) + || mm.equals(B.getMaterial("PURPLE_SHULKER_BOX")) + || mm.equals(B.getMaterial("BLUE_SHULKER_BOX")) + || mm.equals(B.getMaterial("BROWN_SHULKER_BOX")) + || mm.equals(B.getMaterial("GREEN_SHULKER_BOX")) + || mm.equals(B.getMaterial("RED_SHULKER_BOX")) + || mm.equals(B.getMaterial("BLACK_SHULKER_BOX")) + || mm.equals(B.getMaterial("BARREL")) + || mm.equals(B.getMaterial("DISPENSER")) + || mm.equals(B.getMaterial("DROPPER")) + || mm.equals(B.getMaterial("HOPPER")) + || mm.equals(B.getMaterial("FURNACE")) + || mm.equals(B.getMaterial("BLAST_FURNACE")) + || mm.equals(B.getMaterial("SMOKER")); + storageCache.put(mm, f); + return f; + } + + public static boolean isStorageChest(BlockData mat) { + if (!isStorage(mat)) { + return false; + } + + Material mm = mat.getMaterial(); + Boolean f = storageChestCache.get(mm); + + if (f != null) { + return f; + } + + f = mm.equals(B.getMaterial("CHEST")) + || mm.equals(B.getMaterial("TRAPPED_CHEST")) + || mm.equals(B.getMaterial("SHULKER_BOX")) + || mm.equals(B.getMaterial("WHITE_SHULKER_BOX")) + || mm.equals(B.getMaterial("ORANGE_SHULKER_BOX")) + || mm.equals(B.getMaterial("MAGENTA_SHULKER_BOX")) + || mm.equals(B.getMaterial("LIGHT_BLUE_SHULKER_BOX")) + || mm.equals(B.getMaterial("YELLOW_SHULKER_BOX")) + || mm.equals(B.getMaterial("LIME_SHULKER_BOX")) + || mm.equals(B.getMaterial("PINK_SHULKER_BOX")) + || mm.equals(B.getMaterial("GRAY_SHULKER_BOX")) + || mm.equals(B.getMaterial("LIGHT_GRAY_SHULKER_BOX")) + || mm.equals(B.getMaterial("CYAN_SHULKER_BOX")) + || mm.equals(B.getMaterial("PURPLE_SHULKER_BOX")) + || mm.equals(B.getMaterial("BLUE_SHULKER_BOX")) + || mm.equals(B.getMaterial("BROWN_SHULKER_BOX")) + || mm.equals(B.getMaterial("GREEN_SHULKER_BOX")) + || mm.equals(B.getMaterial("RED_SHULKER_BOX")) + || mm.equals(B.getMaterial("BLACK_SHULKER_BOX")) + || mm.equals(B.getMaterial("BARREL")) + || mm.equals(B.getMaterial("DISPENSER")) + || mm.equals(B.getMaterial("DROPPER")) + || mm.equals(B.getMaterial("HOPPER")); + storageChestCache.put(mm, f); + return f; + } + + public static boolean isLit(BlockData mat) { + Material mm = mat.getMaterial(); + Boolean f = litCache.get(mm); + + if (f != null) { + return f; + } + + f = mm.equals(B.getMaterial("GLOWSTONE")) + || mm.equals(B.getMaterial("END_ROD")) + || mm.equals(B.getMaterial("SOUL_SAND")) + || mm.equals(B.getMaterial("TORCH")) + || mm.equals(Material.REDSTONE_TORCH) + || mm.equals(B.getMaterial("SOUL_TORCH")) + || mm.equals(Material.REDSTONE_WALL_TORCH) + || mm.equals(Material.WALL_TORCH) + || mm.equals(B.getMaterial("SOUL_WALL_TORCH")) + || mm.equals(B.getMaterial("LANTERN")) + || mm.equals(Material.JACK_O_LANTERN) + || mm.equals(Material.REDSTONE_LAMP) + || mm.equals(Material.MAGMA_BLOCK) + || mm.equals(B.getMaterial("SHROOMLIGHT")) + || mm.equals(B.getMaterial("SEA_LANTERN")) + || mm.equals(B.getMaterial("SOUL_LANTERN")) + || mm.equals(Material.FIRE) + || mm.equals(B.getMaterial("SOUL_FIRE")) + || mm.equals(B.getMaterial("SEA_PICKLE")) + || mm.equals(Material.BREWING_STAND) + || mm.equals(Material.REDSTONE_ORE); + litCache.put(mm, f); + return f; + } + + public static boolean isUpdatable(BlockData mat) { + Boolean u = updatableCache.get(mat.getMaterial()); + + if (u != null) { + return u; + } + + u = isLit(mat) || isStorage(mat); + updatableCache.put(mat.getMaterial(), u); + return u; + } + + public static boolean isFoliage(Material d) { + return isFoliage(d.createBlockData()); + } + + public static boolean isFoliage(BlockData d) { + Boolean f = foliageCache.get(d.getMaterial()); + if (f != null) { + return f; + } + + if (isFluid(d) || isAir(d) || isSolid(d)) { + foliageCache.put(d.getMaterial(), false); + return false; + } + + Material mat = d.getMaterial(); + f = mat.equals(Material.POPPY) + || mat.equals(Material.DANDELION) + || mat.equals(B.getMaterial("CORNFLOWER")) + || mat.equals(B.getMaterial("SWEET_BERRY_BUSH")) + || mat.equals(B.getMaterial("CRIMSON_ROOTS")) + || mat.equals(B.getMaterial("WARPED_ROOTS")) + || mat.equals(B.getMaterial("NETHER_SPROUTS")) + || mat.equals(B.getMaterial("ALLIUM")) + || mat.equals(B.getMaterial("AZURE_BLUET")) + || mat.equals(B.getMaterial("BLUE_ORCHID")) + || mat.equals(B.getMaterial("POPPY")) + || mat.equals(B.getMaterial("DANDELION")) + || mat.equals(B.getMaterial("OXEYE_DAISY")) + || mat.equals(B.getMaterial("LILY_OF_THE_VALLEY")) + || mat.equals(B.getMaterial("WITHER_ROSE")) + || mat.equals(Material.DARK_OAK_SAPLING) + || mat.equals(Material.ACACIA_SAPLING) + || mat.equals(Material.JUNGLE_SAPLING) + || mat.equals(Material.BIRCH_SAPLING) + || mat.equals(Material.SPRUCE_SAPLING) + || mat.equals(Material.OAK_SAPLING) + || mat.equals(Material.ORANGE_TULIP) + || mat.equals(Material.PINK_TULIP) + || mat.equals(Material.RED_TULIP) + || mat.equals(Material.WHITE_TULIP) + || mat.equals(Material.FERN) + || mat.equals(Material.LARGE_FERN) + || mat.equals(Material.GRASS) + || mat.equals(Material.TALL_GRASS); + foliageCache.put(d.getMaterial(), f); + return f; + } + + public static boolean canPlaceOnto(Material mat, Material onto) { + String key = mat.name() + "" + onto.name(); + + if (isFoliage(mat)) { + if (!isFoliagePlantable(onto)) { + return false; + } + } + + if (onto.equals(Material.AIR) || onto.equals(B.getMaterial("CAVE_AIR")) || onto.equals(B.getMaterial("VOID_AIR"))) { + return false; + } + + if (onto.equals(Material.GRASS_BLOCK) && mat.equals(Material.DEAD_BUSH)) { + return false; + } + + if (onto.equals(Material.DIRT_PATH)) { + if (!mat.isSolid()) { + return false; + } + } + + if (onto.equals(Material.ACACIA_LEAVES) + || onto.equals(Material.BIRCH_LEAVES) + || onto.equals(Material.DARK_OAK_LEAVES) + || onto.equals(Material.JUNGLE_LEAVES) + || onto.equals(Material.OAK_LEAVES) + || onto.equals(Material.SPRUCE_LEAVES)) { + return mat.isSolid(); + } + + return true; + } + + public static boolean isDecorant(BlockData m) { + Material mm = m.getMaterial(); + Boolean f = decorantCache.get(mm); + + if (f != null) { + return f; + } + + f = mm.equals(Material.GRASS) + || mm.equals(Material.TALL_GRASS) + || mm.equals(B.getMaterial("CORNFLOWER")) + || mm.equals(Material.SUNFLOWER) + || mm.equals(Material.CHORUS_FLOWER) + || mm.equals(Material.POPPY) + || mm.equals(Material.DANDELION) + || mm.equals(Material.OXEYE_DAISY) + || mm.equals(Material.ORANGE_TULIP) + || mm.equals(Material.PINK_TULIP) + || mm.equals(Material.RED_TULIP) + || mm.equals(Material.WHITE_TULIP) + || mm.equals(Material.LILAC) + || mm.equals(Material.DEAD_BUSH) + || mm.equals(B.getMaterial("SWEET_BERRY_BUSH")) + || mm.equals(Material.ROSE_BUSH) + || mm.equals(B.getMaterial("WITHER_ROSE")) + || mm.equals(Material.ALLIUM) + || mm.equals(Material.BLUE_ORCHID) + || mm.equals(B.getMaterial("LILY_OF_THE_VALLEY")) + || mm.equals(B.getMaterial("CRIMSON_FUNGUS")) + || mm.equals(B.getMaterial("WARPED_FUNGUS")) + || mm.equals(Material.RED_MUSHROOM) + || mm.equals(Material.BROWN_MUSHROOM) + || mm.equals(B.getMaterial("CRIMSON_ROOTS")) + || mm.equals(B.getMaterial("AZURE_BLUET")) + || mm.equals(B.getMaterial("WEEPING_VINES")) + || mm.equals(B.getMaterial("WEEPING_VINES_PLANT")) + || mm.equals(B.getMaterial("WARPED_ROOTS")) + || mm.equals(B.getMaterial("NETHER_SPROUTS")) + || mm.equals(B.getMaterial("TWISTING_VINES")) + || mm.equals(B.getMaterial("TWISTING_VINES_PLANT")) + || mm.equals(Material.SUGAR_CANE) + || mm.equals(Material.WHEAT) + || mm.equals(Material.POTATOES) + || mm.equals(Material.CARROTS) + || mm.equals(Material.BEETROOTS) + || mm.equals(Material.NETHER_WART) + || mm.equals(B.getMaterial("SEA_PICKLE")) + || mm.equals(B.getMaterial("SEAGRASS")) + || mm.equals(B.getMaterial("ACACIA_BUTTON")) + || mm.equals(B.getMaterial("BIRCH_BUTTON")) + || mm.equals(B.getMaterial("CRIMSON_BUTTON")) + || mm.equals(B.getMaterial("DARK_OAK_BUTTON")) + || mm.equals(B.getMaterial("JUNGLE_BUTTON")) + || mm.equals(B.getMaterial("OAK_BUTTON")) + || mm.equals(B.getMaterial("POLISHED_BLACKSTONE_BUTTON")) + || mm.equals(B.getMaterial("SPRUCE_BUTTON")) + || mm.equals(B.getMaterial("STONE_BUTTON")) + || mm.equals(B.getMaterial("WARPED_BUTTON")) + || mm.equals(Material.TORCH) + || mm.equals(B.getMaterial("SOUL_TORCH")); + decorantCache.put(mm, f); + return f; + } + + public static KList get(KList find) { + KList b = new KList<>(); + + for (String i : find) { + BlockData bd = get(i); + + if (bd != null) { + b.add(bd); + } + } + + return b; + } + + public static boolean isFoliagePlantable(BlockData d) { + return d.getMaterial().equals(Material.GRASS_BLOCK) + || d.getMaterial().equals(Material.DIRT) + || d.getMaterial().equals(Material.COARSE_DIRT) + || d.getMaterial().equals(Material.PODZOL); + } + + public static boolean isFoliagePlantable(Material d) { + return d.equals(Material.GRASS_BLOCK) + || d.equals(Material.DIRT) + || d.equals(Material.COARSE_DIRT) + || d.equals(Material.PODZOL); + } + + public static boolean isFluid(BlockData d) { + return d.getMaterial().equals(Material.WATER) || d.getMaterial().equals(Material.LAVA); + } + + public static boolean isAirOrFluid(BlockData d) { + return isAir(d) || isFluid(d); + } + + public static boolean isAir(BlockData d) { + if (d == null) { + return true; + } + + return d.getMaterial().equals(Material.AIR) || d.getMaterial().equals(Material.CAVE_AIR) || d.getMaterial().equals(Material.VOID_AIR); + } + + + public static String[] getBlockTypes() { + KList bt = new KList(); + + for (Material i : Material.values()) { + if (i.isBlock()) { + String v = i.createBlockData().getAsString(true); + + if (v.contains("[")) { + v = v.split("\\Q[\\E")[0]; + } + + if (v.contains(":")) { + v = v.split("\\Q:\\E")[1]; + } + + bt.add(v); + } + } + + return bt.toArray(new String[bt.size()]); + } + + public static String[] getItemTypes() { + KList bt = new KList(); + + for (Material i : Material.values()) { + String v = i.name().toLowerCase().trim(); + bt.add(v); + } + + return bt.toArray(new String[bt.size()]); + } } diff --git a/src/main/java/com/volmit/iris/util/BiomeMap.java b/src/main/java/com/volmit/iris/util/BiomeMap.java index f790ebb73..b433ca70c 100644 --- a/src/main/java/com/volmit/iris/util/BiomeMap.java +++ b/src/main/java/com/volmit/iris/util/BiomeMap.java @@ -2,22 +2,18 @@ package com.volmit.iris.util; import com.volmit.iris.object.IrisBiome; -public class BiomeMap -{ - private final IrisBiome[] height; +public class BiomeMap { + private final IrisBiome[] height; - public BiomeMap() - { - height = new IrisBiome[256]; - } + public BiomeMap() { + height = new IrisBiome[256]; + } - public void setBiome(int x, int z, IrisBiome h) - { - height[x * 16 + z] = h; - } + public void setBiome(int x, int z, IrisBiome h) { + height[x * 16 + z] = h; + } - public IrisBiome getBiome(int x, int z) - { - return height[x * 16 + z]; - } + public IrisBiome getBiome(int x, int z) { + return height[x * 16 + z]; + } } diff --git a/src/main/java/com/volmit/iris/util/BlockPosition.java b/src/main/java/com/volmit/iris/util/BlockPosition.java index fcfecd8e0..25ae65cd3 100644 --- a/src/main/java/com/volmit/iris/util/BlockPosition.java +++ b/src/main/java/com/volmit/iris/util/BlockPosition.java @@ -5,79 +5,70 @@ import lombok.Data; import java.util.Objects; @Data -public class BlockPosition -{ - private int x; - private int y; - private int z; +public class BlockPosition { + private int x; + private int y; + private int z; - //Magic numbers - private static final int m1 = 1 + MathHelper.f(MathHelper.c(30000000)); - private static final int m2 = 64 - (m1 * 2); - private static final long m3 = m1 + m2; - private static final long m4 = (1L << m1) - 1L; - private static final long m5 = (1L << m2) - 1L; - private static final long m6 = (1L << m1) - 1L; + //Magic numbers + private static final int m1 = 1 + MathHelper.f(MathHelper.c(30000000)); + private static final int m2 = 64 - (m1 * 2); + private static final long m3 = m1 + m2; + private static final long m4 = (1L << m1) - 1L; + private static final long m5 = (1L << m2) - 1L; + private static final long m6 = (1L << m1) - 1L; - public BlockPosition(int x, int y, int z) - { - this.x = x; - this.y = y; - this.z = z; - } + public BlockPosition(int x, int y, int z) { + this.x = x; + this.y = y; + this.z = z; + } - @Override - public int hashCode() { - return Objects.hash(x, y, z); - } + @Override + public int hashCode() { + return Objects.hash(x, y, z); + } - public boolean equals(Object o) - { - if(o == null) - { - return false; - } + public boolean equals(Object o) { + if (o == null) { + return false; + } - if(o instanceof BlockPosition) - { - BlockPosition ot = (BlockPosition) o; + if (o instanceof BlockPosition) { + BlockPosition ot = (BlockPosition) o; - return ot.x == x && ot.y == y && ot.z == z; - } + return ot.x == x && ot.y == y && ot.z == z; + } - return false; - } + return false; + } - public int getChunkX() - { - return x >> 4; - } + public int getChunkX() { + return x >> 4; + } - public int getChunkZ() - { - return z >> 4; - } + public int getChunkZ() { + return z >> 4; + } - public boolean is(int x, int z) - { - return this.x == x && this.z == z; - } + public boolean is(int x, int z) { + return this.x == x && this.z == z; + } - public boolean is(int x, int y, int z) - { - return this.x == x && this.y == y && this.z == z; - } + public boolean is(int x, int y, int z) { + return this.x == x && this.y == y && this.z == z; + } - public long asLong() { - return toLong(getX(), getY(), getZ()); - } + public long asLong() { + return toLong(getX(), getY(), getZ()); + } - public static long toLong(int x, int y, int z) { - long var3 = 0L; - var3 |= (x & m4) << m3; - var3 |= (y & m5) << 0L; - var3 |= (z & m6) << m2; - return var3; - } + public static long toLong(int x, int y, int z) { + long var3 = 0L; + var3 |= (x & m4) << m3; + var3 |= (y & m5) << 0L; + var3 |= (z & m6) << m2; + return var3; + } } diff --git a/src/main/java/com/volmit/iris/util/Board.java b/src/main/java/com/volmit/iris/util/Board.java index 821e1fcd9..af39b1dd2 100644 --- a/src/main/java/com/volmit/iris/util/Board.java +++ b/src/main/java/com/volmit/iris/util/Board.java @@ -1,11 +1,7 @@ package com.volmit.iris.util; -import java.util.Collections; -import java.util.List; -import java.util.function.Function; -import java.util.stream.Collectors; -import java.util.stream.IntStream; - +import lombok.NonNull; +import lombok.Setter; import org.bukkit.Bukkit; import org.bukkit.entity.Player; import org.bukkit.scoreboard.DisplaySlot; @@ -13,135 +9,122 @@ import org.bukkit.scoreboard.Objective; import org.bukkit.scoreboard.Scoreboard; import org.bukkit.scoreboard.Team; -import lombok.NonNull; -import lombok.Setter; +import java.util.Collections; +import java.util.List; +import java.util.function.Function; +import java.util.stream.Collectors; +import java.util.stream.IntStream; /** * @author Missionary (missionarymc@gmail.com) * @since 3/23/2018 */ -public class Board -{ +public class Board { - private static final String[] CACHED_ENTRIES = new String[C.values().length]; + private static final String[] CACHED_ENTRIES = new String[C.values().length]; - private static final Function APPLY_COLOR_TRANSLATION = s -> C.translateAlternateColorCodes('&', s); + private static final Function APPLY_COLOR_TRANSLATION = s -> C.translateAlternateColorCodes('&', s); - static - { - IntStream.range(0, 15).forEach(i -> CACHED_ENTRIES[i] = C.values()[i].toString() + C.RESET); - } + static { + IntStream.range(0, 15).forEach(i -> CACHED_ENTRIES[i] = C.values()[i].toString() + C.RESET); + } - private final Player player; - private final Objective objective; - private final Team team; - @Setter - private BoardSettings boardSettings; - private boolean ready; + private final Player player; + private final Objective objective; + private final Team team; + @Setter + private BoardSettings boardSettings; + private boolean ready; - @SuppressWarnings("deprecation") - public Board(@NonNull final Player player, final BoardSettings boardSettings) - { - this.player = player; - this.boardSettings = boardSettings; - this.objective = this.getScoreboard().getObjective("board") == null ? this.getScoreboard().registerNewObjective("board", "dummy") : this.getScoreboard().getObjective("board"); - this.objective.setDisplaySlot(DisplaySlot.SIDEBAR); - this.team = this.getScoreboard().getTeam("board") == null ? this.getScoreboard().registerNewTeam("board") : this.getScoreboard().getTeam("board"); - this.team.setAllowFriendlyFire(true); - this.team.setCanSeeFriendlyInvisibles(false); - this.team.setPrefix(""); - this.team.setSuffix(""); - this.ready = true; - } + @SuppressWarnings("deprecation") + public Board(@NonNull final Player player, final BoardSettings boardSettings) { + this.player = player; + this.boardSettings = boardSettings; + this.objective = this.getScoreboard().getObjective("board") == null ? this.getScoreboard().registerNewObjective("board", "dummy") : this.getScoreboard().getObjective("board"); + this.objective.setDisplaySlot(DisplaySlot.SIDEBAR); + this.team = this.getScoreboard().getTeam("board") == null ? this.getScoreboard().registerNewTeam("board") : this.getScoreboard().getTeam("board"); + this.team.setAllowFriendlyFire(true); + this.team.setCanSeeFriendlyInvisibles(false); + this.team.setPrefix(""); + this.team.setSuffix(""); + this.ready = true; + } - public Scoreboard getScoreboard() - { - return (player != null) ? player.getScoreboard() : null; - } + public Scoreboard getScoreboard() { + return (player != null) ? player.getScoreboard() : null; + } - public void remove() - { - this.resetScoreboard(); - } + public void remove() { + this.resetScoreboard(); + } - public void update() - { - // Checking if we are ready to start updating the Scoreboard. - if(!ready) - { - return; - } + public void update() { + // Checking if we are ready to start updating the Scoreboard. + if (!ready) { + return; + } - // Making sure the player is connected. - if(!player.isOnline()) - { - remove(); - return; - } + // Making sure the player is connected. + if (!player.isOnline()) { + remove(); + return; + } - // Making sure the Scoreboard Provider is set. - if(boardSettings == null) - { - return; - } + // Making sure the Scoreboard Provider is set. + if (boardSettings == null) { + return; + } - // Getting their Scoreboard display from the Scoreboard Provider. - final List entries = boardSettings.getBoardProvider().getLines(player).stream().map(APPLY_COLOR_TRANSLATION).collect(Collectors.toList()); + // Getting their Scoreboard display from the Scoreboard Provider. + final List entries = boardSettings.getBoardProvider().getLines(player).stream().map(APPLY_COLOR_TRANSLATION).collect(Collectors.toList()); - if(boardSettings.getScoreDirection() == ScoreDirection.UP) - { - Collections.reverse(entries); - } + if (boardSettings.getScoreDirection() == ScoreDirection.UP) { + Collections.reverse(entries); + } - // Setting the Scoreboard title - String title = boardSettings.getBoardProvider().getTitle(player); - if(title.length() > 32) - { - Bukkit.getLogger().warning("The title " + title + " is over 32 characters in length, substringing to prevent errors."); - title = title.substring(0, 32); - } - objective.setDisplayName(C.translateAlternateColorCodes('&', title)); + // Setting the Scoreboard title + String title = boardSettings.getBoardProvider().getTitle(player); + if (title.length() > 32) { + Bukkit.getLogger().warning("The title " + title + " is over 32 characters in length, substringing to prevent errors."); + title = title.substring(0, 32); + } + objective.setDisplayName(C.translateAlternateColorCodes('&', title)); - // Clearing previous Scoreboard values if entry sizes don't match. - if(this.getScoreboard().getEntries().size() != entries.size()) - this.getScoreboard().getEntries().forEach(this::removeEntry); + // Clearing previous Scoreboard values if entry sizes don't match. + if (this.getScoreboard().getEntries().size() != entries.size()) + this.getScoreboard().getEntries().forEach(this::removeEntry); - // Setting Scoreboard lines. - for(int i = 0; i < entries.size(); i++) - { - String str = entries.get(i); - BoardEntry entry = BoardEntry.translateToEntry(str); - Team team = getScoreboard().getTeam(CACHED_ENTRIES[i]); + // Setting Scoreboard lines. + for (int i = 0; i < entries.size(); i++) { + String str = entries.get(i); + BoardEntry entry = BoardEntry.translateToEntry(str); + Team team = getScoreboard().getTeam(CACHED_ENTRIES[i]); - if(team == null) - { - team = this.getScoreboard().registerNewTeam(CACHED_ENTRIES[i]); - team.addEntry(team.getName()); - } + if (team == null) { + team = this.getScoreboard().registerNewTeam(CACHED_ENTRIES[i]); + team.addEntry(team.getName()); + } - team.setPrefix(entry.getPrefix()); - team.setSuffix(entry.getSuffix()); + team.setPrefix(entry.getPrefix()); + team.setSuffix(entry.getSuffix()); - switch(boardSettings.getScoreDirection()) - { - case UP: - objective.getScore(team.getName()).setScore(1 + i); - break; - case DOWN: - objective.getScore(team.getName()).setScore(15 - i); - break; - } - } - } + switch (boardSettings.getScoreDirection()) { + case UP: + objective.getScore(team.getName()).setScore(1 + i); + break; + case DOWN: + objective.getScore(team.getName()).setScore(15 - i); + break; + } + } + } - public void removeEntry(String id) - { - this.getScoreboard().resetScores(id); - } + public void removeEntry(String id) { + this.getScoreboard().resetScores(id); + } - public void resetScoreboard() - { - ready = false; - player.setScoreboard(Bukkit.getScoreboardManager().getMainScoreboard()); - } + public void resetScoreboard() { + ready = false; + player.setScoreboard(Bukkit.getScoreboardManager().getMainScoreboard()); + } } diff --git a/src/main/java/com/volmit/iris/util/BoardEntry.java b/src/main/java/com/volmit/iris/util/BoardEntry.java index 86d4e1124..ec0f9ad7d 100644 --- a/src/main/java/com/volmit/iris/util/BoardEntry.java +++ b/src/main/java/com/volmit/iris/util/BoardEntry.java @@ -1,48 +1,39 @@ package com.volmit.iris.util; -import org.apache.commons.lang.StringUtils; - import lombok.Getter; +import org.apache.commons.lang.StringUtils; /** * @author Missionary (missionarymc@gmail.com) * @since 3/29/2018 */ -public class BoardEntry -{ +public class BoardEntry { - @Getter - private final String prefix, suffix; + @Getter + private final String prefix, suffix; - private BoardEntry(final String prefix, final String suffix) - { - this.prefix = prefix; - this.suffix = suffix; - } + private BoardEntry(final String prefix, final String suffix) { + this.prefix = prefix; + this.suffix = suffix; + } - public static BoardEntry translateToEntry(String input) - { - if(input.isEmpty()) - { - return new BoardEntry("", ""); - } - if(input.length() <= 16) - { - return new BoardEntry(input, ""); - } - else - { - String prefix = input.substring(0, 16); - String suffix = ""; + public static BoardEntry translateToEntry(String input) { + if (input.isEmpty()) { + return new BoardEntry("", ""); + } + if (input.length() <= 16) { + return new BoardEntry(input, ""); + } else { + String prefix = input.substring(0, 16); + String suffix = ""; - if(prefix.endsWith("\u00a7")) - { - prefix = prefix.substring(0, prefix.length() - 1); - suffix = "\u00a7" + suffix; - } + if (prefix.endsWith("\u00a7")) { + prefix = prefix.substring(0, prefix.length() - 1); + suffix = "\u00a7" + suffix; + } - suffix = StringUtils.left(C.getLastColors(prefix) + suffix + input.substring(16), 16); - return new BoardEntry(prefix, suffix); - } - } + suffix = StringUtils.left(C.getLastColors(prefix) + suffix + input.substring(16), 16); + return new BoardEntry(prefix, suffix); + } + } } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/BoardManager.java b/src/main/java/com/volmit/iris/util/BoardManager.java index 927abe9d8..ac1013d55 100644 --- a/src/main/java/com/volmit/iris/util/BoardManager.java +++ b/src/main/java/com/volmit/iris/util/BoardManager.java @@ -1,88 +1,78 @@ package com.volmit.iris.util; +import org.bukkit.Bukkit; +import org.bukkit.entity.Player; +import org.bukkit.plugin.java.JavaPlugin; +import org.bukkit.scheduler.BukkitTask; + import java.util.Collections; import java.util.Map; import java.util.Optional; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; -import org.bukkit.Bukkit; -import org.bukkit.entity.Player; -import org.bukkit.plugin.java.JavaPlugin; -import org.bukkit.scheduler.BukkitTask; - @DontObfuscate -public class BoardManager -{ - @DontObfuscate - private final JavaPlugin plugin; +public class BoardManager { + @DontObfuscate + private final JavaPlugin plugin; - @DontObfuscate - private BoardSettings boardSettings; + @DontObfuscate + private BoardSettings boardSettings; - @DontObfuscate - private Map scoreboards; + @DontObfuscate + private final Map scoreboards; - @DontObfuscate - private BukkitTask updateTask; + @DontObfuscate + private final BukkitTask updateTask; - @DontObfuscate - public BoardManager(JavaPlugin plugin, BoardSettings boardSettings) - { - this.plugin = plugin; - this.boardSettings = boardSettings; - this.scoreboards = new ConcurrentHashMap<>(); - this.updateTask = new BoardUpdateTask(this).runTaskTimer(plugin, 2L, 2L); - plugin.getServer().getOnlinePlayers().forEach(this::setup); - } + @DontObfuscate + public BoardManager(JavaPlugin plugin, BoardSettings boardSettings) { + this.plugin = plugin; + this.boardSettings = boardSettings; + this.scoreboards = new ConcurrentHashMap<>(); + this.updateTask = new BoardUpdateTask(this).runTaskTimer(plugin, 2L, 2L); + plugin.getServer().getOnlinePlayers().forEach(this::setup); + } - @DontObfuscate - public void setBoardSettings(BoardSettings boardSettings) - { - this.boardSettings = boardSettings; - scoreboards.values().forEach(board -> board.setBoardSettings(boardSettings)); - } + @DontObfuscate + public void setBoardSettings(BoardSettings boardSettings) { + this.boardSettings = boardSettings; + scoreboards.values().forEach(board -> board.setBoardSettings(boardSettings)); + } - @DontObfuscate - public boolean hasBoard(Player player) - { - return scoreboards.containsKey(player.getUniqueId()); - } + @DontObfuscate + public boolean hasBoard(Player player) { + return scoreboards.containsKey(player.getUniqueId()); + } - @DontObfuscate - public Optional getBoard(Player player) - { - return Optional.ofNullable(scoreboards.get(player.getUniqueId())); - } + @DontObfuscate + public Optional getBoard(Player player) { + return Optional.ofNullable(scoreboards.get(player.getUniqueId())); + } - @DontObfuscate - public void setup(Player player) - { - Optional.ofNullable(scoreboards.remove(player.getUniqueId())).ifPresent(Board::resetScoreboard); - if(player.getScoreboard().equals(Bukkit.getScoreboardManager().getMainScoreboard())) - { - player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); - } - scoreboards.put(player.getUniqueId(), new Board(player, boardSettings)); - } + @DontObfuscate + public void setup(Player player) { + Optional.ofNullable(scoreboards.remove(player.getUniqueId())).ifPresent(Board::resetScoreboard); + if (player.getScoreboard().equals(Bukkit.getScoreboardManager().getMainScoreboard())) { + player.setScoreboard(Bukkit.getScoreboardManager().getNewScoreboard()); + } + scoreboards.put(player.getUniqueId(), new Board(player, boardSettings)); + } - @DontObfuscate - public void remove(Player player) - { - Optional.ofNullable(scoreboards.remove(player.getUniqueId())).ifPresent(Board::remove); - } + @DontObfuscate + public void remove(Player player) { + Optional.ofNullable(scoreboards.remove(player.getUniqueId())).ifPresent(Board::remove); + } - @DontObfuscate - public Map getScoreboards() - { - return Collections.unmodifiableMap(scoreboards); - } + @DontObfuscate + public Map getScoreboards() { + return Collections.unmodifiableMap(scoreboards); + } - @DontObfuscate - public void onDisable() - { - updateTask.cancel(); - plugin.getServer().getOnlinePlayers().forEach(this::remove); - scoreboards.clear(); - } + @DontObfuscate + public void onDisable() { + updateTask.cancel(); + plugin.getServer().getOnlinePlayers().forEach(this::remove); + scoreboards.clear(); + } } diff --git a/src/main/java/com/volmit/iris/util/BoardProvider.java b/src/main/java/com/volmit/iris/util/BoardProvider.java index ee8174e3f..d9445f47e 100644 --- a/src/main/java/com/volmit/iris/util/BoardProvider.java +++ b/src/main/java/com/volmit/iris/util/BoardProvider.java @@ -1,15 +1,14 @@ package com.volmit.iris.util; -import java.util.List; - import org.bukkit.entity.Player; -@DontObfuscate -public interface BoardProvider -{ - @DontObfuscate - String getTitle(Player player); +import java.util.List; - @DontObfuscate - List getLines(Player player); +@DontObfuscate +public interface BoardProvider { + @DontObfuscate + String getTitle(Player player); + + @DontObfuscate + List getLines(Player player); } diff --git a/src/main/java/com/volmit/iris/util/BoardSettings.java b/src/main/java/com/volmit/iris/util/BoardSettings.java index bf8afedac..692ec79c7 100644 --- a/src/main/java/com/volmit/iris/util/BoardSettings.java +++ b/src/main/java/com/volmit/iris/util/BoardSettings.java @@ -6,11 +6,10 @@ import lombok.Getter; @DontObfuscate @Getter @Builder -public class BoardSettings -{ - @DontObfuscate - private BoardProvider boardProvider; +public class BoardSettings { + @DontObfuscate + private final BoardProvider boardProvider; - @DontObfuscate - private ScoreDirection scoreDirection; + @DontObfuscate + private final ScoreDirection scoreDirection; } diff --git a/src/main/java/com/volmit/iris/util/BoardUpdateTask.java b/src/main/java/com/volmit/iris/util/BoardUpdateTask.java index f27cd302c..ec1c8cc21 100644 --- a/src/main/java/com/volmit/iris/util/BoardUpdateTask.java +++ b/src/main/java/com/volmit/iris/util/BoardUpdateTask.java @@ -1,7 +1,6 @@ package com.volmit.iris.util; import lombok.RequiredArgsConstructor; - import org.bukkit.Bukkit; import org.bukkit.scheduler.BukkitRunnable; diff --git a/src/main/java/com/volmit/iris/util/ByteArrayTag.java b/src/main/java/com/volmit/iris/util/ByteArrayTag.java index f12b43e21..ec60b805c 100644 --- a/src/main/java/com/volmit/iris/util/ByteArrayTag.java +++ b/src/main/java/com/volmit/iris/util/ByteArrayTag.java @@ -2,24 +2,24 @@ package com.volmit.iris.util; /* * JNBT License - * + * * Copyright (c) 2010 Graham Edgecombe * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. - * + * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * * Neither the name of the JNBT team nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -30,13 +30,13 @@ package com.volmit.iris.util; * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * POSSIBILITY OF SUCH DAMAGE. */ + /** * The TAG_Byte_Array tag. * * @author Graham Edgecombe - * */ public final class ByteArrayTag extends Tag { @@ -48,7 +48,7 @@ public final class ByteArrayTag extends Tag { /** * Creates the tag. * - * @param name The name. + * @param name The name. * @param value The value. */ public ByteArrayTag(String name, byte[] value) { @@ -76,7 +76,7 @@ public final class ByteArrayTag extends Tag { if (name != null && !name.equals("")) { append = "(\"" + this.getName() + "\")"; } - return "TAG_Byte_Array" + append + ": " + hex.toString(); + return "TAG_Byte_Array" + append + ": " + hex; } } diff --git a/src/main/java/com/volmit/iris/util/ByteTag.java b/src/main/java/com/volmit/iris/util/ByteTag.java index 81da3e50f..328b255a3 100644 --- a/src/main/java/com/volmit/iris/util/ByteTag.java +++ b/src/main/java/com/volmit/iris/util/ByteTag.java @@ -2,24 +2,24 @@ package com.volmit.iris.util; /* * JNBT License - * + * * Copyright (c) 2010 Graham Edgecombe * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. - * + * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * * Neither the name of the JNBT team nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -30,13 +30,13 @@ package com.volmit.iris.util; * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * POSSIBILITY OF SUCH DAMAGE. */ + /** * The TAG_Byte tag. * * @author Graham Edgecombe - * */ public final class ByteTag extends Tag { @@ -48,7 +48,7 @@ public final class ByteTag extends Tag { /** * Creates the tag. * - * @param name The name. + * @param name The name. * @param value The value. */ public ByteTag(String name, byte value) { diff --git a/src/main/java/com/volmit/iris/util/C.java b/src/main/java/com/volmit/iris/util/C.java index d61637908..66fb0994b 100644 --- a/src/main/java/com/volmit/iris/util/C.java +++ b/src/main/java/com/volmit/iris/util/C.java @@ -1,792 +1,678 @@ package com.volmit.iris.util; -import java.util.HashMap; -import java.util.Map; -import java.util.regex.Pattern; - import org.apache.commons.lang.Validate; import org.bukkit.ChatColor; import org.bukkit.Color; import org.bukkit.DyeColor; +import java.util.HashMap; +import java.util.Map; +import java.util.regex.Pattern; + /** * Colors * * @author cyberpwn */ -public enum C -{ - /** - * Represents black - */ - BLACK('0', 0x00) - { - @Override - public net.md_5.bungee.api.ChatColor asBungee() - { - return net.md_5.bungee.api.ChatColor.BLACK; - } - }, - /** - * Represents dark blue - */ - DARK_BLUE('1', 0x1) - { - @Override - public net.md_5.bungee.api.ChatColor asBungee() - { - return net.md_5.bungee.api.ChatColor.DARK_BLUE; - } - }, - /** - * Represents dark green - */ - DARK_GREEN('2', 0x2) - { - @Override - public net.md_5.bungee.api.ChatColor asBungee() - { - return net.md_5.bungee.api.ChatColor.DARK_GREEN; - } - }, - /** - * Represents dark blue (aqua) - */ - DARK_AQUA('3', 0x3) - { - @Override - public net.md_5.bungee.api.ChatColor asBungee() - { - return net.md_5.bungee.api.ChatColor.DARK_AQUA; - } - }, - /** - * Represents dark red - */ - DARK_RED('4', 0x4) - { - @Override - public net.md_5.bungee.api.ChatColor asBungee() - { - return net.md_5.bungee.api.ChatColor.DARK_RED; - } - }, - /** - * Represents dark purple - */ - DARK_PURPLE('5', 0x5) - { - @Override - public net.md_5.bungee.api.ChatColor asBungee() - { - return net.md_5.bungee.api.ChatColor.DARK_PURPLE; - } - }, - /** - * Represents gold - */ - GOLD('6', 0x6) - { - @Override - public net.md_5.bungee.api.ChatColor asBungee() - { - return net.md_5.bungee.api.ChatColor.GOLD; - } - }, - /** - * Represents gray - */ - GRAY('7', 0x7) - { - @Override - public net.md_5.bungee.api.ChatColor asBungee() - { - return net.md_5.bungee.api.ChatColor.GRAY; - } - }, - /** - * Represents dark gray - */ - DARK_GRAY('8', 0x8) - { - @Override - public net.md_5.bungee.api.ChatColor asBungee() - { - return net.md_5.bungee.api.ChatColor.DARK_GRAY; - } - }, - /** - * Represents blue - */ - BLUE('9', 0x9) - { - @Override - public net.md_5.bungee.api.ChatColor asBungee() - { - return net.md_5.bungee.api.ChatColor.BLUE; - } - }, - /** - * Represents green - */ - GREEN('a', 0xA) - { - @Override - public net.md_5.bungee.api.ChatColor asBungee() - { - return net.md_5.bungee.api.ChatColor.GREEN; - } - }, - /** - * Represents aqua - */ - AQUA('b', 0xB) - { - @Override - public net.md_5.bungee.api.ChatColor asBungee() - { - return net.md_5.bungee.api.ChatColor.AQUA; - } - }, - /** - * Represents red - */ - RED('c', 0xC) - { - @Override - public net.md_5.bungee.api.ChatColor asBungee() - { - return net.md_5.bungee.api.ChatColor.RED; - } - }, - /** - * Represents light purple - */ - LIGHT_PURPLE('d', 0xD) - { - @Override - public net.md_5.bungee.api.ChatColor asBungee() - { - return net.md_5.bungee.api.ChatColor.LIGHT_PURPLE; - } - }, - /** - * Represents yellow - */ - YELLOW('e', 0xE) - { - @Override - public net.md_5.bungee.api.ChatColor asBungee() - { - return net.md_5.bungee.api.ChatColor.YELLOW; - } - }, - /** - * Represents white - */ - WHITE('f', 0xF) - { - @Override - public net.md_5.bungee.api.ChatColor asBungee() - { - return net.md_5.bungee.api.ChatColor.WHITE; - } - }, - /** - * Represents magical characters that change around randomly - */ - MAGIC('k', 0x10, true) - { - @Override - public net.md_5.bungee.api.ChatColor asBungee() - { - return net.md_5.bungee.api.ChatColor.MAGIC; - } - }, - /** - * Makes the text bold. - */ - BOLD('l', 0x11, true) - { - @Override - public net.md_5.bungee.api.ChatColor asBungee() - { - return net.md_5.bungee.api.ChatColor.BOLD; - } - }, - /** - * Makes a line appear through the text. - */ - STRIKETHROUGH('m', 0x12, true) - { - @Override - public net.md_5.bungee.api.ChatColor asBungee() - { - return net.md_5.bungee.api.ChatColor.STRIKETHROUGH; - } - }, - /** - * Makes the text appear underlined. - */ - UNDERLINE('n', 0x13, true) - { - @Override - public net.md_5.bungee.api.ChatColor asBungee() - { - return net.md_5.bungee.api.ChatColor.UNDERLINE; - } - }, - /** - * Makes the text italic. - */ - ITALIC('o', 0x14, true) - { - @Override - public net.md_5.bungee.api.ChatColor asBungee() - { - return net.md_5.bungee.api.ChatColor.ITALIC; - } - }, +public enum C { + /** + * Represents black + */ + BLACK('0', 0x00) { + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.BLACK; + } + }, + /** + * Represents dark blue + */ + DARK_BLUE('1', 0x1) { + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.DARK_BLUE; + } + }, + /** + * Represents dark green + */ + DARK_GREEN('2', 0x2) { + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.DARK_GREEN; + } + }, + /** + * Represents dark blue (aqua) + */ + DARK_AQUA('3', 0x3) { + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.DARK_AQUA; + } + }, + /** + * Represents dark red + */ + DARK_RED('4', 0x4) { + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.DARK_RED; + } + }, + /** + * Represents dark purple + */ + DARK_PURPLE('5', 0x5) { + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.DARK_PURPLE; + } + }, + /** + * Represents gold + */ + GOLD('6', 0x6) { + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.GOLD; + } + }, + /** + * Represents gray + */ + GRAY('7', 0x7) { + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.GRAY; + } + }, + /** + * Represents dark gray + */ + DARK_GRAY('8', 0x8) { + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.DARK_GRAY; + } + }, + /** + * Represents blue + */ + BLUE('9', 0x9) { + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.BLUE; + } + }, + /** + * Represents green + */ + GREEN('a', 0xA) { + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.GREEN; + } + }, + /** + * Represents aqua + */ + AQUA('b', 0xB) { + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.AQUA; + } + }, + /** + * Represents red + */ + RED('c', 0xC) { + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.RED; + } + }, + /** + * Represents light purple + */ + LIGHT_PURPLE('d', 0xD) { + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.LIGHT_PURPLE; + } + }, + /** + * Represents yellow + */ + YELLOW('e', 0xE) { + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.YELLOW; + } + }, + /** + * Represents white + */ + WHITE('f', 0xF) { + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.WHITE; + } + }, + /** + * Represents magical characters that change around randomly + */ + MAGIC('k', 0x10, true) { + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.MAGIC; + } + }, + /** + * Makes the text bold. + */ + BOLD('l', 0x11, true) { + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.BOLD; + } + }, + /** + * Makes a line appear through the text. + */ + STRIKETHROUGH('m', 0x12, true) { + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.STRIKETHROUGH; + } + }, + /** + * Makes the text appear underlined. + */ + UNDERLINE('n', 0x13, true) { + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.UNDERLINE; + } + }, + /** + * Makes the text italic. + */ + ITALIC('o', 0x14, true) { + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.ITALIC; + } + }, - /** - * Resets all previous chat colors or formats. - */ - RESET('r', 0x15) - { - @Override - public net.md_5.bungee.api.ChatColor asBungee() - { - return net.md_5.bungee.api.ChatColor.RESET; - } - }; + /** + * Resets all previous chat colors or formats. + */ + RESET('r', 0x15) { + @Override + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.RESET; + } + }; - /** - * The special character which prefixes all chat colour codes. Use this if you - * need to dynamically convert colour codes from your custom format. - */ - public static final char COLOR_CHAR = '\u00A7'; - private static final Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + String.valueOf(COLOR_CHAR) + "[0-9A-FK-OR]"); - public final static C[] COLORCYCLE = new C[] {C.GOLD, C.YELLOW, C.GREEN, C.AQUA, C.LIGHT_PURPLE, C.AQUA, C.GREEN, C.YELLOW, C.GOLD, C.RED}; - private final static C[] COLORS = new C[] {C.BLACK, C.DARK_BLUE, C.DARK_GREEN, C.DARK_AQUA, C.DARK_RED, C.DARK_PURPLE, C.GOLD, C.GRAY, C.DARK_GRAY, C.BLUE, C.GREEN, C.AQUA, C.RED, C.LIGHT_PURPLE, C.YELLOW, C.WHITE}; - private final int intCode; - private final char code; - private final boolean isFormat; - private final String toString; - private final static Map BY_ID = new HashMap(); - private final static Map BY_CHAR = new HashMap(); - private final static Map dyeChatMap = new HashMap(); - private final static Map chatHexMap = new HashMap(); - private final static Map dyeHexMap = new HashMap(); + /** + * The special character which prefixes all chat colour codes. Use this if you + * need to dynamically convert colour codes from your custom format. + */ + public static final char COLOR_CHAR = '\u00A7'; + private static final Pattern STRIP_COLOR_PATTERN = Pattern.compile("(?i)" + COLOR_CHAR + "[0-9A-FK-OR]"); + public final static C[] COLORCYCLE = new C[]{C.GOLD, C.YELLOW, C.GREEN, C.AQUA, C.LIGHT_PURPLE, C.AQUA, C.GREEN, C.YELLOW, C.GOLD, C.RED}; + private final static C[] COLORS = new C[]{C.BLACK, C.DARK_BLUE, C.DARK_GREEN, C.DARK_AQUA, C.DARK_RED, C.DARK_PURPLE, C.GOLD, C.GRAY, C.DARK_GRAY, C.BLUE, C.GREEN, C.AQUA, C.RED, C.LIGHT_PURPLE, C.YELLOW, C.WHITE}; + private final int intCode; + private final char code; + private final boolean isFormat; + private final String toString; + private final static Map BY_ID = new HashMap(); + private final static Map BY_CHAR = new HashMap(); + private final static Map dyeChatMap = new HashMap(); + private final static Map chatHexMap = new HashMap(); + private final static Map dyeHexMap = new HashMap(); - static - { - chatHexMap.put(C.BLACK, "#000"); - chatHexMap.put(C.DARK_BLUE, "#00a"); - chatHexMap.put(C.DARK_GREEN, "#0a0"); - chatHexMap.put(C.DARK_AQUA, "#0aa"); - chatHexMap.put(C.DARK_RED, "#a00"); - chatHexMap.put(C.DARK_PURPLE, "#a0a"); - chatHexMap.put(C.GOLD, "#fa0"); - chatHexMap.put(C.GRAY, "#999"); - chatHexMap.put(C.DARK_GRAY, "#555"); - chatHexMap.put(C.BLUE, "#55f"); - chatHexMap.put(C.GREEN, "#5c5"); - chatHexMap.put(C.AQUA, "#5cc"); - chatHexMap.put(C.RED, "#f55"); - chatHexMap.put(C.LIGHT_PURPLE, "#f5f"); - chatHexMap.put(C.YELLOW, "#cc5"); - chatHexMap.put(C.WHITE, "#aaa"); - dyeChatMap.put(DyeColor.BLACK, C.DARK_GRAY); - dyeChatMap.put(DyeColor.BLUE, C.DARK_BLUE); - dyeChatMap.put(DyeColor.BROWN, C.GOLD); - dyeChatMap.put(DyeColor.CYAN, C.AQUA); - dyeChatMap.put(DyeColor.GRAY, C.GRAY); - dyeChatMap.put(DyeColor.GREEN, C.DARK_GREEN); - dyeChatMap.put(DyeColor.LIGHT_BLUE, C.BLUE); - dyeChatMap.put(DyeColor.LIME, C.GREEN); - dyeChatMap.put(DyeColor.MAGENTA, C.LIGHT_PURPLE); - dyeChatMap.put(DyeColor.ORANGE, C.GOLD); - dyeChatMap.put(DyeColor.PINK, C.LIGHT_PURPLE); - dyeChatMap.put(DyeColor.PURPLE, C.DARK_PURPLE); - dyeChatMap.put(DyeColor.RED, C.RED); - dyeChatMap.put(DyeColor.LIGHT_GRAY, C.GRAY); - dyeChatMap.put(DyeColor.WHITE, C.WHITE); - dyeChatMap.put(DyeColor.YELLOW, C.YELLOW); - dyeHexMap.put(DyeColor.BLACK, "#181414"); - dyeHexMap.put(DyeColor.BLUE, "#253193"); - dyeHexMap.put(DyeColor.BROWN, "#56331c"); - dyeHexMap.put(DyeColor.CYAN, "#267191"); - dyeHexMap.put(DyeColor.GRAY, "#414141"); - dyeHexMap.put(DyeColor.GREEN, "#364b18"); - dyeHexMap.put(DyeColor.LIGHT_BLUE, "#6387d2"); - dyeHexMap.put(DyeColor.LIME, "#39ba2e"); - dyeHexMap.put(DyeColor.MAGENTA, "#be49c9"); - dyeHexMap.put(DyeColor.ORANGE, "#ea7e35"); - dyeHexMap.put(DyeColor.PINK, "#d98199"); - dyeHexMap.put(DyeColor.PURPLE, "#7e34bf"); - dyeHexMap.put(DyeColor.RED, "#9e2b27"); - dyeHexMap.put(DyeColor.LIGHT_GRAY, "#a0a7a7"); - dyeHexMap.put(DyeColor.WHITE, "#a4a4a4"); - dyeHexMap.put(DyeColor.YELLOW, "#c2b51c"); - } + static { + chatHexMap.put(C.BLACK, "#000"); + chatHexMap.put(C.DARK_BLUE, "#00a"); + chatHexMap.put(C.DARK_GREEN, "#0a0"); + chatHexMap.put(C.DARK_AQUA, "#0aa"); + chatHexMap.put(C.DARK_RED, "#a00"); + chatHexMap.put(C.DARK_PURPLE, "#a0a"); + chatHexMap.put(C.GOLD, "#fa0"); + chatHexMap.put(C.GRAY, "#999"); + chatHexMap.put(C.DARK_GRAY, "#555"); + chatHexMap.put(C.BLUE, "#55f"); + chatHexMap.put(C.GREEN, "#5c5"); + chatHexMap.put(C.AQUA, "#5cc"); + chatHexMap.put(C.RED, "#f55"); + chatHexMap.put(C.LIGHT_PURPLE, "#f5f"); + chatHexMap.put(C.YELLOW, "#cc5"); + chatHexMap.put(C.WHITE, "#aaa"); + dyeChatMap.put(DyeColor.BLACK, C.DARK_GRAY); + dyeChatMap.put(DyeColor.BLUE, C.DARK_BLUE); + dyeChatMap.put(DyeColor.BROWN, C.GOLD); + dyeChatMap.put(DyeColor.CYAN, C.AQUA); + dyeChatMap.put(DyeColor.GRAY, C.GRAY); + dyeChatMap.put(DyeColor.GREEN, C.DARK_GREEN); + dyeChatMap.put(DyeColor.LIGHT_BLUE, C.BLUE); + dyeChatMap.put(DyeColor.LIME, C.GREEN); + dyeChatMap.put(DyeColor.MAGENTA, C.LIGHT_PURPLE); + dyeChatMap.put(DyeColor.ORANGE, C.GOLD); + dyeChatMap.put(DyeColor.PINK, C.LIGHT_PURPLE); + dyeChatMap.put(DyeColor.PURPLE, C.DARK_PURPLE); + dyeChatMap.put(DyeColor.RED, C.RED); + dyeChatMap.put(DyeColor.LIGHT_GRAY, C.GRAY); + dyeChatMap.put(DyeColor.WHITE, C.WHITE); + dyeChatMap.put(DyeColor.YELLOW, C.YELLOW); + dyeHexMap.put(DyeColor.BLACK, "#181414"); + dyeHexMap.put(DyeColor.BLUE, "#253193"); + dyeHexMap.put(DyeColor.BROWN, "#56331c"); + dyeHexMap.put(DyeColor.CYAN, "#267191"); + dyeHexMap.put(DyeColor.GRAY, "#414141"); + dyeHexMap.put(DyeColor.GREEN, "#364b18"); + dyeHexMap.put(DyeColor.LIGHT_BLUE, "#6387d2"); + dyeHexMap.put(DyeColor.LIME, "#39ba2e"); + dyeHexMap.put(DyeColor.MAGENTA, "#be49c9"); + dyeHexMap.put(DyeColor.ORANGE, "#ea7e35"); + dyeHexMap.put(DyeColor.PINK, "#d98199"); + dyeHexMap.put(DyeColor.PURPLE, "#7e34bf"); + dyeHexMap.put(DyeColor.RED, "#9e2b27"); + dyeHexMap.put(DyeColor.LIGHT_GRAY, "#a0a7a7"); + dyeHexMap.put(DyeColor.WHITE, "#a4a4a4"); + dyeHexMap.put(DyeColor.YELLOW, "#c2b51c"); + } - private C(char code, int intCode) - { - this(code, intCode, false); - } + C(char code, int intCode) { + this(code, intCode, false); + } - private C(char code, int intCode, boolean isFormat) - { - this.code = code; - this.intCode = intCode; - this.isFormat = isFormat; - this.toString = new String(new char[] {COLOR_CHAR, code}); - } + C(char code, int intCode, boolean isFormat) { + this.code = code; + this.intCode = intCode; + this.isFormat = isFormat; + this.toString = new String(new char[]{COLOR_CHAR, code}); + } - public net.md_5.bungee.api.ChatColor asBungee() - { - return net.md_5.bungee.api.ChatColor.RESET; - }; + public net.md_5.bungee.api.ChatColor asBungee() { + return net.md_5.bungee.api.ChatColor.RESET; + } - /** - * Gets the char value associated with this color - * - * @return A char value of this color code - */ - public char getChar() - { - return code; - } + /** + * Gets the char value associated with this color + * + * @return A char value of this color code + */ + public char getChar() { + return code; + } - @Override - public String toString() - { - return toString; - } + @Override + public String toString() { + return toString; + } - /** - * get the dye color for the chatcolor - * - * @return - */ - public DyeColor dye() - { - return chatToDye(chatColor()); - } + /** + * get the dye color for the chatcolor + * + * @return + */ + public DyeColor dye() { + return chatToDye(chatColor()); + } - public String hex() - { - return chatToHex(chatColor()); - } + public String hex() { + return chatToHex(chatColor()); + } - /** - * Checks if this code is a format code as opposed to a color code. - * - * @return whether this ChatColor is a format code - */ - public boolean isFormat() - { - return isFormat; - } + /** + * Checks if this code is a format code as opposed to a color code. + * + * @return whether this ChatColor is a format code + */ + public boolean isFormat() { + return isFormat; + } - /** - * Checks if this code is a color code as opposed to a format code. - * - * @return whether this ChatColor is a color code - */ - public boolean isColor() - { - return !isFormat && this != RESET; - } + /** + * Checks if this code is a color code as opposed to a format code. + * + * @return whether this ChatColor is a color code + */ + public boolean isColor() { + return !isFormat && this != RESET; + } - /** - * Gets the color represented by the specified color code - * - * @param code - * Code to check - * @return Associative {@link org.bukkit.ChatColor} with the given code, or null - * if it doesn't exist - */ - public static C getByChar(char code) - { - try - { - return BY_CHAR.get(code); - } + /** + * Gets the color represented by the specified color code + * + * @param code Code to check + * @return Associative {@link org.bukkit.ChatColor} with the given code, or null + * if it doesn't exist + */ + public static C getByChar(char code) { + try { + return BY_CHAR.get(code); + } catch (Exception e) { + return C.WHITE; + } + } - catch(Exception e) - { - return C.WHITE; - } - } + /** + * Gets the color represented by the specified color code + * + * @param code Code to check + * @return Associative {@link org.bukkit.ChatColor} with the given code, or null + * if it doesn't exist + */ + public static C getByChar(String code) { + try { + Validate.notNull(code, "Code cannot be null"); + Validate.isTrue(code.length() > 0, "Code must have at least one char"); - /** - * Gets the color represented by the specified color code - * - * @param code - * Code to check - * @return Associative {@link org.bukkit.ChatColor} with the given code, or null - * if it doesn't exist - */ - public static C getByChar(String code) - { - try - { - Validate.notNull(code, "Code cannot be null"); - Validate.isTrue(code.length() > 0, "Code must have at least one char"); + return BY_CHAR.get(code.charAt(0)); + } catch (Exception e) { + return C.WHITE; + } + } - return BY_CHAR.get(code.charAt(0)); - } + /** + * Strips the given message of all color codes + * + * @param input String to strip of color + * @return A copy of the input string, without any coloring + */ + public static String stripColor(final String input) { + if (input == null) { + return null; + } - catch(Exception e) - { - return C.WHITE; - } - } + return STRIP_COLOR_PATTERN.matcher(input).replaceAll(""); + } - /** - * Strips the given message of all color codes - * - * @param input - * String to strip of color - * @return A copy of the input string, without any coloring - */ - public static String stripColor(final String input) - { - if(input == null) - { - return null; - } + /** + * DyeColor to ChatColor + * + * @param dclr the dye color + * @return the color + */ + public static C dyeToChat(DyeColor dclr) { + if (dyeChatMap.containsKey(dclr)) { + return dyeChatMap.get(dclr); + } - return STRIP_COLOR_PATTERN.matcher(input).replaceAll(""); - } + return C.MAGIC; + } - /** - * DyeColor to ChatColor - * - * @param dclr - * the dye color - * @return the color - */ - public static C dyeToChat(DyeColor dclr) - { - if(dyeChatMap.containsKey(dclr)) - { - return dyeChatMap.get(dclr); - } + public static DyeColor chatToDye(ChatColor color) { + for (DyeColor i : dyeChatMap.keySet()) { + if (dyeChatMap.get(i).toString().equals(color.toString())) { + return i; + } + } - return C.MAGIC; - } + return DyeColor.BLACK; + } - public static DyeColor chatToDye(ChatColor color) - { - for(DyeColor i : dyeChatMap.keySet()) - { - if(dyeChatMap.get(i).toString().equals(color.toString())) - { - return i; - } - } + @SuppressWarnings("unlikely-arg-type") + public static String chatToHex(ChatColor clr) { + if (chatHexMap.containsKey(clr)) { + return chatHexMap.get(clr); + } - return DyeColor.BLACK; - } + return "#000"; + } - @SuppressWarnings("unlikely-arg-type") - public static String chatToHex(ChatColor clr) - { - if(chatHexMap.containsKey(clr)) - { - return chatHexMap.get(clr); - } + public static String dyeToHex(DyeColor clr) { + if (dyeHexMap.containsKey(clr)) { + return dyeHexMap.get(clr); + } - return "#000"; - } + return "#000"; + } - public static String dyeToHex(DyeColor clr) - { - if(dyeHexMap.containsKey(clr)) - { - return dyeHexMap.get(clr); - } + public static Color hexToColor(String hex) { + if (hex.startsWith("#")) { + hex = hex.substring(1); + } - return "#000"; - } + if (hex.indexOf("x") != -1) { + hex = hex.substring(hex.indexOf("x")); + } - public static Color hexToColor(String hex) - { - if(hex.startsWith("#")) - { - hex = hex.substring(1); - } + if (hex.length() != 6 && hex.length() != 3) { + return null; + } + int sz = hex.length() / 3, mult = 1 << ((2 - sz) * 4), x = 0; - if(hex.indexOf("x") != -1) - { - hex = hex.substring(hex.indexOf("x")); - } + for (int i = 0, z = 0; z < hex.length(); ++i, z += sz) { + x |= (mult * Integer.parseInt(hex.substring(z, z + sz), 16)) << (i * 8); + } - if(hex.length() != 6 && hex.length() != 3) - { - return null; - } - int sz = hex.length() / 3, mult = 1 << ((2 - sz) * 4), x = 0; + return Color.fromBGR(x & 0xffffff); + } - for(int i = 0, z = 0; z < hex.length(); ++i, z += sz) - { - x |= (mult * Integer.parseInt(hex.substring(z, z + sz), 16)) << (i * 8); - } + public static Color rgbToColor(String rgb) { + String[] parts = rgb.split("[^0-9]+"); + if (parts.length < 3) { + return null; + } - return Color.fromBGR(x & 0xffffff); - } + int x = 0, i; - public static Color rgbToColor(String rgb) - { - String parts[] = rgb.split("[^0-9]+"); - if(parts.length < 3) - { - return null; - } + for (i = 0; i < 3; ++i) { + x |= Integer.parseInt(parts[i]) << (i * 8); + } - int x = 0, i; + return Color.fromBGR(x & 0xffffff); + } - for(i = 0; i < 3; ++i) - { - x |= Integer.parseInt(parts[i]) << (i * 8); - } + public static String generateColorTable() { + StringBuilder str = new StringBuilder(); - return Color.fromBGR(x & 0xffffff); - } + str.append(""); - public static String generateColorTable() - { - StringBuilder str = new StringBuilder(); + for (Map.Entry e : chatHexMap.entrySet()) { + str.append(String.format("" + "", e.getKey().name(), e.getValue())); + } - str.append("
Chat ColorColor
%1$sTest String
"); + str.append("
Chat ColorColor
"); + str.append(""); + for (Map.Entry e : dyeHexMap.entrySet()) { + str.append(String.format("" + "", e.getKey().name(), e.getValue())); + } - for(Map.Entry e : chatHexMap.entrySet()) - { - str.append(String.format("" + "", e.getKey().name(), e.getValue())); - } + str.append("
Dye ColorColor
%1$sTest String
%1$sTest String
"); - str.append(""); - str.append(""); - for(Map.Entry e : dyeHexMap.entrySet()) - { - str.append(String.format("" + "", e.getKey().name(), e.getValue())); - } + return str.toString(); + } - str.append("
Dye ColorColor
%1$sTest String
"); + /** + * Get the ChatColor enum instance instead of C + * + * @return + */ + public ChatColor chatColor() { + return ChatColor.getByChar(code); + } - return str.toString(); - } + /** + * Translates a string using an alternate color code character into a string + * that uses the internal ChatColor.COLOR_CODE color code character. The + * alternate color code character will only be replaced if it is immediately + * followed by 0-9, A-F, a-f, K-O, k-o, R or r. + * + * @param altColorChar The alternate color code character to replace. Ex: {@literal &} + * @param textToTranslate Text containing the alternate color code character. + * @return Text containing the ChatColor.COLOR_CODE color code character. + */ + public static String translateAlternateColorCodes(char altColorChar, String textToTranslate) { + if (textToTranslate == null) { + return null; + } - /** - * Get the ChatColor enum instance instead of C - * - * @return - */ - public ChatColor chatColor() - { - return ChatColor.getByChar(code); - } + char[] b = textToTranslate.toCharArray(); + for (int i = 0; i < b.length - 1; i++) { + if (b[i] == altColorChar && "0123456789AaBbCcDdEeFfKkLlMmNnOoRr".indexOf(b[i + 1]) > -1) { + b[i] = C.COLOR_CHAR; + b[i + 1] = Character.toLowerCase(b[i + 1]); + } + } + return new String(b); + } - /** - * Translates a string using an alternate color code character into a string - * that uses the internal ChatColor.COLOR_CODE color code character. The - * alternate color code character will only be replaced if it is immediately - * followed by 0-9, A-F, a-f, K-O, k-o, R or r. - * - * @param altColorChar - * The alternate color code character to replace. Ex: {@literal &} - * @param textToTranslate - * Text containing the alternate color code character. - * @return Text containing the ChatColor.COLOR_CODE color code character. - */ - public static String translateAlternateColorCodes(char altColorChar, String textToTranslate) - { - if(textToTranslate == null) - { - return null; - } + public static C fromItemMeta(byte c) { + for (C i : C.values()) { + if (i.getItemMeta() == c) { + return i; + } + } - char[] b = textToTranslate.toCharArray(); - for(int i = 0; i < b.length - 1; i++) - { - if(b[i] == altColorChar && "0123456789AaBbCcDdEeFfKkLlMmNnOoRr".indexOf(b[i + 1]) > -1) - { - b[i] = C.COLOR_CHAR; - b[i + 1] = Character.toLowerCase(b[i + 1]); - } - } - return new String(b); - } + return null; + } - public static C fromItemMeta(byte c) - { - for(C i : C.values()) - { - if(i.getItemMeta() == c) - { - return i; - } - } + public byte getMeta() { + switch (this) { + case AQUA: + return 11; + case BLACK: + return 0; + case BLUE: + return 9; + case BOLD: + return -1; + case DARK_AQUA: + return 9; + case DARK_BLUE: + return 1; + case DARK_GRAY: + return 8; + case DARK_GREEN: + return 2; + case DARK_PURPLE: + return 5; + case DARK_RED: + return 4; + case GOLD: + return 6; + case GRAY: + return 7; + case GREEN: + return 10; + case ITALIC: + return -1; + case LIGHT_PURPLE: + return 13; + case MAGIC: + return -1; + case RED: + return 12; + case RESET: + return -1; + case STRIKETHROUGH: + return -1; + case UNDERLINE: + return -1; + case WHITE: + return 15; + case YELLOW: + return 14; + default: + return -1; + } + } - return null; - } + public byte getItemMeta() { + switch (this) { + case AQUA: + return 9; + case BLACK: + return 15; + case BLUE: + return 3; + case BOLD: + return -1; + case DARK_AQUA: + return 9; + case DARK_BLUE: + return 11; + case DARK_GRAY: + return 7; + case DARK_GREEN: + return 13; + case DARK_PURPLE: + return 10; + case DARK_RED: + return 14; + case GOLD: + return 4; + case GRAY: + return 8; + case GREEN: + return 5; + case ITALIC: + return -1; + case LIGHT_PURPLE: + return 2; + case MAGIC: + return -1; + case RED: + return 14; + case RESET: + return -1; + case STRIKETHROUGH: + return -1; + case UNDERLINE: + return -1; + case WHITE: + return 0; + case YELLOW: + return 4; + default: + return -1; + } + } - public byte getMeta() - { - switch(this) - { - case AQUA: - return 11; - case BLACK: - return 0; - case BLUE: - return 9; - case BOLD: - return -1; - case DARK_AQUA: - return 9; - case DARK_BLUE: - return 1; - case DARK_GRAY: - return 8; - case DARK_GREEN: - return 2; - case DARK_PURPLE: - return 5; - case DARK_RED: - return 4; - case GOLD: - return 6; - case GRAY: - return 7; - case GREEN: - return 10; - case ITALIC: - return -1; - case LIGHT_PURPLE: - return 13; - case MAGIC: - return -1; - case RED: - return 12; - case RESET: - return -1; - case STRIKETHROUGH: - return -1; - case UNDERLINE: - return -1; - case WHITE: - return 15; - case YELLOW: - return 14; - default: - return -1; - } - } + public static C randomColor() { + return COLORS[(int) (Math.random() * (COLORS.length - 1))]; + } - public byte getItemMeta() - { - switch(this) - { - case AQUA: - return 9; - case BLACK: - return 15; - case BLUE: - return 3; - case BOLD: - return -1; - case DARK_AQUA: - return 9; - case DARK_BLUE: - return 11; - case DARK_GRAY: - return 7; - case DARK_GREEN: - return 13; - case DARK_PURPLE: - return 10; - case DARK_RED: - return 14; - case GOLD: - return 4; - case GRAY: - return 8; - case GREEN: - return 5; - case ITALIC: - return -1; - case LIGHT_PURPLE: - return 2; - case MAGIC: - return -1; - case RED: - return 14; - case RESET: - return -1; - case STRIKETHROUGH: - return -1; - case UNDERLINE: - return -1; - case WHITE: - return 0; - case YELLOW: - return 4; - default: - return -1; - } - } + /** + * Gets the ChatColors used at the end of the given input string. + * + * @param input Input string to retrieve the colors from. + * @return Any remaining ChatColors to pass onto the next line. + */ + public static String getLastColors(String input) { + String result = ""; + int length = input.length(); - public static C randomColor() - { - return COLORS[(int) (Math.random() * (COLORS.length - 1))]; - } + // Search backwards from the end as it is faster + for (int index = length - 1; index > -1; index--) { + char section = input.charAt(index); + if (section == COLOR_CHAR && index < length - 1) { + char c = input.charAt(index + 1); + C color = getByChar(c); - /** - * Gets the ChatColors used at the end of the given input string. - * - * @param input - * Input string to retrieve the colors from. - * @return Any remaining ChatColors to pass onto the next line. - */ - public static String getLastColors(String input) - { - String result = ""; - int length = input.length(); + if (color != null) { + result = color + result; - // Search backwards from the end as it is faster - for(int index = length - 1; index > -1; index--) - { - char section = input.charAt(index); - if(section == COLOR_CHAR && index < length - 1) - { - char c = input.charAt(index + 1); - C color = getByChar(c); + // Once we find a color or reset we can stop searching + if (color.isColor() || color.equals(RESET)) { + break; + } + } + } + } - if(color != null) - { - result = color.toString() + result; + return result; + } - // Once we find a color or reset we can stop searching - if(color.isColor() || color.equals(RESET)) - { - break; - } - } - } - } - - return result; - } - - static - { - for(C color : values()) - { - BY_ID.put(color.intCode, color); - BY_CHAR.put(color.code, color); - } - } + static { + for (C color : values()) { + BY_ID.put(color.intCode, color); + BY_CHAR.put(color.code, color); + } + } } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/CDou.java b/src/main/java/com/volmit/iris/util/CDou.java index 7d59125b5..5b807e726 100644 --- a/src/main/java/com/volmit/iris/util/CDou.java +++ b/src/main/java/com/volmit/iris/util/CDou.java @@ -1,49 +1,41 @@ package com.volmit.iris.util; -public class CDou -{ - private double number; - private double max; - - public CDou(double max) - { - number = 0; - this.max = max; - } - - public CDou set(double n) - { - number = n; - circ(); - return this; - } - - public CDou add(double a) - { - number += a; - circ(); - return this; - } - - public CDou sub(double a) - { - number -= a; - circ(); - return this; - } - - public double get() - { - return number; - } - - public void circ() - { - if(number < 0) - { - number = max - (Math.abs(number) > max ? max : Math.abs(number)); - } - - number = number % (max); - } +public class CDou { + private double number; + private final double max; + + public CDou(double max) { + number = 0; + this.max = max; + } + + public CDou set(double n) { + number = n; + circ(); + return this; + } + + public CDou add(double a) { + number += a; + circ(); + return this; + } + + public CDou sub(double a) { + number -= a; + circ(); + return this; + } + + public double get() { + return number; + } + + public void circ() { + if (number < 0) { + number = max - (Math.abs(number) > max ? max : Math.abs(number)); + } + + number = number % (max); + } } diff --git a/src/main/java/com/volmit/iris/util/Callback.java b/src/main/java/com/volmit/iris/util/Callback.java index b4b0b3bfb..9e19acd3b 100644 --- a/src/main/java/com/volmit/iris/util/Callback.java +++ b/src/main/java/com/volmit/iris/util/Callback.java @@ -3,19 +3,15 @@ package com.volmit.iris.util; /** * Callback for async workers * + * @param the type of object to be returned in the runnable * @author cyberpwn - * - * @param - * the type of object to be returned in the runnable */ @FunctionalInterface -public interface Callback -{ - /** - * Called when the callback calls back... - * - * @param t - * the object to be called back - */ - public void run(T t); +public interface Callback { + /** + * Called when the callback calls back... + * + * @param t the object to be called back + */ + void run(T t); } diff --git a/src/main/java/com/volmit/iris/util/CallbackCV.java b/src/main/java/com/volmit/iris/util/CallbackCV.java index 885cf7e8a..3cd8add39 100644 --- a/src/main/java/com/volmit/iris/util/CallbackCV.java +++ b/src/main/java/com/volmit/iris/util/CallbackCV.java @@ -1,6 +1,5 @@ package com.volmit.iris.util; -public interface CallbackCV -{ - public void run(T t); +public interface CallbackCV { + void run(T t); } diff --git a/src/main/java/com/volmit/iris/util/CancellableTask.java b/src/main/java/com/volmit/iris/util/CancellableTask.java index 33c37a2f1..b1e4ef735 100644 --- a/src/main/java/com/volmit/iris/util/CancellableTask.java +++ b/src/main/java/com/volmit/iris/util/CancellableTask.java @@ -1,6 +1,5 @@ package com.volmit.iris.util; -public interface CancellableTask -{ - public void cancel(); +public interface CancellableTask { + void cancel(); } diff --git a/src/main/java/com/volmit/iris/util/CarveResult.java b/src/main/java/com/volmit/iris/util/CarveResult.java index d31defb7e..246ae5c7a 100644 --- a/src/main/java/com/volmit/iris/util/CarveResult.java +++ b/src/main/java/com/volmit/iris/util/CarveResult.java @@ -3,13 +3,11 @@ package com.volmit.iris.util; import lombok.Value; @Value -public class CarveResult -{ - private final int surface; - private final int ceiling; - - public int getHeight() - { - return ceiling - surface; - } +public class CarveResult { + private final int surface; + private final int ceiling; + + public int getHeight() { + return ceiling - surface; + } } diff --git a/src/main/java/com/volmit/iris/util/CaveResult.java b/src/main/java/com/volmit/iris/util/CaveResult.java index 0ebf0f201..8dc21145c 100644 --- a/src/main/java/com/volmit/iris/util/CaveResult.java +++ b/src/main/java/com/volmit/iris/util/CaveResult.java @@ -3,19 +3,16 @@ package com.volmit.iris.util; import lombok.Data; @Data -public class CaveResult -{ - private int floor; - private int ceiling; +public class CaveResult { + private int floor; + private int ceiling; - public CaveResult(int floor, int ceiling) - { - this.floor = floor; - this.ceiling = ceiling; - } + public CaveResult(int floor, int ceiling) { + this.floor = floor; + this.ceiling = ceiling; + } - public boolean isWithin(int v) - { - return v > floor || v < ceiling; - } + public boolean isWithin(int v) { + return v > floor || v < ceiling; + } } diff --git a/src/main/java/com/volmit/iris/util/ChronoLatch.java b/src/main/java/com/volmit/iris/util/ChronoLatch.java index 791bdc6d4..e2df10015 100644 --- a/src/main/java/com/volmit/iris/util/ChronoLatch.java +++ b/src/main/java/com/volmit/iris/util/ChronoLatch.java @@ -1,39 +1,32 @@ package com.volmit.iris.util; -public class ChronoLatch -{ - private long interval; - private long since; +public class ChronoLatch { + private final long interval; + private long since; - public ChronoLatch(long interval, boolean openedAtStart) - { - this.interval = interval; - since = System.currentTimeMillis() - (openedAtStart ? interval * 2 : 0); - } + public ChronoLatch(long interval, boolean openedAtStart) { + this.interval = interval; + since = System.currentTimeMillis() - (openedAtStart ? interval * 2 : 0); + } - public ChronoLatch(long interval) - { - this(interval, true); - } + public ChronoLatch(long interval) { + this(interval, true); + } - public void flipDown() - { - since = System.currentTimeMillis(); - } + public void flipDown() { + since = System.currentTimeMillis(); + } - public boolean couldFlip() - { - return System.currentTimeMillis() - since > interval; - } + public boolean couldFlip() { + return System.currentTimeMillis() - since > interval; + } - public boolean flip() - { - if(System.currentTimeMillis() - since > interval) - { - since = System.currentTimeMillis(); - return true; - } + public boolean flip() { + if (System.currentTimeMillis() - since > interval) { + since = System.currentTimeMillis(); + return true; + } - return false; - } + return false; + } } diff --git a/src/main/java/com/volmit/iris/util/ChunkPosition.java b/src/main/java/com/volmit/iris/util/ChunkPosition.java index 45aed4ca7..9463244f7 100644 --- a/src/main/java/com/volmit/iris/util/ChunkPosition.java +++ b/src/main/java/com/volmit/iris/util/ChunkPosition.java @@ -1,63 +1,52 @@ package com.volmit.iris.util; -public class ChunkPosition -{ - private int x; - private int z; +public class ChunkPosition { + private int x; + private int z; - public ChunkPosition(int x, int z) - { - this.x = x; - this.z = z; - } + public ChunkPosition(int x, int z) { + this.x = x; + this.z = z; + } - public int getX() - { - return x; - } + public int getX() { + return x; + } - public void setX(int x) - { - this.x = x; - } + public void setX(int x) { + this.x = x; + } - public int getZ() - { - return z; - } + public int getZ() { + return z; + } - public void setZ(int z) - { - this.z = z; - } + public void setZ(int z) { + this.z = z; + } - @Override - public int hashCode() - { - final int prime = 31; - int result = 1; - result = prime * result + x; - result = prime * result + z; - return result; - } + @Override + public int hashCode() { + final int prime = 31; + int result = 1; + result = prime * result + x; + result = prime * result + z; + return result; + } - @Override - public boolean equals(Object obj) - { - if(this == obj) - { - return true; - } - if(!(obj instanceof ChunkPosition)) - { - return false; - } - ChunkPosition other = (ChunkPosition) obj; - return x == other.x && z == other.z; - } + @Override + public boolean equals(Object obj) { + if (this == obj) { + return true; + } + if (!(obj instanceof ChunkPosition)) { + return false; + } + ChunkPosition other = (ChunkPosition) obj; + return x == other.x && z == other.z; + } - public double distance(ChunkPosition center) - { - return Math.pow(center.getX() - x, 2) + Math.pow(center.getZ() - z, 2); + public double distance(ChunkPosition center) { + return Math.pow(center.getX() - x, 2) + Math.pow(center.getZ() - z, 2); } } diff --git a/src/main/java/com/volmit/iris/util/Chunker.java b/src/main/java/com/volmit/iris/util/Chunker.java index fc697b048..1b06fdebd 100644 --- a/src/main/java/com/volmit/iris/util/Chunker.java +++ b/src/main/java/com/volmit/iris/util/Chunker.java @@ -5,53 +5,47 @@ import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; -public class Chunker -{ - private ExecutorService executor; - private int threads; - private int workload; - private KList q; +public class Chunker { + private ExecutorService executor; + private int threads; + private int workload; + private final KList q; - public Chunker(KList q) - { - this.q = q; - } + public Chunker(KList q) { + this.q = q; + } - public Chunker threads(int threads) - { - this.threads = threads; - return this; - } + public Chunker threads(int threads) { + this.threads = threads; + return this; + } - public Chunker workload(int workload) - { - this.workload = workload; - return this; - } + public Chunker workload(int workload) { + this.workload = workload; + return this; + } - public void execute(Consumer consumer, Callback progress, int progressInterval) - { - ChronoLatch cl = new ChronoLatch(progressInterval); - Contained consumed = new Contained(0); - executor = Executors.newFixedThreadPool(threads); - int length = q.size(); - int remaining = length; + public void execute(Consumer consumer, Callback progress, int progressInterval) { + ChronoLatch cl = new ChronoLatch(progressInterval); + Contained consumed = new Contained(0); + executor = Executors.newFixedThreadPool(threads); + int length = q.size(); + int remaining = length; - while(remaining > 0) - { - int at = remaining; - remaining -= (remaining > workload ? workload : remaining); - int to = remaining; + while (remaining > 0) { + int at = remaining; + remaining -= (remaining > workload ? workload : remaining); + int to = remaining; - executor.submit(() -> - { - J.dofor(at, (i) -> i >= to, -1, (i) -> J.attempt(() -> consumer.accept(q.get(i)))); - consumed.mod((c) -> c += workload); - J.doif(() -> progress != null && cl.flip(), () -> progress.run((double) consumed.get() / (double) length)); - }); - } + executor.submit(() -> + { + J.dofor(at, (i) -> i >= to, -1, (i) -> J.attempt(() -> consumer.accept(q.get(i)))); + consumed.mod((c) -> c += workload); + J.doif(() -> progress != null && cl.flip(), () -> progress.run((double) consumed.get() / (double) length)); + }); + } - executor.shutdown(); - J.attempt(() -> executor.awaitTermination(100, TimeUnit.HOURS)); - } + executor.shutdown(); + J.attempt(() -> executor.awaitTermination(100, TimeUnit.HOURS)); + } } diff --git a/src/main/java/com/volmit/iris/util/Command.java b/src/main/java/com/volmit/iris/util/Command.java index 63d8177f7..91c1c4dff 100644 --- a/src/main/java/com/volmit/iris/util/Command.java +++ b/src/main/java/com/volmit/iris/util/Command.java @@ -1,14 +1,13 @@ package com.volmit.iris.util; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - 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 Command -{ - String value() default ""; +public @interface Command { + String value() default ""; } diff --git a/src/main/java/com/volmit/iris/util/CompoundTag.java b/src/main/java/com/volmit/iris/util/CompoundTag.java index c1802e9c3..7d73e5a92 100644 --- a/src/main/java/com/volmit/iris/util/CompoundTag.java +++ b/src/main/java/com/volmit/iris/util/CompoundTag.java @@ -6,53 +6,44 @@ import java.util.Map; * The TAG_Compound tag. * * @author Graham Edgecombe - * */ -public final class CompoundTag extends Tag -{ +public final class CompoundTag extends Tag { - /** - * The value. - */ - private final Map value; + /** + * The value. + */ + private final Map value; - /** - * Creates the tag. - * - * @param name - * The name. - * @param value - * The value. - */ - public CompoundTag(String name, Map value) - { - super(name); - this.value = value; - } + /** + * Creates the tag. + * + * @param name The name. + * @param value The value. + */ + public CompoundTag(String name, Map value) { + super(name); + this.value = value; + } - @Override - public Map getValue() - { - return value; - } + @Override + public Map getValue() { + return value; + } - @Override - public String toString() - { - String name = getName(); - String append = ""; - if(name != null && !name.equals("")) - { - append = "(\"" + this.getName() + "\")"; - } - StringBuilder bldr = new StringBuilder(); - bldr.append("TAG_Compound" + append + ": " + value.size() + " entries\r\n{\r\n"); - for(Map.Entry entry : value.entrySet()) - { - bldr.append(" " + entry.getValue().toString().replaceAll("\r\n", "\r\n ") + "\r\n"); - } - bldr.append("}"); - return bldr.toString(); - } + @Override + public String toString() { + String name = getName(); + String append = ""; + if (name != null && !name.equals("")) { + append = "(\"" + this.getName() + "\")"; + } + StringBuilder bldr = new StringBuilder(); + bldr.append("TAG_Compound" + append + ": " + value.size() + " entries\r\n{\r\n"); + for (Map.Entry entry : value.entrySet()) { + bldr.append(" " + entry.getValue().toString().replaceAll("\r\n", "\r\n ") + "\r\n"); + } + bldr.append("}"); + return bldr.toString(); + } } diff --git a/src/main/java/com/volmit/iris/util/Consumer2.java b/src/main/java/com/volmit/iris/util/Consumer2.java index 541c72d98..67a5c81a8 100644 --- a/src/main/java/com/volmit/iris/util/Consumer2.java +++ b/src/main/java/com/volmit/iris/util/Consumer2.java @@ -2,7 +2,6 @@ package com.volmit.iris.util; @SuppressWarnings("hiding") @FunctionalInterface -public interface Consumer2 -{ - public void accept(A a, B b); +public interface Consumer2 { + void accept(A a, B b); } diff --git a/src/main/java/com/volmit/iris/util/Consumer3.java b/src/main/java/com/volmit/iris/util/Consumer3.java index 0df001b3e..2e0d90ee0 100644 --- a/src/main/java/com/volmit/iris/util/Consumer3.java +++ b/src/main/java/com/volmit/iris/util/Consumer3.java @@ -2,7 +2,6 @@ package com.volmit.iris.util; @SuppressWarnings("hiding") @FunctionalInterface -public interface Consumer3 -{ - public void accept(A a, B b, C c); +public interface Consumer3 { + void accept(A a, B b, C c); } diff --git a/src/main/java/com/volmit/iris/util/Consumer4.java b/src/main/java/com/volmit/iris/util/Consumer4.java index 4520cd93e..38fcb5cd1 100644 --- a/src/main/java/com/volmit/iris/util/Consumer4.java +++ b/src/main/java/com/volmit/iris/util/Consumer4.java @@ -2,7 +2,6 @@ package com.volmit.iris.util; @SuppressWarnings("hiding") @FunctionalInterface -public interface Consumer4 -{ - public void accept(A a, B b, C c, D d); +public interface Consumer4 { + void accept(A a, B b, C c, D d); } diff --git a/src/main/java/com/volmit/iris/util/Consumer5.java b/src/main/java/com/volmit/iris/util/Consumer5.java index 66c9154ec..393d0216b 100644 --- a/src/main/java/com/volmit/iris/util/Consumer5.java +++ b/src/main/java/com/volmit/iris/util/Consumer5.java @@ -2,7 +2,6 @@ package com.volmit.iris.util; @SuppressWarnings("hiding") @FunctionalInterface -public interface Consumer5 -{ - public void accept(A a, B b, C c, D d, E e); +public interface Consumer5 { + void accept(A a, B b, C c, D d, E e); } diff --git a/src/main/java/com/volmit/iris/util/Consumer6.java b/src/main/java/com/volmit/iris/util/Consumer6.java index 4404f8f54..e833f2244 100644 --- a/src/main/java/com/volmit/iris/util/Consumer6.java +++ b/src/main/java/com/volmit/iris/util/Consumer6.java @@ -2,7 +2,6 @@ package com.volmit.iris.util; @SuppressWarnings("hiding") @FunctionalInterface -public interface Consumer6 -{ - public void accept(A a, B b, C c, D d, E e, F f); +public interface Consumer6 { + void accept(A a, B b, C c, D d, E e, F f); } diff --git a/src/main/java/com/volmit/iris/util/Consumer7.java b/src/main/java/com/volmit/iris/util/Consumer7.java index a0af81d86..36cfcf4aa 100644 --- a/src/main/java/com/volmit/iris/util/Consumer7.java +++ b/src/main/java/com/volmit/iris/util/Consumer7.java @@ -2,7 +2,6 @@ package com.volmit.iris.util; @SuppressWarnings("hiding") @FunctionalInterface -public interface Consumer7 -{ - public void accept(A a, B b, C c, D d, E e, F f, G g); +public interface Consumer7 { + void accept(A a, B b, C c, D d, E e, F f, G g); } diff --git a/src/main/java/com/volmit/iris/util/Consumer8.java b/src/main/java/com/volmit/iris/util/Consumer8.java index 43d124a61..03d5081c0 100644 --- a/src/main/java/com/volmit/iris/util/Consumer8.java +++ b/src/main/java/com/volmit/iris/util/Consumer8.java @@ -2,7 +2,6 @@ package com.volmit.iris.util; @SuppressWarnings("hiding") @FunctionalInterface -public interface Consumer8 -{ - public void accept(A a, B b, C c, D d, E e, F f, G g, H h); +public interface Consumer8 { + void accept(A a, B b, C c, D d, E e, F f, G g, H h); } diff --git a/src/main/java/com/volmit/iris/util/Contained.java b/src/main/java/com/volmit/iris/util/Contained.java index ec5b93724..928b7b0fc 100644 --- a/src/main/java/com/volmit/iris/util/Contained.java +++ b/src/main/java/com/volmit/iris/util/Contained.java @@ -2,32 +2,26 @@ package com.volmit.iris.util; import java.util.function.Function; -public class Contained -{ - private T t; +public class Contained { + private T t; - public Contained(T t) - { - set(t); - } + public Contained(T t) { + set(t); + } - public Contained() - { - this(null); - } - - public void mod(Function x) - { - set(x.apply(t)); - } + public Contained() { + this(null); + } - public T get() - { - return t; - } + public void mod(Function x) { + set(x.apply(t)); + } - public void set(T t) - { - this.t = t; - } + public T get() { + return t; + } + + public void set(T t) { + this.t = t; + } } diff --git a/src/main/java/com/volmit/iris/util/Control.java b/src/main/java/com/volmit/iris/util/Control.java index 352f43bd0..fc0df07b9 100644 --- a/src/main/java/com/volmit/iris/util/Control.java +++ b/src/main/java/com/volmit/iris/util/Control.java @@ -1,14 +1,13 @@ package com.volmit.iris.util; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - 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 Control -{ +public @interface Control { } diff --git a/src/main/java/com/volmit/iris/util/Controller.java b/src/main/java/com/volmit/iris/util/Controller.java index e9cedf1b9..dcea5c940 100644 --- a/src/main/java/com/volmit/iris/util/Controller.java +++ b/src/main/java/com/volmit/iris/util/Controller.java @@ -2,69 +2,59 @@ package com.volmit.iris.util; import com.volmit.iris.Iris; -public abstract class Controller implements IController -{ - private int tickRate; - private String name; +public abstract class Controller implements IController { + private int tickRate; + private final String name; - public Controller() - { - name = getClass().getSimpleName().replaceAll("Controller", "") + " Controller"; - tickRate = -1; - } + public Controller() { + name = getClass().getSimpleName().replaceAll("Controller", "") + " Controller"; + tickRate = -1; + } - protected void setTickRate(int rate) - { - this.tickRate = rate; - } + protected void setTickRate(int rate) { + this.tickRate = rate; + } - protected void disableTicking() - { - setTickRate(-1); - } + protected void disableTicking() { + setTickRate(-1); + } - @Override - public void l(Object l) - { - Iris.info("[" + getName() + "]: " + l); - } + @Override + public void l(Object l) { + Iris.info("[" + getName() + "]: " + l); + } - @Override - public void w(Object l) - { - Iris.warn("[" + getName() + "]: " + l); - } + @Override + public void w(Object l) { + Iris.warn("[" + getName() + "]: " + l); + } - @Override - public void f(Object l) - { - Iris.error("[" + getName() + "]: " + l); - } + @Override + public void f(Object l) { + Iris.error("[" + getName() + "]: " + l); + } - @Override - public void v(Object l) - { - Iris.verbose("[" + getName() + "]: " + l); - } + @Override + public void v(Object l) { + Iris.verbose("[" + getName() + "]: " + l); + } - @Override - public String getName() - { - return name; - } + @Override + public String getName() { + return name; + } - @Override - public abstract void start(); + @Override + public abstract void start(); - @Override - public abstract void stop(); + @Override + public abstract void stop(); - @Override - public abstract void tick(); + @Override + public abstract void tick(); - @Override - public int getTickInterval() - { - return tickRate; - } + @Override + public int getTickInterval() { + return tickRate; + } } diff --git a/src/main/java/com/volmit/iris/util/Converter.java b/src/main/java/com/volmit/iris/util/Converter.java index b89addd4e..e753d16ee 100644 --- a/src/main/java/com/volmit/iris/util/Converter.java +++ b/src/main/java/com/volmit/iris/util/Converter.java @@ -2,11 +2,10 @@ package com.volmit.iris.util; import java.io.File; -public interface Converter -{ - public String getInExtension(); +public interface Converter { + String getInExtension(); - public String getOutExtension(); + String getOutExtension(); - public void convert(File in, File out); + void convert(File in, File out); } diff --git a/src/main/java/com/volmit/iris/util/Cuboid.java b/src/main/java/com/volmit/iris/util/Cuboid.java index 7d74db104..be75777a7 100644 --- a/src/main/java/com/volmit/iris/util/Cuboid.java +++ b/src/main/java/com/volmit/iris/util/Cuboid.java @@ -1,882 +1,754 @@ package com.volmit.iris.util; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import org.bukkit.Bukkit; -import org.bukkit.Chunk; -import org.bukkit.Location; -import org.bukkit.Material; -import org.bukkit.World; +import org.bukkit.*; import org.bukkit.block.Block; import org.bukkit.configuration.serialization.ConfigurationSerializable; import org.bukkit.entity.Entity; +import java.util.*; + /** * Cuboids * * @author cyberpwn */ -public class Cuboid implements Iterable, Cloneable, ConfigurationSerializable -{ - protected final String worldName; - protected int x1, y1, z1; - protected int x2, y2, z2; +public class Cuboid implements Iterable, Cloneable, ConfigurationSerializable { + protected final String worldName; + protected int x1, y1, z1; + protected int x2, y2, z2; - /** - * Construct a Cuboid given two Location objects which represent any two corners - * of the Cuboid. - * - * @param l1 - * one of the corners - * @param l2 - * the other corner - */ - public Cuboid(Location l1, Location l2) - { - if(!l1.getWorld().equals(l2.getWorld())) - { - throw new IllegalArgumentException("locations must be on the same world"); - } + /** + * Construct a Cuboid given two Location objects which represent any two corners + * of the Cuboid. + * + * @param l1 one of the corners + * @param l2 the other corner + */ + public Cuboid(Location l1, Location l2) { + if (!l1.getWorld().equals(l2.getWorld())) { + throw new IllegalArgumentException("locations must be on the same world"); + } - worldName = l1.getWorld().getName(); - x1 = Math.min(l1.getBlockX(), l2.getBlockX()); - y1 = Math.min(l1.getBlockY(), l2.getBlockY()); - z1 = Math.min(l1.getBlockZ(), l2.getBlockZ()); - x2 = Math.max(l1.getBlockX(), l2.getBlockX()); - y2 = Math.max(l1.getBlockY(), l2.getBlockY()); - z2 = Math.max(l1.getBlockZ(), l2.getBlockZ()); - } + worldName = l1.getWorld().getName(); + x1 = Math.min(l1.getBlockX(), l2.getBlockX()); + y1 = Math.min(l1.getBlockY(), l2.getBlockY()); + z1 = Math.min(l1.getBlockZ(), l2.getBlockZ()); + x2 = Math.max(l1.getBlockX(), l2.getBlockX()); + y2 = Math.max(l1.getBlockY(), l2.getBlockY()); + z2 = Math.max(l1.getBlockZ(), l2.getBlockZ()); + } - public KList getEntities() - { - KList en = new KList(); + public KList getEntities() { + KList en = new KList(); - for(Chunk i : getChunks()) - { - for(Entity j : i.getEntities()) - { - if(contains(j.getLocation())) - { - en.add(j); - } - } - } + for (Chunk i : getChunks()) { + for (Entity j : i.getEntities()) { + if (contains(j.getLocation())) { + en.add(j); + } + } + } - return en; - } + return en; + } - /** - * Set the locations - * - * @param l1 - * a - * @param l2 - * b - */ - public void set(Location l1, Location l2) - { - x1 = Math.min(l1.getBlockX(), l2.getBlockX()); - y1 = Math.min(l1.getBlockY(), l2.getBlockY()); - z1 = Math.min(l1.getBlockZ(), l2.getBlockZ()); - x2 = Math.max(l1.getBlockX(), l2.getBlockX()); - y2 = Math.max(l1.getBlockY(), l2.getBlockY()); - z2 = Math.max(l1.getBlockZ(), l2.getBlockZ()); - } + /** + * Set the locations + * + * @param l1 a + * @param l2 b + */ + public void set(Location l1, Location l2) { + x1 = Math.min(l1.getBlockX(), l2.getBlockX()); + y1 = Math.min(l1.getBlockY(), l2.getBlockY()); + z1 = Math.min(l1.getBlockZ(), l2.getBlockZ()); + x2 = Math.max(l1.getBlockX(), l2.getBlockX()); + y2 = Math.max(l1.getBlockY(), l2.getBlockY()); + z2 = Math.max(l1.getBlockZ(), l2.getBlockZ()); + } - /** - * Construct a one-block Cuboid at the given Location of the Cuboid. - * - * @param l1 - * location of the Cuboid - */ - public Cuboid(Location l1) - { - this(l1, l1); - } + /** + * Construct a one-block Cuboid at the given Location of the Cuboid. + * + * @param l1 location of the Cuboid + */ + public Cuboid(Location l1) { + this(l1, l1); + } - /** - * Copy constructor. - * - * @param other - * the Cuboid to copy - */ - public Cuboid(Cuboid other) - { - this(other.getWorld().getName(), other.x1, other.y1, other.z1, other.x2, other.y2, other.z2); - } + /** + * Copy constructor. + * + * @param other the Cuboid to copy + */ + public Cuboid(Cuboid other) { + this(other.getWorld().getName(), other.x1, other.y1, other.z1, other.x2, other.y2, other.z2); + } - /** - * Construct a Cuboid in the given World and xyz co-ordinates - * - * @param world - * the Cuboid's world - * @param x1 - * X co-ordinate of corner 1 - * @param y1 - * Y co-ordinate of corner 1 - * @param z1 - * Z co-ordinate of corner 1 - * @param x2 - * X co-ordinate of corner 2 - * @param y2 - * Y co-ordinate of corner 2 - * @param z2 - * Z co-ordinate of corner 2 - */ - public Cuboid(World world, int x1, int y1, int z1, int x2, int y2, int z2) - { - this.worldName = world.getName(); - this.x1 = Math.min(x1, x2); - this.x2 = Math.max(x1, x2); - this.y1 = Math.min(y1, y2); - this.y2 = Math.max(y1, y2); - this.z1 = Math.min(z1, z2); - this.z2 = Math.max(z1, z2); - } + /** + * Construct a Cuboid in the given World and xyz co-ordinates + * + * @param world the Cuboid's world + * @param x1 X co-ordinate of corner 1 + * @param y1 Y co-ordinate of corner 1 + * @param z1 Z co-ordinate of corner 1 + * @param x2 X co-ordinate of corner 2 + * @param y2 Y co-ordinate of corner 2 + * @param z2 Z co-ordinate of corner 2 + */ + public Cuboid(World world, int x1, int y1, int z1, int x2, int y2, int z2) { + this.worldName = world.getName(); + this.x1 = Math.min(x1, x2); + this.x2 = Math.max(x1, x2); + this.y1 = Math.min(y1, y2); + this.y2 = Math.max(y1, y2); + this.z1 = Math.min(z1, z2); + this.z2 = Math.max(z1, z2); + } - /** - * Construct a Cuboid in the given world name and xyz co-ordinates. - * - * @param worldName - * the Cuboid's world name - * @param x1 - * X co-ordinate of corner 1 - * @param y1 - * Y co-ordinate of corner 1 - * @param z1 - * Z co-ordinate of corner 1 - * @param x2 - * X co-ordinate of corner 2 - * @param y2 - * Y co-ordinate of corner 2 - * @param z2 - * Z co-ordinate of corner 2 - */ - private Cuboid(String worldName, int x1, int y1, int z1, int x2, int y2, int z2) - { - this.worldName = worldName; - this.x1 = Math.min(x1, x2); - this.x2 = Math.max(x1, x2); - this.y1 = Math.min(y1, y2); - this.y2 = Math.max(y1, y2); - this.z1 = Math.min(z1, z2); - this.z2 = Math.max(z1, z2); - } + /** + * Construct a Cuboid in the given world name and xyz co-ordinates. + * + * @param worldName the Cuboid's world name + * @param x1 X co-ordinate of corner 1 + * @param y1 Y co-ordinate of corner 1 + * @param z1 Z co-ordinate of corner 1 + * @param x2 X co-ordinate of corner 2 + * @param y2 Y co-ordinate of corner 2 + * @param z2 Z co-ordinate of corner 2 + */ + private Cuboid(String worldName, int x1, int y1, int z1, int x2, int y2, int z2) { + this.worldName = worldName; + this.x1 = Math.min(x1, x2); + this.x2 = Math.max(x1, x2); + this.y1 = Math.min(y1, y2); + this.y2 = Math.max(y1, y2); + this.z1 = Math.min(z1, z2); + this.z2 = Math.max(z1, z2); + } - public Cuboid(Map map) - { - worldName = (String) map.get("worldName"); - x1 = (Integer) map.get("x1"); - x2 = (Integer) map.get("x2"); - y1 = (Integer) map.get("y1"); - y2 = (Integer) map.get("y2"); - z1 = (Integer) map.get("z1"); - z2 = (Integer) map.get("z2"); - } + public Cuboid(Map map) { + worldName = (String) map.get("worldName"); + x1 = (Integer) map.get("x1"); + x2 = (Integer) map.get("x2"); + y1 = (Integer) map.get("y1"); + y2 = (Integer) map.get("y2"); + z1 = (Integer) map.get("z1"); + z2 = (Integer) map.get("z2"); + } - @Override - public Map serialize() - { - Map map = new HashMap(); - map.put("worldName", worldName); - map.put("x1", x1); - map.put("y1", y1); - map.put("z1", z1); - map.put("x2", x2); - map.put("y2", y2); - map.put("z2", z2); - return map; - } + @Override + public Map serialize() { + Map map = new HashMap(); + map.put("worldName", worldName); + map.put("x1", x1); + map.put("y1", y1); + map.put("z1", z1); + map.put("x2", x2); + map.put("y2", y2); + map.put("z2", z2); + return map; + } - public Cuboid flatten(int level) - { - return new Cuboid(getWorld(), x1, level, z1, x2, level, z2); - } + public Cuboid flatten(int level) { + return new Cuboid(getWorld(), x1, level, z1, x2, level, z2); + } - /** - * Get the Location of the lower northeast corner of the Cuboid (minimum XYZ - * co-ordinates). - * - * @return Location of the lower northeast corner - */ - public Location getLowerNE() - { - return new Location(getWorld(), x1, y1, z1); - } + /** + * Get the Location of the lower northeast corner of the Cuboid (minimum XYZ + * co-ordinates). + * + * @return Location of the lower northeast corner + */ + public Location getLowerNE() { + return new Location(getWorld(), x1, y1, z1); + } - /** - * Get the Location of the upper southwest corner of the Cuboid (maximum XYZ - * co-ordinates). - * - * @return Location of the upper southwest corner - */ - public Location getUpperSW() - { - return new Location(getWorld(), x2, y2, z2); - } + /** + * Get the Location of the upper southwest corner of the Cuboid (maximum XYZ + * co-ordinates). + * + * @return Location of the upper southwest corner + */ + public Location getUpperSW() { + return new Location(getWorld(), x2, y2, z2); + } - /** - * Get the the centre of the Cuboid - * - * @return Location at the centre of the Cuboid - */ - public Location getCenter() - { - int x1 = getUpperX() + 1; - int y1 = getUpperY() + 1; - int z1 = getUpperZ() + 1; - return new Location(getWorld(), getLowerX() + (x1 - getLowerX()) / 2.0, getLowerY() + (y1 - getLowerY()) / 2.0, getLowerZ() + (z1 - getLowerZ()) / 2.0); - } + /** + * Get the the centre of the Cuboid + * + * @return Location at the centre of the Cuboid + */ + public Location getCenter() { + int x1 = getUpperX() + 1; + int y1 = getUpperY() + 1; + int z1 = getUpperZ() + 1; + return new Location(getWorld(), getLowerX() + (x1 - getLowerX()) / 2.0, getLowerY() + (y1 - getLowerY()) / 2.0, getLowerZ() + (z1 - getLowerZ()) / 2.0); + } - /** - * Get the Cuboid's world. - * - * @return the World object representing this Cuboid's world - * @throws IllegalStateException - * if the world is not loaded - */ - public World getWorld() - { - World world = Bukkit.getWorld(worldName); - if(world == null) - { - throw new IllegalStateException("world '" + worldName + "' is not loaded"); - } - return world; - } + /** + * Get the Cuboid's world. + * + * @return the World object representing this Cuboid's world + * @throws IllegalStateException if the world is not loaded + */ + public World getWorld() { + World world = Bukkit.getWorld(worldName); + if (world == null) { + throw new IllegalStateException("world '" + worldName + "' is not loaded"); + } + return world; + } - /** - * Get the size of this Cuboid along the X axis - * - * @return Size of Cuboid along the X axis - */ - public int getSizeX() - { - return (x2 - x1) + 1; - } + /** + * Get the size of this Cuboid along the X axis + * + * @return Size of Cuboid along the X axis + */ + public int getSizeX() { + return (x2 - x1) + 1; + } - /** - * Get the size of this Cuboid along the Y axis - * - * @return Size of Cuboid along the Y axis - */ - public int getSizeY() - { - return (y2 - y1) + 1; - } + /** + * Get the size of this Cuboid along the Y axis + * + * @return Size of Cuboid along the Y axis + */ + public int getSizeY() { + return (y2 - y1) + 1; + } - /** - * Get the size of this Cuboid along the Z axis - * - * @return Size of Cuboid along the Z axis - */ - public int getSizeZ() - { - return (z2 - z1) + 1; - } + /** + * Get the size of this Cuboid along the Z axis + * + * @return Size of Cuboid along the Z axis + */ + public int getSizeZ() { + return (z2 - z1) + 1; + } - /** - * Get the cuboid dimensions - * - * @return the dimensions - */ - public Dimension getDimension() - { - return new Dimension(getSizeX(), getSizeY(), getSizeZ()); - } + /** + * Get the cuboid dimensions + * + * @return the dimensions + */ + public Dimension getDimension() { + return new Dimension(getSizeX(), getSizeY(), getSizeZ()); + } - /** - * Get the minimum X co-ordinate of this Cuboid - * - * @return the minimum X co-ordinate - */ - public int getLowerX() - { - return x1; - } + /** + * Get the minimum X co-ordinate of this Cuboid + * + * @return the minimum X co-ordinate + */ + public int getLowerX() { + return x1; + } - /** - * Get the minimum Y co-ordinate of this Cuboid - * - * @return the minimum Y co-ordinate - */ - public int getLowerY() - { - return y1; - } + /** + * Get the minimum Y co-ordinate of this Cuboid + * + * @return the minimum Y co-ordinate + */ + public int getLowerY() { + return y1; + } - /** - * Get the minimum Z co-ordinate of this Cuboid - * - * @return the minimum Z co-ordinate - */ - public int getLowerZ() - { - return z1; - } + /** + * Get the minimum Z co-ordinate of this Cuboid + * + * @return the minimum Z co-ordinate + */ + public int getLowerZ() { + return z1; + } - /** - * Get the maximum X co-ordinate of this Cuboid - * - * @return the maximum X co-ordinate - */ - public int getUpperX() - { - return x2; - } + /** + * Get the maximum X co-ordinate of this Cuboid + * + * @return the maximum X co-ordinate + */ + public int getUpperX() { + return x2; + } - /** - * Get the maximum Y co-ordinate of this Cuboid - * - * @return the maximum Y co-ordinate - */ - public int getUpperY() - { - return y2; - } + /** + * Get the maximum Y co-ordinate of this Cuboid + * + * @return the maximum Y co-ordinate + */ + public int getUpperY() { + return y2; + } - /** - * Get the maximum Z co-ordinate of this Cuboid - * - * @return the maximum Z co-ordinate - */ - public int getUpperZ() - { - return z2; - } + /** + * Get the maximum Z co-ordinate of this Cuboid + * + * @return the maximum Z co-ordinate + */ + public int getUpperZ() { + return z2; + } - /** - * Get the Blocks at the eight corners of the Cuboid. - * - * @return array of Block objects representing the Cuboid corners - */ - public Block[] corners() - { - Block[] res = new Block[8]; - World w = getWorld(); - res[0] = w.getBlockAt(x1, y1, z1); - res[1] = w.getBlockAt(x1, y1, z2); - res[2] = w.getBlockAt(x1, y2, z1); - res[3] = w.getBlockAt(x1, y2, z2); - res[4] = w.getBlockAt(x2, y1, z1); - res[5] = w.getBlockAt(x2, y1, z2); - res[6] = w.getBlockAt(x2, y2, z1); - res[7] = w.getBlockAt(x2, y2, z2); - return res; - } + /** + * Get the Blocks at the eight corners of the Cuboid. + * + * @return array of Block objects representing the Cuboid corners + */ + public Block[] corners() { + Block[] res = new Block[8]; + World w = getWorld(); + res[0] = w.getBlockAt(x1, y1, z1); + res[1] = w.getBlockAt(x1, y1, z2); + res[2] = w.getBlockAt(x1, y2, z1); + res[3] = w.getBlockAt(x1, y2, z2); + res[4] = w.getBlockAt(x2, y1, z1); + res[5] = w.getBlockAt(x2, y1, z2); + res[6] = w.getBlockAt(x2, y2, z1); + res[7] = w.getBlockAt(x2, y2, z2); + return res; + } - /** - * Expand the Cuboid in the given direction by the given amount. Negative - * amounts will shrink the Cuboid in the given direction. Shrinking a cuboid's - * face past the opposite face is not an error and will return a valid Cuboid. - * - * @param dir - * the direction in which to expand - * @param amount - * the number of blocks by which to expand - * @return a new Cuboid expanded by the given direction and amount - */ - public Cuboid expand(CuboidDirection dir, int amount) - { - switch(dir) - { - case North: - return new Cuboid(worldName, x1 - amount, y1, z1, x2, y2, z2); - case South: - return new Cuboid(worldName, x1, y1, z1, x2 + amount, y2, z2); - case East: - return new Cuboid(worldName, x1, y1, z1 - amount, x2, y2, z2); - case West: - return new Cuboid(worldName, x1, y1, z1, x2, y2, z2 + amount); - case Down: - return new Cuboid(worldName, x1, y1 - amount, z1, x2, y2, z2); - case Up: - return new Cuboid(worldName, x1, y1, z1, x2, y2 + amount, z2); - default: - throw new IllegalArgumentException("invalid direction " + dir); - } - } + /** + * Expand the Cuboid in the given direction by the given amount. Negative + * amounts will shrink the Cuboid in the given direction. Shrinking a cuboid's + * face past the opposite face is not an error and will return a valid Cuboid. + * + * @param dir the direction in which to expand + * @param amount the number of blocks by which to expand + * @return a new Cuboid expanded by the given direction and amount + */ + public Cuboid expand(CuboidDirection dir, int amount) { + switch (dir) { + case North: + return new Cuboid(worldName, x1 - amount, y1, z1, x2, y2, z2); + case South: + return new Cuboid(worldName, x1, y1, z1, x2 + amount, y2, z2); + case East: + return new Cuboid(worldName, x1, y1, z1 - amount, x2, y2, z2); + case West: + return new Cuboid(worldName, x1, y1, z1, x2, y2, z2 + amount); + case Down: + return new Cuboid(worldName, x1, y1 - amount, z1, x2, y2, z2); + case Up: + return new Cuboid(worldName, x1, y1, z1, x2, y2 + amount, z2); + default: + throw new IllegalArgumentException("invalid direction " + dir); + } + } - public Cuboid expand(Direction dir, int amount) - { - int ax = dir.toVector().getBlockX() == 1 ? amount : 0; - int sx = dir.toVector().getBlockX() == -1 ? -amount : 0; - int ay = dir.toVector().getBlockY() == 1 ? amount : 0; - int sy = dir.toVector().getBlockY() == -1 ? -amount : 0; - int az = dir.toVector().getBlockZ() == 1 ? amount : 0; - int sz = dir.toVector().getBlockZ() == -1 ? -amount : 0; - return new Cuboid(worldName, x1 + sx, y1 + sy, z1 + sz, x2 + ax, y2 + ay, z2 + az); - } + public Cuboid expand(Direction dir, int amount) { + int ax = dir.toVector().getBlockX() == 1 ? amount : 0; + int sx = dir.toVector().getBlockX() == -1 ? -amount : 0; + int ay = dir.toVector().getBlockY() == 1 ? amount : 0; + int sy = dir.toVector().getBlockY() == -1 ? -amount : 0; + int az = dir.toVector().getBlockZ() == 1 ? amount : 0; + int sz = dir.toVector().getBlockZ() == -1 ? -amount : 0; + return new Cuboid(worldName, x1 + sx, y1 + sy, z1 + sz, x2 + ax, y2 + ay, z2 + az); + } - /** - * Shift the Cuboid in the given direction by the given amount. - * - * @param dir - * the direction in which to shift - * @param amount - * the number of blocks by which to shift - * @return a new Cuboid shifted by the given direction and amount - */ - public Cuboid shift(CuboidDirection dir, int amount) - { - return expand(dir, amount).expand(dir.opposite(), -amount); - } + /** + * Shift the Cuboid in the given direction by the given amount. + * + * @param dir the direction in which to shift + * @param amount the number of blocks by which to shift + * @return a new Cuboid shifted by the given direction and amount + */ + public Cuboid shift(CuboidDirection dir, int amount) { + return expand(dir, amount).expand(dir.opposite(), -amount); + } - /** - * Outset (grow) the Cuboid in the given direction by the given amount. - * - * @param dir - * the direction in which to outset (must be Horizontal, Vertical, or - * Both) - * @param amount - * the number of blocks by which to outset - * @return a new Cuboid outset by the given direction and amount - */ - public Cuboid outset(CuboidDirection dir, int amount) - { - Cuboid c; - switch(dir) - { - case Horizontal: - c = expand(CuboidDirection.North, amount).expand(CuboidDirection.South, amount).expand(CuboidDirection.East, amount).expand(CuboidDirection.West, amount); - break; - case Vertical: - c = expand(CuboidDirection.Down, amount).expand(CuboidDirection.Up, amount); - break; - case Both: - c = outset(CuboidDirection.Horizontal, amount).outset(CuboidDirection.Vertical, amount); - break; - default: - throw new IllegalArgumentException("invalid direction " + dir); - } - return c; - } + /** + * Outset (grow) the Cuboid in the given direction by the given amount. + * + * @param dir the direction in which to outset (must be Horizontal, Vertical, or + * Both) + * @param amount the number of blocks by which to outset + * @return a new Cuboid outset by the given direction and amount + */ + public Cuboid outset(CuboidDirection dir, int amount) { + Cuboid c; + switch (dir) { + case Horizontal: + c = expand(CuboidDirection.North, amount).expand(CuboidDirection.South, amount).expand(CuboidDirection.East, amount).expand(CuboidDirection.West, amount); + break; + case Vertical: + c = expand(CuboidDirection.Down, amount).expand(CuboidDirection.Up, amount); + break; + case Both: + c = outset(CuboidDirection.Horizontal, amount).outset(CuboidDirection.Vertical, amount); + break; + default: + throw new IllegalArgumentException("invalid direction " + dir); + } + return c; + } - /** - * Inset (shrink) the Cuboid in the given direction by the given amount. - * Equivalent to calling outset() with a negative amount. - * - * @param dir - * the direction in which to inset (must be Horizontal, Vertical, or - * Both) - * @param amount - * the number of blocks by which to inset - * @return a new Cuboid inset by the given direction and amount - */ - public Cuboid inset(CuboidDirection dir, int amount) - { - return outset(dir, -amount); - } + /** + * Inset (shrink) the Cuboid in the given direction by the given amount. + * Equivalent to calling outset() with a negative amount. + * + * @param dir the direction in which to inset (must be Horizontal, Vertical, or + * Both) + * @param amount the number of blocks by which to inset + * @return a new Cuboid inset by the given direction and amount + */ + public Cuboid inset(CuboidDirection dir, int amount) { + return outset(dir, -amount); + } - /** - * Return true if the point at (x,y,z) is contained within this Cuboid. - * - * @param x - * the X co-ordinate - * @param y - * the Y co-ordinate - * @param z - * the Z co-ordinate - * @return true if the given point is within this Cuboid, false otherwise - */ - public boolean contains(int x, int y, int z) - { - return x >= x1 && x <= x2 && y >= y1 && y <= y2 && z >= z1 && z <= z2; - } + /** + * Return true if the point at (x,y,z) is contained within this Cuboid. + * + * @param x the X co-ordinate + * @param y the Y co-ordinate + * @param z the Z co-ordinate + * @return true if the given point is within this Cuboid, false otherwise + */ + public boolean contains(int x, int y, int z) { + return x >= x1 && x <= x2 && y >= y1 && y <= y2 && z >= z1 && z <= z2; + } - /** - * Check if the given Block is contained within this Cuboid. - * - * @param b - * the Block to check for - * @return true if the Block is within this Cuboid, false otherwise - */ - public boolean contains(Block b) - { - return contains(b.getLocation()); - } + /** + * Check if the given Block is contained within this Cuboid. + * + * @param b the Block to check for + * @return true if the Block is within this Cuboid, false otherwise + */ + public boolean contains(Block b) { + return contains(b.getLocation()); + } - /** - * Check if the given Location is contained within this Cuboid. - * - * @param l - * the Location to check for - * @return true if the Location is within this Cuboid, false otherwise - */ - public boolean contains(Location l) - { - return worldName.equals(l.getWorld().getName()) && contains(l.getBlockX(), l.getBlockY(), l.getBlockZ()); - } + /** + * Check if the given Location is contained within this Cuboid. + * + * @param l the Location to check for + * @return true if the Location is within this Cuboid, false otherwise + */ + public boolean contains(Location l) { + return worldName.equals(l.getWorld().getName()) && contains(l.getBlockX(), l.getBlockY(), l.getBlockZ()); + } - /** - * Get the volume of this Cuboid. - * - * @return the Cuboid volume, in blocks - */ - public int volume() - { - return getSizeX() * getSizeY() * getSizeZ(); - } + /** + * Get the volume of this Cuboid. + * + * @return the Cuboid volume, in blocks + */ + public int volume() { + return getSizeX() * getSizeY() * getSizeZ(); + } - /** - * Get the average light level of all empty (air) blocks in the Cuboid. Returns - * 0 if there are no empty blocks. - * - * @return the average light level of this Cuboid - */ - public byte averageLightLevel() - { - long total = 0; - int n = 0; - for(Block b : this) - { - if(b.isEmpty()) - { - total += b.getLightLevel(); - ++n; - } - } - return n > 0 ? (byte) (total / n) : 0; - } + /** + * Get the average light level of all empty (air) blocks in the Cuboid. Returns + * 0 if there are no empty blocks. + * + * @return the average light level of this Cuboid + */ + public byte averageLightLevel() { + long total = 0; + int n = 0; + for (Block b : this) { + if (b.isEmpty()) { + total += b.getLightLevel(); + ++n; + } + } + return n > 0 ? (byte) (total / n) : 0; + } - /** - * Contract the Cuboid, returning a Cuboid with any air around the edges - * removed, just large enough to include all non-air blocks. - * - * @return a new Cuboid with no external air blocks - */ - public Cuboid contract() - { - return this.contract(CuboidDirection.Down).contract(CuboidDirection.South).contract(CuboidDirection.East).contract(CuboidDirection.Up).contract(CuboidDirection.North).contract(CuboidDirection.West); - } + /** + * Contract the Cuboid, returning a Cuboid with any air around the edges + * removed, just large enough to include all non-air blocks. + * + * @return a new Cuboid with no external air blocks + */ + public Cuboid contract() { + return this.contract(CuboidDirection.Down).contract(CuboidDirection.South).contract(CuboidDirection.East).contract(CuboidDirection.Up).contract(CuboidDirection.North).contract(CuboidDirection.West); + } - /** - * Contract the Cuboid in the given direction, returning a new Cuboid which has - * no exterior empty space. E.g. a direction of Down will push the top face - * downwards as much as possible. - * - * @param dir - * the direction in which to contract - * @return a new Cuboid contracted in the given direction - */ - public Cuboid contract(CuboidDirection dir) - { - Cuboid face = getFace(dir.opposite()); - switch(dir) - { - case Down: - while(face.containsOnly(Material.AIR) && face.getLowerY() > this.getLowerY()) - { - face = face.shift(CuboidDirection.Down, 1); - } - return new Cuboid(worldName, x1, y1, z1, x2, face.getUpperY(), z2); - case Up: - while(face.containsOnly(Material.AIR) && face.getUpperY() < this.getUpperY()) - { - face = face.shift(CuboidDirection.Up, 1); - } - return new Cuboid(worldName, x1, face.getLowerY(), z1, x2, y2, z2); - case North: - while(face.containsOnly(Material.AIR) && face.getLowerX() > this.getLowerX()) - { - face = face.shift(CuboidDirection.North, 1); - } - return new Cuboid(worldName, x1, y1, z1, face.getUpperX(), y2, z2); - case South: - while(face.containsOnly(Material.AIR) && face.getUpperX() < this.getUpperX()) - { - face = face.shift(CuboidDirection.South, 1); - } - return new Cuboid(worldName, face.getLowerX(), y1, z1, x2, y2, z2); - case East: - while(face.containsOnly(Material.AIR) && face.getLowerZ() > this.getLowerZ()) - { - face = face.shift(CuboidDirection.East, 1); - } - return new Cuboid(worldName, x1, y1, z1, x2, y2, face.getUpperZ()); - case West: - while(face.containsOnly(Material.AIR) && face.getUpperZ() < this.getUpperZ()) - { - face = face.shift(CuboidDirection.West, 1); - } - return new Cuboid(worldName, x1, y1, face.getLowerZ(), x2, y2, z2); - default: - throw new IllegalArgumentException("Invalid direction " + dir); - } - } + /** + * Contract the Cuboid in the given direction, returning a new Cuboid which has + * no exterior empty space. E.g. a direction of Down will push the top face + * downwards as much as possible. + * + * @param dir the direction in which to contract + * @return a new Cuboid contracted in the given direction + */ + public Cuboid contract(CuboidDirection dir) { + Cuboid face = getFace(dir.opposite()); + switch (dir) { + case Down: + while (face.containsOnly(Material.AIR) && face.getLowerY() > this.getLowerY()) { + face = face.shift(CuboidDirection.Down, 1); + } + return new Cuboid(worldName, x1, y1, z1, x2, face.getUpperY(), z2); + case Up: + while (face.containsOnly(Material.AIR) && face.getUpperY() < this.getUpperY()) { + face = face.shift(CuboidDirection.Up, 1); + } + return new Cuboid(worldName, x1, face.getLowerY(), z1, x2, y2, z2); + case North: + while (face.containsOnly(Material.AIR) && face.getLowerX() > this.getLowerX()) { + face = face.shift(CuboidDirection.North, 1); + } + return new Cuboid(worldName, x1, y1, z1, face.getUpperX(), y2, z2); + case South: + while (face.containsOnly(Material.AIR) && face.getUpperX() < this.getUpperX()) { + face = face.shift(CuboidDirection.South, 1); + } + return new Cuboid(worldName, face.getLowerX(), y1, z1, x2, y2, z2); + case East: + while (face.containsOnly(Material.AIR) && face.getLowerZ() > this.getLowerZ()) { + face = face.shift(CuboidDirection.East, 1); + } + return new Cuboid(worldName, x1, y1, z1, x2, y2, face.getUpperZ()); + case West: + while (face.containsOnly(Material.AIR) && face.getUpperZ() < this.getUpperZ()) { + face = face.shift(CuboidDirection.West, 1); + } + return new Cuboid(worldName, x1, y1, face.getLowerZ(), x2, y2, z2); + default: + throw new IllegalArgumentException("Invalid direction " + dir); + } + } - /** - * Get the Cuboid representing the face of this Cuboid. The resulting Cuboid - * will be one block thick in the axis perpendicular to the requested face. - * - * @param dir - * which face of the Cuboid to get - * @return the Cuboid representing this Cuboid's requested face - */ - public Cuboid getFace(CuboidDirection dir) - { - switch(dir) - { - case Down: - return new Cuboid(worldName, x1, y1, z1, x2, y1, z2); - case Up: - return new Cuboid(worldName, x1, y2, z1, x2, y2, z2); - case North: - return new Cuboid(worldName, x1, y1, z1, x1, y2, z2); - case South: - return new Cuboid(worldName, x2, y1, z1, x2, y2, z2); - case East: - return new Cuboid(worldName, x1, y1, z1, x2, y2, z1); - case West: - return new Cuboid(worldName, x1, y1, z2, x2, y2, z2); - default: - throw new IllegalArgumentException("Invalid direction " + dir); - } - } + /** + * Get the Cuboid representing the face of this Cuboid. The resulting Cuboid + * will be one block thick in the axis perpendicular to the requested face. + * + * @param dir which face of the Cuboid to get + * @return the Cuboid representing this Cuboid's requested face + */ + public Cuboid getFace(CuboidDirection dir) { + switch (dir) { + case Down: + return new Cuboid(worldName, x1, y1, z1, x2, y1, z2); + case Up: + return new Cuboid(worldName, x1, y2, z1, x2, y2, z2); + case North: + return new Cuboid(worldName, x1, y1, z1, x1, y2, z2); + case South: + return new Cuboid(worldName, x2, y1, z1, x2, y2, z2); + case East: + return new Cuboid(worldName, x1, y1, z1, x2, y2, z1); + case West: + return new Cuboid(worldName, x1, y1, z2, x2, y2, z2); + default: + throw new IllegalArgumentException("Invalid direction " + dir); + } + } - /** - * Check if the Cuboid contains only blocks of the given type - * - * @param material - * the material to check for - * @return true if this Cuboid contains only blocks of the given type - */ - public boolean containsOnly(Material material) - { - for(Block b : this) - { - if(b.getType() != material) - { - return false; - } - } - return true; - } + /** + * Check if the Cuboid contains only blocks of the given type + * + * @param material the material to check for + * @return true if this Cuboid contains only blocks of the given type + */ + public boolean containsOnly(Material material) { + for (Block b : this) { + if (b.getType() != material) { + return false; + } + } + return true; + } - /** - * Get the Cuboid big enough to hold both this Cuboid and the given one. - * - * @param other - * the other Cuboid to include - * @return a new Cuboid large enough to hold this Cuboid and the given Cuboid - */ - public Cuboid getBoundingCuboid(Cuboid other) - { - if(other == null) - { - return this; - } + /** + * Get the Cuboid big enough to hold both this Cuboid and the given one. + * + * @param other the other Cuboid to include + * @return a new Cuboid large enough to hold this Cuboid and the given Cuboid + */ + public Cuboid getBoundingCuboid(Cuboid other) { + if (other == null) { + return this; + } - int xMin = Math.min(getLowerX(), other.getLowerX()); - int yMin = Math.min(getLowerY(), other.getLowerY()); - int zMin = Math.min(getLowerZ(), other.getLowerZ()); - int xMax = Math.max(getUpperX(), other.getUpperX()); - int yMax = Math.max(getUpperY(), other.getUpperY()); - int zMax = Math.max(getUpperZ(), other.getUpperZ()); + int xMin = Math.min(getLowerX(), other.getLowerX()); + int yMin = Math.min(getLowerY(), other.getLowerY()); + int zMin = Math.min(getLowerZ(), other.getLowerZ()); + int xMax = Math.max(getUpperX(), other.getUpperX()); + int yMax = Math.max(getUpperY(), other.getUpperY()); + int zMax = Math.max(getUpperZ(), other.getUpperZ()); - return new Cuboid(worldName, xMin, yMin, zMin, xMax, yMax, zMax); - } + return new Cuboid(worldName, xMin, yMin, zMin, xMax, yMax, zMax); + } - /** - * Get a block relative to the lower NE point of the Cuboid. - * - * @param x - * the X co-ordinate - * @param y - * the Y co-ordinate - * @param z - * the Z co-ordinate - * @return the block at the given position - */ - public Block getRelativeBlock(int x, int y, int z) - { - return getWorld().getBlockAt(x1 + x, y1 + y, z1 + z); - } + /** + * Get a block relative to the lower NE point of the Cuboid. + * + * @param x the X co-ordinate + * @param y the Y co-ordinate + * @param z the Z co-ordinate + * @return the block at the given position + */ + public Block getRelativeBlock(int x, int y, int z) { + return getWorld().getBlockAt(x1 + x, y1 + y, z1 + z); + } - /** - * Get a block relative to the lower NE point of the Cuboid in the given World. - * This version of getRelativeBlock() should be used if being called many times, - * to avoid excessive calls to getWorld(). - * - * @param w - * the World - * @param x - * the X co-ordinate - * @param y - * the Y co-ordinate - * @param z - * the Z co-ordinate - * @return the block at the given position - */ - public Block getRelativeBlock(World w, int x, int y, int z) - { - return w.getBlockAt(x1 + x, y1 + y, z1 + z); - } + /** + * Get a block relative to the lower NE point of the Cuboid in the given World. + * This version of getRelativeBlock() should be used if being called many times, + * to avoid excessive calls to getWorld(). + * + * @param w the World + * @param x the X co-ordinate + * @param y the Y co-ordinate + * @param z the Z co-ordinate + * @return the block at the given position + */ + public Block getRelativeBlock(World w, int x, int y, int z) { + return w.getBlockAt(x1 + x, y1 + y, z1 + z); + } - /** - * Get a list of the chunks which are fully or partially contained in this - * cuboid. - * - * @return a list of Chunk objects - */ - public List getChunks() - { - List res = new ArrayList(); + /** + * Get a list of the chunks which are fully or partially contained in this + * cuboid. + * + * @return a list of Chunk objects + */ + public List getChunks() { + List res = new ArrayList(); - World w = getWorld(); - int x1 = getLowerX() & ~0xf; - int x2 = getUpperX() & ~0xf; - int z1 = getLowerZ() & ~0xf; - int z2 = getUpperZ() & ~0xf; - for(int x = x1; x <= x2; x += 16) - { - for(int z = z1; z <= z2; z += 16) - { - res.add(w.getChunkAt(x >> 4, z >> 4)); - } - } - return res; - } + World w = getWorld(); + int x1 = getLowerX() & ~0xf; + int x2 = getUpperX() & ~0xf; + int z1 = getLowerZ() & ~0xf; + int z2 = getUpperZ() & ~0xf; + for (int x = x1; x <= x2; x += 16) { + for (int z = z1; z <= z2; z += 16) { + res.add(w.getChunkAt(x >> 4, z >> 4)); + } + } + return res; + } - /** - * Set all the blocks within the Cuboid to the given MaterialData, using a - * MassBlockUpdate object for fast updates. - * - * @param mat - * the MaterialData to set - * @param mbu - * the MassBlockUpdate object - */ + /** + * Set all the blocks within the Cuboid to the given MaterialData, using a + * MassBlockUpdate object for fast updates. + * + * @param mat + * the MaterialData to set + * @param mbu + * the MassBlockUpdate object + */ - /** - * Reset the light level of all blocks within this Cuboid. - */ + /** + * Reset the light level of all blocks within this Cuboid. + */ - /* - * (non-Javadoc) - * - * @see java.lang.Iterable#iterator() - */ - @Override - public Iterator iterator() - { - return new CuboidIterator(getWorld(), x1, y1, z1, x2, y2, z2); - } + /* + * (non-Javadoc) + * + * @see java.lang.Iterable#iterator() + */ + @Override + public Iterator iterator() { + return new CuboidIterator(getWorld(), x1, y1, z1, x2, y2, z2); + } - /* - * (non-Javadoc) - * - * @see java.lang.Object#clone() - */ - @Override - public Cuboid clone() throws CloneNotSupportedException - { - return new Cuboid(this); - } + /* + * (non-Javadoc) + * + * @see java.lang.Object#clone() + */ + @Override + public Cuboid clone() throws CloneNotSupportedException { + return new Cuboid(this); + } - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override - public String toString() - { - return "Cuboid: " + worldName + "," + x1 + "," + y1 + "," + z1 + "=>" + x2 + "," + y2 + "," + z2; - } + /* + * (non-Javadoc) + * + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + return "Cuboid: " + worldName + "," + x1 + "," + y1 + "," + z1 + "=>" + x2 + "," + y2 + "," + z2; + } - public class CuboidIterator implements Iterator - { - private World w; - private int baseX, baseY, baseZ; - private int x, y, z; - private int sizeX, sizeY, sizeZ; + public class CuboidIterator implements Iterator { + private final World w; + private final int baseX; + private final int baseY; + private final int baseZ; + private int x, y, z; + private final int sizeX; + private final int sizeY; + private final int sizeZ; - public CuboidIterator(World w, int x1, int y1, int z1, int x2, int y2, int z2) - { - this.w = w; - baseX = x1; - baseY = y1; - baseZ = z1; - sizeX = Math.abs(x2 - x1) + 1; - sizeY = Math.abs(y2 - y1) + 1; - sizeZ = Math.abs(z2 - z1) + 1; - x = y = z = 0; - } + public CuboidIterator(World w, int x1, int y1, int z1, int x2, int y2, int z2) { + this.w = w; + baseX = x1; + baseY = y1; + baseZ = z1; + sizeX = Math.abs(x2 - x1) + 1; + sizeY = Math.abs(y2 - y1) + 1; + sizeZ = Math.abs(z2 - z1) + 1; + x = y = z = 0; + } - @Override - public boolean hasNext() - { - return x < sizeX && y < sizeY && z < sizeZ; - } + @Override + public boolean hasNext() { + return x < sizeX && y < sizeY && z < sizeZ; + } - @Override - public Block next() - { - Block b = w.getBlockAt(baseX + x, baseY + y, baseZ + z); - if(++x >= sizeX) - { - x = 0; - if(++y >= sizeY) - { - y = 0; - ++z; - } - } - return b; - } + @Override + public Block next() { + Block b = w.getBlockAt(baseX + x, baseY + y, baseZ + z); + if (++x >= sizeX) { + x = 0; + if (++y >= sizeY) { + y = 0; + ++z; + } + } + return b; + } - @Override - public void remove() - { - // nop - } - } + @Override + public void remove() { + // nop + } + } - public enum CuboidDirection - { + public enum CuboidDirection { - North, - East, - South, - West, - Up, - Down, - Horizontal, - Vertical, - Both, - Unknown; + North, + East, + South, + West, + Up, + Down, + Horizontal, + Vertical, + Both, + Unknown; - public CuboidDirection opposite() - { - switch(this) - { - case North: - return South; - case East: - return West; - case South: - return North; - case West: - return East; - case Horizontal: - return Vertical; - case Vertical: - return Horizontal; - case Up: - return Down; - case Down: - return Up; - case Both: - return Both; - default: - return Unknown; - } - } - } + public CuboidDirection opposite() { + switch (this) { + case North: + return South; + case East: + return West; + case South: + return North; + case West: + return East; + case Horizontal: + return Vertical; + case Vertical: + return Horizontal; + case Up: + return Down; + case Down: + return Up; + case Both: + return Both; + default: + return Unknown; + } + } + } } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/CuboidException.java b/src/main/java/com/volmit/iris/util/CuboidException.java index 94acd74c9..3bcfa7a61 100644 --- a/src/main/java/com/volmit/iris/util/CuboidException.java +++ b/src/main/java/com/volmit/iris/util/CuboidException.java @@ -5,12 +5,10 @@ package com.volmit.iris.util; * * @author cyberpwn */ -public class CuboidException extends Exception -{ - public CuboidException(String string) - { - super(string); - } +public class CuboidException extends Exception { + public CuboidException(String string) { + super(string); + } - private static final long serialVersionUID = 1L; + private static final long serialVersionUID = 1L; } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/CustomOutputStream.java b/src/main/java/com/volmit/iris/util/CustomOutputStream.java index 2b8205449..e03beaa14 100644 --- a/src/main/java/com/volmit/iris/util/CustomOutputStream.java +++ b/src/main/java/com/volmit/iris/util/CustomOutputStream.java @@ -4,11 +4,9 @@ import java.io.IOException; import java.io.OutputStream; import java.util.zip.GZIPOutputStream; -public class CustomOutputStream extends GZIPOutputStream -{ - public CustomOutputStream(OutputStream out, int level) throws IOException - { - super(out); - def.setLevel(level); - } +public class CustomOutputStream extends GZIPOutputStream { + public CustomOutputStream(OutputStream out, int level) throws IOException { + super(out); + def.setLevel(level); + } } diff --git a/src/main/java/com/volmit/iris/util/DOP.java b/src/main/java/com/volmit/iris/util/DOP.java index 656751e25..7dfe0ad41 100644 --- a/src/main/java/com/volmit/iris/util/DOP.java +++ b/src/main/java/com/volmit/iris/util/DOP.java @@ -2,19 +2,16 @@ package com.volmit.iris.util; import org.bukkit.util.Vector; -public abstract class DOP -{ - private String type; - - public DOP(String type) - { - this.type = type; - } - - public abstract Vector op(Vector v); - - public String getType() - { - return type; - } +public abstract class DOP { + private final String type; + + public DOP(String type) { + this.type = type; + } + + public abstract Vector op(Vector v); + + public String getType() { + return type; + } } diff --git a/src/main/java/com/volmit/iris/util/DataPalette.java b/src/main/java/com/volmit/iris/util/DataPalette.java index 028328d9d..d95bf8fe8 100644 --- a/src/main/java/com/volmit/iris/util/DataPalette.java +++ b/src/main/java/com/volmit/iris/util/DataPalette.java @@ -4,122 +4,101 @@ import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; -public abstract class DataPalette implements Writable -{ - private static final int DEFAULT_BITS_PER_BLOCK = 4; - private static final int CAPACITY = 4096; - private int bpb; - private NibbleArray data; - private KList palette; +public abstract class DataPalette implements Writable { + private static final int DEFAULT_BITS_PER_BLOCK = 4; + private static final int CAPACITY = 4096; + private int bpb; + private NibbleArray data; + private KList palette; - public DataPalette(T defaultValue) - { - palette = new KList<>(); - bpb = DEFAULT_BITS_PER_BLOCK; - data = new NibbleArray(bpb, CAPACITY); - data.setAll(Byte.MIN_VALUE); - getPaletteId(defaultValue); - } + public DataPalette(T defaultValue) { + palette = new KList<>(); + bpb = DEFAULT_BITS_PER_BLOCK; + data = new NibbleArray(bpb, CAPACITY); + data.setAll(Byte.MIN_VALUE); + getPaletteId(defaultValue); + } - public abstract T readType(DataInputStream i) throws IOException; + public abstract T readType(DataInputStream i) throws IOException; - public abstract void writeType(T t, DataOutputStream o) throws IOException; + public abstract void writeType(T t, DataOutputStream o) throws IOException; - @Override - public void write(DataOutputStream o) throws IOException - { - o.writeByte(bpb + Byte.MIN_VALUE); - o.writeByte(palette.size() + Byte.MIN_VALUE); + @Override + public void write(DataOutputStream o) throws IOException { + o.writeByte(bpb + Byte.MIN_VALUE); + o.writeByte(palette.size() + Byte.MIN_VALUE); - for(T i : palette) - { - writeType(i, o); - } + for (T i : palette) { + writeType(i, o); + } - data.write(o); - } + data.write(o); + } - @Override - public void read(DataInputStream i) throws IOException - { - bpb = i.readByte() - Byte.MIN_VALUE; - palette = new KList<>(); - int v = i.readByte() - Byte.MIN_VALUE; + @Override + public void read(DataInputStream i) throws IOException { + bpb = i.readByte() - Byte.MIN_VALUE; + palette = new KList<>(); + int v = i.readByte() - Byte.MIN_VALUE; - for(int j = 0; j < v; j++) - { - palette.add(readType(i)); - } + for (int j = 0; j < v; j++) { + palette.add(readType(i)); + } - data = new NibbleArray(CAPACITY, i); - } + data = new NibbleArray(CAPACITY, i); + } - private final void expand() - { - if(bpb < 8) - { - changeBitsPerBlock(bpb + 1); - } + private final void expand() { + if (bpb < 8) { + changeBitsPerBlock(bpb + 1); + } else { + throw new IndexOutOfBoundsException("The Data Palette can only handle at most 256 block types per 16x16x16 region. We cannot use more than 8 bits per block!"); + } + } - else - { - throw new IndexOutOfBoundsException("The Data Palette can only handle at most 256 block types per 16x16x16 region. We cannot use more than 8 bits per block!"); - } - } + public final void optimize() { + int targetBits = bpb; + int needed = palette.size(); - public final void optimize() - { - int targetBits = bpb; - int needed = palette.size(); + for (int i = 1; i < bpb; i++) { + if (Math.pow(2, i) > needed) { + targetBits = i; + break; + } + } - for(int i = 1; i < bpb; i++) - { - if(Math.pow(2, i) > needed) - { - targetBits = i; - break; - } - } + changeBitsPerBlock(targetBits); + } - changeBitsPerBlock(targetBits); - } + private final void changeBitsPerBlock(int bits) { + bpb = bits; + data = new NibbleArray(bpb, CAPACITY, data); + } - private final void changeBitsPerBlock(int bits) - { - bpb = bits; - data = new NibbleArray(bpb, CAPACITY, data); - } + public final void set(int x, int y, int z, T d) { + data.set(getCoordinateIndex(x, y, z), getPaletteId(d)); + } - public final void set(int x, int y, int z, T d) - { - data.set(getCoordinateIndex(x, y, z), getPaletteId(d)); - } + public final T get(int x, int y, int z) { + return palette.get(data.get(getCoordinateIndex(x, y, z))); + } - public final T get(int x, int y, int z) - { - return palette.get(data.get(getCoordinateIndex(x, y, z))); - } + private final int getPaletteId(T d) { + int index = palette.indexOf(d); - private final int getPaletteId(T d) - { - int index = palette.indexOf(d); + if (index == -1) { + index = palette.size(); + palette.add(d); - if(index == -1) - { - index = palette.size(); - palette.add(d); + if (palette.size() > Math.pow(2, bpb)) { + expand(); + } + } - if(palette.size() > Math.pow(2, bpb)) - { - expand(); - } - } + return index + Byte.MIN_VALUE; + } - return index + Byte.MIN_VALUE; - } - - private final int getCoordinateIndex(int x, int y, int z) - { - return y << 8 | z << 4 | x; - } + private final int getCoordinateIndex(int x, int y, int z) { + return y << 8 | z << 4 | x; + } } diff --git a/src/main/java/com/volmit/iris/util/Denv.java b/src/main/java/com/volmit/iris/util/Denv.java index 9bb0daa87..549134125 100644 --- a/src/main/java/com/volmit/iris/util/Denv.java +++ b/src/main/java/com/volmit/iris/util/Denv.java @@ -1,6 +1,5 @@ package com.volmit.iris.util; -public class Denv -{ - +public class Denv { + } diff --git a/src/main/java/com/volmit/iris/util/DependsOn.java b/src/main/java/com/volmit/iris/util/DependsOn.java index 83dd51417..01bd60143 100644 --- a/src/main/java/com/volmit/iris/util/DependsOn.java +++ b/src/main/java/com/volmit/iris/util/DependsOn.java @@ -1,13 +1,13 @@ package com.volmit.iris.util; -import static java.lang.annotation.ElementType.FIELD; -import static java.lang.annotation.RetentionPolicy.RUNTIME; - 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 }) +@Target({FIELD}) public @interface DependsOn { - String[] value(); + String[] value(); } diff --git a/src/main/java/com/volmit/iris/util/Desc.java b/src/main/java/com/volmit/iris/util/Desc.java index 388e1a678..fb60ec757 100644 --- a/src/main/java/com/volmit/iris/util/Desc.java +++ b/src/main/java/com/volmit/iris/util/Desc.java @@ -1,14 +1,13 @@ package com.volmit.iris.util; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - import java.lang.annotation.Retention; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + @Retention(RUNTIME) @Target({PARAMETER, TYPE, FIELD}) -public @interface Desc -{ - String value(); +public @interface Desc { + String value(); } diff --git a/src/main/java/com/volmit/iris/util/Dimension.java b/src/main/java/com/volmit/iris/util/Dimension.java index 6df9dc78d..77520cf94 100644 --- a/src/main/java/com/volmit/iris/util/Dimension.java +++ b/src/main/java/com/volmit/iris/util/Dimension.java @@ -5,82 +5,67 @@ package com.volmit.iris.util; * * @author cyberpwn */ -public class Dimension -{ - private final int width; - private final int height; - private final int depth; +public class Dimension { + private final int width; + private final int height; + private final int depth; - /** - * Make a dimension - * - * @param width - * width of this (X) - * @param height - * the height (Y) - * @param depth - * the depth (Z) - */ - public Dimension(int width, int height, int depth) - { - this.width = width; - this.height = height; - this.depth = depth; - } + /** + * Make a dimension + * + * @param width width of this (X) + * @param height the height (Y) + * @param depth the depth (Z) + */ + public Dimension(int width, int height, int depth) { + this.width = width; + this.height = height; + this.depth = depth; + } - /** - * Make a dimension - * - * @param width - * width of this (X) - * @param height - * the height (Y) - */ - public Dimension(int width, int height) - { - this.width = width; - this.height = height; - this.depth = 0; - } + /** + * Make a dimension + * + * @param width width of this (X) + * @param height the height (Y) + */ + public Dimension(int width, int height) { + this.width = width; + this.height = height; + this.depth = 0; + } - /** - * Get the direction of the flat part of this dimension (null if no thin - * face) - * - * @return the direction of the flat pane or null - */ - public DimensionFace getPane() - { - if(width == 1) - { - return DimensionFace.X; - } + /** + * Get the direction of the flat part of this dimension (null if no thin + * face) + * + * @return the direction of the flat pane or null + */ + public DimensionFace getPane() { + if (width == 1) { + return DimensionFace.X; + } - if(height == 1) - { - return DimensionFace.Y; - } + if (height == 1) { + return DimensionFace.Y; + } - if(depth == 1) - { - return DimensionFace.Z; - } + if (depth == 1) { + return DimensionFace.Z; + } - return null; - } + return null; + } - public int getWidth() - { - return width; - } + public int getWidth() { + return width; + } - public int getHeight() - { - return height; - } + public int getHeight() { + return height; + } - public int getDepth() - { - return depth; - } + public int getDepth() { + return depth; + } } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/DimensionFace.java b/src/main/java/com/volmit/iris/util/DimensionFace.java index dce11d0e6..f537fe5ee 100644 --- a/src/main/java/com/volmit/iris/util/DimensionFace.java +++ b/src/main/java/com/volmit/iris/util/DimensionFace.java @@ -5,20 +5,19 @@ package com.volmit.iris.util; * * @author cyberpwn */ -public enum DimensionFace -{ - /** - * The X dimension (width) - */ - X, +public enum DimensionFace { + /** + * The X dimension (width) + */ + X, - /** - * The Y dimension (height) - */ - Y, + /** + * The Y dimension (height) + */ + Y, - /** - * The Z dimension (depth) - */ - Z + /** + * The Z dimension (depth) + */ + Z } \ No newline at end of file diff --git a/src/main/java/com/volmit/iris/util/Direction.java b/src/main/java/com/volmit/iris/util/Direction.java index 4c4d32835..5c00663c4 100644 --- a/src/main/java/com/volmit/iris/util/Direction.java +++ b/src/main/java/com/volmit/iris/util/Direction.java @@ -1,533 +1,415 @@ - package com.volmit.iris.util; +import com.volmit.iris.util.Cuboid.CuboidDirection; import org.bukkit.Axis; import org.bukkit.block.BlockFace; import org.bukkit.util.Vector; -import com.volmit.iris.util.Cuboid.CuboidDirection; - /** * Directions * * @author cyberpwn */ -public enum Direction -{ - U(0, 1, 0, CuboidDirection.Up), - D(0, -1, 0, CuboidDirection.Down), - N(0, 0, -1, CuboidDirection.North), - S(0, 0, 1, CuboidDirection.South), - E(1, 0, 0, CuboidDirection.East), - W(-1, 0, 0, CuboidDirection.West); +public enum Direction { + U(0, 1, 0, CuboidDirection.Up), + D(0, -1, 0, CuboidDirection.Down), + N(0, 0, -1, CuboidDirection.North), + S(0, 0, 1, CuboidDirection.South), + E(1, 0, 0, CuboidDirection.East), + W(-1, 0, 0, CuboidDirection.West); - private static KMap, DOP> permute = null; + private static KMap, DOP> permute = null; - private int x; - private int y; - private int z; - private CuboidDirection f; + private final int x; + private final int y; + private final int z; + private final CuboidDirection f; - public static Direction getDirection(BlockFace f) - { - switch(f) - { - case DOWN: - return D; - case EAST: - return E; - case EAST_NORTH_EAST: - return E; - case EAST_SOUTH_EAST: - return E; - case NORTH: - return N; - case NORTH_EAST: - return N; - case NORTH_NORTH_EAST: - return N; - case NORTH_NORTH_WEST: - return N; - case NORTH_WEST: - return N; - case SELF: - return U; - case SOUTH: - return S; - case SOUTH_EAST: - return S; - case SOUTH_SOUTH_EAST: - return S; - case SOUTH_SOUTH_WEST: - return S; - case SOUTH_WEST: - return S; - case UP: - return U; - case WEST: - return W; - case WEST_NORTH_WEST: - return W; - case WEST_SOUTH_WEST: - return W; - } + public static Direction getDirection(BlockFace f) { + switch (f) { + case DOWN: + return D; + case EAST: + return E; + case EAST_NORTH_EAST: + return E; + case EAST_SOUTH_EAST: + return E; + case NORTH: + return N; + case NORTH_EAST: + return N; + case NORTH_NORTH_EAST: + return N; + case NORTH_NORTH_WEST: + return N; + case NORTH_WEST: + return N; + case SELF: + return U; + case SOUTH: + return S; + case SOUTH_EAST: + return S; + case SOUTH_SOUTH_EAST: + return S; + case SOUTH_SOUTH_WEST: + return S; + case SOUTH_WEST: + return S; + case UP: + return U; + case WEST: + return W; + case WEST_NORTH_WEST: + return W; + case WEST_SOUTH_WEST: + return W; + } - return D; - } + return D; + } - @Override - public String toString() - { - switch(this) - { - case D: - return "Down"; - case E: - return "East"; - case N: - return "North"; - case S: - return "South"; - case U: - return "Up"; - case W: - return "West"; - } + @Override + public String toString() { + switch (this) { + case D: + return "Down"; + case E: + return "East"; + case N: + return "North"; + case S: + return "South"; + case U: + return "Up"; + case W: + return "West"; + } - return "?"; - } + return "?"; + } - public boolean isVertical() - { - return equals(D) || equals(U); - } + public boolean isVertical() { + return equals(D) || equals(U); + } - public static Direction closest(Vector v) - { - double m = Double.MAX_VALUE; - Direction s = null; + public static Direction closest(Vector v) { + double m = Double.MAX_VALUE; + Direction s = null; - for(Direction i : values()) - { - Vector x = i.toVector(); - double g = x.dot(v); + for (Direction i : values()) { + Vector x = i.toVector(); + double g = x.dot(v); - if(g < m) - { - m = g; - s = i; - } - } + if (g < m) { + m = g; + s = i; + } + } - return s; - } + return s; + } - public static Direction closest(Vector v, Direction... d) - { - double m = Double.MAX_VALUE; - Direction s = null; + public static Direction closest(Vector v, Direction... d) { + double m = Double.MAX_VALUE; + Direction s = null; - for(Direction i : d) - { - Vector x = i.toVector(); - double g = x.distance(v); + for (Direction i : d) { + Vector x = i.toVector(); + double g = x.distance(v); - if(g < m) - { - m = g; - s = i; - } - } + if (g < m) { + m = g; + s = i; + } + } - return s; - } + return s; + } - public static Direction closest(Vector v, KList d) - { - double m = Double.MAX_VALUE; - Direction s = null; + public static Direction closest(Vector v, KList d) { + double m = Double.MAX_VALUE; + Direction s = null; - for(Direction i : d) - { - Vector x = i.toVector(); - double g = x.distance(v); + for (Direction i : d) { + Vector x = i.toVector(); + double g = x.distance(v); - if(g < m) - { - m = g; - s = i; - } - } + if (g < m) { + m = g; + s = i; + } + } - return s; - } + return s; + } - public Vector toVector() - { - return new Vector(x, y, z); - } + public Vector toVector() { + return new Vector(x, y, z); + } - public boolean isCrooked(Direction to) - { - if(equals(to.reverse())) - { - return false; - } + public boolean isCrooked(Direction to) { + if (equals(to.reverse())) { + return false; + } - if(equals(to)) - { - return false; - } + return !equals(to); + } - return true; - } + Direction(int x, int y, int z, CuboidDirection f) { + this.x = x; + this.y = y; + this.z = z; + this.f = f; + } - private Direction(int x, int y, int z, CuboidDirection f) - { - this.x = x; - this.y = y; - this.z = z; - this.f = f; - } + public Vector angle(Vector initial, Direction d) { + calculatePermutations(); - public Vector angle(Vector initial, Direction d) - { - calculatePermutations(); + for (GBiset i : permute.keySet()) { + if (i.getA().equals(this) && i.getB().equals(d)) { + return permute.get(i).op(initial); + } + } - for(GBiset i : permute.keySet()) - { - if(i.getA().equals(this) && i.getB().equals(d)) - { - return permute.get(i).op(initial); - } - } + return initial; + } - return initial; - } + public Direction reverse() { + switch (this) { + case D: + return U; + case E: + return W; + case N: + return S; + case S: + return N; + case U: + return D; + case W: + return E; + default: + break; + } - public Direction reverse() - { - switch(this) - { - case D: - return U; - case E: - return W; - case N: - return S; - case S: - return N; - case U: - return D; - case W: - return E; - default: - break; - } + return null; + } - return null; - } + public int x() { + return x; + } - public int x() - { - return x; - } + public int y() { + return y; + } - public int y() - { - return y; - } + public int z() { + return z; + } - public int z() - { - return z; - } + public CuboidDirection f() { + return f; + } - public CuboidDirection f() - { - return f; - } + public static KList news() { + return new KList().add(N, E, W, S); + } - public static KList news() - { - return new KList().add(N, E, W, S); - } + public static Direction getDirection(Vector v) { + Vector k = VectorMath.triNormalize(v.clone().normalize()); - public static Direction getDirection(Vector v) - { - Vector k = VectorMath.triNormalize(v.clone().normalize()); + for (Direction i : udnews()) { + if (i.x == k.getBlockX() && i.y == k.getBlockY() && i.z == k.getBlockZ()) { + return i; + } + } - for(Direction i : udnews()) - { - if(i.x == k.getBlockX() && i.y == k.getBlockY() && i.z == k.getBlockZ()) - { - return i; - } - } + return Direction.N; + } - return Direction.N; - } + public static KList udnews() { + return new KList().add(U, D, N, E, W, S); + } - public static KList udnews() - { - return new KList().add(U, D, N, E, W, S); - } + /** + * 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 Direction fromByte(byte b) { + if (b > 5 || b < 0) { + return null; + } - /** - * 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 Direction fromByte(byte b) - { - if(b > 5 || b < 0) - { - return null; - } + if (b == 0) { + return D; + } else if (b == 1) { + return U; + } else if (b == 2) { + return N; + } else if (b == 3) { + return S; + } else if (b == 4) { + return W; + } else { + return E; + } + } - if(b == 0) - { - return D; - } + /** + * Get the byte value represented in some directional blocks + * + * @return the byte value + */ + public byte byteValue() { + switch (this) { + case D: + return 0; + case E: + return 5; + case N: + return 2; + case S: + return 3; + case U: + return 1; + case W: + return 4; + default: + break; + } - else if(b == 1) - { - return U; - } + return -1; + } - else if(b == 2) - { - return N; - } + public static void calculatePermutations() { + if (permute != null) { + return; + } - else if(b == 3) - { - return S; - } + permute = new KMap, DOP>(); - else if(b == 4) - { - return W; - } + for (Direction i : udnews()) { + for (Direction j : udnews()) { + GBiset b = new GBiset(i, j); - else - { - return E; - } - } + 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; + } + }); + } + } + } + } - /** - * Get the byte value represented in some directional blocks - * - * @return the byte value - */ - public byte byteValue() - { - switch(this) - { - case D: - return 0; - case E: - return 5; - case N: - return 2; - case S: - return 3; - case U: - return 1; - case W: - return 4; - default: - break; - } + public BlockFace getFace() { + switch (this) { + case D: + return BlockFace.DOWN; + case E: + return BlockFace.EAST; + case N: + return BlockFace.NORTH; + case S: + return BlockFace.SOUTH; + case U: + return BlockFace.UP; + case W: + return BlockFace.WEST; + } - return -1; - } + return null; + } - public static void calculatePermutations() - { - if(permute != null) - { - return; - } + public Axis getAxis() { + switch (this) { + case D: + return Axis.Y; + case E: + return Axis.X; + case N: + return Axis.Z; + case S: + return Axis.Z; + case U: + return Axis.Y; + case W: + return Axis.X; + } - permute = new KMap, DOP>(); - - for(Direction i : udnews()) - { - for(Direction 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; - } - }); - } - } - } - } - - public BlockFace getFace() - { - switch(this) - { - case D: - return BlockFace.DOWN; - case E: - return BlockFace.EAST; - case N: - return BlockFace.NORTH; - case S: - return BlockFace.SOUTH; - case U: - return BlockFace.UP; - case W: - return BlockFace.WEST; - } - - return null; - } - - public Axis getAxis() - { - switch(this) - { - case D: - return Axis.Y; - case E: - return Axis.X; - case N: - return Axis.Z; - case S: - return Axis.Z; - case U: - return Axis.Y; - case W: - return Axis.X; - } - - return null; - } + return null; + } } diff --git a/src/main/java/com/volmit/iris/util/DontObfuscate.java b/src/main/java/com/volmit/iris/util/DontObfuscate.java index d578bdda9..4055d41ca 100644 --- a/src/main/java/com/volmit/iris/util/DontObfuscate.java +++ b/src/main/java/com/volmit/iris/util/DontObfuscate.java @@ -1,14 +1,13 @@ package com.volmit.iris.util; -import static java.lang.annotation.ElementType.*; -import static java.lang.annotation.RetentionPolicy.*; - import java.lang.annotation.Retention; import java.lang.annotation.Target; +import static java.lang.annotation.ElementType.*; +import static java.lang.annotation.RetentionPolicy.RUNTIME; + @Retention(RUNTIME) @Target({FIELD, TYPE, CONSTRUCTOR, METHOD}) -public @interface DontObfuscate -{ +public @interface DontObfuscate { } diff --git a/src/main/java/com/volmit/iris/util/DoubleArrayUtils.java b/src/main/java/com/volmit/iris/util/DoubleArrayUtils.java index 7e0172388..461553438 100644 --- a/src/main/java/com/volmit/iris/util/DoubleArrayUtils.java +++ b/src/main/java/com/volmit/iris/util/DoubleArrayUtils.java @@ -5,35 +5,28 @@ import com.google.common.util.concurrent.AtomicDoubleArray; import java.util.Arrays; -public class DoubleArrayUtils -{ - public static void shiftRight(double[] values, double push) - { - for(int index = values.length - 2; index >= 0; index--) - { - values[index + 1] = values[index]; - } +public class DoubleArrayUtils { + public static void shiftRight(double[] values, double push) { + for (int index = values.length - 2; index >= 0; index--) { + values[index + 1] = values[index]; + } - values[0] = push; - } + values[0] = push; + } - public static void wrapRight(double[] values) - { - double last = values[values.length - 1]; - shiftRight(values, last); - } + public static void wrapRight(double[] values) { + double last = values[values.length - 1]; + shiftRight(values, last); + } - public static void fill(double[] values, double value) - { - Arrays.fill(values, value); - } + public static void fill(double[] values, double value) { + Arrays.fill(values, value); + } - public static void fill(AtomicDoubleArray values, double value) - { - for(int i = 0; i < values.length(); i++) - { - values.set(i, value); - } - } + public static void fill(AtomicDoubleArray values, double value) { + for (int i = 0; i < values.length(); i++) { + values.set(i, value); + } + } } diff --git a/src/main/java/com/volmit/iris/util/DoubleTag.java b/src/main/java/com/volmit/iris/util/DoubleTag.java index 655471b2a..c4bd090f4 100644 --- a/src/main/java/com/volmit/iris/util/DoubleTag.java +++ b/src/main/java/com/volmit/iris/util/DoubleTag.java @@ -2,24 +2,24 @@ package com.volmit.iris.util; /* * JNBT License - * + * * Copyright (c) 2010 Graham Edgecombe * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. - * + * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * * Neither the name of the JNBT team nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -30,13 +30,13 @@ package com.volmit.iris.util; * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * POSSIBILITY OF SUCH DAMAGE. */ + /** * The TAG_Double tag. * * @author Graham Edgecombe - * */ public final class DoubleTag extends Tag { @@ -48,7 +48,7 @@ public final class DoubleTag extends Tag { /** * Creates the tag. * - * @param name The name. + * @param name The name. * @param value The value. */ public DoubleTag(String name, double value) { diff --git a/src/main/java/com/volmit/iris/util/Element.java b/src/main/java/com/volmit/iris/util/Element.java index b5eb06f2d..d4c5c0425 100644 --- a/src/main/java/com/volmit/iris/util/Element.java +++ b/src/main/java/com/volmit/iris/util/Element.java @@ -2,53 +2,52 @@ package com.volmit.iris.util; import org.bukkit.inventory.ItemStack; -public interface Element -{ - public MaterialBlock getMaterial(); +public interface Element { + MaterialBlock getMaterial(); - public Element setMaterial(MaterialBlock b); + Element setMaterial(MaterialBlock b); - public boolean isEnchanted(); + boolean isEnchanted(); - public Element setEnchanted(boolean enchanted); + Element setEnchanted(boolean enchanted); - public String getId(); + String getId(); - public String getName(); + String getName(); - public Element setProgress(double progress); + Element setProgress(double progress); - public double getProgress(); + double getProgress(); - public short getEffectiveDurability(); + short getEffectiveDurability(); - public Element setCount(int c); + Element setCount(int c); - public int getCount(); + int getCount(); - public ItemStack computeItemStack(); + ItemStack computeItemStack(); - public Element setBackground(boolean bg); + Element setBackground(boolean bg); - public boolean isBackgrond(); + boolean isBackgrond(); - public Element setName(String name); + Element setName(String name); - public Element addLore(String loreLine); + Element addLore(String loreLine); - public KList getLore(); + KList getLore(); - public Element call(ElementEvent event, Element context); + Element call(ElementEvent event, Element context); - public Element onLeftClick(Callback clicked); + Element onLeftClick(Callback clicked); - public Element onRightClick(Callback clicked); + Element onRightClick(Callback clicked); - public Element onShiftLeftClick(Callback clicked); + Element onShiftLeftClick(Callback clicked); - public Element onShiftRightClick(Callback clicked); + Element onShiftRightClick(Callback clicked); - public Element onDraggedInto(Callback into); + Element onDraggedInto(Callback into); - public Element onOtherDraggedInto(Callback other); + Element onOtherDraggedInto(Callback other); } diff --git a/src/main/java/com/volmit/iris/util/ElementEvent.java b/src/main/java/com/volmit/iris/util/ElementEvent.java index 2208c1344..691fb84cf 100644 --- a/src/main/java/com/volmit/iris/util/ElementEvent.java +++ b/src/main/java/com/volmit/iris/util/ElementEvent.java @@ -4,14 +4,12 @@ package com.volmit.iris.util; * Element Event. * * @author cyberpwn - * */ -public enum ElementEvent -{ - LEFT, - RIGHT, - SHIFT_LEFT, - SHIFT_RIGHT, - DRAG_INTO, - OTHER_DRAG_INTO; +public enum ElementEvent { + LEFT, + RIGHT, + SHIFT_LEFT, + SHIFT_RIGHT, + DRAG_INTO, + OTHER_DRAG_INTO } diff --git a/src/main/java/com/volmit/iris/util/EndTag.java b/src/main/java/com/volmit/iris/util/EndTag.java index c6d88a345..00ef6e163 100644 --- a/src/main/java/com/volmit/iris/util/EndTag.java +++ b/src/main/java/com/volmit/iris/util/EndTag.java @@ -2,24 +2,24 @@ package com.volmit.iris.util; /* * JNBT License - * + * * Copyright (c) 2010 Graham Edgecombe * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. - * + * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * * Neither the name of the JNBT team nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -30,13 +30,13 @@ package com.volmit.iris.util; * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * POSSIBILITY OF SUCH DAMAGE. */ + /** * The TAG_End tag. * * @author Graham Edgecombe - * */ public final class EndTag extends Tag { diff --git a/src/main/java/com/volmit/iris/util/FakeWorld.java b/src/main/java/com/volmit/iris/util/FakeWorld.java index dc9b560be..ddec84287 100644 --- a/src/main/java/com/volmit/iris/util/FakeWorld.java +++ b/src/main/java/com/volmit/iris/util/FakeWorld.java @@ -26,1298 +26,1120 @@ import java.util.*; import java.util.function.Predicate; @SuppressWarnings("deprecation") -public class FakeWorld implements World -{ - private final int height; - private final int minHeight; - private final long seed; - private final File worldFolder; - private final Environment environment; - @Setter - private String worldName; +public class FakeWorld implements World { + private final int height; + private final int minHeight; + private final long seed; + private final File worldFolder; + private final Environment environment; + @Setter + private String worldName; - public FakeWorld(String name, int minHeight, int height, long seed, File worldFolder, Environment environment) - { - this.worldName = name; - this.height = height; - this.seed = seed; - this.worldFolder = worldFolder; - this.minHeight = minHeight; - this.environment = environment; - worldFolder.mkdirs(); - } + public FakeWorld(String name, int minHeight, int height, long seed, File worldFolder, Environment environment) { + this.worldName = name; + this.height = height; + this.seed = seed; + this.worldFolder = worldFolder; + this.minHeight = minHeight; + this.environment = environment; + worldFolder.mkdirs(); + } - @Override - public void sendPluginMessage(Plugin source, String channel, byte[] message) - { + @Override + public void sendPluginMessage(Plugin source, String channel, byte[] message) { - } + } - @Override - public Set getListeningPluginChannels() - { + @Override + public Set getListeningPluginChannels() { - return null; - } + return null; + } - @Override - public void setMetadata(String metadataKey, MetadataValue newMetadataValue) - { + @Override + public void setMetadata(String metadataKey, MetadataValue newMetadataValue) { - } + } - @Override - public List getMetadata(String metadataKey) - { + @Override + public List getMetadata(String metadataKey) { - return null; - } + return null; + } - @Override - public boolean hasMetadata(String metadataKey) - { + @Override + public boolean hasMetadata(String metadataKey) { - return false; - } + return false; + } - @Override - public void removeMetadata(String metadataKey, Plugin owningPlugin) - { + @Override + public void removeMetadata(String metadataKey, Plugin owningPlugin) { - } + } - @Override - public Block getBlockAt(int x, int y, int z) - { + @Override + public Block getBlockAt(int x, int y, int z) { - return null; - } + return null; + } - @Override - public Block getBlockAt(Location location) - { + @Override + public Block getBlockAt(Location location) { - return null; - } + return null; + } - @Override - public int getHighestBlockYAt(int x, int z) - { + @Override + public int getHighestBlockYAt(int x, int z) { - return 0; - } + return 0; + } - @Override - public int getHighestBlockYAt(Location location) - { + @Override + public int getHighestBlockYAt(Location location) { - return 0; - } + return 0; + } - @Override - public Block getHighestBlockAt(int x, int z) - { + @Override + public Block getHighestBlockAt(int x, int z) { - return null; - } + return null; + } - @Override - public Block getHighestBlockAt(Location location) - { + @Override + public Block getHighestBlockAt(Location location) { - return null; - } + return null; + } - @Override - public int getHighestBlockYAt(int x, int z, HeightMap heightMap) - { + @Override + public int getHighestBlockYAt(int x, int z, HeightMap heightMap) { - return 0; - } + return 0; + } - @Override - public int getHighestBlockYAt(Location location, HeightMap heightMap) - { + @Override + public int getHighestBlockYAt(Location location, HeightMap heightMap) { - return 0; - } + return 0; + } - @Override - public Block getHighestBlockAt(int x, int z, HeightMap heightMap) - { + @Override + public Block getHighestBlockAt(int x, int z, HeightMap heightMap) { - return null; - } + return null; + } - @Override - public Block getHighestBlockAt(Location location, HeightMap heightMap) - { + @Override + public Block getHighestBlockAt(Location location, HeightMap heightMap) { - return null; - } + return null; + } - @Override - public Chunk getChunkAt(int x, int z) - { + @Override + public Chunk getChunkAt(int x, int z) { - return null; - } + return null; + } - @Override - public Chunk getChunkAt(Location location) - { + @Override + public Chunk getChunkAt(Location location) { - return null; - } + return null; + } - @Override - public Chunk getChunkAt(Block block) - { + @Override + public Chunk getChunkAt(Block block) { - return null; - } + return null; + } - @Override - public boolean isChunkLoaded(Chunk chunk) - { + @Override + public boolean isChunkLoaded(Chunk chunk) { - return false; - } + return false; + } - @Override - public Chunk[] getLoadedChunks() - { + @Override + public Chunk[] getLoadedChunks() { - return null; - } + return null; + } - @Override - public void loadChunk(Chunk chunk) - { + @Override + public void loadChunk(Chunk chunk) { - } + } - @Override - public boolean isChunkLoaded(int x, int z) - { + @Override + public boolean isChunkLoaded(int x, int z) { - return false; - } + return false; + } - @Override - public boolean isChunkGenerated(int x, int z) - { + @Override + public boolean isChunkGenerated(int x, int z) { - return false; - } + return false; + } - @Override - public boolean isChunkInUse(int x, int z) - { + @Override + public boolean isChunkInUse(int x, int z) { - return false; - } + return false; + } - @Override - public void loadChunk(int x, int z) - { + @Override + public void loadChunk(int x, int z) { - } + } - @Override - public boolean loadChunk(int x, int z, boolean generate) - { + @Override + public boolean loadChunk(int x, int z, boolean generate) { - return false; - } + return false; + } - @Override - public boolean unloadChunk(Chunk chunk) - { + @Override + public boolean unloadChunk(Chunk chunk) { - return false; - } + return false; + } - @Override - public boolean unloadChunk(int x, int z) - { + @Override + public boolean unloadChunk(int x, int z) { - return false; - } + return false; + } - @Override - public boolean unloadChunk(int x, int z, boolean save) - { + @Override + public boolean unloadChunk(int x, int z, boolean save) { - return false; - } + return false; + } - @Override - public boolean unloadChunkRequest(int x, int z) - { + @Override + public boolean unloadChunkRequest(int x, int z) { - return false; - } + return false; + } - @Override - public boolean regenerateChunk(int x, int z) - { + @Override + public boolean regenerateChunk(int x, int z) { - return false; - } + return false; + } - @Override - public boolean refreshChunk(int x, int z) - { + @Override + public boolean refreshChunk(int x, int z) { - return false; - } + return false; + } - @Override - public boolean isChunkForceLoaded(int x, int z) - { + @Override + public boolean isChunkForceLoaded(int x, int z) { - return false; - } + return false; + } - @Override - public void setChunkForceLoaded(int x, int z, boolean forced) - { + @Override + public void setChunkForceLoaded(int x, int z, boolean forced) { - } + } - @Override - public Collection getForceLoadedChunks() - { + @Override + public Collection getForceLoadedChunks() { - return null; - } + return null; + } - @Override - public boolean addPluginChunkTicket(int x, int z, Plugin plugin) - { + @Override + public boolean addPluginChunkTicket(int x, int z, Plugin plugin) { - return false; - } + return false; + } - @Override - public boolean removePluginChunkTicket(int x, int z, Plugin plugin) - { + @Override + public boolean removePluginChunkTicket(int x, int z, Plugin plugin) { - return false; - } + return false; + } - @Override - public void removePluginChunkTickets(Plugin plugin) - { + @Override + public void removePluginChunkTickets(Plugin plugin) { - } + } - @Override - public Collection getPluginChunkTickets(int x, int z) - { + @Override + public Collection getPluginChunkTickets(int x, int z) { - return null; - } + return null; + } - @Override - public Map> getPluginChunkTickets() - { + @Override + public Map> getPluginChunkTickets() { - return null; - } + return null; + } - @Override - public Item dropItem(Location location, ItemStack item) - { + @Override + public Item dropItem(Location location, ItemStack item) { - return null; - } + return null; + } - @NotNull @Override public Item dropItem(@NotNull Location location, @NotNull ItemStack itemStack, @Nullable Consumer consumer) { - return null; - } + @NotNull + @Override + public Item dropItem(@NotNull Location location, @NotNull ItemStack itemStack, @Nullable Consumer consumer) { + return null; + } - @Override - public Item dropItemNaturally(Location location, ItemStack item) - { + @Override + public Item dropItemNaturally(Location location, ItemStack item) { - return null; - } + return null; + } - @NotNull @Override public Item dropItemNaturally(@NotNull Location location, @NotNull ItemStack itemStack, @Nullable Consumer consumer) { - return null; - } + @NotNull + @Override + public Item dropItemNaturally(@NotNull Location location, @NotNull ItemStack itemStack, @Nullable Consumer consumer) { + return null; + } - @Override - public Arrow spawnArrow(Location location, Vector direction, float speed, float spread) - { + @Override + public Arrow spawnArrow(Location location, Vector direction, float speed, float spread) { - return null; - } + return null; + } - @Override - public T spawnArrow(Location location, Vector direction, float speed, float spread, Class clazz) - { + @Override + public T spawnArrow(Location location, Vector direction, float speed, float spread, Class clazz) { - return null; - } + return null; + } - @Override - public boolean generateTree(Location location, TreeType type) - { + @Override + public boolean generateTree(Location location, TreeType type) { - return false; - } + return false; + } - @Override - public boolean generateTree(Location loc, TreeType type, BlockChangeDelegate delegate) - { + @Override + public boolean generateTree(Location loc, TreeType type, BlockChangeDelegate delegate) { - return false; - } + return false; + } - @Override - public Entity spawnEntity(Location loc, EntityType type) - { + @Override + public Entity spawnEntity(Location loc, EntityType type) { - return null; - } + return null; + } - @Override - public LightningStrike strikeLightning(Location loc) - { + @Override + public LightningStrike strikeLightning(Location loc) { - return null; - } + return null; + } - @Override - public LightningStrike strikeLightningEffect(Location loc) - { + @Override + public LightningStrike strikeLightningEffect(Location loc) { - return null; - } + return null; + } - @Override - public List getEntities() - { + @Override + public List getEntities() { - return null; - } + return null; + } - @Override - public List getLivingEntities() - { + @Override + public List getLivingEntities() { - return null; - } + return null; + } - @Override - public Collection getEntitiesByClass(@SuppressWarnings("unchecked") Class... classes) - { + @Override + public Collection getEntitiesByClass(@SuppressWarnings("unchecked") Class... classes) { - return null; - } + return null; + } - @Override - public Collection getEntitiesByClass(Class cls) - { + @Override + public Collection getEntitiesByClass(Class cls) { - return null; - } + return null; + } - @Override - public Collection getEntitiesByClasses(Class... classes) - { + @Override + public Collection getEntitiesByClasses(Class... classes) { - return null; - } + return null; + } - @Override - public List getPlayers() - { + @Override + public List getPlayers() { - return null; - } + return null; + } - @Override - public Collection getNearbyEntities(Location location, double x, double y, double z) - { + @Override + public Collection getNearbyEntities(Location location, double x, double y, double z) { - return null; - } + return null; + } - @Override - public Collection getNearbyEntities(Location location, double x, double y, double z, Predicate filter) - { + @Override + public Collection getNearbyEntities(Location location, double x, double y, double z, Predicate filter) { - return null; - } + return null; + } - @Override - public Collection getNearbyEntities(BoundingBox boundingBox) - { + @Override + public Collection getNearbyEntities(BoundingBox boundingBox) { - return null; - } + return null; + } - @Override - public Collection getNearbyEntities(BoundingBox boundingBox, Predicate filter) - { + @Override + public Collection getNearbyEntities(BoundingBox boundingBox, Predicate filter) { - return null; - } + return null; + } - @Override - public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance) - { + @Override + public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance) { - return null; - } + return null; + } - @Override - public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance, double raySize) - { + @Override + public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance, double raySize) { - return null; - } + return null; + } - @Override - public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance, Predicate filter) - { + @Override + public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance, Predicate filter) { - return null; - } + return null; + } - @Override - public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance, double raySize, Predicate filter) - { + @Override + public RayTraceResult rayTraceEntities(Location start, Vector direction, double maxDistance, double raySize, Predicate filter) { - return null; - } + return null; + } - @Override - public RayTraceResult rayTraceBlocks(Location start, Vector direction, double maxDistance) - { + @Override + public RayTraceResult rayTraceBlocks(Location start, Vector direction, double maxDistance) { - return null; - } + return null; + } - @Override - public RayTraceResult rayTraceBlocks(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode) - { + @Override + public RayTraceResult rayTraceBlocks(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode) { - return null; - } + return null; + } - @Override - public RayTraceResult rayTraceBlocks(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode, boolean ignorePassableBlocks) - { + @Override + public RayTraceResult rayTraceBlocks(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode, boolean ignorePassableBlocks) { - return null; - } + return null; + } - @Override - public RayTraceResult rayTrace(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode, boolean ignorePassableBlocks, double raySize, Predicate filter) - { + @Override + public RayTraceResult rayTrace(Location start, Vector direction, double maxDistance, FluidCollisionMode fluidCollisionMode, boolean ignorePassableBlocks, double raySize, Predicate filter) { - return null; - } + return null; + } - @Override - public String getName() - { + @Override + public String getName() { - return worldName; - } + return worldName; + } - @Override - public UUID getUID() - { + @Override + public UUID getUID() { - return null; - } + return null; + } - @Override - public Location getSpawnLocation() - { + @Override + public Location getSpawnLocation() { - return null; - } + return null; + } - @Override - public boolean setSpawnLocation(Location location) - { + @Override + public boolean setSpawnLocation(Location location) { - return false; - } + return false; + } - @Override public boolean setSpawnLocation(int i, int i1, int i2, float v) { - return false; - } + @Override + public boolean setSpawnLocation(int i, int i1, int i2, float v) { + return false; + } - @Override - public boolean setSpawnLocation(int x, int y, int z) - { + @Override + public boolean setSpawnLocation(int x, int y, int z) { - return false; - } + return false; + } - @Override - public long getTime() - { + @Override + public long getTime() { - return 0; - } + return 0; + } - @Override - public void setTime(long time) - { + @Override + public void setTime(long time) { - } + } - @Override - public long getFullTime() - { + @Override + public long getFullTime() { - return 0; - } + return 0; + } - @Override - public void setFullTime(long time) - { + @Override + public void setFullTime(long time) { - } + } - @Override public long getGameTime() { - return 0; - } + @Override + public long getGameTime() { + return 0; + } - @Override - public boolean hasStorm() - { + @Override + public boolean hasStorm() { - return false; - } + return false; + } - @Override - public void setStorm(boolean hasStorm) - { + @Override + public void setStorm(boolean hasStorm) { - } + } - @Override - public int getWeatherDuration() - { + @Override + public int getWeatherDuration() { - return 0; - } + return 0; + } - @Override - public void setWeatherDuration(int duration) - { + @Override + public void setWeatherDuration(int duration) { - } + } - @Override - public boolean isThundering() - { + @Override + public boolean isThundering() { - return false; - } + return false; + } - @Override - public void setThundering(boolean thundering) - { + @Override + public void setThundering(boolean thundering) { - } + } - @Override - public int getThunderDuration() - { + @Override + public int getThunderDuration() { - return 0; - } + return 0; + } - @Override - public void setThunderDuration(int duration) - { + @Override + public void setThunderDuration(int duration) { - } + } - @Override public boolean isClearWeather() { - return false; - } + @Override + public boolean isClearWeather() { + return false; + } - @Override public void setClearWeatherDuration(int i) { + @Override + public void setClearWeatherDuration(int i) { - } + } - @Override public int getClearWeatherDuration() { - return 0; - } + @Override + public int getClearWeatherDuration() { + return 0; + } - @Override - public boolean createExplosion(double x, double y, double z, float power) - { + @Override + public boolean createExplosion(double x, double y, double z, float power) { - return false; - } + return false; + } - @Override - public boolean createExplosion(double x, double y, double z, float power, boolean setFire) - { + @Override + public boolean createExplosion(double x, double y, double z, float power, boolean setFire) { - return false; - } + return false; + } - @Override - public boolean createExplosion(double x, double y, double z, float power, boolean setFire, boolean breakBlocks) - { + @Override + public boolean createExplosion(double x, double y, double z, float power, boolean setFire, boolean breakBlocks) { - return false; - } + return false; + } - @Override - public boolean createExplosion(double x, double y, double z, float power, boolean setFire, boolean breakBlocks, Entity source) - { + @Override + public boolean createExplosion(double x, double y, double z, float power, boolean setFire, boolean breakBlocks, Entity source) { - return false; - } + return false; + } - @Override - public boolean createExplosion(Location loc, float power) - { + @Override + public boolean createExplosion(Location loc, float power) { - return false; - } + return false; + } - @Override - public boolean createExplosion(Location loc, float power, boolean setFire) - { + @Override + public boolean createExplosion(Location loc, float power, boolean setFire) { - return false; - } + return false; + } - @Override - public boolean createExplosion(Location loc, float power, boolean setFire, boolean breakBlocks) - { + @Override + public boolean createExplosion(Location loc, float power, boolean setFire, boolean breakBlocks) { - return false; - } + return false; + } - @Override - public boolean createExplosion(Location loc, float power, boolean setFire, boolean breakBlocks, Entity source) - { + @Override + public boolean createExplosion(Location loc, float power, boolean setFire, boolean breakBlocks, Entity source) { - return false; - } + return false; + } - @Override - public Environment getEnvironment() - { + @Override + public Environment getEnvironment() { - return environment; - } + return environment; + } - @Override - public long getSeed() - { + @Override + public long getSeed() { - return seed; - } + return seed; + } - @Override - public boolean getPVP() - { + @Override + public boolean getPVP() { - return false; - } + return false; + } - @Override - public void setPVP(boolean pvp) - { + @Override + public void setPVP(boolean pvp) { - } + } - @Override - public ChunkGenerator getGenerator() - { + @Override + public ChunkGenerator getGenerator() { - return null; - } + return null; + } - @Override - public void save() - { + @Override + public void save() { - } + } - @Override - public List getPopulators() - { + @Override + public List getPopulators() { - return null; - } + return null; + } - @Override - public T spawn(Location location, Class clazz) throws IllegalArgumentException - { + @Override + public T spawn(Location location, Class clazz) throws IllegalArgumentException { - return null; - } + return null; + } - @Override - public T spawn(Location location, Class clazz, Consumer function) throws IllegalArgumentException - { + @Override + public T spawn(Location location, Class clazz, Consumer function) throws IllegalArgumentException { - return null; - } + return null; + } - @Override - public FallingBlock spawnFallingBlock(Location location, MaterialData data) throws IllegalArgumentException - { + @Override + public FallingBlock spawnFallingBlock(Location location, MaterialData data) throws IllegalArgumentException { - return null; - } + return null; + } - @Override - public FallingBlock spawnFallingBlock(Location location, BlockData data) throws IllegalArgumentException - { + @Override + public FallingBlock spawnFallingBlock(Location location, BlockData data) throws IllegalArgumentException { - return null; - } + return null; + } - @Override - public FallingBlock spawnFallingBlock(Location location, Material material, byte data) throws IllegalArgumentException - { + @Override + public FallingBlock spawnFallingBlock(Location location, Material material, byte data) throws IllegalArgumentException { - return null; - } + return null; + } - @Override - public void playEffect(Location location, Effect effect, int data) - { + @Override + public void playEffect(Location location, Effect effect, int data) { - } + } - @Override - public void playEffect(Location location, Effect effect, int data, int radius) - { + @Override + public void playEffect(Location location, Effect effect, int data, int radius) { - } + } - @Override - public void playEffect(Location location, Effect effect, T data) - { + @Override + public void playEffect(Location location, Effect effect, T data) { - } + } - @Override - public void playEffect(Location location, Effect effect, T data, int radius) - { + @Override + public void playEffect(Location location, Effect effect, T data, int radius) { - } + } - @Override - public ChunkSnapshot getEmptyChunkSnapshot(int x, int z, boolean includeBiome, boolean includeBiomeTemp) - { + @Override + public ChunkSnapshot getEmptyChunkSnapshot(int x, int z, boolean includeBiome, boolean includeBiomeTemp) { - return null; - } + return null; + } - @Override - public void setSpawnFlags(boolean allowMonsters, boolean allowAnimals) - { + @Override + public void setSpawnFlags(boolean allowMonsters, boolean allowAnimals) { - } + } - @Override - public boolean getAllowAnimals() - { + @Override + public boolean getAllowAnimals() { - return false; - } + return false; + } - @Override - public boolean getAllowMonsters() - { + @Override + public boolean getAllowMonsters() { - return false; - } + return false; + } - @Override - public Biome getBiome(int x, int z) - { + @Override + public Biome getBiome(int x, int z) { - return null; - } + return null; + } - @Override - public Biome getBiome(int x, int y, int z) - { + @Override + public Biome getBiome(int x, int y, int z) { - return null; - } + return null; + } - @Override - public void setBiome(int x, int z, Biome bio) - { + @Override + public void setBiome(int x, int z, Biome bio) { - } + } - @Override - public void setBiome(int x, int y, int z, Biome bio) - { + @Override + public void setBiome(int x, int y, int z, Biome bio) { - } + } - @Override - public double getTemperature(int x, int z) - { + @Override + public double getTemperature(int x, int z) { - return 0; - } + return 0; + } - @Override - public double getTemperature(int x, int y, int z) - { + @Override + public double getTemperature(int x, int y, int z) { - return 0; - } + return 0; + } - @Override - public double getHumidity(int x, int z) - { + @Override + public double getHumidity(int x, int z) { - return 0; - } + return 0; + } - @Override - public double getHumidity(int x, int y, int z) - { + @Override + public double getHumidity(int x, int y, int z) { - return 0; - } + return 0; + } - @Override public int getMinHeight() { - return minHeight; - } + @Override + public int getMinHeight() { + return minHeight; + } - @Override - public int getMaxHeight() - { + @Override + public int getMaxHeight() { - return height; - } + return height; + } - @Override - public int getSeaLevel() - { + @Override + public int getSeaLevel() { - return 0; - } + return 0; + } - @Override - public boolean getKeepSpawnInMemory() - { + @Override + public boolean getKeepSpawnInMemory() { - return false; - } + return false; + } - @Override - public void setKeepSpawnInMemory(boolean keepLoaded) - { + @Override + public void setKeepSpawnInMemory(boolean keepLoaded) { - } + } - @Override - public boolean isAutoSave() - { + @Override + public boolean isAutoSave() { - return false; - } + return false; + } - @Override - public void setAutoSave(boolean value) - { + @Override + public void setAutoSave(boolean value) { - } + } - @Override - public void setDifficulty(Difficulty difficulty) - { + @Override + public void setDifficulty(Difficulty difficulty) { - } + } - @Override - public Difficulty getDifficulty() - { + @Override + public Difficulty getDifficulty() { - return null; - } + return null; + } - @Override - public File getWorldFolder() - { + @Override + public File getWorldFolder() { - return worldFolder; - } + return worldFolder; + } - @Override - public WorldType getWorldType() - { + @Override + public WorldType getWorldType() { - return null; - } + return null; + } - @Override - public boolean canGenerateStructures() - { + @Override + public boolean canGenerateStructures() { - return false; - } + return false; + } - @Override - public boolean isHardcore() - { + @Override + public boolean isHardcore() { - return false; - } + return false; + } - @Override - public void setHardcore(boolean hardcore) - { + @Override + public void setHardcore(boolean hardcore) { - } + } - @Override - public long getTicksPerAnimalSpawns() - { + @Override + public long getTicksPerAnimalSpawns() { - return 0; - } + return 0; + } - @Override - public void setTicksPerAnimalSpawns(int ticksPerAnimalSpawns) - { + @Override + public void setTicksPerAnimalSpawns(int ticksPerAnimalSpawns) { - } + } - @Override - public long getTicksPerMonsterSpawns() - { + @Override + public long getTicksPerMonsterSpawns() { - return 0; - } + return 0; + } - @Override - public void setTicksPerMonsterSpawns(int ticksPerMonsterSpawns) - { + @Override + public void setTicksPerMonsterSpawns(int ticksPerMonsterSpawns) { - } + } - @Override - public long getTicksPerWaterSpawns() - { + @Override + public long getTicksPerWaterSpawns() { - return 0; - } + return 0; + } - @Override - public void setTicksPerWaterSpawns(int ticksPerWaterSpawns) - { + @Override + public void setTicksPerWaterSpawns(int ticksPerWaterSpawns) { - } + } - @Override - public long getTicksPerWaterAmbientSpawns() - { + @Override + public long getTicksPerWaterAmbientSpawns() { - return 0; - } + return 0; + } - @Override - public void setTicksPerWaterAmbientSpawns(int ticksPerAmbientSpawns) - { + @Override + public void setTicksPerWaterAmbientSpawns(int ticksPerAmbientSpawns) { - } + } - @Override - public long getTicksPerAmbientSpawns() - { + @Override + public long getTicksPerAmbientSpawns() { - return 0; - } + return 0; + } - @Override - public void setTicksPerAmbientSpawns(int ticksPerAmbientSpawns) - { + @Override + public void setTicksPerAmbientSpawns(int ticksPerAmbientSpawns) { - } + } - @Override - public int getMonsterSpawnLimit() - { + @Override + public int getMonsterSpawnLimit() { - return 0; - } + return 0; + } - @Override - public void setMonsterSpawnLimit(int limit) - { + @Override + public void setMonsterSpawnLimit(int limit) { - } + } - @Override - public int getAnimalSpawnLimit() - { + @Override + public int getAnimalSpawnLimit() { - return 0; - } + return 0; + } - @Override - public void setAnimalSpawnLimit(int limit) - { + @Override + public void setAnimalSpawnLimit(int limit) { - } + } - @Override - public int getWaterAnimalSpawnLimit() - { + @Override + public int getWaterAnimalSpawnLimit() { - return 0; - } + return 0; + } - @Override - public void setWaterAnimalSpawnLimit(int limit) - { + @Override + public void setWaterAnimalSpawnLimit(int limit) { - } + } - @Override - public int getWaterAmbientSpawnLimit() - { + @Override + public int getWaterAmbientSpawnLimit() { - return 0; - } + return 0; + } - @Override - public void setWaterAmbientSpawnLimit(int limit) - { + @Override + public void setWaterAmbientSpawnLimit(int limit) { - } + } - @Override - public int getAmbientSpawnLimit() - { + @Override + public int getAmbientSpawnLimit() { - return 0; - } + return 0; + } - @Override - public void setAmbientSpawnLimit(int limit) - { + @Override + public void setAmbientSpawnLimit(int limit) { - } + } - @Override - public void playSound(Location location, Sound sound, float volume, float pitch) - { + @Override + public void playSound(Location location, Sound sound, float volume, float pitch) { - } + } - @Override - public void playSound(Location location, String sound, float volume, float pitch) - { + @Override + public void playSound(Location location, String sound, float volume, float pitch) { - } + } - @Override - public void playSound(Location location, Sound sound, SoundCategory category, float volume, float pitch) - { + @Override + public void playSound(Location location, Sound sound, SoundCategory category, float volume, float pitch) { - } + } - @Override - public void playSound(Location location, String sound, SoundCategory category, float volume, float pitch) - { + @Override + public void playSound(Location location, String sound, SoundCategory category, float volume, float pitch) { - } + } - @Override - public String[] getGameRules() - { + @Override + public String[] getGameRules() { - return null; - } + return null; + } - @Override - public String getGameRuleValue(String rule) - { + @Override + public String getGameRuleValue(String rule) { - return null; - } + return null; + } - @Override - public boolean setGameRuleValue(String rule, String value) - { + @Override + public boolean setGameRuleValue(String rule, String value) { - return false; - } + return false; + } - @Override - public boolean isGameRule(String rule) - { + @Override + public boolean isGameRule(String rule) { - return false; - } + return false; + } - @Override - public T getGameRuleValue(GameRule rule) - { + @Override + public T getGameRuleValue(GameRule rule) { - return null; - } + return null; + } - @Override - public T getGameRuleDefault(GameRule rule) - { + @Override + public T getGameRuleDefault(GameRule rule) { - return null; - } + return null; + } - @Override - public boolean setGameRule(GameRule rule, T newValue) - { + @Override + public boolean setGameRule(GameRule rule, T newValue) { - return false; - } + return false; + } - @Override - public WorldBorder getWorldBorder() - { + @Override + public WorldBorder getWorldBorder() { - return null; - } + return null; + } - @Override - public void spawnParticle(Particle particle, Location location, int count) - { + @Override + public void spawnParticle(Particle particle, Location location, int count) { - } + } - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count) - { + @Override + public void spawnParticle(Particle particle, double x, double y, double z, int count) { - } + } - @Override - public void spawnParticle(Particle particle, Location location, int count, T data) - { + @Override + public void spawnParticle(Particle particle, Location location, int count, T data) { - } + } - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, T data) - { + @Override + public void spawnParticle(Particle particle, double x, double y, double z, int count, T data) { - } + } - @Override - public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ) - { + @Override + public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ) { - } + } - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ) - { + @Override + public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ) { - } + } - @Override - public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, T data) - { + @Override + public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, T data) { - } + } - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, T data) - { + @Override + public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, T data) { - } + } - @Override - public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra) - { + @Override + public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra) { - } + } - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra) - { + @Override + public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra) { - } + } - @Override - public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, T data) - { + @Override + public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, T data) { - } + } - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, T data) - { + @Override + public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, T data) { - } + } - @Override - public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, T data, boolean force) - { + @Override + public void spawnParticle(Particle particle, Location location, int count, double offsetX, double offsetY, double offsetZ, double extra, T data, boolean force) { - } + } - @Override - public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, T data, boolean force) - { + @Override + public void spawnParticle(Particle particle, double x, double y, double z, int count, double offsetX, double offsetY, double offsetZ, double extra, T data, boolean force) { - } + } - @Override - public Location locateNearestStructure(Location origin, StructureType structureType, int radius, boolean findUnexplored) - { - return null; - } + @Override + public Location locateNearestStructure(Location origin, StructureType structureType, int radius, boolean findUnexplored) { + return null; + } - @Override - public int getViewDistance() - { - return 0; - } + @Override + public int getViewDistance() { + return 0; + } - @Override - public Spigot spigot() - { - return null; - } + @Override + public Spigot spigot() { + return null; + } - @Override - public Raid locateNearestRaid(Location location, int radius) - { - return null; - } + @Override + public Raid locateNearestRaid(Location location, int radius) { + return null; + } - @Override - public List getRaids() - { - return null; - } + @Override + public List getRaids() { + return null; + } - @Override - public DragonBattle getEnderDragonBattle() - { - return null; - } + @Override + public DragonBattle getEnderDragonBattle() { + return null; + } } diff --git a/src/main/java/com/volmit/iris/util/FileWatcher.java b/src/main/java/com/volmit/iris/util/FileWatcher.java index 41ceffd76..009a3d1ff 100644 --- a/src/main/java/com/volmit/iris/util/FileWatcher.java +++ b/src/main/java/com/volmit/iris/util/FileWatcher.java @@ -2,38 +2,33 @@ package com.volmit.iris.util; import java.io.File; -public class FileWatcher -{ - protected final File file; - private boolean exists; - private long lastModified; - private long size; +public class FileWatcher { + protected final File file; + private boolean exists; + private long lastModified; + private long size; - public FileWatcher(File file) - { - this.file = file; - readProperties(); - } + public FileWatcher(File file) { + this.file = file; + readProperties(); + } - protected void readProperties() - { - exists = file.exists(); - lastModified = exists ? file.lastModified() : -1; - size = exists ? file.isDirectory() ? -2 : file.length() : -1; - } + protected void readProperties() { + exists = file.exists(); + lastModified = exists ? file.lastModified() : -1; + size = exists ? file.isDirectory() ? -2 : file.length() : -1; + } - public boolean checkModified() - { - long m = lastModified; - long g = size; - boolean mod = false; - readProperties(); + public boolean checkModified() { + long m = lastModified; + long g = size; + boolean mod = false; + readProperties(); - if(lastModified != m || g != size) - { - mod = true; - } + if (lastModified != m || g != size) { + mod = true; + } - return mod; - } + return mod; + } } diff --git a/src/main/java/com/volmit/iris/util/FinalInteger.java b/src/main/java/com/volmit/iris/util/FinalInteger.java index e4fe46488..093c95e38 100644 --- a/src/main/java/com/volmit/iris/util/FinalInteger.java +++ b/src/main/java/com/volmit/iris/util/FinalInteger.java @@ -5,32 +5,26 @@ package com.volmit.iris.util; * * @author cyberpwn */ -public class FinalInteger extends Wrapper -{ - public FinalInteger(Integer t) - { - super(t); - } +public class FinalInteger extends Wrapper { + public FinalInteger(Integer t) { + super(t); + } - /** - * Add to this value - * - * @param i - * the number to add to this value (value = value + i) - */ - public void add(int i) - { - set(get() + i); - } + /** + * Add to this value + * + * @param i the number to add to this value (value = value + i) + */ + public void add(int i) { + set(get() + i); + } - /** - * Subtract from this value - * - * @param i - * the number to subtract from this value (value = value - i) - */ - public void sub(int i) - { - set(get() - i); - } + /** + * Subtract from this value + * + * @param i the number to subtract from this value (value = value - i) + */ + public void sub(int i) { + set(get() - i); + } } diff --git a/src/main/java/com/volmit/iris/util/FloatTag.java b/src/main/java/com/volmit/iris/util/FloatTag.java index e4ddbf270..236c484ee 100644 --- a/src/main/java/com/volmit/iris/util/FloatTag.java +++ b/src/main/java/com/volmit/iris/util/FloatTag.java @@ -2,24 +2,24 @@ package com.volmit.iris.util; /* * JNBT License - * + * * Copyright (c) 2010 Graham Edgecombe * All rights reserved. - * + * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: - * + * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. - * + * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * + * * * Neither the name of the JNBT team nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. - * + * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -30,13 +30,13 @@ package com.volmit.iris.util; * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * POSSIBILITY OF SUCH DAMAGE. */ + /** * The TAG_Float tag. * * @author Graham Edgecombe - * */ public final class FloatTag extends Tag { @@ -48,7 +48,7 @@ public final class FloatTag extends Tag { /** * Creates the tag. * - * @param name The name. + * @param name The name. * @param value The value. */ public FloatTag(String name, float value) { diff --git a/src/main/java/com/volmit/iris/util/FolderWatcher.java b/src/main/java/com/volmit/iris/util/FolderWatcher.java index 5fa6d720a..6acdcf32c 100644 --- a/src/main/java/com/volmit/iris/util/FolderWatcher.java +++ b/src/main/java/com/volmit/iris/util/FolderWatcher.java @@ -2,121 +2,94 @@ package com.volmit.iris.util; import java.io.File; -public class FolderWatcher extends FileWatcher -{ - private KMap watchers; - private KList changed; - private KList created; - private KList deleted; +public class FolderWatcher extends FileWatcher { + private KMap watchers; + private KList changed; + private KList created; + private KList deleted; - public FolderWatcher(File file) - { - super(file); - } + public FolderWatcher(File file) { + super(file); + } - protected void readProperties() - { - if(watchers == null) - { - watchers = new KMap<>(); - changed = new KList<>(); - created = new KList<>(); - deleted = new KList<>(); - } + protected void readProperties() { + if (watchers == null) { + watchers = new KMap<>(); + changed = new KList<>(); + created = new KList<>(); + deleted = new KList<>(); + } - if(file.isDirectory()) - { - for(File i : file.listFiles()) - { - if(!watchers.containsKey(i)) - { - watchers.put(i, new FolderWatcher(i)); - } - } + if (file.isDirectory()) { + for (File i : file.listFiles()) { + if (!watchers.containsKey(i)) { + watchers.put(i, new FolderWatcher(i)); + } + } - if(watchers == null) - { - System.out.print("wtf"); - } + if (watchers == null) { + System.out.print("wtf"); + } - for(File i : watchers.k()) - { - if(!i.exists()) - { - watchers.remove(i); - } - } - } + for (File i : watchers.k()) { + if (!i.exists()) { + watchers.remove(i); + } + } + } else { + super.readProperties(); + } + } - else - { - super.readProperties(); - } - } + public boolean checkModified() { + changed.clear(); + created.clear(); + deleted.clear(); - public boolean checkModified() - { - changed.clear(); - created.clear(); - deleted.clear(); + if (file.isDirectory()) { + KMap w = watchers.copy(); + readProperties(); - if(file.isDirectory()) - { - KMap w = watchers.copy(); - readProperties(); + for (File i : w.k()) { + if (!watchers.containsKey(i)) { + deleted.add(i); + } + } - for(File i : w.k()) - { - if(!watchers.containsKey(i)) - { - deleted.add(i); - } - } + for (File i : watchers.k()) { + if (!w.containsKey(i)) { + created.add(i); + } else { + FolderWatcher fw = watchers.get(i); + if (fw.checkModified()) { + changed.add(fw.file); + } - for(File i : watchers.k()) - { - if(!w.containsKey(i)) - { - created.add(i); - } + changed.addAll(fw.getChanged()); + created.addAll(fw.getCreated()); + deleted.addAll(fw.getDeleted()); + } + } - else - { - FolderWatcher fw = watchers.get(i); - if(fw.checkModified()) - { - changed.add(fw.file); - } + return !changed.isEmpty() || !created.isEmpty() || !deleted.isEmpty(); + } - changed.addAll(fw.getChanged()); - created.addAll(fw.getCreated()); - deleted.addAll(fw.getDeleted()); - } - } + return super.checkModified(); + } - return !changed.isEmpty() || !created.isEmpty() || !deleted.isEmpty(); - } + public KMap getWatchers() { + return watchers; + } - return super.checkModified(); - } + public KList getChanged() { + return changed; + } - public KMap getWatchers() - { - return watchers; - } + public KList getCreated() { + return created; + } - public KList getChanged() - { - return changed; - } - - public KList getCreated() - { - return created; - } - - public KList getDeleted() - { - return deleted; - } + public KList getDeleted() { + return deleted; + } } diff --git a/src/main/java/com/volmit/iris/util/Form.java b/src/main/java/com/volmit/iris/util/Form.java index ac5f83ec6..4e879bda5 100644 --- a/src/main/java/com/volmit/iris/util/Form.java +++ b/src/main/java/com/volmit/iris/util/Form.java @@ -3,1562 +3,1256 @@ package com.volmit.iris.util; import java.math.BigInteger; import java.text.DecimalFormat; import java.text.NumberFormat; -import java.util.Calendar; -import java.util.Date; -import java.util.LinkedHashMap; -import java.util.Locale; -import java.util.Map; +import java.util.*; import java.util.Map.Entry; -import java.util.NavigableMap; -import java.util.TreeMap; import java.util.concurrent.TimeUnit; import java.util.regex.Matcher; import java.util.regex.Pattern; -public class Form -{ - private static NumberFormat NF; - private static DecimalFormat DF; - - private static final String NAMES[] = new String[] {"Thousand", "Million", "Billion", "Trillion", "Quadrillion", "Quintillion", "Sextillion", "Septillion", "Octillion", "Nonillion", "Decillion", "Undecillion", "Duodecillion", "Tredecillion", "Quattuordecillion", "Quindecillion", "Sexdecillion", "Septendecillion", "Octodecillion", "Novemdecillion", "Vigintillion",}; - private static final BigInteger THOUSAND = BigInteger.valueOf(1000); - private static final NavigableMap MAP; - - static - { - MAP = new TreeMap(); - for(int i = 0; i < NAMES.length; i++) - { - MAP.put(THOUSAND.pow(i + 1), NAMES[i]); - } - } - - private static void instantiate() - { - if(NF == null) - { - NF = NumberFormat.getInstance(Locale.US); - } - } - - /** - * Scroll text - * - * @param smx - * the text - * @param viewport - * the viewport length - * @param time - * the timeline value - * @return - */ - public static String scroll(String smx, int viewport, long time) - { - String src = Form.repeat(" ", viewport) + smx + Form.repeat(" ", viewport); - int len = src.length(); - int walk = (int) (time % (len - viewport)); - String base = src.substring(walk, M.min(walk + viewport, len - 1)); - base = base.length() < viewport ? base + Form.repeat(" ", (viewport - base.length()) - 3) : base; - - return base; - } - - /** - * Capitalize the first letter - * - * @param s - * the string - * @return the capitalized string - */ - public static String capitalize(String s) - { - String roll = ""; - boolean f = true; - - for(Character i : s.trim().toCharArray()) - { - if(f) - { - roll += Character.toUpperCase(i); - f = false; - } - - else - { - roll += i; - } - } - - return roll; - } - - /** - * Capitalize all words in the string - * - * @param s - * the string - * @return the capitalized string - */ - public static String capitalizeWords(String s) - { - String rollx = ""; - - for(String i : s.trim().split(" ")) - { - rollx += " " + capitalize(i.trim()); - } - - return rollx.substring(1); - } - - /** - * Hard word wrap - * - * @param s - * the words - * @param len - * the length per line - * @return the wrapped string - */ - public static String wrap(String s, int len) - { - return wrap(s, len, (String) null, false); - } - - /** - * Soft Word wrap - * - * @param s - * the string - * @param len - * the length to wrap - * @return the wrapped string - */ - public static String wrapWords(String s, int len) - { - return wrap(s, len, (String) null, true); - } - - /** - * Wrap words - * - * @param s - * the string - * @param len - * the wrap length - * @param newLineSep - * the new line seperator - * @param soft - * should it be soft wrapped or hard wrapped? - * @return the wrapped words - */ - public static String wrap(String s, int len, String newLineSep, boolean soft) - { - return wrap(s, len, newLineSep, soft, " "); - } - - /** - * Wrap words - * - * @param s - * the string - * @param len - * the length - * @param newLineSep - * the new line seperator - * @param soft - * soft or hard wrapping - * @param regex - * the regex - * @return the wrapped string - */ - public static String wrap(String s, int len, String newLineSep, boolean soft, String regex) - { - if(s == null) - { - return null; - } - - else - { - if(newLineSep == null) - { - newLineSep = "\n"; - } - - if(len < 1) - { - len = 1; - } - - if(regex.trim().equals("")) - { - regex = " "; - } - - Pattern arg4 = Pattern.compile(regex); - int arg5 = s.length(); - int arg6 = 0; - StringBuilder arg7 = new StringBuilder(arg5 + 32); - - while(arg6 < arg5) - { - int arg8 = -1; - Matcher arg9 = arg4.matcher(s.substring(arg6, Math.min(arg6 + len + 1, arg5))); - if(arg9.find()) - { - if(arg9.start() == 0) - { - arg6 += arg9.end(); - continue; - } - - arg8 = arg9.start(); - } - - if(arg5 - arg6 <= len) - { - break; - } - - while(arg9.find()) - { - arg8 = arg9.start() + arg6; - } - - if(arg8 >= arg6) - { - arg7.append(s.substring(arg6, arg8)); - arg7.append(newLineSep); - arg6 = arg8 + 1; - } - else if(soft) - { - arg7.append(s.substring(arg6, len + arg6)); - arg7.append(newLineSep); - arg6 += len; - } - else - { - arg9 = arg4.matcher(s.substring(arg6 + len)); - if(arg9.find()) - { - arg8 = arg9.start() + arg6 + len; - } - - if(arg8 >= 0) - { - arg7.append(s.substring(arg6, arg8)); - arg7.append(newLineSep); - arg6 = arg8 + 1; - } - else - { - arg7.append(s.substring(arg6)); - arg6 = arg5; - } - } - } - - arg7.append(s.substring(arg6)); - return arg7.toString(); - } - } - - /** - * Returns a fancy duration up to Years - * - * @param rollingSequence - * - * @param duration - * the duration in ms - * @return the fancy duration - */ - public static String duration(RollingSequence rollingSequence, long duration) - { - String suffix = "Millisecond"; - double phantom = duration; - int div = 1000; - - if(phantom > div) - { - phantom /= div; - suffix = "Second"; - div = 60; - - if(phantom > div) - { - phantom /= div; - suffix = "Minute"; - - if(phantom > div) - { - phantom /= div; - suffix = "Hour"; - div = 24; - - if(phantom > 24) - { - phantom /= div; - suffix = "Day"; - div = 7; - - if(phantom > div) - { - phantom /= div; - suffix = "Week"; - div = 4; - - if(phantom > div) - { - phantom /= div; - suffix = "Month"; - div = 12; - - if(phantom > div) - { - phantom /= div; - suffix = "Year"; - return Form.fd(phantom, 0) + " " + suffix + ((int) phantom == 1 ? "" : "s"); - } - - else - { - return Form.fd(phantom, 0) + " " + suffix + ((int) phantom == 1 ? "" : "s"); - } - } - - else - { - return Form.fd(phantom, 0) + " " + suffix + ((int) phantom == 1 ? "" : "s"); - } - } - - else - { - return Form.fd(phantom, 0) + " " + suffix + ((int) phantom == 1 ? "" : "s"); - } - } - - else - { - return Form.fd(phantom, 0) + " " + suffix + ((int) phantom == 1 ? "" : "s"); - } - } - - else - { - return Form.fd(phantom, 0) + " " + suffix + ((int) phantom == 1 ? "" : "s"); - } - } - - else - { - return Form.fd(phantom, 0) + " " + suffix + ((int) phantom == 1 ? "" : "s"); - } - } - - else - { - return "Under a Second"; - } - } - - /** - * Fixes the minute issue with formatting - * - * @param c - * the calendar - * @return the minute string - */ - public static String fmin(Calendar c) - { - String s = c.get(Calendar.MINUTE) + ""; - if(s.length() == 1) - { - return "0" + s; - } - - return s; - } - - /** - * Get a fancy time stamp - * - * @param time - * the stamp in time (ago) - * @return the fancy stamp in time (ago) - */ - public static String ago(long time) - { - long current = M.ms(); - - if(time > current - TimeUnit.SECONDS.toMillis(30) && time < current) - { - return "Just Now"; - } - - else if(time > current - TimeUnit.SECONDS.toMillis(60) && time < current) - { - return "Seconds Ago"; - } - - else if(time > current - TimeUnit.MINUTES.toMillis(10) && time < current) - { - return "Minutes Ago"; - } - - else - { - Calendar now = Calendar.getInstance(); - Calendar c = Calendar.getInstance(); - c.setTimeInMillis(time); - boolean sameYear = now.get(Calendar.YEAR) == c.get(Calendar.YEAR); - boolean sameDay = now.get(Calendar.DAY_OF_YEAR) == c.get(Calendar.DAY_OF_YEAR); - - if(sameDay) - { - int h = c.get(Calendar.HOUR); - h = h == 0 ? 12 : h; - - return "Today at " + h + ":" + fmin(c) + " " + (c.get(Calendar.AM_PM) == Calendar.PM ? "PM" : "AM"); - } - - else if(sameYear) - { - boolean yesterday = now.get(Calendar.DAY_OF_YEAR) - 1 == c.get(Calendar.DAY_OF_YEAR); - - if(yesterday) - { - int h = c.get(Calendar.HOUR); - h = h == 0 ? 12 : h; - - return "Yesterday at " + h + ":" + fmin(c) + " " + (c.get(Calendar.AM_PM) == Calendar.PM ? "PM" : "AM"); - } - - else - { - int h = c.get(Calendar.HOUR); - h = h == 0 ? 12 : h; - String dow = "Error Day"; - - switch(c.get(Calendar.DAY_OF_WEEK)) - { - case Calendar.SUNDAY: - dow = "Sunday"; - break; - case Calendar.MONDAY: - dow = "Monday"; - break; - case Calendar.TUESDAY: - dow = "Tuesday"; - break; - case Calendar.WEDNESDAY: - dow = "Wednesday"; - break; - case Calendar.THURSDAY: - dow = "Thursday"; - break; - case Calendar.FRIDAY: - dow = "Friday"; - break; - case Calendar.SATURDAY: - dow = "Saturday"; - break; - } - - String monthName = "Error Month"; - int month = c.get(Calendar.MONTH); - - switch(month) - { - case Calendar.JANUARY: - monthName = "Jan"; - break; - case Calendar.FEBRUARY: - monthName = "Feb"; - break; - case Calendar.MARCH: - monthName = "Mar"; - break; - case Calendar.APRIL: - monthName = "Apr"; - break; - case Calendar.MAY: - monthName = "May"; - break; - case Calendar.JUNE: - monthName = "Jun"; - break; - case Calendar.JULY: - monthName = "Jul"; - break; - case Calendar.AUGUST: - monthName = "Aug"; - break; - case Calendar.SEPTEMBER: - monthName = "Sep"; - break; - case Calendar.OCTOBER: - monthName = "Oct"; - break; - case Calendar.NOVEMBER: - monthName = "Nov"; - break; - case Calendar.DECEMBER: - monthName = "Dec"; - break; - } - - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - String suffix = numberSuffix(dayOfMonth); - - return dow + ", " + monthName + " " + suffix + " at " + h + ":" + fmin(c) + " " + (c.get(Calendar.AM_PM) == Calendar.PM ? "PM" : "AM"); - } - } - - else - { - int h = c.get(Calendar.HOUR); - h = h == 0 ? 12 : h; - String dow = "Error Day"; - - switch(c.get(Calendar.DAY_OF_WEEK)) - { - case Calendar.SUNDAY: - dow = "Sunday"; - break; - case Calendar.MONDAY: - dow = "Monday"; - break; - case Calendar.TUESDAY: - dow = "Tuesday"; - break; - case Calendar.WEDNESDAY: - dow = "Wednesday"; - break; - case Calendar.THURSDAY: - dow = "Thursday"; - break; - case Calendar.FRIDAY: - dow = "Friday"; - break; - case Calendar.SATURDAY: - dow = "Saturday"; - break; - } - - String monthName = "Error Month"; - int month = c.get(Calendar.MONTH); - - switch(month) - { - case Calendar.JANUARY: - monthName = "Jan"; - break; - case Calendar.FEBRUARY: - monthName = "Feb"; - break; - case Calendar.MARCH: - monthName = "Mar"; - break; - case Calendar.APRIL: - monthName = "Apr"; - break; - case Calendar.MAY: - monthName = "May"; - break; - case Calendar.JUNE: - monthName = "Jun"; - break; - case Calendar.JULY: - monthName = "Jul"; - break; - case Calendar.AUGUST: - monthName = "Aug"; - break; - case Calendar.SEPTEMBER: - monthName = "Sep"; - break; - case Calendar.OCTOBER: - monthName = "Oct"; - break; - case Calendar.NOVEMBER: - monthName = "Nov"; - break; - case Calendar.DECEMBER: - monthName = "Dec"; - break; - } - - int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); - String suffix = numberSuffix(dayOfMonth); - int year = c.get(Calendar.YEAR); - - return year + ", " + dow + ", " + monthName + " " + suffix + " at " + h + ":" + fmin(c) + " " + (c.get(Calendar.AM_PM) == Calendar.PM ? "PM" : "AM"); - } - } - } - - /** - * Get the suffix for a number i.e. 1st 2nd 3rd - * - * @param i - * the number - * @return the suffix - */ - public static String numberSuffix(int i) - { - String[] sufixes = new String[] {"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"}; - switch(i % 100) - { - case 11: - case 12: - case 13: - return i + "th"; - default: - return i + sufixes[i % 10]; - - } - } - - /** - * Get a high accuracy but limited range duration (accurate up to a couple - * minutes) - * - * @param ms - * the milliseconds (double) - * @param prec - * the precision (decimal format) - * @return the formatted string - */ - public static String duration(double ms, int prec) - { - if(ms < 1000.0) - { - return Form.f(ms, prec) + "ms"; - } - - if(ms / 1000.0 < 60.0) - { - return Form.f(ms / 1000.0, prec) + "s"; - } - - if(ms / 1000.0 / 60.0 < 60.0) - { - return Form.f(ms / 1000.0 / 60.0, prec) + "m"; - } - - if(ms / 1000.0 / 60.0 / 60.0 < 24.0) - { - return Form.f(ms / 1000.0 / 60.0 / 60.0, prec) + " hours"; - } - - if(ms / 1000.0 / 60.0 / 60.0 / 24.0 < 7) - { - return Form.f(ms / 1000.0 / 60.0 / 24.0, prec) + " days"; - } - - return Form.f(ms, prec) + "ms"; - } - - public static String duration(long ms) - { - return duration(ms, 0); - } - - /** - * Get a duration from milliseconds up to days - * - * @param ms - * the ms - * @param prec - * the precision (decimal format) - * @return the formatted string - */ - public static String duration(long ms, int prec) - { - if(ms < 1000.0) - { - return Form.f(ms, prec) + "ms"; - } - - if(ms / 1000.0 < 60.0) - { - return Form.f(ms / 1000.0, prec) + " seconds"; - } - - if(ms / 1000.0 / 60.0 < 60.0) - { - return Form.f(ms / 1000.0 / 60.0, prec) + " minutes"; - } - - if(ms / 1000.0 / 60.0 / 60.0 < 24.0) - { - return Form.f(ms / 1000.0 / 60.0 / 60.0, prec) + " hours"; - } - - if(ms / 1000.0 / 60.0 / 60.0 / 24.0 < 7) - { - return Form.f(ms / 1000.0 / 60.0 / 24.0, prec) + " days"; - } - - return Form.f(ms, prec) + "ms"; - } - - /** - * Format a big value - * - * @param i - * the number - * @return the full value in string - */ - public static String b(int i) - { - return b(new BigInteger(String.valueOf(i))); - } - - /** - * Format a big value - * - * @param i - * the number - * @return the full value in string - */ - public static String b(long i) - { - return b(new BigInteger(String.valueOf(i))); - } - - /** - * Format a big value - * - * @param i - * the number - * @return the full value in string - */ - public static String b(double i) - { - return b(new BigInteger(String.valueOf((long) i))); - } - - /** - * Format a big number - * - * @param number - * the big number - * @return the value in string - */ - public static String b(BigInteger number) - { - Entry entry = MAP.floorEntry(number); - if(entry == null) - { - return "Nearly nothing"; - } - - BigInteger key = entry.getKey(); - BigInteger d = key.divide(THOUSAND); - BigInteger m = number.divide(d); - float f = m.floatValue() / 1000.0f; - float rounded = ((int) (f * 100.0)) / 100.0f; - - if(rounded % 1 == 0) - { - return ((int) rounded) + " " + entry.getValue(); - } - - return rounded + " " + entry.getValue(); - } - - /** - * Calculate a fancy string representation of a file size. Adds a suffix of B, - * KB, MB, GB, or TB - * - * @param s - * the size (in bytes) - * @return the string - */ - public static String fileSize(long s) - { - return ofSize(s, 1000); - } - - /** - * ":", "a", "b", "c" -> a:b:c - * - * @param splitter - * the splitter that goes in between - * @param strings - * the strings - * @return the result - */ - public static String split(String splitter, String... strings) - { - StringBuilder b = new StringBuilder(); - - for(String i : strings) - { - b.append(splitter); - b.append(i); - } - - return b.toString().substring(splitter.length()); - } - - /** - * Calculate a fancy string representation of a file size. Adds a suffix of B, - * KB, MB, GB, or TB - * - * @param s - * the size (in bytes) - * @return the string - */ - public static String memSize(long s) - { - return ofSize(s, 1024); - } - - public static String memSize(long s, int dec) - { - return ofSize(s, 1024, dec); - } - - /** - * Get the timestamp of the time t (ms since 1970) - * - * @param t - * the time - * @return the stamp - */ - @SuppressWarnings("deprecation") - public static String stamp(long t) - { - Date d = new Date(t); - return d.getMonth() + "-" + d.getDate() + "-" + (d.getYear() + 1900) + " " + d.getHours() + "h " + d.getMinutes() + "m " + d.getSeconds() + "s "; - } - - @SuppressWarnings("deprecation") - public static String stampTime(long t) - { - Date d = new Date(t); - - return Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":" + forceDoubleDigit(d.getMinutes()) + ":" + forceDoubleDigit(d.getSeconds()); - } - - public static String forceDoubleDigit(int dig) - { - if(dig < 10) - { - return "0" + dig; - } - - return dig + ""; - } - - @SuppressWarnings("deprecation") - public static String stampDay(long t) - { - Date d = new Date(t); - return d.getMonth() + "-" + d.getDate() + "-" + (d.getYear() + 1900); - } - - /** - * Calculate a fancy string representation of a size in B, KB, MB, GB, or TB - * with a special divisor. The divisor decides how much goes up in the suffix - * chain. - * - * @param s - * the size (in bytes) - * @param div - * the divisor - * @return the string - */ - public static String ofSize(long s, int div) - { - Double d = (double) s; - String sub = "Bytes"; - - if(d > div - 1) - { - d /= div; - sub = "KB"; - - if(d > div - 1) - { - d /= div; - sub = "MB"; - - if(d > div - 1) - { - d /= div; - sub = "GB"; - - if(d > div - 1) - { - d /= div; - sub = "TB"; - } - } - } - } - - if(sub.equals("GB") || sub.equals("TB")) - { - return Form.f(d, 1) + sub; - } - - else - { - return Form.f(d, 0) + sub; - } - } - - /** - * Calculate a fancy string representation of a size in B, KB, MB, GB, or TB - * with a special divisor. The divisor decides how much goes up in the suffix - * chain. - * - * @param s - * the size (in bytes) - * @param div - * the divisor - * @param dec - * the decimal places - * @return the string - */ - public static String ofSize(long s, int div, int dec) - { - Double d = (double) s; - String sub = "Bytes"; - - if(d > div - 1) - { - d /= div; - sub = "KB"; - - if(d > div - 1) - { - d /= div; - sub = "MB"; - - if(d > div - 1) - { - d /= div; - sub = "GB"; - - if(d > div - 1) - { - d /= div; - sub = "TB"; - } - } - } - } - - return Form.f(d, dec) + " " + sub; - } - - /** - * Calculate a fancy string representation of a size in Grams, KG, MG, GG, TG - * with a special divisor. The divisor decides how much goes up in the suffix - * chain. - * - * @param s - * the size (in bytes) - * @param div - * the divisor - * @param dec - * the decimal places - * @return the string - */ - public static String ofSizeMetricWeight(long s, int div, int dec) - { - boolean neg = s < 0; - if(neg) - { - s = -s; - } - Double d = (double) s; - String sub = "Grams"; - - if(d > div - 1) - { - d /= div; - sub = "KG"; - - if(d > div - 1) - { - d /= div; - sub = "MG"; - - if(d > div - 1) - { - d /= div; - sub = "GG"; - - if(d > div - 1) - { - d /= div; - sub = "TG"; - } - } - } - } - - return (neg ? "-" : "") + Form.f(d, dec) + " " + sub; - } - - /** - * Trim a string to a length, then append ... at the end if it extends the limit - * - * @param s - * the string - * @param l - * the limit - * @return the modified string - */ - public static String trim(String s, int l) - { - if(s.length() <= l) - { - return s; - } - - return s.substring(0, l) + "..."; - } - - /** - * Get a class name into a configuration/filename key For example, - * PhantomController.class is converted to phantom-controller - * - * @param clazz - * the class - * @return the string representation - */ - public static String cname(String clazz) - { - String codeName = ""; - - for(Character i : clazz.toCharArray()) - { - if(Character.isUpperCase(i)) - { - codeName = codeName + "-" + Character.toLowerCase(i); - } - - else - { - codeName = codeName + i; - } - } - - if(codeName.startsWith("-")) - { - codeName = codeName.substring(1); - } - - return codeName; - } - - /** - * Get a formatted representation of the memory given in megabytes - * - * @param mb - * the megabytes - * @return the string representation with suffixes - */ - public static String mem(long mb) - { - if(mb < 1024) - { - return f(mb) + " MB"; - } - - else - { - return f(((double) mb / (double) 1024), 1) + " GB"; - } - } - - /** - * Get a formatted representation of the memory given in kilobytes - * - * @param mb - * the kilobytes - * @return the string representation with suffixes - */ - public static String memx(long kb) - { - if(kb < 1024) - { - return fd(kb, 2) + " KB"; - } - - else - { - double mb = (double) kb / 1024.0; - - if(mb < 1024) - { - return fd(mb, 2) + " MB"; - } - - else - { - double gb = (double) mb / 1024.0; - - return fd(gb, 2) + " GB"; - } - } - } - - /** - * Format a long. Changes -10334 into -10,334 - * - * @param i - * the number - * @return the string representation of the number - */ - public static String f(long i) - { - instantiate(); - return NF.format(i); - } - - /** - * Format a number. Changes -10334 into -10,334 - * - * @param i - * the number - * @return the string representation of the number - */ - public static String f(int i) - { - instantiate(); - return NF.format(i); - } - - /** - * Formats a double's decimals to a limit - * - * @param i - * the double - * @param p - * the number of decimal places to use - * @return the formated string - */ - public static String f(double i, int p) - { - String form = "#"; - - if(p > 0) - { - form = form + "." + repeat("#", p); - } - - DF = new DecimalFormat(form); - - return DF.format(i); - } - - /** - * Formats a double's decimals to a limit, however, this will add zeros to the - * decimal places that dont need to be placed down. 2.4343 formatted with 6 - * decimals gets returned as 2.434300 - * - * @param i - * the double - * @param p - * the number of decimal places to use - * @return the formated string - */ - public static String fd(double i, int p) - { - String form = "0"; - - if(p > 0) - { - form = form + "." + repeat("0", p); - } - - DF = new DecimalFormat(form); - - return DF.format(i); - } - - /** - * Formats a float's decimals to a limit - * - * @param i - * the float - * @param p - * the number of decimal places to use - * @return the formated string - */ - public static String f(float i, int p) - { - String form = "#"; - - if(p > 0) - { - form = form + "." + repeat("#", p); - } - - DF = new DecimalFormat(form); - - return DF.format(i); - } - - /** - * Formats a double's decimals (one decimal point) - * - * @param i - * the double - */ - public static String f(double i) - { - return f(i, 1); - } - - /** - * Formats a float's decimals (one decimal point) - * - * @param i - * the float - */ - public static String f(float i) - { - return f(i, 1); - } - - /** - * Get a percent representation of a double and decimal places (0.53) would - * return 53% - * - * @param i - * the double - * @param p - * the number of decimal points - * @return a string - */ - public static String pc(double i, int p) - { - return f(i * 100.0, p) + "%"; - } - - /** - * Get a percent representation of a float and decimal places (0.53) would - * return 53% - * - * @param i - * the float - * @param p - * the number of decimal points - * @return a string - */ - public static String pc(float i, int p) - { - return f(i * 100, p) + "%"; - } - - /** - * Get a percent representation of a double and zero decimal places (0.53) would - * return 53% - * - * @param i - * the double - * @return a string - */ - public static String pc(double i) - { - return f(i * 100, 0) + "%"; - } - - /** - * Get a percent representation of a float and zero decimal places (0.53) would - * return 53% - * - * @param i - * the double - * @return a string - */ - public static String pc(float i) - { - return f(i * 100, 0) + "%"; - } - - /** - * Get a percent as the percent of i out of "of" with custom decimal places - * - * @param i - * the percent out of - * @param of - * of of - * @param p - * the decimal places - * @return the string - */ - public static String pc(int i, int of, int p) - { - return f(100.0 * (((double) i) / ((double) of)), p) + "%"; - } - - /** - * Get a percent as the percent of i out of "of" - * - * @param i - * the percent out of - * @param of - * of of - * @return the string - */ - public static String pc(int i, int of) - { - return pc(i, of, 0); - } - - /** - * Get a percent as the percent of i out of "of" with custom decimal places - * - * @param i - * the percent out of - * @param of - * of of - * @param p - * the decimal places - * @return the string - */ - public static String pc(long i, long of, int p) - { - return f(100.0 * (((double) i) / ((double) of)), p) + "%"; - } - - /** - * Get a percent as the percent of i out of "of" - * - * @param i - * the percent out of - * @param of - * of of - * @return the string - */ - public static String pc(long i, long of) - { - return pc(i, of, 0); - } - - /** - * Milliseconds to seconds (double) - * - * @param ms - * the milliseconds - * @return a formatted string to milliseconds - */ - public static String msSeconds(long ms) - { - return f((double) ms / 1000.0); - } - - /** - * Milliseconds to seconds (double) custom decimals - * - * @param ms - * the milliseconds - * @param p - * number of decimal points - * @return a formatted string to milliseconds - */ - public static String msSeconds(long ms, int p) - { - return f((double) ms / 1000.0, p); - } - - /** - * nanoseconds to seconds (double) - * - * @param ms - * the nanoseconds - * @return a formatted string to nanoseconds - */ - public static String nsMs(long ns) - { - return f((double) ns / 1000000.0); - } - - /** - * nanoseconds to seconds (double) custom decimals - * - * @param ms - * the nanoseconds - * @param p - * number of decimal points - * @return a formatted string to nanoseconds - */ - public static String nsMs(long ns, int p) - { - return f((double) ns / 1000000.0, p); - } - - /** - * nanoseconds to seconds (double) custom decimals - * - * @param ms - * the nanoseconds - * @param p - * number of decimal points - * @return a formatted string to nanoseconds - */ - public static String nsMsd(long ns, int p) - { - return fd((double) ns / 1000000.0, p); - } - - /** - * Get roman numeral representation of the int - * - * @param num - * the int - * @return the numerals - */ - public static String toRoman(int num) - { - LinkedHashMap roman_numerals = new LinkedHashMap(); - - roman_numerals.put("M", 1000); - roman_numerals.put("CM", 900); - roman_numerals.put("D", 500); - roman_numerals.put("CD", 400); - roman_numerals.put("C", 100); - roman_numerals.put("XC", 90); - roman_numerals.put("L", 50); - roman_numerals.put("XL", 40); - roman_numerals.put("X", 10); - roman_numerals.put("IX", 9); - roman_numerals.put("V", 5); - roman_numerals.put("IV", 4); - roman_numerals.put("I", 1); - - String res = ""; - - for(Map.Entry entry : roman_numerals.entrySet()) - { - int matches = num / entry.getValue(); - - res += repeat(entry.getKey(), matches); - num = num % entry.getValue(); - } - - return res; - } - - /** - * Get the number representation from roman numerals. - * - * @param number - * the roman number - * @return the int representation - */ - public static int fromRoman(String number) - { - if(number.isEmpty()) - { - return 0; - } - - number = number.toUpperCase(); - - if(number.startsWith("M")) - { - return 1000 + fromRoman(number.substring(1)); - } - - if(number.startsWith("CM")) - { - return 900 + fromRoman(number.substring(2)); - } - - if(number.startsWith("D")) - { - return 500 + fromRoman(number.substring(1)); - } - - if(number.startsWith("CD")) - { - return 400 + fromRoman(number.substring(2)); - } - - if(number.startsWith("C")) - { - return 100 + fromRoman(number.substring(1)); - } - - if(number.startsWith("XC")) - { - return 90 + fromRoman(number.substring(2)); - } - - if(number.startsWith("L")) - { - return 50 + fromRoman(number.substring(1)); - } - - if(number.startsWith("XL")) - { - return 40 + fromRoman(number.substring(2)); - } - - if(number.startsWith("X")) - { - return 10 + fromRoman(number.substring(1)); - } - - if(number.startsWith("IX")) - { - return 9 + fromRoman(number.substring(2)); - } - - if(number.startsWith("V")) - { - return 5 + fromRoman(number.substring(1)); - } - - if(number.startsWith("IV")) - { - return 4 + fromRoman(number.substring(2)); - } - - if(number.startsWith("I")) - { - return 1 + fromRoman(number.substring(1)); - } - - return 0; - } - - /** - * Repeat a string - * - * @param s - * the string - * @param n - * the amount of times to repeat - * @return the repeated string - */ - public static String repeat(String s, int n) - { - if(s == null) - { - return null; - } - - final StringBuilder sb = new StringBuilder(); - - for(int i = 0; i < n; i++) - { - sb.append(s); - } - - return sb.toString(); - } +public class Form { + private static NumberFormat NF; + private static DecimalFormat DF; + + private static final String[] NAMES = new String[]{"Thousand", "Million", "Billion", "Trillion", "Quadrillion", "Quintillion", "Sextillion", "Septillion", "Octillion", "Nonillion", "Decillion", "Undecillion", "Duodecillion", "Tredecillion", "Quattuordecillion", "Quindecillion", "Sexdecillion", "Septendecillion", "Octodecillion", "Novemdecillion", "Vigintillion",}; + private static final BigInteger THOUSAND = BigInteger.valueOf(1000); + private static final NavigableMap MAP; + + static { + MAP = new TreeMap(); + for (int i = 0; i < NAMES.length; i++) { + MAP.put(THOUSAND.pow(i + 1), NAMES[i]); + } + } + + private static void instantiate() { + if (NF == null) { + NF = NumberFormat.getInstance(Locale.US); + } + } + + /** + * Scroll text + * + * @param smx the text + * @param viewport the viewport length + * @param time the timeline value + * @return + */ + public static String scroll(String smx, int viewport, long time) { + String src = Form.repeat(" ", viewport) + smx + Form.repeat(" ", viewport); + int len = src.length(); + int walk = (int) (time % (len - viewport)); + String base = src.substring(walk, M.min(walk + viewport, len - 1)); + base = base.length() < viewport ? base + Form.repeat(" ", (viewport - base.length()) - 3) : base; + + return base; + } + + /** + * Capitalize the first letter + * + * @param s the string + * @return the capitalized string + */ + public static String capitalize(String s) { + String roll = ""; + boolean f = true; + + for (Character i : s.trim().toCharArray()) { + if (f) { + roll += Character.toUpperCase(i); + f = false; + } else { + roll += i; + } + } + + return roll; + } + + /** + * Capitalize all words in the string + * + * @param s the string + * @return the capitalized string + */ + public static String capitalizeWords(String s) { + String rollx = ""; + + for (String i : s.trim().split(" ")) { + rollx += " " + capitalize(i.trim()); + } + + return rollx.substring(1); + } + + /** + * Hard word wrap + * + * @param s the words + * @param len the length per line + * @return the wrapped string + */ + public static String wrap(String s, int len) { + return wrap(s, len, null, false); + } + + /** + * Soft Word wrap + * + * @param s the string + * @param len the length to wrap + * @return the wrapped string + */ + public static String wrapWords(String s, int len) { + return wrap(s, len, null, true); + } + + /** + * Wrap words + * + * @param s the string + * @param len the wrap length + * @param newLineSep the new line seperator + * @param soft should it be soft wrapped or hard wrapped? + * @return the wrapped words + */ + public static String wrap(String s, int len, String newLineSep, boolean soft) { + return wrap(s, len, newLineSep, soft, " "); + } + + /** + * Wrap words + * + * @param s the string + * @param len the length + * @param newLineSep the new line seperator + * @param soft soft or hard wrapping + * @param regex the regex + * @return the wrapped string + */ + public static String wrap(String s, int len, String newLineSep, boolean soft, String regex) { + if (s == null) { + return null; + } else { + if (newLineSep == null) { + newLineSep = "\n"; + } + + if (len < 1) { + len = 1; + } + + if (regex.trim().equals("")) { + regex = " "; + } + + Pattern arg4 = Pattern.compile(regex); + int arg5 = s.length(); + int arg6 = 0; + StringBuilder arg7 = new StringBuilder(arg5 + 32); + + while (arg6 < arg5) { + int arg8 = -1; + Matcher arg9 = arg4.matcher(s.substring(arg6, Math.min(arg6 + len + 1, arg5))); + if (arg9.find()) { + if (arg9.start() == 0) { + arg6 += arg9.end(); + continue; + } + + arg8 = arg9.start(); + } + + if (arg5 - arg6 <= len) { + break; + } + + while (arg9.find()) { + arg8 = arg9.start() + arg6; + } + + if (arg8 >= arg6) { + arg7.append(s, arg6, arg8); + arg7.append(newLineSep); + arg6 = arg8 + 1; + } else if (soft) { + arg7.append(s, arg6, len + arg6); + arg7.append(newLineSep); + arg6 += len; + } else { + arg9 = arg4.matcher(s.substring(arg6 + len)); + if (arg9.find()) { + arg8 = arg9.start() + arg6 + len; + } + + if (arg8 >= 0) { + arg7.append(s, arg6, arg8); + arg7.append(newLineSep); + arg6 = arg8 + 1; + } else { + arg7.append(s.substring(arg6)); + arg6 = arg5; + } + } + } + + arg7.append(s.substring(arg6)); + return arg7.toString(); + } + } + + /** + * Returns a fancy duration up to Years + * + * @param rollingSequence + * @param duration the duration in ms + * @return the fancy duration + */ + public static String duration(RollingSequence rollingSequence, long duration) { + String suffix = "Millisecond"; + double phantom = duration; + int div = 1000; + + if (phantom > div) { + phantom /= div; + suffix = "Second"; + div = 60; + + if (phantom > div) { + phantom /= div; + suffix = "Minute"; + + if (phantom > div) { + phantom /= div; + suffix = "Hour"; + div = 24; + + if (phantom > 24) { + phantom /= div; + suffix = "Day"; + div = 7; + + if (phantom > div) { + phantom /= div; + suffix = "Week"; + div = 4; + + if (phantom > div) { + phantom /= div; + suffix = "Month"; + div = 12; + + if (phantom > div) { + phantom /= div; + suffix = "Year"; + return Form.fd(phantom, 0) + " " + suffix + ((int) phantom == 1 ? "" : "s"); + } else { + return Form.fd(phantom, 0) + " " + suffix + ((int) phantom == 1 ? "" : "s"); + } + } else { + return Form.fd(phantom, 0) + " " + suffix + ((int) phantom == 1 ? "" : "s"); + } + } else { + return Form.fd(phantom, 0) + " " + suffix + ((int) phantom == 1 ? "" : "s"); + } + } else { + return Form.fd(phantom, 0) + " " + suffix + ((int) phantom == 1 ? "" : "s"); + } + } else { + return Form.fd(phantom, 0) + " " + suffix + ((int) phantom == 1 ? "" : "s"); + } + } else { + return Form.fd(phantom, 0) + " " + suffix + ((int) phantom == 1 ? "" : "s"); + } + } else { + return "Under a Second"; + } + } + + /** + * Fixes the minute issue with formatting + * + * @param c the calendar + * @return the minute string + */ + public static String fmin(Calendar c) { + String s = c.get(Calendar.MINUTE) + ""; + if (s.length() == 1) { + return "0" + s; + } + + return s; + } + + /** + * Get a fancy time stamp + * + * @param time the stamp in time (ago) + * @return the fancy stamp in time (ago) + */ + public static String ago(long time) { + long current = M.ms(); + + if (time > current - TimeUnit.SECONDS.toMillis(30) && time < current) { + return "Just Now"; + } else if (time > current - TimeUnit.SECONDS.toMillis(60) && time < current) { + return "Seconds Ago"; + } else if (time > current - TimeUnit.MINUTES.toMillis(10) && time < current) { + return "Minutes Ago"; + } else { + Calendar now = Calendar.getInstance(); + Calendar c = Calendar.getInstance(); + c.setTimeInMillis(time); + boolean sameYear = now.get(Calendar.YEAR) == c.get(Calendar.YEAR); + boolean sameDay = now.get(Calendar.DAY_OF_YEAR) == c.get(Calendar.DAY_OF_YEAR); + + if (sameDay) { + int h = c.get(Calendar.HOUR); + h = h == 0 ? 12 : h; + + return "Today at " + h + ":" + fmin(c) + " " + (c.get(Calendar.AM_PM) == Calendar.PM ? "PM" : "AM"); + } else if (sameYear) { + boolean yesterday = now.get(Calendar.DAY_OF_YEAR) - 1 == c.get(Calendar.DAY_OF_YEAR); + + if (yesterday) { + int h = c.get(Calendar.HOUR); + h = h == 0 ? 12 : h; + + return "Yesterday at " + h + ":" + fmin(c) + " " + (c.get(Calendar.AM_PM) == Calendar.PM ? "PM" : "AM"); + } else { + int h = c.get(Calendar.HOUR); + h = h == 0 ? 12 : h; + String dow = "Error Day"; + + switch (c.get(Calendar.DAY_OF_WEEK)) { + case Calendar.SUNDAY: + dow = "Sunday"; + break; + case Calendar.MONDAY: + dow = "Monday"; + break; + case Calendar.TUESDAY: + dow = "Tuesday"; + break; + case Calendar.WEDNESDAY: + dow = "Wednesday"; + break; + case Calendar.THURSDAY: + dow = "Thursday"; + break; + case Calendar.FRIDAY: + dow = "Friday"; + break; + case Calendar.SATURDAY: + dow = "Saturday"; + break; + } + + String monthName = "Error Month"; + int month = c.get(Calendar.MONTH); + + switch (month) { + case Calendar.JANUARY: + monthName = "Jan"; + break; + case Calendar.FEBRUARY: + monthName = "Feb"; + break; + case Calendar.MARCH: + monthName = "Mar"; + break; + case Calendar.APRIL: + monthName = "Apr"; + break; + case Calendar.MAY: + monthName = "May"; + break; + case Calendar.JUNE: + monthName = "Jun"; + break; + case Calendar.JULY: + monthName = "Jul"; + break; + case Calendar.AUGUST: + monthName = "Aug"; + break; + case Calendar.SEPTEMBER: + monthName = "Sep"; + break; + case Calendar.OCTOBER: + monthName = "Oct"; + break; + case Calendar.NOVEMBER: + monthName = "Nov"; + break; + case Calendar.DECEMBER: + monthName = "Dec"; + break; + } + + int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); + String suffix = numberSuffix(dayOfMonth); + + return dow + ", " + monthName + " " + suffix + " at " + h + ":" + fmin(c) + " " + (c.get(Calendar.AM_PM) == Calendar.PM ? "PM" : "AM"); + } + } else { + int h = c.get(Calendar.HOUR); + h = h == 0 ? 12 : h; + String dow = "Error Day"; + + switch (c.get(Calendar.DAY_OF_WEEK)) { + case Calendar.SUNDAY: + dow = "Sunday"; + break; + case Calendar.MONDAY: + dow = "Monday"; + break; + case Calendar.TUESDAY: + dow = "Tuesday"; + break; + case Calendar.WEDNESDAY: + dow = "Wednesday"; + break; + case Calendar.THURSDAY: + dow = "Thursday"; + break; + case Calendar.FRIDAY: + dow = "Friday"; + break; + case Calendar.SATURDAY: + dow = "Saturday"; + break; + } + + String monthName = "Error Month"; + int month = c.get(Calendar.MONTH); + + switch (month) { + case Calendar.JANUARY: + monthName = "Jan"; + break; + case Calendar.FEBRUARY: + monthName = "Feb"; + break; + case Calendar.MARCH: + monthName = "Mar"; + break; + case Calendar.APRIL: + monthName = "Apr"; + break; + case Calendar.MAY: + monthName = "May"; + break; + case Calendar.JUNE: + monthName = "Jun"; + break; + case Calendar.JULY: + monthName = "Jul"; + break; + case Calendar.AUGUST: + monthName = "Aug"; + break; + case Calendar.SEPTEMBER: + monthName = "Sep"; + break; + case Calendar.OCTOBER: + monthName = "Oct"; + break; + case Calendar.NOVEMBER: + monthName = "Nov"; + break; + case Calendar.DECEMBER: + monthName = "Dec"; + break; + } + + int dayOfMonth = c.get(Calendar.DAY_OF_MONTH); + String suffix = numberSuffix(dayOfMonth); + int year = c.get(Calendar.YEAR); + + return year + ", " + dow + ", " + monthName + " " + suffix + " at " + h + ":" + fmin(c) + " " + (c.get(Calendar.AM_PM) == Calendar.PM ? "PM" : "AM"); + } + } + } + + /** + * Get the suffix for a number i.e. 1st 2nd 3rd + * + * @param i the number + * @return the suffix + */ + public static String numberSuffix(int i) { + String[] sufixes = new String[]{"th", "st", "nd", "rd", "th", "th", "th", "th", "th", "th"}; + switch (i % 100) { + case 11: + case 12: + case 13: + return i + "th"; + default: + return i + sufixes[i % 10]; + + } + } + + /** + * Get a high accuracy but limited range duration (accurate up to a couple + * minutes) + * + * @param ms the milliseconds (double) + * @param prec the precision (decimal format) + * @return the formatted string + */ + public static String duration(double ms, int prec) { + if (ms < 1000.0) { + return Form.f(ms, prec) + "ms"; + } + + if (ms / 1000.0 < 60.0) { + return Form.f(ms / 1000.0, prec) + "s"; + } + + if (ms / 1000.0 / 60.0 < 60.0) { + return Form.f(ms / 1000.0 / 60.0, prec) + "m"; + } + + if (ms / 1000.0 / 60.0 / 60.0 < 24.0) { + return Form.f(ms / 1000.0 / 60.0 / 60.0, prec) + " hours"; + } + + if (ms / 1000.0 / 60.0 / 60.0 / 24.0 < 7) { + return Form.f(ms / 1000.0 / 60.0 / 24.0, prec) + " days"; + } + + return Form.f(ms, prec) + "ms"; + } + + public static String duration(long ms) { + return duration(ms, 0); + } + + /** + * Get a duration from milliseconds up to days + * + * @param ms the ms + * @param prec the precision (decimal format) + * @return the formatted string + */ + public static String duration(long ms, int prec) { + if (ms < 1000.0) { + return Form.f(ms, prec) + "ms"; + } + + if (ms / 1000.0 < 60.0) { + return Form.f(ms / 1000.0, prec) + " seconds"; + } + + if (ms / 1000.0 / 60.0 < 60.0) { + return Form.f(ms / 1000.0 / 60.0, prec) + " minutes"; + } + + if (ms / 1000.0 / 60.0 / 60.0 < 24.0) { + return Form.f(ms / 1000.0 / 60.0 / 60.0, prec) + " hours"; + } + + if (ms / 1000.0 / 60.0 / 60.0 / 24.0 < 7) { + return Form.f(ms / 1000.0 / 60.0 / 24.0, prec) + " days"; + } + + return Form.f(ms, prec) + "ms"; + } + + /** + * Format a big value + * + * @param i the number + * @return the full value in string + */ + public static String b(int i) { + return b(new BigInteger(String.valueOf(i))); + } + + /** + * Format a big value + * + * @param i the number + * @return the full value in string + */ + public static String b(long i) { + return b(new BigInteger(String.valueOf(i))); + } + + /** + * Format a big value + * + * @param i the number + * @return the full value in string + */ + public static String b(double i) { + return b(new BigInteger(String.valueOf((long) i))); + } + + /** + * Format a big number + * + * @param number the big number + * @return the value in string + */ + public static String b(BigInteger number) { + Entry entry = MAP.floorEntry(number); + if (entry == null) { + return "Nearly nothing"; + } + + BigInteger key = entry.getKey(); + BigInteger d = key.divide(THOUSAND); + BigInteger m = number.divide(d); + float f = m.floatValue() / 1000.0f; + float rounded = ((int) (f * 100.0)) / 100.0f; + + if (rounded % 1 == 0) { + return ((int) rounded) + " " + entry.getValue(); + } + + return rounded + " " + entry.getValue(); + } + + /** + * Calculate a fancy string representation of a file size. Adds a suffix of B, + * KB, MB, GB, or TB + * + * @param s the size (in bytes) + * @return the string + */ + public static String fileSize(long s) { + return ofSize(s, 1000); + } + + /** + * ":", "a", "b", "c" -> a:b:c + * + * @param splitter the splitter that goes in between + * @param strings the strings + * @return the result + */ + public static String split(String splitter, String... strings) { + StringBuilder b = new StringBuilder(); + + for (String i : strings) { + b.append(splitter); + b.append(i); + } + + return b.substring(splitter.length()); + } + + /** + * Calculate a fancy string representation of a file size. Adds a suffix of B, + * KB, MB, GB, or TB + * + * @param s the size (in bytes) + * @return the string + */ + public static String memSize(long s) { + return ofSize(s, 1024); + } + + public static String memSize(long s, int dec) { + return ofSize(s, 1024, dec); + } + + /** + * Get the timestamp of the time t (ms since 1970) + * + * @param t the time + * @return the stamp + */ + @SuppressWarnings("deprecation") + public static String stamp(long t) { + Date d = new Date(t); + return d.getMonth() + "-" + d.getDate() + "-" + (d.getYear() + 1900) + " " + d.getHours() + "h " + d.getMinutes() + "m " + d.getSeconds() + "s "; + } + + @SuppressWarnings("deprecation") + public static String stampTime(long t) { + Date d = new Date(t); + + return Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + ":" + forceDoubleDigit(d.getMinutes()) + ":" + forceDoubleDigit(d.getSeconds()); + } + + public static String forceDoubleDigit(int dig) { + if (dig < 10) { + return "0" + dig; + } + + return dig + ""; + } + + @SuppressWarnings("deprecation") + public static String stampDay(long t) { + Date d = new Date(t); + return d.getMonth() + "-" + d.getDate() + "-" + (d.getYear() + 1900); + } + + /** + * Calculate a fancy string representation of a size in B, KB, MB, GB, or TB + * with a special divisor. The divisor decides how much goes up in the suffix + * chain. + * + * @param s the size (in bytes) + * @param div the divisor + * @return the string + */ + public static String ofSize(long s, int div) { + Double d = (double) s; + String sub = "Bytes"; + + if (d > div - 1) { + d /= div; + sub = "KB"; + + if (d > div - 1) { + d /= div; + sub = "MB"; + + if (d > div - 1) { + d /= div; + sub = "GB"; + + if (d > div - 1) { + d /= div; + sub = "TB"; + } + } + } + } + + if (sub.equals("GB") || sub.equals("TB")) { + return Form.f(d, 1) + sub; + } else { + return Form.f(d, 0) + sub; + } + } + + /** + * Calculate a fancy string representation of a size in B, KB, MB, GB, or TB + * with a special divisor. The divisor decides how much goes up in the suffix + * chain. + * + * @param s the size (in bytes) + * @param div the divisor + * @param dec the decimal places + * @return the string + */ + public static String ofSize(long s, int div, int dec) { + Double d = (double) s; + String sub = "Bytes"; + + if (d > div - 1) { + d /= div; + sub = "KB"; + + if (d > div - 1) { + d /= div; + sub = "MB"; + + if (d > div - 1) { + d /= div; + sub = "GB"; + + if (d > div - 1) { + d /= div; + sub = "TB"; + } + } + } + } + + return Form.f(d, dec) + " " + sub; + } + + /** + * Calculate a fancy string representation of a size in Grams, KG, MG, GG, TG + * with a special divisor. The divisor decides how much goes up in the suffix + * chain. + * + * @param s the size (in bytes) + * @param div the divisor + * @param dec the decimal places + * @return the string + */ + public static String ofSizeMetricWeight(long s, int div, int dec) { + boolean neg = s < 0; + if (neg) { + s = -s; + } + Double d = (double) s; + String sub = "Grams"; + + if (d > div - 1) { + d /= div; + sub = "KG"; + + if (d > div - 1) { + d /= div; + sub = "MG"; + + if (d > div - 1) { + d /= div; + sub = "GG"; + + if (d > div - 1) { + d /= div; + sub = "TG"; + } + } + } + } + + return (neg ? "-" : "") + Form.f(d, dec) + " " + sub; + } + + /** + * Trim a string to a length, then append ... at the end if it extends the limit + * + * @param s the string + * @param l the limit + * @return the modified string + */ + public static String trim(String s, int l) { + if (s.length() <= l) { + return s; + } + + return s.substring(0, l) + "..."; + } + + /** + * Get a class name into a configuration/filename key For example, + * PhantomController.class is converted to phantom-controller + * + * @param clazz the class + * @return the string representation + */ + public static String cname(String clazz) { + String codeName = ""; + + for (Character i : clazz.toCharArray()) { + if (Character.isUpperCase(i)) { + codeName = codeName + "-" + Character.toLowerCase(i); + } else { + codeName = codeName + i; + } + } + + if (codeName.startsWith("-")) { + codeName = codeName.substring(1); + } + + return codeName; + } + + /** + * Get a formatted representation of the memory given in megabytes + * + * @param mb the megabytes + * @return the string representation with suffixes + */ + public static String mem(long mb) { + if (mb < 1024) { + return f(mb) + " MB"; + } else { + return f(((double) mb / (double) 1024), 1) + " GB"; + } + } + + /** + * Get a formatted representation of the memory given in kilobytes + * + * @param mb the kilobytes + * @return the string representation with suffixes + */ + public static String memx(long kb) { + if (kb < 1024) { + return fd(kb, 2) + " KB"; + } else { + double mb = (double) kb / 1024.0; + + if (mb < 1024) { + return fd(mb, 2) + " MB"; + } else { + double gb = mb / 1024.0; + + return fd(gb, 2) + " GB"; + } + } + } + + /** + * Format a long. Changes -10334 into -10,334 + * + * @param i the number + * @return the string representation of the number + */ + public static String f(long i) { + instantiate(); + return NF.format(i); + } + + /** + * Format a number. Changes -10334 into -10,334 + * + * @param i the number + * @return the string representation of the number + */ + public static String f(int i) { + instantiate(); + return NF.format(i); + } + + /** + * Formats a double's decimals to a limit + * + * @param i the double + * @param p the number of decimal places to use + * @return the formated string + */ + public static String f(double i, int p) { + String form = "#"; + + if (p > 0) { + form = form + "." + repeat("#", p); + } + + DF = new DecimalFormat(form); + + return DF.format(i); + } + + /** + * Formats a double's decimals to a limit, however, this will add zeros to the + * decimal places that dont need to be placed down. 2.4343 formatted with 6 + * decimals gets returned as 2.434300 + * + * @param i the double + * @param p the number of decimal places to use + * @return the formated string + */ + public static String fd(double i, int p) { + String form = "0"; + + if (p > 0) { + form = form + "." + repeat("0", p); + } + + DF = new DecimalFormat(form); + + return DF.format(i); + } + + /** + * Formats a float's decimals to a limit + * + * @param i the float + * @param p the number of decimal places to use + * @return the formated string + */ + public static String f(float i, int p) { + String form = "#"; + + if (p > 0) { + form = form + "." + repeat("#", p); + } + + DF = new DecimalFormat(form); + + return DF.format(i); + } + + /** + * Formats a double's decimals (one decimal point) + * + * @param i the double + */ + public static String f(double i) { + return f(i, 1); + } + + /** + * Formats a float's decimals (one decimal point) + * + * @param i the float + */ + public static String f(float i) { + return f(i, 1); + } + + /** + * Get a percent representation of a double and decimal places (0.53) would + * return 53% + * + * @param i the double + * @param p the number of decimal points + * @return a string + */ + public static String pc(double i, int p) { + return f(i * 100.0, p) + "%"; + } + + /** + * Get a percent representation of a float and decimal places (0.53) would + * return 53% + * + * @param i the float + * @param p the number of decimal points + * @return a string + */ + public static String pc(float i, int p) { + return f(i * 100, p) + "%"; + } + + /** + * Get a percent representation of a double and zero decimal places (0.53) would + * return 53% + * + * @param i the double + * @return a string + */ + public static String pc(double i) { + return f(i * 100, 0) + "%"; + } + + /** + * Get a percent representation of a float and zero decimal places (0.53) would + * return 53% + * + * @param i the double + * @return a string + */ + public static String pc(float i) { + return f(i * 100, 0) + "%"; + } + + /** + * Get a percent as the percent of i out of "of" with custom decimal places + * + * @param i the percent out of + * @param of of of + * @param p the decimal places + * @return the string + */ + public static String pc(int i, int of, int p) { + return f(100.0 * (((double) i) / ((double) of)), p) + "%"; + } + + /** + * Get a percent as the percent of i out of "of" + * + * @param i the percent out of + * @param of of of + * @return the string + */ + public static String pc(int i, int of) { + return pc(i, of, 0); + } + + /** + * Get a percent as the percent of i out of "of" with custom decimal places + * + * @param i the percent out of + * @param of of of + * @param p the decimal places + * @return the string + */ + public static String pc(long i, long of, int p) { + return f(100.0 * (((double) i) / ((double) of)), p) + "%"; + } + + /** + * Get a percent as the percent of i out of "of" + * + * @param i the percent out of + * @param of of of + * @return the string + */ + public static String pc(long i, long of) { + return pc(i, of, 0); + } + + /** + * Milliseconds to seconds (double) + * + * @param ms the milliseconds + * @return a formatted string to milliseconds + */ + public static String msSeconds(long ms) { + return f((double) ms / 1000.0); + } + + /** + * Milliseconds to seconds (double) custom decimals + * + * @param ms the milliseconds + * @param p number of decimal points + * @return a formatted string to milliseconds + */ + public static String msSeconds(long ms, int p) { + return f((double) ms / 1000.0, p); + } + + /** + * nanoseconds to seconds (double) + * + * @param ms the nanoseconds + * @return a formatted string to nanoseconds + */ + public static String nsMs(long ns) { + return f((double) ns / 1000000.0); + } + + /** + * nanoseconds to seconds (double) custom decimals + * + * @param ms the nanoseconds + * @param p number of decimal points + * @return a formatted string to nanoseconds + */ + public static String nsMs(long ns, int p) { + return f((double) ns / 1000000.0, p); + } + + /** + * nanoseconds to seconds (double) custom decimals + * + * @param ms the nanoseconds + * @param p number of decimal points + * @return a formatted string to nanoseconds + */ + public static String nsMsd(long ns, int p) { + return fd((double) ns / 1000000.0, p); + } + + /** + * Get roman numeral representation of the int + * + * @param num the int + * @return the numerals + */ + public static String toRoman(int num) { + LinkedHashMap roman_numerals = new LinkedHashMap(); + + roman_numerals.put("M", 1000); + roman_numerals.put("CM", 900); + roman_numerals.put("D", 500); + roman_numerals.put("CD", 400); + roman_numerals.put("C", 100); + roman_numerals.put("XC", 90); + roman_numerals.put("L", 50); + roman_numerals.put("XL", 40); + roman_numerals.put("X", 10); + roman_numerals.put("IX", 9); + roman_numerals.put("V", 5); + roman_numerals.put("IV", 4); + roman_numerals.put("I", 1); + + String res = ""; + + for (Map.Entry entry : roman_numerals.entrySet()) { + int matches = num / entry.getValue(); + + res += repeat(entry.getKey(), matches); + num = num % entry.getValue(); + } + + return res; + } + + /** + * Get the number representation from roman numerals. + * + * @param number the roman number + * @return the int representation + */ + public static int fromRoman(String number) { + if (number.isEmpty()) { + return 0; + } + + number = number.toUpperCase(); + + if (number.startsWith("M")) { + return 1000 + fromRoman(number.substring(1)); + } + + if (number.startsWith("CM")) { + return 900 + fromRoman(number.substring(2)); + } + + if (number.startsWith("D")) { + return 500 + fromRoman(number.substring(1)); + } + + if (number.startsWith("CD")) { + return 400 + fromRoman(number.substring(2)); + } + + if (number.startsWith("C")) { + return 100 + fromRoman(number.substring(1)); + } + + if (number.startsWith("XC")) { + return 90 + fromRoman(number.substring(2)); + } + + if (number.startsWith("L")) { + return 50 + fromRoman(number.substring(1)); + } + + if (number.startsWith("XL")) { + return 40 + fromRoman(number.substring(2)); + } + + if (number.startsWith("X")) { + return 10 + fromRoman(number.substring(1)); + } + + if (number.startsWith("IX")) { + return 9 + fromRoman(number.substring(2)); + } + + if (number.startsWith("V")) { + return 5 + fromRoman(number.substring(1)); + } + + if (number.startsWith("IV")) { + return 4 + fromRoman(number.substring(2)); + } + + if (number.startsWith("I")) { + return 1 + fromRoman(number.substring(1)); + } + + return 0; + } + + /** + * Repeat a string + * + * @param s the string + * @param n the amount of times to repeat + * @return the repeated string + */ + public static String repeat(String s, int n) { + if (s == null) { + return null; + } + + final StringBuilder sb = new StringBuilder(); + + for (int i = 0; i < n; i++) { + sb.append(s); + } + + return sb.toString(); + } } diff --git a/src/main/java/com/volmit/iris/util/Function2.java b/src/main/java/com/volmit/iris/util/Function2.java index 238b2c957..55f7b1df3 100644 --- a/src/main/java/com/volmit/iris/util/Function2.java +++ b/src/main/java/com/volmit/iris/util/Function2.java @@ -2,7 +2,6 @@ package com.volmit.iris.util; @SuppressWarnings("hiding") @FunctionalInterface -public interface Function2 -{ - public R apply(A a, B b); +public interface Function2 { + R apply(A a, B b); } diff --git a/src/main/java/com/volmit/iris/util/Function3.java b/src/main/java/com/volmit/iris/util/Function3.java index bb6e5ab87..41723d93d 100644 --- a/src/main/java/com/volmit/iris/util/Function3.java +++ b/src/main/java/com/volmit/iris/util/Function3.java @@ -2,7 +2,6 @@ package com.volmit.iris.util; @SuppressWarnings("hiding") @FunctionalInterface -public interface Function3 -{ - public R apply(A a, B b, C c); +public interface Function3 { + R apply(A a, B b, C c); } diff --git a/src/main/java/com/volmit/iris/util/Function4.java b/src/main/java/com/volmit/iris/util/Function4.java index 7026829f2..5478f6fc1 100644 --- a/src/main/java/com/volmit/iris/util/Function4.java +++ b/src/main/java/com/volmit/iris/util/Function4.java @@ -2,7 +2,6 @@ package com.volmit.iris.util; @SuppressWarnings("hiding") @FunctionalInterface -public interface Function4 -{ - public R apply(A a, B b, C c, D d); +public interface Function4 { + R apply(A a, B b, C c, D d); } diff --git a/src/main/java/com/volmit/iris/util/GBiset.java b/src/main/java/com/volmit/iris/util/GBiset.java index 2409d99ab..eb5ba37e8 100644 --- a/src/main/java/com/volmit/iris/util/GBiset.java +++ b/src/main/java/com/volmit/iris/util/GBiset.java @@ -6,72 +6,60 @@ import java.io.Serializable; /** * A Biset * + * @param
the first object type + * @param the second object type * @author cyberpwn - * - * @param - * the first object type - * @param - * the second object type */ @SuppressWarnings("hiding") -public class GBiset implements Serializable -{ - private static final long serialVersionUID = 1L; - private A a; - private B b; +public class GBiset implements Serializable { + private static final long serialVersionUID = 1L; + private A a; + private B b; - /** - * Create a new Biset - * - * @param a - * the first object - * @param b - * the second object - */ - public GBiset(A a, B b) - { - this.a = a; - this.b = b; - } + /** + * Create a new Biset + * + * @param a the first object + * @param b the second object + */ + public GBiset(A a, B b) { + this.a = a; + this.b = b; + } - /** - * Get the object of the type A - * - * @return the first object - */ - public A getA() - { - return a; - } + /** + * Get the object of the type A + * + * @return the first object + */ + public A getA() { + return a; + } - /** - * Set the first object - * - * @param a - * the first object A - */ - public void setA(A a) - { - this.a = a; - } + /** + * Set the first object + * + * @param a the first object A + */ + public void setA(A a) { + this.a = a; + } - /** - * Get the second object - * - * @return the second object - */ - public B getB() - { - return b; - } + /** + * Get the second object + * + * @return the second object + */ + public B getB() { + return b; + } - /** - * Set the second object - * - * @param b - */ - public void setB(B b) - { - this.b = b; - } + /** + * Set the second object + * + * @param b + */ + public void setB(B b) { + this.b = b; + } } diff --git a/src/main/java/com/volmit/iris/util/GListAdapter.java b/src/main/java/com/volmit/iris/util/GListAdapter.java index a17e9bf7c..b77167e3d 100644 --- a/src/main/java/com/volmit/iris/util/GListAdapter.java +++ b/src/main/java/com/volmit/iris/util/GListAdapter.java @@ -6,44 +6,36 @@ import java.util.List; /** * Adapts a list of objects into a list of other objects * + * @param the from object in lists (the item INSIDE the list) + * @param the to object in lists (the item INSIDE the list) * @author cyberpwn - * @param - * the from object in lists (the item INSIDE the list) - * @param - * the to object in lists (the item INSIDE the list) */ -public abstract class GListAdapter -{ - /** - * Adapts a list of FROM to a list of TO - * - * @param from - * the from list - * @return the to list - */ - public List adapt(List from) - { - List adapted = new KList(); +public abstract class GListAdapter { + /** + * Adapts a list of FROM to a list of TO + * + * @param from the from list + * @return the to list + */ + public List adapt(List from) { + List adapted = new KList(); - for(FROM i : from) - { - TO t = onAdapt(i); + for (FROM i : from) { + TO t = onAdapt(i); - if(t != null) - { - adapted.add(onAdapt(i)); - } - } + if (t != null) { + adapted.add(onAdapt(i)); + } + } - return adapted; - } + return adapted; + } - /** - * Adapts a list object FROM to TO for use with the adapt method - * - * @param from - * the from object - * @return the to object - */ - public abstract TO onAdapt(FROM from); + /** + * Adapts a list object FROM to TO for use with the adapt method + * + * @param from the from object + * @return the to object + */ + public abstract TO onAdapt(FROM from); } diff --git a/src/main/java/com/volmit/iris/util/GroupedExecutor.java b/src/main/java/com/volmit/iris/util/GroupedExecutor.java index 620d48ef7..c844ca4ea 100644 --- a/src/main/java/com/volmit/iris/util/GroupedExecutor.java +++ b/src/main/java/com/volmit/iris/util/GroupedExecutor.java @@ -6,111 +6,88 @@ import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinPool.ForkJoinWorkerThreadFactory; import java.util.concurrent.ForkJoinWorkerThread; -public class GroupedExecutor -{ - private int xc; - private ExecutorService service; - private KMap mirror; +public class GroupedExecutor { + private int xc; + private final ExecutorService service; + private final KMap mirror; - public GroupedExecutor(int threadLimit, int priority, String name) - { - xc = 1; - mirror = new KMap(); + public GroupedExecutor(int threadLimit, int priority, String name) { + xc = 1; + mirror = new KMap(); - if(threadLimit == 1) - { - service = Executors.newSingleThreadExecutor((r) -> - { - Thread t = new Thread(r); - t.setName(name); - t.setPriority(priority); + if (threadLimit == 1) { + service = Executors.newSingleThreadExecutor((r) -> + { + Thread t = new Thread(r); + t.setName(name); + t.setPriority(priority); - return t; - }); - } + return t; + }); + } else if (threadLimit > 1) { + final ForkJoinWorkerThreadFactory factory = new ForkJoinWorkerThreadFactory() { + @Override + public ForkJoinWorkerThread newThread(ForkJoinPool pool) { + final ForkJoinWorkerThread worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool); + worker.setName(name + " " + xc++); + worker.setPriority(priority); + return worker; + } + }; - else if(threadLimit > 1) - { - final ForkJoinWorkerThreadFactory factory = new ForkJoinWorkerThreadFactory() - { - @Override - public ForkJoinWorkerThread newThread(ForkJoinPool pool) - { - final ForkJoinWorkerThread worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool); - worker.setName(name + " " + xc++); - worker.setPriority(priority); - return worker; - } - }; + service = new ForkJoinPool(threadLimit, factory, null, false); + } else { + service = Executors.newCachedThreadPool((r) -> + { + Thread t = new Thread(r); + t.setName(name + " " + xc++); + t.setPriority(priority); - service = new ForkJoinPool(threadLimit, factory, null, false); - } + return t; + }); + } + } - else - { - service = Executors.newCachedThreadPool((r) -> - { - Thread t = new Thread(r); - t.setName(name + " " + xc++); - t.setPriority(priority); + public void waitFor(String g) { + if (g == null) { + return; + } - return t; - }); - } - } + if (!mirror.containsKey(g)) { + return; + } - public void waitFor(String g) - { - if(g == null) - { - return; - } + while (true) { + if (mirror.get(g) == 0) { + break; + } + } + } - if(!mirror.containsKey(g)) - { - return; - } + public void queue(String q, NastyRunnable r) { + mirror.compute(q, (k, v) -> k == null || v == null ? 1 : v + 1); - while(true) - { - if(mirror.get(g) == 0) - { - break; - } - } - } + service.execute(() -> + { + try { + r.run(); + } catch (Throwable e) { + e.printStackTrace(); + } - public void queue(String q, NastyRunnable r) - { - mirror.compute(q, (k, v) -> k == null || v == null ? 1 : v + 1); + mirror.compute(q, (k, v) -> v - 1); + }); + } - service.execute(() -> - { - try - { - r.run(); - } + public void close() { + J.a(() -> + { + J.sleep(100); + service.shutdown(); + }); + } - catch(Throwable e) - { - e.printStackTrace(); - } - - mirror.compute(q, (k, v) -> v - 1); - }); - } - - public void close() - { - J.a(() -> - { - J.sleep(100); - service.shutdown(); - }); - } - - public void closeNow() - { - service.shutdown(); - } + public void closeNow() { + service.shutdown(); + } } diff --git a/src/main/java/com/volmit/iris/util/HTTP.java b/src/main/java/com/volmit/iris/util/HTTP.java index 66bf0b1aa..3cc19f0d4 100644 --- a/src/main/java/com/volmit/iris/util/HTTP.java +++ b/src/main/java/com/volmit/iris/util/HTTP.java @@ -29,173 +29,161 @@ import java.util.Iterator; /** * Convert an HTTP header to a JSONObject and back. - * + * * @author JSON.org * @version 2014-05-03 */ -public class HTTP -{ - - /** Carriage return/line feed. */ - public static final String CRLF = "\r\n"; - - /** - * Convert an HTTP header string into a JSONObject. It can be a request - * header or a response header. A request header will contain - * - *