From 98e296b666618aaebc9580a0bf250db81ef66661 Mon Sep 17 00:00:00 2001 From: piexel Date: Sat, 14 Nov 2026 22:22:44 +0100 Subject: [PATCH] Add image maps and pregeneration views to the studio - List the pack's image maps with a preview over the area they cover - Show the running pregeneration's chunk map, progress and pause --- .../command/CommandStudioDesktopTest.java | 83 - .../iris/command/StudioMapPositionTest.java | 99 - .../art/arcane/iris/studio/map/BakeMeter.java | 154 -- .../arcane/iris/studio/map/BakeTiming.java | 71 - .../arcane/iris/studio/map/BakeWeight.java | 74 - .../arcane/iris/studio/map/BiomeExplorer.java | 177 -- .../arcane/iris/studio/map/BlockFaces.java | 320 --- .../studio/map/BlockHeightColorScale.java | 47 - .../arcane/iris/studio/map/BlockModel.java | 213 -- .../iris/studio/map/BlockModelBuilder.java | 351 ---- .../arcane/iris/studio/map/ColumnArea.java | 25 - .../arcane/iris/studio/map/EmptyState.java | 102 - .../iris/studio/map/EntityBlockShapes.java | 298 --- .../iris/studio/map/FloatingPanels.java | 81 - .../iris/studio/map/FloatingSlider.java | 175 -- .../iris/studio/map/FrameCrossfade.java | 103 - .../iris/studio/map/FrameRateLabel.java | 64 - .../arcane/iris/studio/map/GlxDisplay.java | 381 ---- .../art/arcane/iris/studio/map/GpuCache.java | 106 - .../art/arcane/iris/studio/map/GpuCanvas.java | 187 -- .../art/arcane/iris/studio/map/GpuColors.java | 75 - .../arcane/iris/studio/map/GpuContext.java | 301 --- .../art/arcane/iris/studio/map/GpuFaces.java | 139 -- .../iris/studio/map/GpuFrameTarget.java | 67 - .../iris/studio/map/GpuFramebuffer.java | 90 - .../art/arcane/iris/studio/map/GpuFrames.java | 191 -- .../arcane/iris/studio/map/GpuLibrary.java | 63 - .../arcane/iris/studio/map/GpuObjectMesh.java | 293 --- .../iris/studio/map/GpuObjectRenderer.java | 300 --- .../arcane/iris/studio/map/GpuProgram.java | 131 -- .../iris/studio/map/GpuTerrainRenderer.java | 400 ---- .../art/arcane/iris/studio/map/GpuTile.java | 101 - .../arcane/iris/studio/map/GpuTileCache.java | 82 - .../iris/studio/map/GpuWindowFrame.java | 96 - .../arcane/iris/studio/map/GroundSight.java | 130 -- .../arcane/iris/studio/map/HoledLayer.java | 41 - .../iris/studio/map/ImageMapExplorer.java | 1041 ---------- .../iris/studio/map/ImageMapStudioModel.java | 411 ---- .../map/ImageMapStudioPreviewPanel.java | 626 ------ .../arcane/iris/studio/map/IslandOverlay.java | 105 - .../arcane/iris/studio/map/IslandPanel.java | 93 - .../iris/studio/map/LatestMeasurement.java | 92 - .../iris/studio/map/LoadingAnimation.java | 159 -- .../art/arcane/iris/studio/map/MapCanvas.java | 1343 ------------- .../art/arcane/iris/studio/map/MapCensus.java | 183 -- .../art/arcane/iris/studio/map/MapHost.java | 122 -- .../arcane/iris/studio/map/MapHoverCard.java | 538 ----- .../iris/studio/map/MapLegendPanel.java | 244 --- .../art/arcane/iris/studio/map/MapView.java | 130 -- .../arcane/iris/studio/map/MapViewIcon.java | 57 - .../arcane/iris/studio/map/MapViewList.java | 246 --- .../art/arcane/iris/studio/map/MapWindow.java | 719 ------- .../iris/studio/map/NoiseColorScale.java | 43 - .../arcane/iris/studio/map/NoiseColumns.java | 42 - .../iris/studio/map/NoiseExplorerGUI.java | 1766 ----------------- .../arcane/iris/studio/map/NoisePalette.java | 124 -- .../iris/studio/map/NoisePickChart.java | 340 ---- .../studio/map/NoiseRenderCoordinator.java | 397 ---- .../arcane/iris/studio/map/NoiseTerrain.java | 98 - .../iris/studio/map/NoiseTerrainRenderer.java | 440 ---- .../iris/studio/map/NoiseTerrainScene.java | 139 -- .../iris/studio/map/NoiseTerrainView.java | 256 --- .../arcane/iris/studio/map/NoiseViewport.java | 70 - .../arcane/iris/studio/map/ObjectBrowser.java | 276 --- .../iris/studio/map/ObjectExplorer.java | 649 ------ .../iris/studio/map/ObjectLayerCut.java | 86 - .../arcane/iris/studio/map/ObjectMesh.java | 289 --- .../iris/studio/map/ObjectOverviewPanel.java | 368 ---- .../iris/studio/map/ObjectRenderer.java | 305 --- .../iris/studio/map/ObjectSeedChooser.java | 160 -- .../arcane/iris/studio/map/ObjectSummary.java | 66 - .../iris/studio/map/ObjectVariantGallery.java | 376 ---- .../iris/studio/map/ObjectVariantPicker.java | 201 -- .../arcane/iris/studio/map/OrbitCamera.java | 48 - .../arcane/iris/studio/map/OrbitLimits.java | 34 - .../arcane/iris/studio/map/OrbitPicture.java | 63 - .../iris/studio/map/OrbitProjection.java | 171 -- .../arcane/iris/studio/map/OrbitScene.java | 63 - .../arcane/iris/studio/map/OrbitViewport.java | 683 ------- .../iris/studio/map/PackFileOpener.java | 58 - .../iris/studio/map/PaletteExplorerStart.java | 26 - .../studio/map/PaletteInspectorPanel.java | 401 ---- .../iris/studio/map/PaletteLayerPreview.java | 425 ---- .../iris/studio/map/PaletteLayerScale.java | 107 - .../iris/studio/map/PaletteNavigator.java | 527 ----- .../iris/studio/map/PickInspectorPanel.java | 388 ---- .../arcane/iris/studio/map/PicturePatch.java | 31 - .../studio/map/PlayerLocationTracker.java | 141 -- .../arcane/iris/studio/map/PlayerMarker.java | 123 -- .../iris/studio/map/RegionExplorer.java | 185 -- .../iris/studio/map/RegionNavigator.java | 173 -- .../arcane/iris/studio/map/ResourceUsage.java | 134 -- .../arcane/iris/studio/map/ScreenTarget.java | 30 - .../iris/studio/map/StickyFolderHeaders.java | 268 --- .../arcane/iris/studio/map/StudioOverlay.java | 64 - .../iris/studio/map/StudioStatusBar.java | 110 - .../arcane/iris/studio/map/StudioTheme.java | 307 --- .../arcane/iris/studio/map/StudioToolbar.java | 144 -- .../iris/studio/map/SystemAppearance.java | 110 - .../iris/studio/map/TerrainColumns.java | 30 - .../arcane/iris/studio/map/TerrainCover.java | 349 ---- .../arcane/iris/studio/map/TerrainGrid.java | 26 - .../iris/studio/map/TerrainHeightSlider.java | 83 - .../arcane/iris/studio/map/TerrainHole.java | 109 - .../arcane/iris/studio/map/TerrainLayer.java | 33 - .../iris/studio/map/TerrainSampling.java | 43 - .../arcane/iris/studio/map/TerrainTile.java | 86 - .../arcane/iris/studio/map/TerrainTiles.java | 272 --- .../arcane/iris/studio/map/ThemeColor.java | 55 - .../iris/studio/map/ViewportWidthPanel.java | 58 - .../studio/map/VisionRenderController.java | 744 ------- .../iris/studio/map/VisionViewport.java | 60 - .../arcane/iris/studio/map/WorldColoring.java | 78 - .../arcane/iris/studio/map/WorldColumns.java | 43 - .../arcane/iris/studio/map/WorldExplorer.java | 494 ----- .../studio/map/XwaylandWindowManagerHint.java | 86 - .../iris/studio/map/components/Renderer.java | 26 - .../iris/studio/view/PregenMapPanel.java | 331 --- .../iris/studio/view/PregenRenderer.java | 560 ------ .../iris/studio/map/FrameCrossfadeTest.java | 119 -- .../iris/studio/map/GpuLibraryTest.java | 48 - .../iris/studio/map/ImageMapExplorerTest.java | 20 - .../studio/map/ImageMapStudioModelTest.java | 168 -- .../map/ImageMapStudioPreviewPanelTest.java | 146 -- .../studio/map/MapCavePoolRefreshTest.java | 197 -- .../iris/studio/map/NoiseExplorerGUITest.java | 109 - .../iris/studio/map/NoisePaletteTest.java | 36 - .../map/NoiseRenderCoordinatorTest.java | 419 ---- .../iris/studio/map/NoiseTerrainViewTest.java | 89 - .../iris/studio/map/NoiseViewportTest.java | 31 - .../map/ObjectExplorerLifecycleTest.java | 224 --- .../map/OrbitViewportLifecycleTest.java | 97 - .../iris/studio/map/TerrainCoverTest.java | 90 - .../iris/studio/map/TerrainTilesTest.java | 72 - .../map/VisionRenderControllerTest.java | 465 ----- .../iris/studio/map/VisionViewportTest.java | 33 - .../iris/studio/map/WorldExplorerTest.java | 111 -- .../studio/view/DesktopGuiLaunchTest.java | 90 - .../view/GuiHostServerGuiLaunchTest.java | 63 - .../arcane/iris/studio/view/GuiHostTest.java | 71 - .../iris/studio/view/PregenMapPanelTest.java | 241 --- .../studio/view/PregenMapRetentionTest.java | 164 -- .../iris/studio/view/PregenRendererTest.java | 274 --- .../src/renderer/src/bridge/BridgeClient.ts | 32 + studio/src/renderer/src/bridge/types.ts | 50 + .../renderer/src/studio/ImageMapStudio.tsx | 109 + studio/src/renderer/src/studio/MapStudio.tsx | 10 +- .../src/renderer/src/studio/PregenStudio.tsx | 131 ++ studio/src/renderer/src/studio/ViewList.tsx | 4 +- 149 files changed, 334 insertions(+), 29970 deletions(-) delete mode 100644 adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/CommandStudioDesktopTest.java delete mode 100644 adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/StudioMapPositionTest.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/BakeMeter.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/BakeTiming.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/BakeWeight.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/BiomeExplorer.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/BlockFaces.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/BlockHeightColorScale.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/BlockModel.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/BlockModelBuilder.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/ColumnArea.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/EmptyState.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/EntityBlockShapes.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/FloatingPanels.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/FloatingSlider.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/FrameCrossfade.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/FrameRateLabel.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/GlxDisplay.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/GpuCache.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/GpuCanvas.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/GpuColors.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/GpuContext.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/GpuFaces.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/GpuFrameTarget.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/GpuFramebuffer.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/GpuFrames.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/GpuLibrary.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/GpuObjectMesh.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/GpuObjectRenderer.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/GpuProgram.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/GpuTerrainRenderer.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/GpuTile.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/GpuTileCache.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/GpuWindowFrame.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/GroundSight.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/HoledLayer.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/ImageMapExplorer.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/ImageMapStudioModel.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/ImageMapStudioPreviewPanel.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/IslandOverlay.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/IslandPanel.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/LatestMeasurement.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/LoadingAnimation.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/MapCanvas.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/MapCensus.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/MapHost.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/MapHoverCard.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/MapLegendPanel.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/MapView.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/MapViewIcon.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/MapViewList.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/MapWindow.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/NoiseColorScale.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/NoiseColumns.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/NoiseExplorerGUI.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/NoisePalette.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/NoisePickChart.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/NoiseRenderCoordinator.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/NoiseTerrain.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/NoiseTerrainRenderer.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/NoiseTerrainScene.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/NoiseTerrainView.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/NoiseViewport.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/ObjectBrowser.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/ObjectExplorer.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/ObjectLayerCut.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/ObjectMesh.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/ObjectOverviewPanel.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/ObjectRenderer.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/ObjectSeedChooser.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/ObjectSummary.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/ObjectVariantGallery.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/ObjectVariantPicker.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/OrbitCamera.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/OrbitLimits.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/OrbitPicture.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/OrbitProjection.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/OrbitScene.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/OrbitViewport.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/PackFileOpener.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/PaletteExplorerStart.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/PaletteInspectorPanel.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/PaletteLayerPreview.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/PaletteLayerScale.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/PaletteNavigator.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/PickInspectorPanel.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/PicturePatch.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/PlayerLocationTracker.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/PlayerMarker.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/RegionExplorer.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/RegionNavigator.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/ResourceUsage.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/ScreenTarget.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/StickyFolderHeaders.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/StudioOverlay.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/StudioStatusBar.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/StudioTheme.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/StudioToolbar.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/SystemAppearance.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/TerrainColumns.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/TerrainCover.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/TerrainGrid.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/TerrainHeightSlider.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/TerrainHole.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/TerrainLayer.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/TerrainSampling.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/TerrainTile.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/TerrainTiles.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/ThemeColor.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/ViewportWidthPanel.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/VisionRenderController.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/VisionViewport.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/WorldColoring.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/WorldColumns.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/WorldExplorer.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/XwaylandWindowManagerHint.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/map/components/Renderer.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/view/PregenMapPanel.java delete mode 100644 core/src/main/java/art/arcane/iris/studio/view/PregenRenderer.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/map/FrameCrossfadeTest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/map/GpuLibraryTest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/map/ImageMapExplorerTest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/map/ImageMapStudioModelTest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/map/ImageMapStudioPreviewPanelTest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/map/MapCavePoolRefreshTest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/map/NoiseExplorerGUITest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/map/NoisePaletteTest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/map/NoiseRenderCoordinatorTest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/map/NoiseTerrainViewTest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/map/NoiseViewportTest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/map/ObjectExplorerLifecycleTest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/map/OrbitViewportLifecycleTest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/map/TerrainCoverTest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/map/TerrainTilesTest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/map/VisionRenderControllerTest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/map/VisionViewportTest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/map/WorldExplorerTest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/view/DesktopGuiLaunchTest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/view/GuiHostServerGuiLaunchTest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/view/GuiHostTest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/view/PregenMapPanelTest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/view/PregenMapRetentionTest.java delete mode 100644 core/src/test/java/art/arcane/iris/studio/view/PregenRendererTest.java create mode 100644 studio/src/renderer/src/studio/ImageMapStudio.tsx create mode 100644 studio/src/renderer/src/studio/PregenStudio.tsx diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/CommandStudioDesktopTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/CommandStudioDesktopTest.java deleted file mode 100644 index 3744b6042..000000000 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/CommandStudioDesktopTest.java +++ /dev/null @@ -1,83 +0,0 @@ -package art.arcane.iris.command; - -import art.arcane.iris.configuration.IrisSettings; -import art.arcane.iris.platform.bukkit.plugin.VolmitSender; -import art.arcane.iris.studio.view.GuiHost; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.util.ArrayList; -import java.util.List; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public class CommandStudioDesktopTest { - private IrisSettings previousSettings; - private boolean previousSuppressed; - private RecordingSender sender; - private CommandStudio command; - - @Before - public void setup() { - previousSettings = IrisSettings.settings; - previousSuppressed = GuiHost.isDesktopSuppressed(); - IrisSettings.settings = new IrisSettings(); - IrisSettings.settings.getGui().setUseServerLaunchedGuis(true); - GuiHost.suppressDesktop(true); - sender = new RecordingSender(); - command = new TestCommand(sender); - } - - @After - public void restore() { - IrisSettings.settings = previousSettings; - GuiHost.suppressDesktop(previousSuppressed); - } - - @Test - public void mapReportsMissingDisplayBeforeAccessingWorld() { - command.map(null); - - assertDisplayMessage(); - } - - @Test - public void imageMapReportsMissingDisplayInsteadOfDisabledSetting() { - command.imagemap(null); - - assertDisplayMessage(); - } - - private void assertDisplayMessage() { - assertEquals(1, sender.messages.size()); - assertTrue(sender.messages.getFirst(), sender.messages.getFirst().contains("display")); - } - - private static final class TestCommand extends CommandStudio { - private final VolmitSender sender; - - private TestCommand(VolmitSender sender) { - this.sender = sender; - } - - @Override - public VolmitSender sender() { - return sender; - } - } - - private static final class RecordingSender extends VolmitSender { - private final List messages = new ArrayList<>(); - - private RecordingSender() { - super(null); - } - - @Override - public void sendMessage(String message) { - messages.add(message); - } - } -} diff --git a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/StudioMapPositionTest.java b/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/StudioMapPositionTest.java deleted file mode 100644 index 4879a9495..000000000 --- a/adapters/bukkit/plugin/src/test/java/art/arcane/iris/command/StudioMapPositionTest.java +++ /dev/null @@ -1,99 +0,0 @@ -package art.arcane.iris.command; - -import art.arcane.iris.configuration.IrisSettings; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.platform.bukkit.plugin.VolmitSender; -import art.arcane.iris.platform.generation.PlatformChunkGenerator; -import art.arcane.iris.studio.map.MapWindow; -import art.arcane.iris.studio.map.PaletteExplorerStart; -import art.arcane.iris.studio.view.GuiHost; -import art.arcane.iris.world.IrisToolbelt; -import art.arcane.iris.world.task.J; -import org.bukkit.Location; -import org.bukkit.World; -import org.bukkit.entity.Player; -import org.junit.Test; -import org.mockito.MockedStatic; - -import java.util.UUID; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.ArgumentMatchers.same; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockStatic; -import static org.mockito.Mockito.when; - -public class StudioMapPositionTest { - @Test - public void mapCapturesItsStartingPositionOnThePlayerScheduler() { - IrisSettings previous = IrisSettings.settings; - IrisSettings.settings = new IrisSettings(); - IrisSettings.settings.getGui().setUseServerLaunchedGuis(true); - World world = mock(World.class); - Player player = mock(Player.class); - VolmitSender sender = mock(VolmitSender.class); - PlatformChunkGenerator generator = mock(PlatformChunkGenerator.class); - Engine engine = mock(Engine.class); - UUID playerId = UUID.randomUUID(); - UUID worldId = UUID.randomUUID(); - AtomicBoolean owned = new AtomicBoolean(); - AtomicReference task = new AtomicReference<>(); - AtomicReference start = new AtomicReference<>(); - when(world.getUID()).thenReturn(worldId); - when(player.getUniqueId()).thenReturn(playerId); - when(player.isOnline()).thenReturn(true); - when(player.getWorld()).thenAnswer(invocation -> { - assertTrue("world read must use the player scheduler", owned.get()); - return world; - }); - when(player.getLocation()).thenAnswer(invocation -> { - assertTrue("location read must use the player scheduler", owned.get()); - return new Location(world, 33.25D, 91D, -72.5D); - }); - when(sender.isPlayer()).thenReturn(true); - when(sender.player()).thenReturn(player); - when(generator.getEngine()).thenReturn(engine); - CommandStudio command = new CommandStudio() { - @Override - public VolmitSender sender() { - return sender; - } - }; - try (MockedStatic host = mockStatic(GuiHost.class); - MockedStatic toolbelt = mockStatic(IrisToolbelt.class); - MockedStatic scheduling = mockStatic(J.class); - MockedStatic windows = mockStatic(MapWindow.class)) { - host.when(GuiHost::isAvailable).thenReturn(true); - toolbelt.when(() -> IrisToolbelt.isIrisWorld(world)).thenReturn(true); - toolbelt.when(() -> IrisToolbelt.access(world)).thenReturn(generator); - scheduling.when(() -> J.runEntity(same(player), any(Runnable.class), eq(0), any(Runnable.class))) - .thenAnswer(invocation -> { - task.set(invocation.getArgument(1)); - return true; - }); - windows.when(() -> MapWindow.openMap(any(PaletteExplorerStart.class))).thenAnswer(invocation -> { - start.set(invocation.getArgument(0)); - return null; - }); - - command.map(world); - assertNull(start.get()); - owned.set(true); - task.get().run(); - - assertEquals(engine, start.get().engine()); - assertEquals(playerId, start.get().playerId()); - assertEquals(worldId, start.get().worldId()); - assertEquals(33.25D, start.get().centerX(), 0D); - assertEquals(-72.5D, start.get().centerZ(), 0D); - } finally { - IrisSettings.settings = previous; - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/BakeMeter.java b/core/src/main/java/art/arcane/iris/studio/map/BakeMeter.java deleted file mode 100644 index 9e6c53c01..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/BakeMeter.java +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import com.formdev.flatlaf.extras.FlatSVGIcon; - -import javax.swing.JComponent; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.RenderingHints; - -/** - * IntelliJ's profiler gauge, how heavy the measured bake is, a meter and the time it took, all in the weight's colour. - */ -final class BakeMeter extends JComponent { - private static final long serialVersionUID = 4120925066373218716L; - private static final String PROFILER_ICON = "iris/icons/profiler.svg"; - private static final String TIMING_LABEL = "Timing"; - private static final String WIDEST_TIME = "999 ms"; - private static final int ICON_SIZE = 16; - private static final int GAP = 6; - private static final int BAR_HEIGHT = 4; - private static final int HEIGHT = 20; - - private final FlatSVGIcon icon = new FlatSVGIcon(PROFILER_ICON, ICON_SIZE, ICON_SIZE, BakeMeter.class.getClassLoader()); - private BakeTiming timing; - private boolean timingUnderWay; - - BakeMeter() { - icon.setColorFilter(new FlatSVGIcon.ColorFilter(drawn -> color())); - } - - void showTiming() { - timing = null; - timingUnderWay = true; - setToolTipText("Baking every variant five times over"); - repaint(); - } - - void show(BakeTiming measured) { - timing = measured; - timingUnderWay = false; - setToolTipText(measured.explain()); - repaint(); - } - - void clear() { - timing = null; - timingUnderWay = false; - setToolTipText(null); - repaint(); - } - - @Override - public Dimension getPreferredSize() { - return new Dimension(0, StudioTheme.scale(HEIGHT)); - } - - @Override - protected void paintComponent(Graphics graphics) { - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - icon.paintIcon(this, canvas, 0, (getHeight() - icon.getIconHeight()) / 2); - int labelX = icon.getIconWidth() + StudioTheme.scale(GAP); - int barX = drawLabel(canvas, labelX) + StudioTheme.scale(GAP); - int timeX = getWidth() - timeWidth(canvas); - drawBar(canvas, barX, timeX - StudioTheme.scale(GAP) - barX); - drawTime(canvas, timeX); - } finally { - canvas.dispose(); - } - } - - private Color color() { - return timing == null ? StudioTheme.MUTED_TEXT : weight().color(); - } - - private BakeWeight weight() { - return BakeWeight.of(timing.totalMillis()); - } - - // Returns where the label ends. - private int drawLabel(Graphics2D canvas, int x) { - canvas.setFont(StudioTheme.boldFont()); - FontMetrics metrics = canvas.getFontMetrics(); - canvas.setColor(color()); - canvas.drawString(labelText(), x, baseline(metrics)); - int widestLabelWidth = metrics.stringWidth(TIMING_LABEL); - for (BakeWeight each : BakeWeight.values()) { - widestLabelWidth = Math.max(widestLabelWidth, metrics.stringWidth(each.label())); - } - return x + widestLabelWidth; - } - - private String labelText() { - if (timing != null) { - return weight().label(); - } - return timingUnderWay ? TIMING_LABEL : "—"; - } - - private void drawBar(Graphics2D canvas, int x, int width) { - int barHeight = StudioTheme.scale(BAR_HEIGHT); - int y = (getHeight() - barHeight) / 2; - canvas.setColor(StudioTheme.HOVER_BACKGROUND); - canvas.fillRoundRect(x, y, width, barHeight, barHeight, barHeight); - if (timing == null) { - return; - } - int filledWidth = (int) Math.round(width * BakeWeight.meterFill(timing.totalMillis())); - canvas.setColor(color()); - canvas.fillRoundRect(x, y, Math.max(barHeight, filledWidth), barHeight, barHeight, barHeight); - } - - private int timeWidth(Graphics2D canvas) { - return canvas.getFontMetrics(StudioTheme.smallFont()).stringWidth(WIDEST_TIME); - } - - private void drawTime(Graphics2D canvas, int x) { - if (timing == null) { - return; - } - canvas.setFont(StudioTheme.smallFont()); - FontMetrics metrics = canvas.getFontMetrics(); - String time = BakeTiming.formatMillis(timing.totalMillis()); - canvas.setColor(StudioTheme.SECONDARY_TEXT); - canvas.drawString(time, x + timeWidth(canvas) - metrics.stringWidth(time), baseline(metrics)); - } - - private int baseline(FontMetrics metrics) { - return (getHeight() + metrics.getAscent() - metrics.getDescent()) / 2; - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/BakeTiming.java b/core/src/main/java/art/arcane/iris/studio/map/BakeTiming.java deleted file mode 100644 index 5713c3635..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/BakeTiming.java +++ /dev/null @@ -1,71 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Locale; -import java.util.function.BooleanSupplier; -import java.util.function.Supplier; - -/** - * A procedural object's variants baked five times over, keeping the median run. The first run is slow while the JIT - * compiles the baker, and the garbage collector or chunk generation can slow any other, so neither ends up in the middle. - */ -record BakeTiming(BakeRun median) { - private static final int RUN_COUNT = 5; - private static final double NANOS_PER_MILLI = 1_000_000D; - - /** Null when {@code bake} finds nothing to bake, or once the timing is no longer wanted. */ - static BakeTiming measure(Supplier bake, BooleanSupplier stillWanted) { - List runs = new ArrayList<>(); - for (int run = 0; run < RUN_COUNT; run++) { - if (!stillWanted.getAsBoolean()) { - return null; - } - BakeRun measured = bake.get(); - if (measured == null) { - return null; - } - runs.add(measured); - } - runs.sort(Comparator.comparingLong(BakeRun::totalNanos)); - return new BakeTiming(runs.get(runs.size() / 2)); - } - - double totalMillis() { - return median.totalNanos() / NANOS_PER_MILLI; - } - - /** How long the bake took and when world generation pays for it. */ - String explain() { - String variants = median.variantCount() == 1 ? "1 variant" : median.variantCount() + " variants"; - return "" + variants + " in " + formatMillis(totalMillis()) + " · median of " + RUN_COUNT + " runs
" - + "Paid once per pack load, by the first chunk placing it
" - + BakeWeight.scale() + ""; - } - - static String formatMillis(double millis) { - if (millis >= 1000D) { - return String.format(Locale.ROOT, "%.1f s", millis / 1000D); - } - return String.format(Locale.ROOT, millis < 10D ? "%.1f ms" : "%.0f ms", millis); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/BakeWeight.java b/core/src/main/java/art/arcane/iris/studio/map/BakeWeight.java deleted file mode 100644 index 99fb999e2..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/BakeWeight.java +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.awt.Color; - -/** - * How long a procedural object's bake stalls the chunk that first places it, against a server tick of 50 ms. - */ -enum BakeWeight { - LIGHT("Light", 1D, 50D, StudioTheme.SUCCESS), - MODERATE("Moderate", 50D, 500D, StudioTheme.WARNING), - HEAVY("Heavy", 500D, 5_000D, StudioTheme.ERROR); - - private final String label; - private final double fromMillis; - private final double meterFullAtMillis; - private final Color color; - - BakeWeight(String label, double fromMillis, double meterFullAtMillis, Color color) { - this.label = label; - this.fromMillis = fromMillis; - this.meterFullAtMillis = meterFullAtMillis; - this.color = color; - } - - static BakeWeight of(double millis) { - for (BakeWeight weight : values()) { - if (millis < weight.meterFullAtMillis) { - return weight; - } - } - return HEAVY; - } - - /** - * How full the meter is for a bake of {@code millis}: each weight takes an equal share of the meter, filled on a - * logarithmic scale, since bakes span thousands of times. - */ - static double meterFill(double millis) { - BakeWeight weight = of(millis); - double clamped = Math.clamp(millis, weight.fromMillis, weight.meterFullAtMillis); - double withinWeight = Math.log(clamped / weight.fromMillis) / Math.log(weight.meterFullAtMillis / weight.fromMillis); - return (weight.ordinal() + withinWeight) / values().length; - } - - static String scale() { - return "Light under " + BakeTiming.formatMillis(MODERATE.fromMillis) + ", heavy from " + BakeTiming.formatMillis(HEAVY.fromMillis); - } - - String label() { - return label; - } - - Color color() { - return color; - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/BiomeExplorer.java b/core/src/main/java/art/arcane/iris/studio/map/BiomeExplorer.java deleted file mode 100644 index bbdd6568c..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/BiomeExplorer.java +++ /dev/null @@ -1,177 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.studio.map.PickMeasuring.TypedSpread; -import art.arcane.iris.studio.map.components.PickDisplay; -import art.arcane.iris.generation.runtime.IrisComplex; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.generation.terrain.InferredType; -import art.arcane.iris.generation.terrain.IrisRegion; -import art.arcane.volmlib.util.stream.ProceduralStream; - -import javax.swing.JComponent; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.EnumMap; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Consumer; -import java.util.function.Supplier; - -/** - * The biome view's explorer: every region picks the biomes on its ground from its own biome lists, so for each region - * in view it shows how its noise picks them. - */ -final class BiomeExplorer { - private final Supplier engineSource; - private final PickInspectorPanel inspector; - private final LatestMeasurement measurer = new LatestMeasurement<>("Iris Biome Explorer"); - private MapCensus.ViewArea latestArea; - private MapCensus.ViewArea measuredArea; - - /** - * @param onDisplayChosen receives how the map should draw the picks - */ - BiomeExplorer(Supplier engineSource, Consumer onDisplayChosen) { - this.engineSource = engineSource; - this.inspector = new PickInspectorPanel("Biomes", onDisplayChosen); - } - - PickInspectorPanel inspector() { - return inspector; - } - - /** - * Measures the regions in this area and how they pick their biomes, unless that was already done. - */ - void measure(MapCensus.ViewArea area) { - latestArea = area; - if (area == null || area.equals(measuredArea)) { - return; - } - measuredArea = area; - measurer.measure(() -> measurePicks(area), this::show); - } - - /** - * The pack changed, so the regions and their biomes are read again. - */ - void refresh() { - measuredArea = null; - measure(latestArea); - } - - void close() { - measurer.close(); - } - - private void show(Measurement measurement) { - List sections = new ArrayList<>(); - for (RegionPicks region : measurement.regions()) { - List charts = region.spreads().stream() - .map(spread -> (JComponent) inspector.noiseChart(spread, "Biomes", region.key() + "/" + spread.title())) - .toList(); - sections.add(new PickInspectorPanel.Section(region.key(), region.name(), region.color(), region.share(), - biomeCountText(region.biomeCount()), charts)); - } - inspector.showRegionSections("Each region splits its own biome noise by rarity", sections); - } - - private static String biomeCountText(int count) { - return count == 1 ? "1 biome" : count + " biomes"; - } - - private Measurement measurePicks(MapCensus.ViewArea area) { - Engine engine = engineSource.get(); - IrisComplex complex = engine == null ? null : engine.getComplex(); - if (complex == null) { - return null; - } - Map samplesByRegion = new IdentityHashMap<>(); - int[] total = {0}; - PickMeasuring.forEachSample(area, (x, z) -> { - IrisRegion region = complex.getRegionStream().get(x, z); - if (region == null) { - return; - } - total[0]++; - samplesByRegion.computeIfAbsent(region, subject -> new RegionSamples(engine, complex, subject)).add(x, z); - }); - List regions = samplesByRegion.values().stream() - .sorted(Comparator.comparingInt(RegionSamples::count).reversed()) - .map(samples -> samples.picks(engine, total[0])) - .toList(); - return new Measurement(regions); - } - - /** - * The spots in view one region owns. The biome view shows each spot's base biome, which the region picks from the - * biome list of the spot's continent type. - */ - private static final class RegionSamples { - private final IrisComplex complex; - private final IrisRegion region; - private final List spreads; - private final Map> noiseByType = new EnumMap<>(InferredType.class); - private int count; - - private RegionSamples(Engine engine, IrisComplex complex, IrisRegion region) { - this.complex = complex; - this.region = region; - this.spreads = PickMeasuring.biomeSpreads(engine, complex, region); - } - - private void add(double x, double z) { - count++; - InferredType type = complex.getBridgeStream().get(x, z); - for (TypedSpread typed : spreads) { - if (typed.type() == type) { - typed.spread().add(noiseByType.computeIfAbsent(type, shown -> complex.biomePickNoiseStream(region, shown)).get(x, z)); - } - } - } - - private int count() { - return count; - } - - private RegionPicks picks(Engine engine, int totalCount) { - double share = totalCount == 0 ? 0D : count / (double) totalCount; - String key = region.getLoadKey(); - String name = region.getName(); - int color = PickMeasuring.regionColor(engine, region); - List inView = spreads.stream().filter(typed -> typed.spread().sampleCount() > 0).toList(); - int biomeCount = (int) inView.stream() - .flatMap(typed -> typed.spread().rows().stream()) - .map(row -> row.option().key()) - .distinct() - .count(); - return new RegionPicks(key, name, color, share, biomeCount, inView.stream().map(TypedSpread::spread).toList()); - } - } - - private record RegionPicks(String key, String name, int color, double share, int biomeCount, - List spreads) { - } - - private record Measurement(List regions) { - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/BlockFaces.java b/core/src/main/java/art/arcane/iris/studio/map/BlockFaces.java deleted file mode 100644 index abc7dfa84..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/BlockFaces.java +++ /dev/null @@ -1,320 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.util.Arrays; -import java.util.function.IntUnaryOperator; - -/** - * The visible faces of noise terrain as columns, with neighbouring columns merged into one face where they show the - * same stretch: tops of one height along X, and sides of one height range along the side. A face runs {@code columns} - * columns from its first one and reaches {@code height} across: one column along Z for tops, blocks up for sides. - *

- * Hole walls follow the surface: a side from the floor up for each column next to where a {@link TerrainHole} may end, - * shown in place of the usual side while the column beside it is left out. No face crosses a hole's cell edge, so one - * set of faces serves every hole. - *

- * Faces depend on neither the camera nor the hole, so they are found once per terrain rather than every frame. - */ -final class BlockFaces { - private static final int INITIAL_CAPACITY = 1024; - private static final Facing[] FACINGS = Facing.values(); - private static final Kind[] KINDS = Kind.values(); - - private final NoiseTerrain terrain; - private final int floorY; - // Faces are kept kind by kind, and facing by facing within a kind. - private final int[] firstOfGroup = new int[KINDS.length * FACINGS.length + 1]; - private int count; - private int[] firstColumn = new int[INITIAL_CAPACITY]; - private int[] firstRow = new int[INITIAL_CAPACITY]; - private int[] bottomY = new int[INITIAL_CAPACITY]; - private int[] columns = new int[INITIAL_CAPACITY]; - private int[] height = new int[INITIAL_CAPACITY]; - private byte[] facing = new byte[INITIAL_CAPACITY]; - - private BlockFaces(NoiseTerrain terrain, int floorY) { - this.terrain = terrain; - this.floorY = floorY; - } - - /** - * @param floorY where sides on the edge, next to a gap or into a hole end - */ - static BlockFaces of(NoiseTerrain terrain, int floorY) { - BlockFaces faces = new BlockFaces(terrain, floorY); - for (Kind kind : KINDS) { - for (Facing facing : FACINGS) { - faces.firstOfGroup[group(kind, facing)] = faces.count; - faces.add(kind, facing); - } - } - faces.firstOfGroup[KINDS.length * FACINGS.length] = faces.count; - faces.trimToCount(); - return faces; - } - - private static int group(Kind kind, Facing facing) { - return kind.ordinal() * FACINGS.length + facing.ordinal(); - } - - private void add(Kind kind, Facing facing) { - if (kind == Kind.HOLE_WALL) { - addHoleWalls(facing); - } else if (facing == Facing.TOP) { - addTops(); - } else { - addSides(facing); - } - } - - // A height of 64 places blocks up to y 64, so the column's top face is at 65. - static int blockTop(double height) { - return (int) Math.floor(height) + 1; - } - - int count() { - return count; - } - - // All faces of one kind and facing follow on from the first. - int first(Kind kind, Facing facing) { - return firstOfGroup[group(kind, facing)]; - } - - int count(Kind kind, Facing facing) { - return firstOfGroup[group(kind, facing) + 1] - firstOfGroup[group(kind, facing)]; - } - - boolean isHoleWall(int face) { - return face >= first(Kind.HOLE_WALL, FACINGS[0]); - } - - int bottomY(int face) { - return bottomY[face]; - } - - Facing facing(int face) { - return FACINGS[facing[face]]; - } - - int columns(int face) { - return columns[face]; - } - - int height(int face) { - return height[face]; - } - - // The column and row of the face's first column; the others follow along its run. - int firstColumn(int face) { - return firstColumn[face]; - } - - int firstRow(int face) { - return firstRow[face]; - } - - // The corner the face runs and reaches from; east and south sides lie on the far edge of their column. - double originX(int face) { - return terrain.worldX(firstColumn[face] + (facing(face).normalX > 0 ? 1 : 0)); - } - - double originY(int face) { - return bottomY[face]; - } - - double originZ(int face) { - return terrain.worldZ(firstRow[face] + (facing(face).normalZ > 0 ? 1 : 0)); - } - - double runX(int face) { - return facing(face).runsAlongX() ? (double) columns[face] * terrain.step() : 0D; - } - - double runZ(int face) { - return facing(face).runsAlongX() ? 0D : (double) columns[face] * terrain.step(); - } - - double reachY(int face) { - return facing(face) == Facing.TOP ? 0D : height[face]; - } - - double reachZ(int face) { - return facing(face) == Facing.TOP ? (double) height[face] * terrain.step() : 0D; - } - - private boolean hasColumn(int column, int row) { - return terrain.hasHeight(column, row); - } - - private static boolean startsCell(int columnOrRow) { - return columnOrRow % TerrainHole.CELL_COLUMNS == 0; - } - - private void addTops() { - for (int row = 0; row < terrain.rows(); row++) { - int column = 0; - while (column < terrain.columns()) { - if (!hasColumn(column, row)) { - column++; - continue; - } - int top = blockTop(terrain.height(column, row)); - int runEnd = column + 1; - while (runEnd < terrain.columns() && !startsCell(runEnd) && hasColumn(runEnd, row) - && blockTop(terrain.height(runEnd, row)) == top) { - runEnd++; - } - add(Facing.TOP, column, row, top, runEnd - column, 1); - column = runEnd; - } - } - } - - private void addSides(Facing side) { - for (int lane = 0; lane < lanes(side); lane++) { - int sideLane = lane; - addSideRuns(side, lane, step -> sideBottom(side, sideLane, step)); - } - } - - // A hole only ends on the lines between cells, so walls only stand along those inside the terrain. - private void addHoleWalls(Facing side) { - if (side == Facing.TOP) { - return; - } - int towardNeighbour = side.runsAlongX() ? side.normalZ : side.normalX; - for (int lane = 0; lane < lanes(side); lane++) { - int neighbourLane = lane + towardNeighbour; - boolean facesNextCell = lane / TerrainHole.CELL_COLUMNS != neighbourLane / TerrainHole.CELL_COLUMNS; - if (neighbourLane >= 0 && neighbourLane < lanes(side) && facesNextCell) { - addSideRuns(side, lane, step -> floorY); - } - } - } - - private int lanes(Facing side) { - return side.runsAlongX() ? terrain.rows() : terrain.columns(); - } - - private void addSideRuns(Facing side, int lane, IntUnaryOperator bottomAt) { - int steps = side.runsAlongX() ? terrain.columns() : terrain.rows(); - int step = 0; - while (step < steps) { - int top = sideTop(side, lane, step); - int bottom = bottomAt.applyAsInt(step); - if (bottom >= top) { - step++; - continue; - } - int runEnd = step + 1; - while (runEnd < steps && !startsCell(runEnd) && sideTop(side, lane, runEnd) == top && bottomAt.applyAsInt(runEnd) == bottom) { - runEnd++; - } - add(side, side.column(lane, step), side.row(lane, step), bottom, runEnd - step, top - bottom); - step = runEnd; - } - } - - // No column means no side, which the caller sees as a side with no height. - private int sideTop(Facing side, int lane, int step) { - int column = side.column(lane, step); - int row = side.row(lane, step); - return hasColumn(column, row) ? blockTop(terrain.height(column, row)) : Integer.MIN_VALUE; - } - - // Columns on the edge, or next to a gap, show their side all the way down to the floor. - private int sideBottom(Facing side, int lane, int step) { - int column = side.column(lane, step) + side.normalX; - int row = side.row(lane, step) + side.normalZ; - return hasColumn(column, row) ? blockTop(terrain.height(column, row)) : floorY; - } - - private void add(Facing faceFacing, int column, int row, int bottom, int runColumns, int reach) { - if (count == facing.length) { - grow(); - } - firstColumn[count] = column; - firstRow[count] = row; - bottomY[count] = bottom; - columns[count] = runColumns; - height[count] = reach; - facing[count] = (byte) faceFacing.ordinal(); - count++; - } - - private void grow() { - resizeTo(facing.length * 2); - } - - // Large terrain keeps millions of faces, so the room left over from growing would be a lot of memory. - private void trimToCount() { - resizeTo(count); - } - - private void resizeTo(int capacity) { - firstColumn = Arrays.copyOf(firstColumn, capacity); - firstRow = Arrays.copyOf(firstRow, capacity); - bottomY = Arrays.copyOf(bottomY, capacity); - columns = Arrays.copyOf(columns, capacity); - height = Arrays.copyOf(height, capacity); - facing = Arrays.copyOf(facing, capacity); - } - - /** - * Which way a face looks. Tops and north and south sides run along X; east and west sides run along Z. - */ - enum Facing { - TOP(0, 1, 0), - NORTH(0, 0, -1), - SOUTH(0, 0, 1), - WEST(-1, 0, 0), - EAST(1, 0, 0); - - final int normalX; - final int normalY; - final int normalZ; - - Facing(int normalX, int normalY, int normalZ) { - this.normalX = normalX; - this.normalY = normalY; - this.normalZ = normalZ; - } - - boolean runsAlongX() { - return normalX == 0; - } - - // A lane is a row for faces running along X and a column for the others; steps go along the lane. - int column(int lane, int step) { - return runsAlongX() ? step : lane; - } - - int row(int lane, int step) { - return runsAlongX() ? lane : step; - } - } - - // Surface faces show unless their column is in a hole; hole walls only beside one. - enum Kind { - SURFACE, - HOLE_WALL - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/BlockHeightColorScale.java b/core/src/main/java/art/arcane/iris/studio/map/BlockHeightColorScale.java deleted file mode 100644 index 14c2b722a..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/BlockHeightColorScale.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.awt.Color; - -/** - * Colours noise that is already a height in blocks, spreading a palette over the heights it can reach. - */ -record BlockHeightColorScale(NoisePalette palette, double minimum, double maximum) implements NoiseColorScale { - @Override - public int colorFinite(double value) { - double span = maximum - minimum; - return palette.colorNormalized(span <= 0D ? 0.5D : (value - minimum) / span); - } - - @Override - public int colorInvalid() { - return palette.colorInvalid(); - } - - @Override - public Color displayColorNormalized(double normalized) { - return palette.displayColorNormalized(normalized); - } - - @Override - public String label() { - return "Blocks"; - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/BlockModel.java b/core/src/main/java/art/arcane/iris/studio/map/BlockModel.java deleted file mode 100644 index a95bf0cf9..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/BlockModel.java +++ /dev/null @@ -1,213 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -package art.arcane.iris.studio.map; - -import art.arcane.iris.studio.map.BlockTextures.BlockTexture; - -import java.util.ArrayList; -import java.util.EnumSet; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.function.UnaryOperator; - -/** - * A block as the object viewer draws it: the textured faces of its model, in block units, already turned the way the - * blockstate faces. - * - * @param faces every face of every box in the model - * @param coveredSides the block's sides that a solid face fills completely, which hide whatever touches them - * @param hidesSameBlockSides whether the model fills the whole block, so like glass it hides the sides between two of - * the same blocks - */ -record BlockModel(List faces, Set coveredSides, boolean hidesSameBlockSides) { - static final BlockModel EMPTY = new BlockModel(List.of(), Set.of(), false); - private static final int SIDE_CELLS = 16; - private static final double ON_SIDE_TOLERANCE = 1e-4D; - - static BlockModel of(List faces) { - Set coveredSides = EnumSet.noneOf(CubeFace.class); - boolean fillsEverySide = true; - for (CubeFace side : CubeFace.values()) { - if (sideIsFilled(faces, side, true)) { - coveredSides.add(side); - } - fillsEverySide &= sideIsFilled(faces, side, false); - } - return new BlockModel(List.copyOf(faces), Set.copyOf(coveredSides), fillsEverySide); - } - - static BlockModel solidColor(int color) { - BlockTexture texture = BlockTexture.solid(color); - List faces = new ArrayList<>(); - for (CubeFace side : CubeFace.values()) { - faces.add(Face.boxSide(Vec3.ZERO, new Vec3(1D, 1D, 1D), side, texture, side)); - } - return of(faces); - } - - boolean isEmpty() { - return faces.isEmpty(); - } - - BlockModel withTextures(UnaryOperator change) { - Map changed = new IdentityHashMap<>(); - List changedFaces = new ArrayList<>(faces.size()); - for (Face face : faces) { - changedFaces.add(face.withTexture(changed.computeIfAbsent(face.texture(), change))); - } - return new BlockModel(List.copyOf(changedFaces), coveredSides, hidesSameBlockSides); - } - - // The side is split into a grid, and every cell has to lie under a face pressed flat against it. - private static boolean sideIsFilled(List faces, CubeFace side, boolean onlySolidFaces) { - boolean[] filled = new boolean[SIDE_CELLS * SIDE_CELLS]; - for (Face face : faces) { - if (face.liesOn(side) && (!onlySolidFaces || face.texture().isFullyOpaque())) { - face.fillCells(side, filled, SIDE_CELLS); - } - } - for (boolean cell : filled) { - if (!cell) { - return false; - } - } - return true; - } - - /** - * A parallelogram from {@code origin} along {@code edgeU} and {@code edgeV}. The texture point at the origin and - * how it moves along each edge are given as fractions of the texture. - * - * @param normal the way the face looks out; it is hidden when seen from behind - * @param cullFace the block side whose neighbour hides this face when it covers that side, or null - */ - record Face(Vec3 origin, Vec3 edgeU, Vec3 edgeV, Vec3 normal, BlockTexture texture, TextureMapping mapping, - double shade, CubeFace cullFace) { - - // Laid out as seen from outside: u to the right and v downwards, matching Minecraft's UVs for a whole texture. - static Face boxSide(Vec3 from, Vec3 to, CubeFace side, BlockTexture texture, CubeFace cullFace) { - Vec3[] corners = BoxCorners.of(from, to, side); - return new Face(corners[0], corners[3].minus(corners[0]), corners[1].minus(corners[0]), side.direction(), - texture, TextureMapping.WHOLE, side.shade(), cullFace); - } - - Face withTexture(BlockTexture changedTexture) { - return new Face(origin, edgeU, edgeV, normal, changedTexture, mapping, shade, cullFace); - } - - Face transformed(Transform transform) { - Vec3 turnedNormal = transform.direction(normal); - double length = Math.sqrt(turnedNormal.x() * turnedNormal.x() + turnedNormal.y() * turnedNormal.y() + turnedNormal.z() * turnedNormal.z()); - return new Face(transform.point(origin), transform.direction(edgeU), transform.direction(edgeV), - length == 0D ? turnedNormal : turnedNormal.times(1D / length), texture, mapping, shade, - cullFace == null ? null : CubeFace.nearest(transform.direction(cullFace.direction()))); - } - - Face withCullFace(CubeFace side) { - return new Face(origin, edgeU, edgeV, normal, texture, mapping, shade, side); - } - - Face withShade(double changedShade) { - return new Face(origin, edgeU, edgeV, normal, texture, mapping, changedShade, cullFace); - } - - private boolean liesOn(CubeFace side) { - int axis = side.axis(); - double plane = side.pointsPositive() ? 1D : 0D; - return CubeFace.nearest(normal) == side - && Math.abs(normal.component(axis)) > 1D - ON_SIDE_TOLERANCE - && Math.abs(origin.component(axis) - plane) < ON_SIDE_TOLERANCE - && Math.abs(edgeU.component(axis)) < ON_SIDE_TOLERANCE - && Math.abs(edgeV.component(axis)) < ON_SIDE_TOLERANCE; - } - - private void fillCells(CubeFace side, boolean[] filled, int cells) { - int firstAxis = side.axis() == 0 ? 1 : 0; - int secondAxis = side.axis() == 2 ? 1 : 2; - double[] firstRange = range(firstAxis); - double[] secondRange = range(secondAxis); - for (int first = 0; first < cells; first++) { - double firstCenter = (first + 0.5D) / cells; - if (firstCenter < firstRange[0] || firstCenter > firstRange[1]) { - continue; - } - for (int second = 0; second < cells; second++) { - double secondCenter = (second + 0.5D) / cells; - if (secondCenter >= secondRange[0] && secondCenter <= secondRange[1]) { - filled[first * cells + second] = true; - } - } - } - } - - private double[] range(int axis) { - double start = origin.component(axis); - double alongU = edgeU.component(axis); - double alongV = edgeV.component(axis); - double low = start + Math.min(0D, alongU) + Math.min(0D, alongV); - double high = start + Math.max(0D, alongU) + Math.max(0D, alongV); - return new double[]{low, high}; - } - } - - /** - * Where a face's corner sits in its texture and how the texture point moves along the face's two edges, all as - * fractions of the texture's width and height. - */ - record TextureMapping(double u, double v, double uAlongU, double vAlongU, double uAlongV, double vAlongV) { - static final TextureMapping WHOLE = new TextureMapping(0D, 0D, 1D, 0D, 0D, 1D); - } - - /** - * A box side's corners in Minecraft's order: top left, bottom left, bottom right and top right, as seen from - * outside the box. - */ - static final class BoxCorners { - private BoxCorners() { - } - - static Vec3[] of(Vec3 from, Vec3 to, CubeFace side) { - double minX = from.x(); - double minY = from.y(); - double minZ = from.z(); - double maxX = to.x(); - double maxY = to.y(); - double maxZ = to.z(); - return switch (side) { - case DOWN -> corners(minX, minY, maxZ, minX, minY, minZ, maxX, minY, minZ, maxX, minY, maxZ); - case UP -> corners(minX, maxY, minZ, minX, maxY, maxZ, maxX, maxY, maxZ, maxX, maxY, minZ); - case NORTH -> corners(maxX, maxY, minZ, maxX, minY, minZ, minX, minY, minZ, minX, maxY, minZ); - case SOUTH -> corners(minX, maxY, maxZ, minX, minY, maxZ, maxX, minY, maxZ, maxX, maxY, maxZ); - case WEST -> corners(minX, maxY, minZ, minX, minY, minZ, minX, minY, maxZ, minX, maxY, maxZ); - case EAST -> corners(maxX, maxY, maxZ, maxX, minY, maxZ, maxX, minY, minZ, maxX, maxY, minZ); - }; - } - - private static Vec3[] corners(double... coordinates) { - Vec3[] corners = new Vec3[4]; - for (int corner = 0; corner < 4; corner++) { - corners[corner] = new Vec3(coordinates[corner * 3], coordinates[corner * 3 + 1], coordinates[corner * 3 + 2]); - } - return corners; - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/BlockModelBuilder.java b/core/src/main/java/art/arcane/iris/studio/map/BlockModelBuilder.java deleted file mode 100644 index 2990b72ca..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/BlockModelBuilder.java +++ /dev/null @@ -1,351 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -package art.arcane.iris.studio.map; - -import com.google.gson.JsonArray; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; -import art.arcane.iris.studio.map.BlockModel.BoxCorners; -import art.arcane.iris.studio.map.BlockModel.Face; -import art.arcane.iris.studio.map.BlockModel.TextureMapping; -import art.arcane.iris.studio.map.BlockTextures.BlockStateId; -import art.arcane.iris.studio.map.BlockTextures.BlockTexture; -import art.arcane.iris.studio.map.BlockTextures.ModelDefinition; - -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -/** - * Reads a block's look the way Minecraft does: every model part the blockstate picks, every box with its own texture - * and UVs, tilted boxes, the blockstate's turn with or without locked textures, and which faces a neighbour hides. - */ -final class BlockModelBuilder { - private static final double MODEL_UNITS = 16D; - private static final double BLOCK_CENTER = 0.5D; - private static final int QUARTER_TURN = 90; - - private final BlockTextures textures; - private final EntityBlockShapes entityShapes; - - BlockModelBuilder(BlockTextures textures) { - this.textures = textures; - this.entityShapes = new EntityBlockShapes(textures); - } - - Optional build(String blockState) { - try { - BlockStateId state = BlockStateId.parse(blockState); - List placements = placementsOf(state); - if (placements == null) { - return Optional.empty(); - } - List faces = new ArrayList<>(); - for (JsonObject placement : placements) { - faces.addAll(placedFaces(state, placement)); - } - faces.addAll(entityShapes.facesAddedTo(state)); - return Optional.of(BlockModel.of(faces)); - } catch (IOException | RuntimeException error) { - return Optional.empty(); - } - } - - /** - * A box with Minecraft's default UVs on each side, for shapes the game draws in code. - */ - static List box(Vec3 fromPixels, Vec3 toPixels, BlockTexture texture, boolean culledBySides) { - List faces = new ArrayList<>(); - for (CubeFace side : CubeFace.values()) { - FaceUv uv = FaceUv.byDefault(side, fromPixels, toPixels); - Face face = boxFace(fromPixels, toPixels, side, texture, uv).withShade(side.shade()); - faces.add(culledBySides ? face.withCullFace(side) : face); - } - return faces; - } - - // A variant names one model; a multipart blockstate, like a fence's, adds a part for every condition that holds. - private List placementsOf(BlockStateId state) throws IOException { - JsonObject definition = textures.readJson(BlockTextures.assetPath(state.namespace() + ":" + state.name(), "blockstates", ".json")); - if (definition == null) { - return null; - } - List placements = new ArrayList<>(); - if (definition.has("variants")) { - for (Map.Entry variant : definition.getAsJsonObject("variants").entrySet()) { - if (BlockTextures.variantMatches(variant.getKey(), state.properties())) { - addPlacement(placements, variant.getValue()); - break; - } - } - } - if (definition.has("multipart")) { - for (JsonElement part : definition.getAsJsonArray("multipart")) { - JsonObject rule = part.getAsJsonObject(); - if (!rule.has("when") || BlockTextures.conditionMatches(rule.getAsJsonObject("when"), state.properties())) { - addPlacement(placements, rule.get("apply")); - } - } - } - return placements; - } - - private static void addPlacement(List placements, JsonElement models) { - JsonObject first = BlockTextures.firstModel(models); - if (first != null && first.has("model")) { - placements.add(first); - } - } - - private List placedFaces(BlockStateId state, JsonObject placement) throws IOException { - ModelDefinition model = textures.readModel(placement.get("model").getAsString()); - if (model.elements() == null) { - return entityShapes.facesOf(state, model); - } - BlockRotation rotation = BlockRotation.of(placement); - List faces = new ArrayList<>(); - for (JsonElement element : model.elements()) { - addElementFaces(faces, state, model, element.getAsJsonObject(), rotation); - } - return faces; - } - - private void addElementFaces(List faces, BlockStateId state, ModelDefinition model, JsonObject element, BlockRotation rotation) { - JsonObject elementFaces = element.getAsJsonObject("faces"); - if (elementFaces == null) { - return; - } - Vec3 from = vector(element.getAsJsonArray("from")); - Vec3 to = vector(element.getAsJsonArray("to")); - Transform tilt = tiltOf(element); - boolean shaded = !element.has("shade") || element.get("shade").getAsBoolean(); - CubeFace shadeSide = element.has("shade_direction_override") - ? CubeFace.named(element.get("shade_direction_override").getAsString()) : null; - for (Map.Entry entry : elementFaces.entrySet()) { - CubeFace side = CubeFace.named(entry.getKey()); - JsonObject faceJson = entry.getValue().getAsJsonObject(); - if (side == null || !faceJson.has("texture")) { - continue; - } - String textureName = BlockTextures.dereference(faceJson.get("texture").getAsString(), model.textures()); - if (textureName == null) { - continue; - } - Optional texture = textures.faceTexture(state, textureName, BlockTextures.tintIndexOf(faceJson)); - if (texture.isEmpty()) { - continue; - } - FaceUv uv = FaceUv.of(faceJson, side, from, to); - if (rotation.locksTextures()) { - uv = uv.lockedTo(side, rotation); - } - Face face = boxFace(from, to, side, texture.get(), uv).transformed(tilt); - if (faceJson.has("cullface")) { - face = face.withCullFace(CubeFace.named(faceJson.get("cullface").getAsString())); - } - face = face.transformed(rotation.transform()); - faces.add(face.withShade(shadeOf(face, shaded, shadeSide, rotation))); - } - } - - private static Face boxFace(Vec3 fromPixels, Vec3 toPixels, CubeFace side, BlockTexture texture, FaceUv uv) { - Vec3[] corners = BoxCorners.of(fromPixels.times(1D / MODEL_UNITS), toPixels.times(1D / MODEL_UNITS), side); - return new Face(corners[0], corners[3].minus(corners[0]), corners[1].minus(corners[0]), side.direction(), - texture, uv.mapping(), side.shade(), null); - } - - private static double shadeOf(Face face, boolean shaded, CubeFace shadeSide, BlockRotation rotation) { - if (!shaded) { - return CubeFace.UP.shade(); - } - if (shadeSide != null) { - return CubeFace.nearest(rotation.transform().direction(shadeSide.direction())).shade(); - } - return CubeFace.nearest(face.normal()).shade(); - } - - // A box can be tilted around a point, on one axis or, since 1.21.?, on all three; rescaling stretches a tilted - // plant back to the full block width. - private static Transform tiltOf(JsonObject element) { - if (!element.has("rotation")) { - return Transform.IDENTITY; - } - JsonObject rotation = element.getAsJsonObject("rotation"); - Vec3 origin = rotation.has("origin") ? vector(rotation.getAsJsonArray("origin")).times(1D / MODEL_UNITS) : new Vec3(BLOCK_CENTER, BLOCK_CENTER, BLOCK_CENTER); - Transform around = Transform.IDENTITY.translate(origin.x(), origin.y(), origin.z()); - Transform back = Transform.IDENTITY.translate(-origin.x(), -origin.y(), -origin.z()); - if (!rotation.has("axis")) { - return around - .rotateX(numberOr(rotation, "x", 0D)) - .rotateY(numberOr(rotation, "y", 0D)) - .rotateZ(numberOr(rotation, "z", 0D)) - .then(back); - } - String axis = rotation.get("axis").getAsString(); - double angle = numberOr(rotation, "angle", 0D); - boolean rescale = rotation.has("rescale") && rotation.get("rescale").getAsBoolean(); - double stretch = rescale ? 1D / Math.cos(Math.toRadians(angle)) : 1D; - Transform stretched = around.scale(axis.equals("x") ? 1D : stretch, axis.equals("y") ? 1D : stretch, axis.equals("z") ? 1D : stretch); - Transform tilted = switch (axis) { - case "x" -> stretched.rotateX(angle); - case "y" -> stretched.rotateY(angle); - default -> stretched.rotateZ(angle); - }; - return tilted.then(back); - } - - private static double numberOr(JsonObject object, String key, double fallback) { - return object.has(key) ? object.get(key).getAsDouble() : fallback; - } - - private static Vec3 vector(JsonArray values) { - return new Vec3(values.get(0).getAsDouble(), values.get(1).getAsDouble(), values.get(2).getAsDouble()); - } - - /** - * How a blockstate turns its model: around the x axis first, then the y axis, both in quarter turns against the - * right-hand rule. With uvlock the textures stay put while the shape turns. - */ - private record BlockRotation(int x, int y, boolean uvlock) { - static BlockRotation of(JsonObject placement) { - int x = placement.has("x") ? Math.floorMod(placement.get("x").getAsInt(), 360) : 0; - int y = placement.has("y") ? Math.floorMod(placement.get("y").getAsInt(), 360) : 0; - return new BlockRotation(x, y, placement.has("uvlock") && placement.get("uvlock").getAsBoolean()); - } - - boolean locksTextures() { - return uvlock && (x != 0 || y != 0); - } - - Transform transform() { - return Transform.IDENTITY - .translate(BLOCK_CENTER, BLOCK_CENTER, BLOCK_CENTER) - .then(turn()) - .translate(-BLOCK_CENTER, -BLOCK_CENTER, -BLOCK_CENTER); - } - - Transform turn() { - return Transform.IDENTITY.rotateY(-y).rotateX(-x); - } - - Transform inverseTurn() { - return Transform.IDENTITY.rotateX(x).rotateY(y); - } - } - - /** - * A face's corner UVs in model pixels and the quarter turn of the texture on it. - */ - private record FaceUv(double u1, double v1, double u2, double v2, int rotation) { - static FaceUv of(JsonObject face, CubeFace side, Vec3 from, Vec3 to) { - int rotation = face.has("rotation") ? Math.floorMod(face.get("rotation").getAsInt(), 360) : 0; - if (!face.has("uv")) { - return byDefault(side, from, to).withRotation(rotation); - } - JsonArray uv = face.getAsJsonArray("uv"); - return new FaceUv(uv.get(0).getAsDouble(), uv.get(1).getAsDouble(), uv.get(2).getAsDouble(), uv.get(3).getAsDouble(), rotation); - } - - // The part of the texture the face would cover if the texture were laid over the whole block side. - static FaceUv byDefault(CubeFace side, Vec3 from, Vec3 to) { - double full = MODEL_UNITS; - return switch (side) { - case DOWN -> new FaceUv(from.x(), full - to.z(), to.x(), full - from.z(), 0); - case UP -> new FaceUv(from.x(), from.z(), to.x(), to.z(), 0); - case NORTH -> new FaceUv(full - to.x(), full - to.y(), full - from.x(), full - from.y(), 0); - case SOUTH -> new FaceUv(from.x(), full - to.y(), to.x(), full - from.y(), 0); - case WEST -> new FaceUv(from.z(), full - to.y(), to.z(), full - from.y(), 0); - case EAST -> new FaceUv(full - to.z(), full - to.y(), full - from.z(), full - from.y(), 0); - }; - } - - FaceUv withRotation(int changedRotation) { - return new FaceUv(u1, v1, u2, v2, changedRotation); - } - - // Each corner takes the UV a quarter turn further along for every quarter turn of the texture. - TextureMapping mapping() { - double[] origin = cornerUv(0); - double[] alongU = cornerUv(3); - double[] alongV = cornerUv(1); - return new TextureMapping(origin[0] / MODEL_UNITS, origin[1] / MODEL_UNITS, - (alongU[0] - origin[0]) / MODEL_UNITS, (alongU[1] - origin[1]) / MODEL_UNITS, - (alongV[0] - origin[0]) / MODEL_UNITS, (alongV[1] - origin[1]) / MODEL_UNITS); - } - - private double[] cornerUv(int corner) { - return switch ((corner + rotation / QUARTER_TURN) % 4) { - case 0 -> new double[]{u1, v1}; - case 1 -> new double[]{u1, v2}; - case 2 -> new double[]{u2, v2}; - default -> new double[]{u2, v1}; - }; - } - - /** - * Minecraft's uvlock: the UVs are carried through the reverse of the blockstate's turn, so the texture keeps - * its place in the world while the face moves to another side. - */ - FaceUv lockedTo(CubeFace side, BlockRotation blockRotation) { - CubeFace turnedSide = CubeFace.nearest(blockRotation.turn().direction(side.direction())); - Transform uvTurn = Transform.IDENTITY - .translate(BLOCK_CENTER, BLOCK_CENTER, BLOCK_CENTER) - .then(faceFromWorld(side)) - .then(blockRotation.inverseTurn()) - .then(worldFromFace(turnedSide)) - .translate(-BLOCK_CENTER, -BLOCK_CENTER, -BLOCK_CENTER); - Vec3 first = uvTurn.point(new Vec3(u1 / MODEL_UNITS, v1 / MODEL_UNITS, 0D)).times(MODEL_UNITS); - Vec3 second = uvTurn.point(new Vec3(u2 / MODEL_UNITS, v2 / MODEL_UNITS, 0D)).times(MODEL_UNITS); - boolean keepsUOrder = Math.signum(u2 - u1) == Math.signum(second.x() - first.x()); - boolean keepsVOrder = Math.signum(v2 - v1) == Math.signum(second.y() - first.y()); - Vec3 textureRight = uvTurn.direction(new Vec3(Math.cos(Math.toRadians(rotation)), Math.sin(Math.toRadians(rotation)), 0D)); - long quarterTurns = Math.round(Math.toDegrees(Math.atan2(textureRight.y(), textureRight.x())) / QUARTER_TURN); - return new FaceUv( - keepsUOrder ? first.x() : second.x(), keepsVOrder ? first.y() : second.y(), - keepsUOrder ? second.x() : first.x(), keepsVOrder ? second.y() : first.y(), - (int) Math.floorMod(-quarterTurns * QUARTER_TURN, 360L)); - } - - // Minecraft lays every side's texture out as if it were the south side, turned into place. - private static Transform worldFromFace(CubeFace side) { - return switch (side) { - case SOUTH -> Transform.IDENTITY; - case EAST -> Transform.IDENTITY.rotateY(90D); - case WEST -> Transform.IDENTITY.rotateY(-90D); - case NORTH -> Transform.IDENTITY.rotateY(180D); - case UP -> Transform.IDENTITY.rotateX(-90D); - case DOWN -> Transform.IDENTITY.rotateX(90D); - }; - } - - private static Transform faceFromWorld(CubeFace side) { - return switch (side) { - case SOUTH -> Transform.IDENTITY; - case EAST -> Transform.IDENTITY.rotateY(-90D); - case WEST -> Transform.IDENTITY.rotateY(90D); - case NORTH -> Transform.IDENTITY.rotateY(180D); - case UP -> Transform.IDENTITY.rotateX(90D); - case DOWN -> Transform.IDENTITY.rotateX(-90D); - }; - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/ColumnArea.java b/core/src/main/java/art/arcane/iris/studio/map/ColumnArea.java deleted file mode 100644 index 5cb250e38..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/ColumnArea.java +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -/** - * A rectangle of a terrain's columns and rows, from the first up to but not including the last. - */ -record ColumnArea(int fromColumn, int fromRow, int toColumn, int toRow) { -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/EmptyState.java b/core/src/main/java/art/arcane/iris/studio/map/EmptyState.java deleted file mode 100644 index 65391817e..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/EmptyState.java +++ /dev/null @@ -1,102 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import javax.swing.Icon; -import java.awt.Color; -import java.awt.Component; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.geom.RoundRectangle2D; - -/** - * What an empty view says, drawn in the middle of it the way IntelliJ fills an empty tool window: a large icon, what - * is missing, and where to add it. - * - * @param location the pack folder or file the hint points to, drawn as code - */ -record EmptyState(Icon icon, String title, String hint, String location, String footer) { - private static final int ICON_GAP = 18; - private static final int TITLE_GAP = 8; - private static final int LOCATION_GAP = 10; - private static final int FOOTER_GAP = 14; - private static final int CHIP_PADDING_X = 8; - private static final int CHIP_PADDING_Y = 4; - private static final int CHIP_ARC = 8; - - /** - * Draws the empty state centred on the given point. - */ - void paint(Graphics2D graphics, Component owner, int centerX, int centerY) { - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - int top = centerY - height(canvas) / 2; - icon.paintIcon(owner, canvas, centerX - icon.getIconWidth() / 2, top); - top += icon.getIconHeight() + StudioTheme.scale(ICON_GAP); - top = drawCentered(canvas, title, StudioTheme.titleFont(), StudioTheme.TEXT, centerX, top); - top = drawCentered(canvas, hint, StudioTheme.font(), StudioTheme.SECONDARY_TEXT, centerX, - top + StudioTheme.scale(TITLE_GAP)); - top = drawLocationChip(canvas, centerX, top + StudioTheme.scale(LOCATION_GAP)); - drawCentered(canvas, footer, StudioTheme.smallFont(), StudioTheme.MUTED_TEXT, centerX, top + StudioTheme.scale(FOOTER_GAP)); - } finally { - canvas.dispose(); - } - } - - private int height(Graphics2D canvas) { - return icon.getIconHeight() + StudioTheme.scale(ICON_GAP) - + canvas.getFontMetrics(StudioTheme.titleFont()).getHeight() - + StudioTheme.scale(TITLE_GAP) + canvas.getFontMetrics(StudioTheme.font()).getHeight() - + StudioTheme.scale(LOCATION_GAP) + chipHeight(canvas) - + StudioTheme.scale(FOOTER_GAP) + canvas.getFontMetrics(StudioTheme.smallFont()).getHeight(); - } - - private int chipHeight(Graphics2D canvas) { - return canvas.getFontMetrics(StudioTheme.monospacedFont()).getHeight() + StudioTheme.scale(CHIP_PADDING_Y) * 2; - } - - private int drawLocationChip(Graphics2D canvas, int centerX, int top) { - canvas.setFont(StudioTheme.monospacedFont()); - FontMetrics metrics = canvas.getFontMetrics(); - int width = metrics.stringWidth(location) + StudioTheme.scale(CHIP_PADDING_X) * 2; - int height = chipHeight(canvas); - int left = centerX - width / 2; - RoundRectangle2D chip = new RoundRectangle2D.Double(left + 0.5D, top + 0.5D, width - 1D, height - 1D, - StudioTheme.scale(CHIP_ARC), StudioTheme.scale(CHIP_ARC)); - canvas.setColor(StudioTheme.PANEL_BACKGROUND); - canvas.fill(chip); - canvas.setColor(StudioTheme.CONTROL_BORDER); - canvas.draw(chip); - canvas.setColor(StudioTheme.TEXT); - canvas.drawString(location, left + StudioTheme.scale(CHIP_PADDING_X), top + StudioTheme.scale(CHIP_PADDING_Y) + metrics.getAscent()); - return top + height; - } - - private static int drawCentered(Graphics2D canvas, String text, Font font, Color color, int centerX, int top) { - canvas.setFont(font); - canvas.setColor(color); - FontMetrics metrics = canvas.getFontMetrics(); - canvas.drawString(text, centerX - metrics.stringWidth(text) / 2, top + metrics.getAscent()); - return top + metrics.getHeight(); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/EntityBlockShapes.java b/core/src/main/java/art/arcane/iris/studio/map/EntityBlockShapes.java deleted file mode 100644 index 893b70e2f..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/EntityBlockShapes.java +++ /dev/null @@ -1,298 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -package art.arcane.iris.studio.map; - -import art.arcane.iris.studio.map.BlockModel.Face; -import art.arcane.iris.studio.map.BlockModel.TextureMapping; -import art.arcane.iris.studio.map.BlockTextures.BlockStateId; -import art.arcane.iris.studio.map.BlockTextures.BlockTexture; -import art.arcane.iris.studio.map.BlockTextures.ModelDefinition; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; - -/** - * Shapes for the blocks Minecraft draws in code instead of from a model file, like chests, heads, banners and - * fluids, which fill their block. Chests, heads, banners and the bell use their entity textures laid out the way Minecraft's model parts are; - * rarer ones are a simple box in their particle texture. - */ -final class EntityBlockShapes { - private static final Set INVISIBLE = Set.of("air", "cave_air", "void_air", "barrier", "light", - "structure_void", "moving_piston", "pitcher_crop"); - private static final int END_PORTAL_COLOR = 0x0E1219; - private static final double SKULL_WALL_OFFSET = 0.25D; - private static final double ROTATION_SEGMENT_DEGREES = 22.5D; - private static final double BANNER_SCALE = 2D / 3D; - private static final double MODEL_UNITS = 16D; - private static final Map DYE_COLORS = Map.ofEntries( - Map.entry("white", 0xF9FFFE), Map.entry("orange", 0xF9801D), Map.entry("magenta", 0xC74EBD), - Map.entry("light_blue", 0x3AB3DA), Map.entry("yellow", 0xFED83D), Map.entry("lime", 0x80C71F), - Map.entry("pink", 0xF38BAA), Map.entry("gray", 0x474F52), Map.entry("light_gray", 0x9D9D97), - Map.entry("cyan", 0x169C9C), Map.entry("purple", 0x8932B8), Map.entry("blue", 0x3C44AA), - Map.entry("brown", 0x835432), Map.entry("green", 0x5E7C16), Map.entry("red", 0xB02E26), - Map.entry("black", 0x1D1D21)); - - private final BlockTextures textures; - - EntityBlockShapes(BlockTextures textures) { - this.textures = textures; - } - - /** - * The faces of a block whose model has no boxes of its own. - */ - List facesOf(BlockStateId state, ModelDefinition model) { - String name = state.name(); - if (INVISIBLE.contains(name)) { - return List.of(); - } - if (name.endsWith("chest")) { - return chest(state); - } - if (name.endsWith("_skull") || name.endsWith("_head")) { - return head(state, model); - } - if (name.endsWith("banner")) { - return banner(state); - } - return switch (name) { - case "conduit" -> particleBox(state, model, new Vec3(5, 5, 5), new Vec3(11, 11, 11), false); - case "decorated_pot" -> decoratedPot(state, model); - case "end_portal" -> BlockModelBuilder.box(new Vec3(0, 0, 0), new Vec3(16, 12, 16), BlockTexture.solid(END_PORTAL_COLOR), true); - case "end_gateway" -> BlockModelBuilder.box(new Vec3(0, 0, 0), new Vec3(16, 16, 16), BlockTexture.solid(END_PORTAL_COLOR), true); - default -> name.endsWith("copper_golem_statue") - ? particleBox(state, model, new Vec3(4, 0, 4), new Vec3(12, 14, 12), false) - : particleBox(state, model, new Vec3(0, 0, 0), new Vec3(16, 16, 16), true); - }; - } - - /** - * Parts a block draws in code on top of its model, like the bell hanging in its frame. - */ - List facesAddedTo(BlockStateId state) { - if (!state.name().equals("bell")) { - return List.of(); - } - Optional texture = textures.entityTexture("entity/bell/bell_body", MinecraftBlockTints.NO_TINT); - if (texture.isEmpty()) { - return List.of(); - } - List faces = new ArrayList<>(); - faces.addAll(modelPartBox(texture.get(), 0, 0, new Vec3(5, 6, 5), new Vec3(6, 7, 6), Transform.IDENTITY)); - faces.addAll(modelPartBox(texture.get(), 0, 13, new Vec3(4, 4, 4), new Vec3(8, 2, 8), Transform.IDENTITY)); - return faces; - } - - private List particleBox(BlockStateId state, ModelDefinition model, Vec3 from, Vec3 to, boolean culledBySides) { - String particle = BlockTextures.dereference("#particle", model.textures()); - if (particle == null) { - return List.of(); - } - return textures.faceTexture(state, particle, BlockTextures.NO_TINT_INDEX) - .map(texture -> BlockModelBuilder.box(from, to, texture, culledBySides)) - .orElse(List.of()); - } - - private List decoratedPot(BlockStateId state, ModelDefinition model) { - List faces = new ArrayList<>(particleBox(state, model, new Vec3(1, 0, 1), new Vec3(15, 16, 15), false)); - faces.addAll(particleBox(state, model, new Vec3(4, 16, 4), new Vec3(12, 20, 12), false)); - return faces; - } - - // Single chests are 14 pixels wide; each half of a double chest is 15, reaching over to its partner. - private List chest(BlockStateId state) { - String type = state.properties().getOrDefault("type", "single"); - String suffix = type.equals("single") ? "" : "_" + type; - Optional texture = textures.entityTexture("entity/chest/" + chestTextureName(state.name()) + suffix, MinecraftBlockTints.NO_TINT); - if (texture.isEmpty()) { - return List.of(); - } - Transform place = Transform.IDENTITY - .translate(0.5D, 0.5D, 0.5D) - .rotateY(-yRotationOf(state.properties().getOrDefault("facing", "north"))) - .translate(-0.5D, -0.5D, -0.5D); - double left = type.equals("left") ? 0D : 1D; - double width = type.equals("single") ? 14D : 15D; - double lockX = switch (type) { - case "left" -> 0D; - case "right" -> 15D; - default -> 7D; - }; - double lockWidth = type.equals("single") ? 2D : 1D; - List faces = new ArrayList<>(); - faces.addAll(modelPartBox(texture.get(), 0, 19, new Vec3(left, 0, 1), new Vec3(width, 10, 14), place)); - faces.addAll(modelPartBox(texture.get(), 0, 0, new Vec3(left, 9, 1), new Vec3(width, 5, 14), place)); - faces.addAll(modelPartBox(texture.get(), 0, 0, new Vec3(lockX, 7, 15), new Vec3(lockWidth, 4, 1), place)); - return faces; - } - - private static String chestTextureName(String blockName) { - String name = blockName.startsWith("waxed_") ? blockName.substring("waxed_".length()) : blockName; - return switch (name) { - case "trapped_chest" -> "trapped"; - case "ender_chest" -> "ender"; - case "copper_chest" -> "copper"; - case "exposed_copper_chest" -> "copper_exposed"; - case "weathered_copper_chest" -> "copper_weathered"; - case "oxidized_copper_chest" -> "copper_oxidized"; - default -> "normal"; - }; - } - - // Heads are drawn upside down and mirrored in their model, and turn in sixteenths like signs. - private List head(BlockStateId state, ModelDefinition model) { - boolean onWall = state.name().contains("_wall_"); - String kind = state.name().replace("_wall_", "_"); - Optional look = HeadLook.of(kind); - Optional texture = look.flatMap(found -> textures.entityTexture(found.texture(), MinecraftBlockTints.NO_TINT)); - if (texture.isEmpty()) { - return onWall - ? particleBox(state, model, new Vec3(4, 4, 8), new Vec3(12, 12, 16), false) - : particleBox(state, model, new Vec3(4, 0, 4), new Vec3(12, 8, 12), false); - } - Transform place; - if (onWall) { - CubeFace facing = CubeFace.named(state.properties().getOrDefault("facing", "north")); - place = Transform.IDENTITY - .translate(0.5D - facing.stepX() * SKULL_WALL_OFFSET, SKULL_WALL_OFFSET, 0.5D - facing.stepZ() * SKULL_WALL_OFFSET) - .scale(-1D, -1D, 1D) - .rotateY(yRotationOf(facing.opposite().modelName())); - } else { - int rotation = Integer.parseInt(state.properties().getOrDefault("rotation", "0")); - place = Transform.IDENTITY - .translate(0.5D, 0D, 0.5D) - .scale(-1D, -1D, 1D) - .rotateY(rotation * ROTATION_SEGMENT_DEGREES); - } - HeadLook found = look.get(); - return modelPartBox(texture.get(), 0, 0, new Vec3(-found.width() / 2D, -8, -4), new Vec3(found.width(), 8, 8), place); - } - - private List banner(BlockStateId state) { - boolean onWall = state.name().endsWith("_wall_banner"); - String color = state.name().substring(0, state.name().length() - (onWall ? "_wall_banner" : "_banner").length()); - Optional frame = textures.entityTexture("entity/banner/banner_base", MinecraftBlockTints.NO_TINT); - Optional cloth = textures.entityTexture("entity/banner/base", DYE_COLORS.getOrDefault(color, MinecraftBlockTints.NO_TINT)); - if (frame.isEmpty() || cloth.isEmpty()) { - return List.of(); - } - Transform place; - if (onWall) { - CubeFace facing = CubeFace.named(state.properties().getOrDefault("facing", "north")); - place = Transform.IDENTITY - .translate(0.5D, -1D / 6D, 0.5D) - .rotateY(-yRotationOf(facing.modelName())) - .translate(0D, -0.3125D, -0.4375D) - .scale(BANNER_SCALE, -BANNER_SCALE, -BANNER_SCALE); - } else { - int rotation = Integer.parseInt(state.properties().getOrDefault("rotation", "0")); - place = Transform.IDENTITY - .translate(0.5D, 0.5D, 0.5D) - .rotateY(-rotation * ROTATION_SEGMENT_DEGREES) - .scale(BANNER_SCALE, -BANNER_SCALE, -BANNER_SCALE); - } - List faces = new ArrayList<>(); - if (!onWall) { - faces.addAll(modelPartBox(frame.get(), 44, 0, new Vec3(-1, -30, -1), new Vec3(2, 42, 2), place)); - } - faces.addAll(modelPartBox(frame.get(), 0, 42, new Vec3(-10, -32, -1), new Vec3(20, 2, 2), place)); - faces.addAll(modelPartBox(cloth.get(), 0, 0, new Vec3(-10, -32, -2), new Vec3(20, 40, 1), place)); - return faces; - } - - // Minecraft's facing angle: south is 0 and each quarter turn clockwise seen from above adds 90 degrees. - private static double yRotationOf(String facing) { - return switch (facing) { - case "west" -> 90D; - case "north" -> 180D; - case "east" -> 270D; - default -> 0D; - }; - } - - /** - * A box of a block entity's model, in model pixels, with its sides laid out on the texture the way Minecraft's - * model parts are: the top and bottom in a row above the four sides. - */ - static List modelPartBox(BlockTexture texture, int textureU, int textureV, Vec3 from, Vec3 size, Transform place) { - double minX = from.x() / MODEL_UNITS; - double minY = from.y() / MODEL_UNITS; - double minZ = from.z() / MODEL_UNITS; - double maxX = (from.x() + size.x()) / MODEL_UNITS; - double maxY = (from.y() + size.y()) / MODEL_UNITS; - double maxZ = (from.z() + size.z()) / MODEL_UNITS; - Vec3 v0 = new Vec3(minX, minY, minZ); - Vec3 v1 = new Vec3(maxX, minY, minZ); - Vec3 v2 = new Vec3(maxX, maxY, minZ); - Vec3 v3 = new Vec3(minX, maxY, minZ); - Vec3 v4 = new Vec3(minX, minY, maxZ); - Vec3 v5 = new Vec3(maxX, minY, maxZ); - Vec3 v6 = new Vec3(maxX, maxY, maxZ); - Vec3 v7 = new Vec3(minX, maxY, maxZ); - double u = textureU; - double v = textureV; - double width = size.x(); - double height = size.y(); - double depth = size.z(); - List faces = new ArrayList<>(6); - faces.add(polygon(texture, place, CubeFace.DOWN, v5, v4, v0, u + depth, v, u + depth + width, v + depth)); - faces.add(polygon(texture, place, CubeFace.UP, v2, v3, v7, u + depth + width, v + depth, u + depth + width + width, v)); - faces.add(polygon(texture, place, CubeFace.WEST, v0, v4, v7, u, v + depth, u + depth, v + depth + height)); - faces.add(polygon(texture, place, CubeFace.NORTH, v1, v0, v3, u + depth, v + depth, u + depth + width, v + depth + height)); - faces.add(polygon(texture, place, CubeFace.EAST, v5, v1, v2, u + depth + width, v + depth, u + depth + width + depth, v + depth + height)); - faces.add(polygon(texture, place, CubeFace.SOUTH, v4, v5, v6, u + depth + width + depth, v + depth, u + depth + width + depth + width, v + depth + height)); - return faces; - } - - // A model part's polygon gives its first corner (u2, v1), its second (u1, v1) and its third (u1, v2). - private static Face polygon(BlockTexture texture, Transform place, CubeFace side, Vec3 first, Vec3 second, Vec3 third, - double u1, double v1, double u2, double v2) { - double textureWidth = texture.width(); - double textureHeight = texture.height(); - TextureMapping mapping = new TextureMapping(u1 / textureWidth, v1 / textureHeight, - (u2 - u1) / textureWidth, 0D, 0D, (v2 - v1) / textureHeight); - Face face = new Face(second, first.minus(second), third.minus(second), side.direction(), texture, mapping, side.shade(), null) - .transformed(place); - return face.withShade(CubeFace.nearest(face.normal()).shade()); - } - - /** - * The entity texture of a mob head and how wide its head is. - */ - private record HeadLook(String texture, double width) { - private static final double HEAD_WIDTH = 8D; - private static final double PIGLIN_HEAD_WIDTH = 10D; - - static Optional of(String kind) { - return Optional.ofNullable(switch (kind) { - case "skeleton_skull" -> new HeadLook("entity/skeleton/skeleton", HEAD_WIDTH); - case "wither_skeleton_skull" -> new HeadLook("entity/skeleton/wither_skeleton", HEAD_WIDTH); - case "zombie_head" -> new HeadLook("entity/zombie/zombie", HEAD_WIDTH); - case "creeper_head" -> new HeadLook("entity/creeper/creeper", HEAD_WIDTH); - case "player_head" -> new HeadLook("entity/player/wide/steve", HEAD_WIDTH); - case "piglin_head" -> new HeadLook("entity/piglin/piglin", PIGLIN_HEAD_WIDTH); - default -> null; - }); - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/FloatingPanels.java b/core/src/main/java/art/arcane/iris/studio/map/FloatingPanels.java deleted file mode 100644 index c3e293e1a..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/FloatingPanels.java +++ /dev/null @@ -1,81 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import javax.swing.SwingUtilities; -import java.awt.Component; -import java.awt.Container; -import java.awt.Rectangle; -import java.util.ArrayList; -import java.util.List; - -/** - * Finds the Swing panels floating over a native window, the way AWT does when it cuts them out of that window. Only - * for the Swing thread. - */ -final class FloatingPanels { - private FloatingPanels() { - } - - /** - * A floating panel that hides what lies behind most of it, and only lets it show through some parts. - */ - interface PartlySeeThrough { - /** - * @return where what lies behind shows through, in the panel's own coordinates - */ - List seeThroughParts(); - } - - /** - * @return where what the window shows has to show through the panels over it, in the window's coordinates - */ - static List seeThroughOver(Component window) { - List parts = new ArrayList<>(); - Rectangle windowBounds = new Rectangle(0, 0, window.getWidth(), window.getHeight()); - Component child = window; - Container parent = child.getParent(); - while (parent != null) { - for (int index = parent.getComponentZOrder(child) - 1; index >= 0; index--) { - Component above = parent.getComponent(index); - if (above.isLightweight() && above.isShowing()) { - addSeeThroughParts(above, window, windowBounds, parts); - } - } - if (!parent.isLightweight()) { - break; - } - child = parent; - parent = parent.getParent(); - } - return parts; - } - - private static void addSeeThroughParts(Component panel, Component window, Rectangle windowBounds, List parts) { - List panelParts = panel instanceof PartlySeeThrough partly - ? partly.seeThroughParts() - : List.of(new Rectangle(0, 0, panel.getWidth(), panel.getHeight())); - for (Rectangle part : panelParts) { - Rectangle inWindow = SwingUtilities.convertRectangle(panel, part, window).intersection(windowBounds); - if (!inWindow.isEmpty()) { - parts.add(inWindow); - } - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/FloatingSlider.java b/core/src/main/java/art/arcane/iris/studio/map/FloatingSlider.java deleted file mode 100644 index 484628fd6..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/FloatingSlider.java +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSlider; -import javax.swing.SwingConstants; -import java.awt.AlphaComposite; -import java.awt.BorderLayout; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.function.IntConsumer; - -/** - * A slim vertical slider floating over the right edge of a 3D view, halfway down, with a short label above it. It - * stays faint so it hides little of the view, until the mouse comes near or it is told to stand out. - */ -final class FloatingSlider extends JPanel { - private static final long serialVersionUID = 4473820211915526120L; - private static final int PANEL_WIDTH = 30; - private static final int MAX_HEIGHT = 320; - private static final double HEIGHT_SHARE_OF_VIEW = 0.5D; - private static final int EDGE_MARGIN = 8; - private static final float FAINT_OPACITY = 0.28F; - private static final String BLANK_LABEL = " "; - - private final JSlider slider = new JSlider(SwingConstants.VERTICAL, 0, 1, 1); - private final JLabel label = new JLabel(BLANK_LABEL, SwingConstants.CENTER); - private boolean movingQuietly; - private boolean hovered; - private boolean standingOut; - - /** - * @param onMoved told the slider's value whenever the user moves it - */ - FloatingSlider(String tooltip, IntConsumer onMoved) { - super(new BorderLayout(0, StudioTheme.scale(4))); - setOpaque(false); - setToolTipText(tooltip); - label.setFont(StudioTheme.smallFont()); - label.setForeground(StudioTheme.SECONDARY_TEXT); - slider.setOpaque(false); - slider.setFocusable(false); - slider.setToolTipText(tooltip); - slider.addChangeListener(event -> { - if (!movingQuietly) { - onMoved.accept(slider.getValue()); - } - }); - MouseAdapter hover = new MouseAdapter() { - @Override - public void mouseEntered(MouseEvent event) { - setHovered(true); - } - - @Override - public void mouseExited(MouseEvent event) { - setHovered(slider.getValueIsAdjusting()); - } - - @Override - public void mouseReleased(MouseEvent event) { - setHovered(slider.contains(event.getPoint())); - } - }; - slider.addMouseListener(hover); - addMouseListener(hover); - add(label, BorderLayout.NORTH); - add(slider, BorderLayout.CENTER); - } - - /** - * The view with this slider floating over its right edge, halfway down. - */ - JComponent floatingOver(JComponent view) { - FloatingSlider floating = this; - JPanel stack = new JPanel(null) { - private static final long serialVersionUID = -1950381405658102347L; - - // The slider overlaps the view, so the view may not repaint without the slider on top of it. - @Override - public boolean isOptimizedDrawingEnabled() { - return false; - } - - @Override - public void doLayout() { - view.setBounds(0, 0, getWidth(), getHeight()); - int width = StudioTheme.scale(PANEL_WIDTH); - int height = Math.min(StudioTheme.scale(MAX_HEIGHT), (int) (getHeight() * HEIGHT_SHARE_OF_VIEW)); - floating.setBounds(getWidth() - width - StudioTheme.scale(EDGE_MARGIN), (getHeight() - height) / 2, width, height); - } - }; - stack.add(floating); - stack.add(view); - return stack; - } - - /** - * Shows a range and value the user didn't choose, without telling anyone the slider moved. - */ - void showQuietly(int minimum, int maximum, int value) { - movingQuietly = true; - try { - slider.getModel().setRangeProperties(value, 0, minimum, maximum, false); - } finally { - movingQuietly = false; - } - } - - // Moves the slider as if the user had. - void moveBy(int steps) { - slider.setValue(slider.getValue() + steps); - } - - int value() { - return slider.getValue(); - } - - int maximum() { - return slider.getMaximum(); - } - - void showLabel(String text) { - label.setText(text.isEmpty() ? BLANK_LABEL : text); - repaint(); - } - - void setStandingOut(boolean nowStandingOut) { - if (standingOut != nowStandingOut) { - standingOut = nowStandingOut; - repaint(); - } - } - - @Override - protected void paintChildren(Graphics graphics) { - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - if (!hovered && !standingOut) { - canvas.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, FAINT_OPACITY)); - } - super.paintChildren(canvas); - } finally { - canvas.dispose(); - } - } - - private void setHovered(boolean nowHovered) { - if (hovered != nowHovered) { - hovered = nowHovered; - repaint(); - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/FrameCrossfade.java b/core/src/main/java/art/arcane/iris/studio/map/FrameCrossfade.java deleted file mode 100644 index b5701d203..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/FrameCrossfade.java +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import javax.swing.Timer; -import java.util.concurrent.TimeUnit; - -/** - * Keeps the last frame of what the explorer showed before on screen while the next thing loads, then fades it out over - * the first frame of the new one, so switching never shows an empty view in between. - */ -final class FrameCrossfade { - private static final long FADE_NANOS = TimeUnit.MILLISECONDS.toNanos(70L); - private static final int REPAINT_INTERVAL_MILLIS = 16; - - private final Timer repaintTimer; - private Phase phase = Phase.NONE; - private NoiseRenderCoordinator.Result outgoing; - private long fadeStartedNanos; - - FrameCrossfade(Runnable repaint) { - this.repaintTimer = new Timer(REPAINT_INTERVAL_MILLIS, event -> { - outgoing(); - repaint.run(); - }); - } - - /** - * Keeps showing the frame until the next one arrives. Without a frame, as when the switch before hasn't drawn yet, - * the frame already held stays. - */ - void hold(NoiseRenderCoordinator.Result frame) { - if (frame == null && outgoing != null) { - enter(Phase.HOLDING, outgoing); - return; - } - enter(frame == null ? Phase.NONE : Phase.HOLDING, frame); - } - - /** - * The new frame is in, so the held one starts fading out over it. - */ - void reveal() { - if (phase != Phase.HOLDING) { - return; - } - fadeStartedNanos = System.nanoTime(); - phase = Phase.FADING; - repaintTimer.start(); - } - - void clear() { - enter(Phase.NONE, null); - } - - /** - * @return the frame to draw over the current one, or null when there is none - */ - NoiseRenderCoordinator.Result outgoing() { - if (phase == Phase.FADING && fadedShare() >= 1F) { - clear(); - } - return outgoing; - } - - float outgoingOpacity() { - return phase == Phase.FADING ? 1F - fadedShare() : 1F; - } - - private float fadedShare() { - return Math.min(1F, (System.nanoTime() - fadeStartedNanos) / (float) FADE_NANOS); - } - - private void enter(Phase nextPhase, NoiseRenderCoordinator.Result frame) { - phase = nextPhase; - outgoing = frame; - if (nextPhase != Phase.FADING) { - repaintTimer.stop(); - } - } - - private enum Phase { - NONE, - HOLDING, - FADING - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/FrameRateLabel.java b/core/src/main/java/art/arcane/iris/studio/map/FrameRateLabel.java deleted file mode 100644 index 5eca6f1b4..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/FrameRateLabel.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import javax.swing.JComponent; -import java.awt.Dimension; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.RenderingHints; - -/** - * How many frames a second a 3D view keeps up, right-aligned, floating over the view. - */ -final class FrameRateLabel extends JComponent { - private static final long serialVersionUID = -6402187316475095871L; - private static final String WIDEST_TEXT = "8888 fps"; - - private String text = ""; - - FrameRateLabel() { - setOpaque(false); - } - - void showRate(double framesPerSecond) { - String next = Math.round(framesPerSecond) + " fps"; - if (!next.equals(text)) { - text = next; - repaint(); - } - } - - @Override - public Dimension getPreferredSize() { - FontMetrics metrics = getFontMetrics(StudioTheme.smallFont()); - return new Dimension(metrics.stringWidth(WIDEST_TEXT), metrics.getHeight()); - } - - @Override - protected void paintComponent(Graphics graphics) { - Graphics2D canvas = (Graphics2D) graphics; - canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - canvas.setFont(StudioTheme.smallFont()); - canvas.setColor(StudioTheme.MUTED_TEXT); - FontMetrics metrics = canvas.getFontMetrics(); - canvas.drawString(text, getWidth() - metrics.stringWidth(text), metrics.getAscent()); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/GlxDisplay.java b/core/src/main/java/art/arcane/iris/studio/map/GlxDisplay.java deleted file mode 100644 index 05b7c03c7..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/GlxDisplay.java +++ /dev/null @@ -1,381 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.spi.IrisLogging; -import org.lwjgl.PointerBuffer; -import org.lwjgl.opengl.GL; -import org.lwjgl.opengl.GLXCapabilities; -import org.lwjgl.system.Callback; -import org.lwjgl.system.CallbackI; -import org.lwjgl.system.Configuration; -import org.lwjgl.system.JNI; -import org.lwjgl.system.MemoryStack; -import org.lwjgl.system.linux.DynamicLinkLoader; -import org.lwjgl.system.linux.X11; -import org.lwjgl.system.linux.XErrorEvent; - -import java.awt.GraphicsEnvironment; -import java.awt.Toolkit; -import java.lang.invoke.MethodHandles; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.HashSet; -import java.util.Locale; -import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; - -import static org.lwjgl.opengl.GL11.GL_RENDERER; -import static org.lwjgl.opengl.GL11.glGetString; -import static org.lwjgl.opengl.GLX.glXDestroyContext; -import static org.lwjgl.opengl.GLX.glXMakeCurrent; -import static org.lwjgl.opengl.GLX.glXSwapBuffers; -import static org.lwjgl.opengl.GLX13.GLX_BLUE_SIZE; -import static org.lwjgl.opengl.GLX13.GLX_DEPTH_SIZE; -import static org.lwjgl.opengl.GLX13.GLX_DOUBLEBUFFER; -import static org.lwjgl.opengl.GLX13.GLX_DRAWABLE_TYPE; -import static org.lwjgl.opengl.GLX13.GLX_GREEN_SIZE; -import static org.lwjgl.opengl.GLX13.GLX_RED_SIZE; -import static org.lwjgl.opengl.GLX13.GLX_RENDER_TYPE; -import static org.lwjgl.opengl.GLX13.GLX_RGBA_BIT; -import static org.lwjgl.opengl.GLX13.GLX_VISUAL_ID; -import static org.lwjgl.opengl.GLX13.GLX_WINDOW_BIT; -import static org.lwjgl.opengl.GLX13.GLX_X_RENDERABLE; -import static org.lwjgl.opengl.GLX13.glXChooseFBConfig; -import static org.lwjgl.opengl.GLX13.glXGetFBConfigAttrib; -import static org.lwjgl.opengl.GLX13.glXMakeContextCurrent; -import static org.lwjgl.opengl.GLXARBCreateContext.GLX_CONTEXT_MAJOR_VERSION_ARB; -import static org.lwjgl.opengl.GLXARBCreateContext.GLX_CONTEXT_MINOR_VERSION_ARB; -import static org.lwjgl.opengl.GLXARBCreateContext.glXCreateContextAttribsARB; -import static org.lwjgl.opengl.GLXARBCreateContextProfile.GLX_CONTEXT_CORE_PROFILE_BIT_ARB; -import static org.lwjgl.opengl.GLXARBCreateContextProfile.GLX_CONTEXT_PROFILE_MASK_ARB; -import static org.lwjgl.opengl.GLXEXTSwapControl.glXSwapIntervalEXT; -import static org.lwjgl.system.APIUtil.apiClosureRet; -import static org.lwjgl.system.APIUtil.apiCreateCIF; -import static org.lwjgl.system.MemoryUtil.NULL; -import static org.lwjgl.system.MemoryUtil.memAddress; -import static org.lwjgl.system.MemoryUtil.memGetAddress; -import static org.lwjgl.system.libffi.LibFFI.ffi_type_pointer; -import static org.lwjgl.system.libffi.LibFFI.ffi_type_sint32; - -/** - * A connection of our own to the X server Swing's windows are on, with one OpenGL context that draws straight into - * those windows, so a frame never has to be copied back and painted by Swing. Only for the GPU thread. - */ -final class GlxDisplay { - private static final String X11_TOOLKIT = "sun.awt.X11.XToolkit"; - private static final String NATIVE_CONTEXT_API = "native"; - private static final String NVIDIA_DRIVER_VERSION_FILE = "/proc/driver/nvidia/version"; - private static final Set SOFTWARE_RENDERERS = Set.of("llvmpipe", "softpipe", "software rasterizer"); - private static final int OPENGL_MAJOR_VERSION = 3; - private static final int OPENGL_MINOR_VERSION = 3; - private static final int COLOR_CHANNEL_BITS = 8; - private static final int DEPTH_BITS = 24; - // Frames are only drawn when something moves, and the compositor keeps them from tearing. - private static final int SWAP_EVERY_FRAME = 0; - - private final long display; - private final long context; - private final long visualId; - private final boolean canSetSwapInterval; - private final Set windowsWithSwapIntervalSet = new HashSet<>(); - private final String renderer; - private long currentWindow; - - private GlxDisplay(long display, long context, long visualId, boolean canSetSwapInterval, String renderer) { - this.display = display; - this.context = context; - this.visualId = visualId; - this.canSetSwapInterval = canSetSwapInterval; - this.renderer = renderer; - } - - /** - * Opens the connection and makes its context current on this thread, without any window yet. - * - * @throws IllegalStateException when Swing doesn't draw on X or no card there draws OpenGL 3.3 in hardware - */ - static GlxDisplay open() { - if (!isSwingOnX()) { - throw new IllegalStateException("Swing doesn't draw on X"); - } - preferNvidiaCard(); - // LWJGL would take EGL in a Wayland session, even though Swing's windows are on X. - Configuration.OPENGL_CONTEXT_API.set(NATIVE_CONTEXT_API); - GL.create(); - long display = X11.nXOpenDisplay(NULL); - if (display == NULL) { - GL.destroy(); - throw new IllegalStateException("Can't connect to the X server"); - } - XErrors.watch(display); - try { - return openOn(display); - } catch (RuntimeException failure) { - XErrors.forget(display); - X11.XCloseDisplay(display); - GL.destroy(); - throw failure; - } - } - - static boolean isSwingOnX() { - return !GraphicsEnvironment.isHeadless() && X11_TOOLKIT.equals(Toolkit.getDefaultToolkit().getClass().getName()); - } - - private static GlxDisplay openOn(long display) { - int screen = X11.XDefaultScreen(display); - GLXCapabilities glx = GL.createCapabilitiesGLX(display, screen); - if (!glx.GLX13 || !glx.GLX_ARB_create_context || !glx.GLX_ARB_create_context_profile) { - throw new IllegalStateException("GLX can't make an OpenGL " + OPENGL_MAJOR_VERSION + "." + OPENGL_MINOR_VERSION + " context"); - } - long visualId = Xlib.defaultVisualId(display, screen); - long config = configFor(display, screen, visualId); - long context = glXCreateContextAttribsARB(display, config, NULL, true, new int[]{ - GLX_CONTEXT_MAJOR_VERSION_ARB, OPENGL_MAJOR_VERSION, - GLX_CONTEXT_MINOR_VERSION_ARB, OPENGL_MINOR_VERSION, - GLX_CONTEXT_PROFILE_MASK_ARB, GLX_CONTEXT_CORE_PROFILE_BIT_ARB, - 0}); - Xlib.sync(display); - if (context == NULL || XErrors.takeFailed(display)) { - throw new IllegalStateException("GLX can't make an OpenGL " + OPENGL_MAJOR_VERSION + "." + OPENGL_MINOR_VERSION + " context"); - } - if (!glXMakeContextCurrent(display, NULL, NULL, context)) { - glXDestroyContext(display, context); - throw new IllegalStateException("GLX can't use a context without a window"); - } - GL.createCapabilities(); - String renderer = glGetString(GL_RENDERER); - if (isDrawnInSoftware(renderer)) { - glXMakeContextCurrent(display, NULL, NULL, NULL); - glXDestroyContext(display, context); - throw new IllegalStateException("GLX only draws in software, on " + renderer); - } - return new GlxDisplay(display, context, visualId, glx.GLX_EXT_swap_control, renderer); - } - - /** - * Laptops show X on the built-in card and only lend the faster one out when asked to. Asked the way NVIDIA's own - * prime-run does, unless whoever started the server asked for something else already. - */ - private static void preferNvidiaCard() { - if (!Files.exists(Path.of(NVIDIA_DRIVER_VERSION_FILE))) { - return; - } - LibC.setenvUnlessSet("__NV_PRIME_RENDER_OFFLOAD", "1"); - LibC.setenvUnlessSet("__GLX_VENDOR_LIBRARY_NAME", "nvidia"); - } - - // Windows are only drawn into with the visual they were made with; Swing makes them with the screen's default one. - private static long configFor(long display, int screen, long visualId) { - PointerBuffer configs = glXChooseFBConfig(display, screen, new int[]{ - GLX_X_RENDERABLE, 1, - GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, - GLX_RENDER_TYPE, GLX_RGBA_BIT, - GLX_DOUBLEBUFFER, 1, - GLX_RED_SIZE, COLOR_CHANNEL_BITS, - GLX_GREEN_SIZE, COLOR_CHANNEL_BITS, - GLX_BLUE_SIZE, COLOR_CHANNEL_BITS, - GLX_DEPTH_SIZE, DEPTH_BITS, - 0}); - if (configs == null) { - throw new IllegalStateException("GLX has no double-buffered config with a depth buffer"); - } - try { - int[] configVisual = new int[1]; - for (int index = 0; index < configs.remaining(); index++) { - long config = configs.get(index); - glXGetFBConfigAttrib(display, config, GLX_VISUAL_ID, configVisual); - if (configVisual[0] == visualId) { - return config; - } - } - } finally { - X11.XFree(configs); - } - throw new IllegalStateException("GLX can't draw into windows of the default visual 0x" + Long.toHexString(visualId)); - } - - private static boolean isDrawnInSoftware(String renderer) { - String lowerCase = renderer == null ? "" : renderer.toLowerCase(Locale.ROOT); - return SOFTWARE_RENDERERS.stream().anyMatch(lowerCase::contains); - } - - String renderer() { - return renderer; - } - - boolean canDrawInto(long windowVisualId) { - return windowVisualId == visualId; - } - - /** - * Makes the window what the default framebuffer draws into. - * - * @return false when the window can't be drawn into - */ - boolean drawInto(long window) { - if (window == currentWindow) { - return true; - } - boolean madeCurrent = glXMakeCurrent(display, window, context); - Xlib.sync(display); - if (!madeCurrent || XErrors.takeFailed(display)) { - currentWindow = NULL; - return false; - } - currentWindow = window; - if (canSetSwapInterval && windowsWithSwapIntervalSet.add(window)) { - glXSwapIntervalEXT(display, window, SWAP_EVERY_FRAME); - } - return true; - } - - /** - * Puts what was drawn into the window on screen. - * - * @return false when the window couldn't take it, or something drawn into it before failed - */ - boolean show(long window) { - glXSwapBuffers(display, window); - return !XErrors.takeFailed(display); - } - - /** - * Stops drawing into a window before it goes away, keeping the context for the rest. - */ - void forget(long window) { - windowsWithSwapIntervalSet.remove(window); - if (window != currentWindow) { - return; - } - glXMakeContextCurrent(display, NULL, NULL, context); - currentWindow = NULL; - Xlib.sync(display); - XErrors.takeFailed(display); - } - - /** - * Destroys the context and the connection. Nothing is drawn through this display afterwards. - */ - void close() { - glXMakeContextCurrent(display, NULL, NULL, NULL); - glXDestroyContext(display, context); - currentWindow = NULL; - windowsWithSwapIntervalSet.clear(); - Xlib.sync(display); - XErrors.forget(display); - X11.XCloseDisplay(display); - } - - /** - * Notes X errors on our own connection instead of letting Xlib end the process over them, which is what it does - * for any connection but Swing's. Errors on other connections go wherever they went before. - */ - private static final class XErrors { - private static final Set watchedDisplays = ConcurrentHashMap.newKeySet(); - private static final Set failedDisplays = ConcurrentHashMap.newKeySet(); - private static long previousHandler; - private static ErrorHandler handler; - - static synchronized void watch(long display) { - if (handler == null) { - handler = XErrors::handle; - previousHandler = Xlib.setErrorHandler(handler.address()); - } - watchedDisplays.add(display); - } - - static void forget(long display) { - watchedDisplays.remove(display); - failedDisplays.remove(display); - } - - static boolean takeFailed(long display) { - return failedDisplays.remove(display); - } - - private static int handle(long display, long errorEvent) { - if (watchedDisplays.contains(display)) { - failedDisplays.add(display); - IrisLogging.debug("X error " + Byte.toUnsignedInt(XErrorEvent.create(errorEvent).error_code()) + " drawing a 3D view"); - return 0; - } - return previousHandler == NULL ? 0 : JNI.callPPI(display, errorEvent, previousHandler); - } - } - - @FunctionalInterface - private interface ErrorHandler extends CallbackI { - Callback.Descriptor DESCRIPTOR = new Callback.Descriptor(ErrorHandler.class, MethodHandles.lookup(), - apiCreateCIF(ffi_type_sint32, ffi_type_pointer, ffi_type_pointer)); - - @Override - default Callback.Descriptor getDescriptor() { - return DESCRIPTOR; - } - - @Override - default void callback(long ret, long args) { - apiClosureRet(ret, invoke(memGetAddress(memGetAddress(args)), memGetAddress(memGetAddress(args + Long.BYTES)))); - } - - int invoke(long display, long errorEvent); - } - - // The few Xlib calls LWJGL has no binding for. - private static final class Xlib { - static long defaultVisualId(long display, int screen) { - long visual = JNI.callPP(display, screen, function("XDefaultVisual")); - return JNI.callPP(visual, function("XVisualIDFromVisual")); - } - - static void sync(long display) { - JNI.callPI(display, 0, function("XSync")); - } - - static long setErrorHandler(long handler) { - return JNI.callPP(handler, function("XSetErrorHandler")); - } - - private static long function(String name) { - long address = X11.getLibrary().getFunctionAddress(name); - if (address == NULL) { - throw new IllegalStateException("Xlib has no " + name); - } - return address; - } - } - - private static final class LibC { - private static final int KEEP_EXISTING = 0; - private static final long EVERYTHING_LOADED = NULL; - - // Looked up among everything the process loaded, which LWJGL's own dlsym won't do. - static void setenvUnlessSet(String name, String value) { - try (MemoryStack stack = MemoryStack.stackPush()) { - long setenv = DynamicLinkLoader.ndlsym(EVERYTHING_LOADED, memAddress(stack.ASCII("setenv"))); - if (setenv == NULL) { - return; - } - JNI.callPPI(memAddress(stack.ASCII(name)), memAddress(stack.ASCII(value)), KEEP_EXISTING, setenv); - } - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/GpuCache.java b/core/src/main/java/art/arcane/iris/studio/map/GpuCache.java deleted file mode 100644 index 10ab045f9..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/GpuCache.java +++ /dev/null @@ -1,106 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.lang.ref.Reference; -import java.lang.ref.ReferenceQueue; -import java.lang.ref.WeakReference; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; - -/** - * What was put on the graphics card, by what it was made from. The sources are held weakly: once nothing else keeps - * one, its upload can never be asked for again and is deleted. Only for the GPU thread. - */ -final class GpuCache { - private final LinkedHashMap leastRecentlyUsedFirst = new LinkedHashMap<>(16, 0.75F, true); - private final ReferenceQueue collectedSources = new ReferenceQueue<>(); - - U get(Object source) { - return leastRecentlyUsedFirst.get(Source.lookingFor(source)); - } - - void put(Object source, U upload) { - leastRecentlyUsedFirst.put(new Source(source, collectedSources), upload); - } - - void forgetCollected() { - for (Reference collected = collectedSources.poll(); collected != null; collected = collectedSources.poll()) { - U upload = leastRecentlyUsedFirst.remove(collected); - if (upload != null) { - upload.delete(); - } - } - } - - /** - * Deletes the least recently used uploads until the cache fits, sparing those made from what is kept. - */ - void forgetBeyond(long mostBytes, Set kept) { - long bytes = 0L; - for (U upload : leastRecentlyUsedFirst.values()) { - bytes += upload.bytes(); - } - Iterator> oldestFirst = leastRecentlyUsedFirst.entrySet().iterator(); - while (bytes > mostBytes && oldestFirst.hasNext()) { - Map.Entry entry = oldestFirst.next(); - if (!kept.contains(entry.getKey().get())) { - bytes -= entry.getValue().bytes(); - entry.getValue().delete(); - oldestFirst.remove(); - } - } - } - - interface Upload { - long bytes(); - - void delete(); - } - - // Equal only to a source of the same object, so a collected one is equal to nothing but itself. - private static final class Source extends WeakReference { - private final int identityHash; - - private Source(Object source, ReferenceQueue collected) { - super(source, collected); - identityHash = System.identityHashCode(source); - } - - static Source lookingFor(Object source) { - return new Source(source, null); - } - - @Override - public int hashCode() { - return identityHash; - } - - @Override - public boolean equals(Object other) { - if (this == other) { - return true; - } - Object source = get(); - return source != null && other instanceof Source otherSource && source == otherSource.get(); - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/GpuCanvas.java b/core/src/main/java/art/arcane/iris/studio/map/GpuCanvas.java deleted file mode 100644 index 9fdad12b9..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/GpuCanvas.java +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import org.lwjgl.system.MemoryStack; -import org.lwjgl.system.jawt.JAWT; -import org.lwjgl.system.jawt.JAWTDrawingSurface; -import org.lwjgl.system.jawt.JAWTDrawingSurfaceInfo; -import org.lwjgl.system.jawt.JAWTX11DrawingSurfaceInfo; - -import javax.swing.SwingUtilities; -import java.awt.Canvas; -import java.awt.Component; -import java.awt.Graphics; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseWheelEvent; - -import static org.lwjgl.system.jawt.JAWTFunctions.JAWT_DrawingSurface_FreeDrawingSurfaceInfo; -import static org.lwjgl.system.jawt.JAWTFunctions.JAWT_DrawingSurface_GetDrawingSurfaceInfo; -import static org.lwjgl.system.jawt.JAWTFunctions.JAWT_DrawingSurface_Lock; -import static org.lwjgl.system.jawt.JAWTFunctions.JAWT_DrawingSurface_Unlock; -import static org.lwjgl.system.jawt.JAWTFunctions.JAWT_FreeDrawingSurface; -import static org.lwjgl.system.jawt.JAWTFunctions.JAWT_GetAWT; -import static org.lwjgl.system.jawt.JAWTFunctions.JAWT_GetDrawingSurface; -import static org.lwjgl.system.jawt.JAWTFunctions.JAWT_LOCK_ERROR; -import static org.lwjgl.system.jawt.JAWTFunctions.JAWT_VERSION_1_4; - -/** - * A native window inside a 3D view that the graphics card draws frames straight into. Swing can't paint over it, so - * panels floating over the view are cut out of it, and the view paints what lies behind them itself. The mouse belongs - * to the view behind it, as if this window weren't there. - */ -final class GpuCanvas extends Canvas { - private static final long serialVersionUID = 2874650379461920137L; - - private final transient Component view; - private final transient Runnable onExposed; - private volatile long window; - private volatile long visualId; - - /** - * @param onExposed runs on the Swing thread when what the window showed was lost and has to be drawn again - */ - GpuCanvas(Component view, Runnable onExposed) { - this.view = view; - this.onExposed = onExposed; - setFocusable(false); - setBackground(StudioTheme.EDITOR_BACKGROUND); - handMouseToView(); - } - - /** - * @return the X window frames go into, or 0 while there is none - */ - long window() { - return window; - } - - long visualId() { - return visualId; - } - - @Override - public void addNotify() { - super.addNotify(); - readNativeWindow(); - } - - // A frame on its way into the window would otherwise draw into one that no longer exists. - @Override - public void removeNotify() { - long goingWindow = window; - window = 0L; - if (goingWindow != 0L) { - GpuContext.forgetWindow(goingWindow); - } - super.removeNotify(); - } - - // Erasing to the background first would flash it between frames. - @Override - public void update(Graphics graphics) { - onExposed.run(); - } - - @Override - public void paint(Graphics graphics) { - onExposed.run(); - } - - private void readNativeWindow() { - try (MemoryStack stack = MemoryStack.stackPush()) { - JAWT awt = JAWT.calloc(stack).version(JAWT_VERSION_1_4); - if (!JAWT_GetAWT(awt)) { - return; - } - JAWTDrawingSurface surface = JAWT_GetDrawingSurface(this, awt.GetDrawingSurface()); - if (surface == null) { - return; - } - try { - readLocked(surface); - } finally { - JAWT_FreeDrawingSurface(surface, awt.FreeDrawingSurface()); - } - } - } - - private void readLocked(JAWTDrawingSurface surface) { - if ((JAWT_DrawingSurface_Lock(surface, surface.Lock()) & JAWT_LOCK_ERROR) != 0) { - return; - } - try { - JAWTDrawingSurfaceInfo info = JAWT_DrawingSurface_GetDrawingSurfaceInfo(surface, surface.GetDrawingSurfaceInfo()); - if (info == null) { - return; - } - try { - JAWTX11DrawingSurfaceInfo x11 = JAWTX11DrawingSurfaceInfo.create(info.platformInfo()); - visualId = x11.visualID(); - window = x11.drawable(); - } finally { - JAWT_DrawingSurface_FreeDrawingSurfaceInfo(info, surface.FreeDrawingSurfaceInfo()); - } - } finally { - JAWT_DrawingSurface_Unlock(surface, surface.Unlock()); - } - } - - private void handMouseToView() { - MouseAdapter handOver = new MouseAdapter() { - @Override - public void mousePressed(MouseEvent event) { - handOver(event); - } - - @Override - public void mouseReleased(MouseEvent event) { - handOver(event); - } - - @Override - public void mouseClicked(MouseEvent event) { - handOver(event); - } - - @Override - public void mouseDragged(MouseEvent event) { - handOver(event); - } - - @Override - public void mouseMoved(MouseEvent event) { - handOver(event); - } - - @Override - public void mouseWheelMoved(MouseWheelEvent event) { - handOver(event); - } - }; - addMouseListener(handOver); - addMouseMotionListener(handOver); - addMouseWheelListener(handOver); - } - - private void handOver(MouseEvent event) { - view.dispatchEvent(SwingUtilities.convertMouseEvent(this, event, view)); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/GpuColors.java b/core/src/main/java/art/arcane/iris/studio/map/GpuColors.java deleted file mode 100644 index db6a90fc0..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/GpuColors.java +++ /dev/null @@ -1,75 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import static org.lwjgl.opengl.GL12.GL_BGRA; -import static org.lwjgl.opengl.GL12.GL_NEAREST; -import static org.lwjgl.opengl.GL12.GL_RGBA8; -import static org.lwjgl.opengl.GL12.GL_TEXTURE_2D; -import static org.lwjgl.opengl.GL12.GL_TEXTURE_MAG_FILTER; -import static org.lwjgl.opengl.GL12.GL_TEXTURE_MIN_FILTER; -import static org.lwjgl.opengl.GL12.GL_UNSIGNED_INT_8_8_8_8_REV; -import static org.lwjgl.opengl.GL12.glBindTexture; -import static org.lwjgl.opengl.GL12.glDeleteTextures; -import static org.lwjgl.opengl.GL12.glGenTextures; -import static org.lwjgl.opengl.GL12.glTexImage2D; -import static org.lwjgl.opengl.GL12.glTexParameteri; - -/** - * Terrain's column colours on the graphics card, one texel per column, so faces running over many columns still colour - * each one. Only for the GPU thread. - */ -final class GpuColors { - private static final int BYTES_PER_COLUMN = 4; - - private final int texture = glGenTextures(); - private final long bytes; - - private GpuColors(NoiseTerrain terrain) { - this.bytes = (long) terrain.columns() * terrain.rows() * BYTES_PER_COLUMN; - } - - /** - * @param largestSide the card's GL_MAX_TEXTURE_SIZE - * @return the colours, or null when the terrain has more columns or rows than the card's textures can hold - */ - static GpuColors upload(NoiseTerrain terrain, int largestSide) { - if (terrain.columns() > largestSide || terrain.rows() > largestSide) { - return null; - } - GpuColors uploaded = new GpuColors(terrain); - glBindTexture(GL_TEXTURE_2D, uploaded.texture); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); - glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, terrain.columns(), terrain.rows(), 0, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, terrain.colors()); - return uploaded; - } - - long bytes() { - return bytes; - } - - void bind() { - glBindTexture(GL_TEXTURE_2D, texture); - } - - void delete() { - glDeleteTextures(texture); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/GpuContext.java b/core/src/main/java/art/arcane/iris/studio/map/GpuContext.java deleted file mode 100644 index f7ccd596d..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/GpuContext.java +++ /dev/null @@ -1,301 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.studio.view.GuiHost; -import org.lwjgl.PointerBuffer; -import org.lwjgl.egl.EGL; -import org.lwjgl.opengl.GL; -import org.lwjgl.system.Configuration; - -import java.util.Arrays; -import java.util.Optional; -import java.util.Set; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; - -import static org.lwjgl.egl.EGL15.EGL_CONTEXT_MAJOR_VERSION; -import static org.lwjgl.egl.EGL15.EGL_CONTEXT_MINOR_VERSION; -import static org.lwjgl.egl.EGL15.EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT; -import static org.lwjgl.egl.EGL15.EGL_CONTEXT_OPENGL_PROFILE_MASK; -import static org.lwjgl.egl.EGL15.EGL_EXTENSIONS; -import static org.lwjgl.egl.EGL15.EGL_NONE; -import static org.lwjgl.egl.EGL15.EGL_NO_CONTEXT; -import static org.lwjgl.egl.EGL15.EGL_NO_DISPLAY; -import static org.lwjgl.egl.EGL15.EGL_NO_SURFACE; -import static org.lwjgl.egl.EGL15.EGL_OPENGL_API; -import static org.lwjgl.egl.EGL15.EGL_OPENGL_BIT; -import static org.lwjgl.egl.EGL15.EGL_PBUFFER_BIT; -import static org.lwjgl.egl.EGL15.EGL_RENDERABLE_TYPE; -import static org.lwjgl.egl.EGL15.EGL_SURFACE_TYPE; -import static org.lwjgl.egl.EGL15.eglBindAPI; -import static org.lwjgl.egl.EGL15.eglChooseConfig; -import static org.lwjgl.egl.EGL15.eglCreateContext; -import static org.lwjgl.egl.EGL15.eglDestroyContext; -import static org.lwjgl.egl.EGL15.eglInitialize; -import static org.lwjgl.egl.EGL15.eglMakeCurrent; -import static org.lwjgl.egl.EGL15.eglQueryString; -import static org.lwjgl.egl.EGL15.eglReleaseThread; -import static org.lwjgl.egl.EGL15.eglTerminate; -import static org.lwjgl.egl.EXTDeviceEnumeration.eglQueryDevicesEXT; -import static org.lwjgl.egl.EXTDeviceQuery.eglQueryDeviceStringEXT; -import static org.lwjgl.egl.EXTPlatformBase.eglGetPlatformDisplayEXT; -import static org.lwjgl.egl.EXTPlatformDevice.EGL_PLATFORM_DEVICE_EXT; -import static org.lwjgl.opengl.GL11.GL_RENDERER; -import static org.lwjgl.opengl.GL11.glGetString; - -/** - * An OpenGL context on a graphics card, and the one thread allowed to use it. Where Swing draws on X, the context draws - * straight into Swing's windows through GLX. Anywhere else, or when GLX only draws in software, it is made through - * EGL without any window: EGL lists the cards and the first one that isn't drawn in software is taken. - */ -final class GpuContext { - private static final String THREAD_NAME = "Iris GPU"; - private static final long RELEASE_WAIT_SECONDS = 5L; - private static final int OPENGL_MAJOR_VERSION = 3; - private static final int OPENGL_MINOR_VERSION = 3; - private static final String SOFTWARE_DEVICE_EXTENSION = "EGL_MESA_device_software"; - private static final Set REQUIRED_CLIENT_EXTENSIONS = Set.of("EGL_EXT_device_enumeration", "EGL_EXT_device_query", - "EGL_EXT_platform_base", "EGL_EXT_platform_device"); - - private static volatile GpuContext shared; - private static boolean unavailable; - - private final ExecutorService thread = Executors.newSingleThreadExecutor(runnable -> { - Thread gpuThread = new Thread(runnable, THREAD_NAME); - gpuThread.setDaemon(true); - return gpuThread; - }); - private String renderer; - private GlxDisplay windows; - private volatile boolean drawsIntoWindows; - private long eglDisplay = EGL_NO_DISPLAY; - private long eglContext = EGL_NO_CONTEXT; - - private GpuContext() { - } - - /** - * Whether frames can go straight into windows, as far as is known without opening the context. - */ - static boolean drawsIntoWindows() { - GpuContext context = shared; - return context != null && context.drawsIntoWindows; - } - - /** - * Only for the context's thread. - * - * @return the connection drawing into windows, or nothing when frames are only drawn off screen - */ - Optional windows() { - return drawsIntoWindows ? Optional.of(windows) : Optional.empty(); - } - - /** - * Stops drawing into a window about to be destroyed, waiting for a frame going into it to finish first. - */ - static void forgetWindow(long window) { - GpuContext context = shared; - if (context == null || context.windows == null) { - return; - } - try { - context.call(() -> { - context.windows.forget(window); - return null; - }); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - } catch (RuntimeException failure) { - IrisLogging.reportError(failure); - } - } - - // Off-screen frames still work in the same context, read back like on a machine without GLX. - void stopDrawingIntoWindows(RuntimeException failure) { - if (!drawsIntoWindows) { - return; - } - drawsIntoWindows = false; - IrisLogging.reportError(failure); - IrisLogging.warn("3D views stop drawing straight into windows: %s", failure.getMessage()); - } - - /** - * @return the context every view shares, opened on first use, or nothing when this machine has no usable card - */ - static synchronized Optional shared() { - if (shared == null && !unavailable) { - shared = open(); - unavailable = shared == null; - } - return Optional.ofNullable(shared); - } - - private static GpuContext open() { - GpuContext context = new GpuContext(); - try { - context.thread.submit(context::openOnCard).get(); - IrisLogging.info(context.drawsIntoWindows ? "3D views draw on %s, straight into their windows" : "3D views draw on %s", - context.renderer); - releaseOnShutdown(); - return context; - } catch (ExecutionException failure) { - IrisLogging.warn("3D views draw without a graphics card: %s", failure.getCause()); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - } - context.thread.shutdownNow(); - return null; - } - - // NVIDIA's driver crashes the JVM on its way out when a context is still current on some thread. - private static void releaseOnShutdown() { - GuiHost.runAtShutdown(GpuContext::releaseShared); - } - - /** - * Lets go of the card once frames already asked for are drawn. Frames asked for later are drawn without it. - */ - static synchronized void releaseShared() { - GpuContext context = shared; - if (context == null) { - return; - } - context.thread.execute(context::release); - context.thread.shutdown(); - try { - if (!context.thread.awaitTermination(RELEASE_WAIT_SECONDS, TimeUnit.SECONDS)) { - IrisLogging.warn("3D views didn't let go of the graphics card in time"); - } - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - } - } - - private void release() { - drawsIntoWindows = false; - if (windows != null) { - windows.close(); - return; - } - eglMakeCurrent(eglDisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); - eglDestroyContext(eglDisplay, eglContext); - eglTerminate(eglDisplay); - eglReleaseThread(); - } - - /** - * Runs {@code work} on the context's thread and waits for it. - */ - T call(Callable work) throws InterruptedException { - try { - return thread.submit(work).get(); - } catch (ExecutionException failure) { - throw new IllegalStateException("Drawing on the graphics card failed", failure.getCause()); - } - } - - // GL would otherwise look for a GLX library as soon as it loads, which a context from EGL doesn't use. - private Void openOnCard() { - Configuration.OPENGL_EXPLICIT_INIT.set(true); - try { - windows = GlxDisplay.open(); - renderer = windows.renderer(); - drawsIntoWindows = true; - return null; - } catch (RuntimeException | LinkageError noWindows) { - IrisLogging.info("3D views can't draw straight into windows: %s", noWindows); - } - openWithoutWindows(); - return null; - } - - private void openWithoutWindows() { - if (!canListDevices()) { - throw new IllegalStateException("EGL can't list graphics cards"); - } - GL.create(EGL.getFunctionProvider()); - for (long device : devices()) { - if (!isDrawnInSoftware(device) && makeCurrentOn(device)) { - GL.createCapabilities(); - renderer = glGetString(GL_RENDERER); - return; - } - } - throw new IllegalStateException("No graphics card supports OpenGL " + OPENGL_MAJOR_VERSION + "." + OPENGL_MINOR_VERSION); - } - - // LWJGL's own capability flags read false for these even where the library has them, so the list is asked for. - private static boolean canListDevices() { - String extensions = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS); - return extensions != null && Arrays.asList(extensions.split(" ")).containsAll(REQUIRED_CLIENT_EXTENSIONS); - } - - private static long[] devices() { - int[] count = new int[1]; - eglQueryDevicesEXT(null, count); - PointerBuffer found = PointerBuffer.allocateDirect(count[0]); - eglQueryDevicesEXT(found, count); - long[] devices = new long[count[0]]; - for (int device = 0; device < devices.length; device++) { - devices[device] = found.get(device); - } - return devices; - } - - private static boolean isDrawnInSoftware(long device) { - String extensions = eglQueryDeviceStringEXT(device, EGL_EXTENSIONS); - return extensions != null && extensions.contains(SOFTWARE_DEVICE_EXTENSION); - } - - // Nothing is drawn to a surface, only to framebuffers of the context's own, so the context needs none. Configs - // default to window surfaces, which a card without a display has none of. - private boolean makeCurrentOn(long device) { - long display = eglGetPlatformDisplayEXT(EGL_PLATFORM_DEVICE_EXT, device, (int[]) null); - if (display == EGL_NO_DISPLAY || !eglInitialize(display, new int[1], new int[1])) { - return false; - } - PointerBuffer config = PointerBuffer.allocateDirect(1); - int[] configCount = new int[1]; - int[] wanted = {EGL_SURFACE_TYPE, EGL_PBUFFER_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, EGL_NONE}; - if (!eglChooseConfig(display, wanted, config, configCount) || configCount[0] == 0 - || !eglBindAPI(EGL_OPENGL_API)) { - eglTerminate(display); - return false; - } - long context = eglCreateContext(display, config.get(0), EGL_NO_CONTEXT, new int[]{ - EGL_CONTEXT_MAJOR_VERSION, OPENGL_MAJOR_VERSION, - EGL_CONTEXT_MINOR_VERSION, OPENGL_MINOR_VERSION, - EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT, - EGL_NONE}); - if (context == EGL_NO_CONTEXT || !eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, context)) { - eglTerminate(display); - return false; - } - eglDisplay = display; - eglContext = context; - return true; - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/GpuFaces.java b/core/src/main/java/art/arcane/iris/studio/map/GpuFaces.java deleted file mode 100644 index ff54ab70f..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/GpuFaces.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import org.lwjgl.system.MemoryUtil; - -import java.nio.IntBuffer; - -import static org.lwjgl.opengl.GL33.GL_RGBA32I; -import static org.lwjgl.opengl.GL33.GL_STATIC_DRAW; -import static org.lwjgl.opengl.GL33.GL_TEXTURE_BUFFER; -import static org.lwjgl.opengl.GL33.glBindBuffer; -import static org.lwjgl.opengl.GL33.glBindTexture; -import static org.lwjgl.opengl.GL33.glBufferData; -import static org.lwjgl.opengl.GL33.glBufferSubData; -import static org.lwjgl.opengl.GL33.glDeleteBuffers; -import static org.lwjgl.opengl.GL33.glDeleteTextures; -import static org.lwjgl.opengl.GL33.glGenBuffers; -import static org.lwjgl.opengl.GL33.glGenTextures; -import static org.lwjgl.opengl.GL33.glTexBuffer; - -/** - * A layer's block faces on the graphics card, four ints each: first column, first row, bottom, and run with height. - * The vertex shader reads them from a buffer texture and works out each face's two triangles itself, which cards draw - * far faster than millions of tiny instances. Only for the GPU thread. - */ -final class GpuFaces { - static final int CORNERS_PER_FACE = 6; - private static final int INTS_PER_FACE = 4; - private static final int BYTES_PER_FACE = INTS_PER_FACE * Integer.BYTES; - private static final int FACES_PER_UPLOAD = 1 << 20; - private static final int LARGEST_PACKED = 0xFFFF; - private static final BlockFaces.Facing[] FACINGS = BlockFaces.Facing.values(); - private static final BlockFaces.Kind[] KINDS = BlockFaces.Kind.values(); - - // Copied rather than kept, so the faces left in memory can be dropped once nothing else uses them. - private final int[][] firstOf = new int[KINDS.length][FACINGS.length]; - private final int[][] countOf = new int[KINDS.length][FACINGS.length]; - private final long bytes; - private final int buffer = glGenBuffers(); - private final int texture = glGenTextures(); - - private GpuFaces(BlockFaces faces) { - for (BlockFaces.Kind kind : KINDS) { - for (BlockFaces.Facing facing : FACINGS) { - firstOf[kind.ordinal()][facing.ordinal()] = faces.first(kind, facing); - countOf[kind.ordinal()][facing.ordinal()] = faces.count(kind, facing); - } - } - bytes = (long) faces.count() * BYTES_PER_FACE; - } - - /** - * @throws IllegalArgumentException when there are more faces than the card's buffer textures hold, or a face runs - * or reaches further than four ints can hold - * @param mostFaces the card's GL_MAX_TEXTURE_BUFFER_SIZE - */ - static GpuFaces upload(BlockFaces faces, int mostFaces) { - if (faces.count() > mostFaces || (long) faces.count() * CORNERS_PER_FACE > Integer.MAX_VALUE) { - throw new IllegalArgumentException(faces.count() + " faces are more than the graphics card can hold"); - } - GpuFaces uploaded = new GpuFaces(faces); - try { - uploaded.fill(faces); - } catch (RuntimeException failure) { - uploaded.delete(); - throw failure; - } - return uploaded; - } - - // Packed a slice at a time, so large terrain doesn't need all of it twice in memory. - private void fill(BlockFaces faces) { - glBindBuffer(GL_TEXTURE_BUFFER, buffer); - glBufferData(GL_TEXTURE_BUFFER, (long) Math.max(1, faces.count()) * BYTES_PER_FACE, GL_STATIC_DRAW); - IntBuffer packed = MemoryUtil.memAllocInt(Math.max(1, Math.min(faces.count(), FACES_PER_UPLOAD)) * INTS_PER_FACE); - try { - for (int from = 0; from < faces.count(); from += FACES_PER_UPLOAD) { - int to = Math.min(faces.count(), from + FACES_PER_UPLOAD); - pack(faces, packed, from, to); - glBufferSubData(GL_TEXTURE_BUFFER, (long) from * BYTES_PER_FACE, packed); - } - } finally { - MemoryUtil.memFree(packed); - } - glBindTexture(GL_TEXTURE_BUFFER, texture); - glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32I, buffer); - } - - private static void pack(BlockFaces faces, IntBuffer packed, int fromFace, int toFace) { - packed.clear(); - for (int face = fromFace; face < toFace; face++) { - int run = faces.columns(face); - int reach = faces.height(face); - if (run > LARGEST_PACKED || reach > LARGEST_PACKED) { - throw new IllegalArgumentException("A face of " + run + " by " + reach + " is too large to draw on the graphics card"); - } - packed.put(faces.firstColumn(face)).put(faces.firstRow(face)).put(faces.bottomY(face)).put(run | reach << 16); - } - packed.flip(); - } - - void bind() { - glBindTexture(GL_TEXTURE_BUFFER, texture); - } - - int first(BlockFaces.Kind kind, BlockFaces.Facing facing) { - return firstOf[kind.ordinal()][facing.ordinal()]; - } - - int count(BlockFaces.Kind kind, BlockFaces.Facing facing) { - return countOf[kind.ordinal()][facing.ordinal()]; - } - - long bytes() { - return bytes; - } - - void delete() { - glDeleteTextures(texture); - glDeleteBuffers(buffer); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/GpuFrameTarget.java b/core/src/main/java/art/arcane/iris/studio/map/GpuFrameTarget.java deleted file mode 100644 index b8320e513..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/GpuFrameTarget.java +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.util.OptionalDouble; - -import static org.lwjgl.opengl.GL11.GL_DEPTH_COMPONENT; -import static org.lwjgl.opengl.GL11.GL_FLOAT; -import static org.lwjgl.opengl.GL11.glReadPixels; - -/** - * Where the graphics card draws a frame: a picture read back for Swing, or straight into a window. Only for the GPU - * thread. - */ -interface GpuFrameTarget { - double FARTHEST_DEPTH = 1D; - - /** - * Makes the target the one drawn into, at the given size. - */ - void bindSized(int width, int height); - - /** - * Ends the frame drawn since {@link #bindSized}. - * - * @param depthRange the range the clip matrix was made for - */ - OrbitPicture finish(OrbitProjection projection, double depthRange); - - /** - * Reads the one depth a picture keeps, the middle's, from what is bound. - */ - static OptionalDouble depthInMiddle(OrbitProjection projection, double depthRange, int width, int height) { - int middleX = (int) projection.screenCenterX(); - int middleY = (int) projection.screenCenterY(); - if (middleX < 0 || middleY < 0 || middleX >= width || middleY >= height) { - return OptionalDouble.empty(); - } - float[] middleDepth = new float[1]; - glReadPixels(middleX, height - 1 - middleY, 1, 1, GL_DEPTH_COMPONENT, GL_FLOAT, middleDepth); - return OrbitPicture.finite(blockDepth(middleDepth[0], depthRange)); - } - - // The depth buffer holds 0 at the near plane and 1 at the far one, nearer being smaller. - private static double blockDepth(float bufferDepth, double depthRange) { - if (bufferDepth >= FARTHEST_DEPTH) { - return Double.NEGATIVE_INFINITY; - } - return -(2D * bufferDepth - 1D) * depthRange; - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/GpuFramebuffer.java b/core/src/main/java/art/arcane/iris/studio/map/GpuFramebuffer.java deleted file mode 100644 index a40efa058..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/GpuFramebuffer.java +++ /dev/null @@ -1,90 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.awt.image.BufferedImage; -import java.awt.image.DataBufferInt; - -import static org.lwjgl.opengl.GL30.GL_BGRA; -import static org.lwjgl.opengl.GL30.GL_COLOR_ATTACHMENT0; -import static org.lwjgl.opengl.GL30.GL_DEPTH_ATTACHMENT; -import static org.lwjgl.opengl.GL30.GL_DEPTH_COMPONENT24; -import static org.lwjgl.opengl.GL30.GL_FRAMEBUFFER; -import static org.lwjgl.opengl.GL30.GL_FRAMEBUFFER_COMPLETE; -import static org.lwjgl.opengl.GL30.GL_RENDERBUFFER; -import static org.lwjgl.opengl.GL30.GL_RGBA8; -import static org.lwjgl.opengl.GL30.GL_UNSIGNED_INT_8_8_8_8_REV; -import static org.lwjgl.opengl.GL30.glBindFramebuffer; -import static org.lwjgl.opengl.GL30.glBindRenderbuffer; -import static org.lwjgl.opengl.GL30.glCheckFramebufferStatus; -import static org.lwjgl.opengl.GL30.glFramebufferRenderbuffer; -import static org.lwjgl.opengl.GL30.glGenFramebuffers; -import static org.lwjgl.opengl.GL30.glGenRenderbuffers; -import static org.lwjgl.opengl.GL30.glReadPixels; -import static org.lwjgl.opengl.GL30.glRenderbufferStorage; -import static org.lwjgl.opengl.GL30.glViewport; - -/** - * A picture the graphics card draws into instead of a window, read back as an {@link OrbitPicture} so Swing shows it - * like any other. Only for the GPU thread. - */ -final class GpuFramebuffer implements GpuFrameTarget { - private final int framebuffer = glGenFramebuffers(); - private final int colorBuffer = glGenRenderbuffers(); - private final int depthBuffer = glGenRenderbuffers(); - private int width; - private int height; - private int[] colorRows = new int[0]; - - @Override - public void bindSized(int nextWidth, int nextHeight) { - glBindFramebuffer(GL_FRAMEBUFFER, framebuffer); - if (nextWidth != width || nextHeight != height) { - resizeTo(nextWidth, nextHeight); - } - glViewport(0, 0, width, height); - } - - private void resizeTo(int nextWidth, int nextHeight) { - width = nextWidth; - height = nextHeight; - glBindRenderbuffer(GL_RENDERBUFFER, colorBuffer); - glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, width, height); - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, colorBuffer); - glBindRenderbuffer(GL_RENDERBUFFER, depthBuffer); - glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width, height); - glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBuffer); - if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { - throw new IllegalStateException("The graphics card can't draw a " + width + "x" + height + " picture"); - } - colorRows = new int[width * height]; - } - - // Reads what was drawn. Only the middle's depth is read back, the one depth a picture keeps. - @Override - public OrbitPicture finish(OrbitProjection projection, double depthRange) { - glReadPixels(0, 0, width, height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, colorRows); - BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); - for (int row = 0; row < height; row++) { - System.arraycopy(colorRows, (height - 1 - row) * width, pixels, row * width, width); - } - return OrbitPicture.whole(image, GpuFrameTarget.depthInMiddle(projection, depthRange, width, height)); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/GpuFrames.java b/core/src/main/java/art/arcane/iris/studio/map/GpuFrames.java deleted file mode 100644 index 297363140..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/GpuFrames.java +++ /dev/null @@ -1,191 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.spi.IrisLogging; - -import java.util.Optional; - -import static org.lwjgl.opengl.GL33.GL_BLEND; -import static org.lwjgl.opengl.GL33.GL_COLOR_BUFFER_BIT; -import static org.lwjgl.opengl.GL33.GL_CULL_FACE; -import static org.lwjgl.opengl.GL33.GL_DEPTH_BUFFER_BIT; -import static org.lwjgl.opengl.GL33.GL_DEPTH_TEST; -import static org.lwjgl.opengl.GL33.GL_LESS; -import static org.lwjgl.opengl.GL33.GL_NO_ERROR; -import static org.lwjgl.opengl.GL33.GL_POLYGON_OFFSET_FILL; -import static org.lwjgl.opengl.GL33.glClear; -import static org.lwjgl.opengl.GL33.glClearColor; -import static org.lwjgl.opengl.GL33.glClearDepth; -import static org.lwjgl.opengl.GL33.glDepthFunc; -import static org.lwjgl.opengl.GL33.glDepthMask; -import static org.lwjgl.opengl.GL33.glDisable; -import static org.lwjgl.opengl.GL33.glEnable; -import static org.lwjgl.opengl.GL33.glGetError; - -/** - * Runs a 3D view's frame on the graphics card, straight into the view's window where frames can go there, or else into - * a picture read back for Swing. A card that fails once isn't used again, as it would most likely fail every frame, - * each time only after costing the frame its time. - */ -final class GpuFrames { - private static final double COLOR_CHANNEL_MAX = 255D; - - private static GpuFramebuffer offScreen; - private static volatile boolean failed; - - private GpuFrames() { - } - - /** - * A frame drawn on the card's thread. - */ - @FunctionalInterface - interface Drawing { - /** - * @return the frame, or nothing when the card can't draw this scene and it should be drawn without one - */ - Optional drawInto(GpuFrameTarget target); - } - - /** - * @return the picture, or nothing when the caller should draw it without a card - */ - static Optional drawPicture(Drawing drawing) { - return onCard(gpu -> drawing.drawInto(offScreenFramebuffer())); - } - - static boolean canDrawOnScreen() { - return !failed && GpuContext.drawsIntoWindows(); - } - - /** - * @return the frame, or nothing when it can't go straight into the window and the caller should draw a picture - */ - static Optional drawOnScreen(ScreenTarget screen, Drawing drawing) { - return onCard(gpu -> { - Optional windows = gpu.windows(); - long window = screen.canvas().window(); - if (windows.isEmpty() || window == 0L) { - return Optional.empty(); - } - try { - if (!windows.get().canDrawInto(screen.canvas().visualId())) { - throw new IllegalStateException("The view's window has another visual than the one GLX draws with"); - } - if (!windows.get().drawInto(window)) { - throw new IllegalStateException("GLX can't draw into the view's window"); - } - return drawing.drawInto(new GpuWindowFrame(screen.seeThrough())); - } catch (RuntimeException failure) { - gpu.stopDrawingIntoWindows(failure); - return Optional.empty(); - } - }); - } - - /** - * Puts the last frame drawn into the view's window on screen. Another view may have drawn into its own window - * since, so the view's window is made current again first. - * - * @return false when the window didn't take it, and the caller should draw a picture instead - */ - static boolean showOnScreen(ScreenTarget screen) { - return onCard(gpu -> { - Optional windows = gpu.windows(); - long window = screen.canvas().window(); - if (windows.isEmpty() || window == 0L) { - return Optional.empty(); - } - try { - if (!windows.get().drawInto(window) || !windows.get().show(window)) { - throw new IllegalStateException("The window didn't take the frame"); - } - return Optional.of(true); - } catch (RuntimeException failure) { - gpu.stopDrawingIntoWindows(failure); - return Optional.empty(); - } - }).isPresent(); - } - - static void failOnError() { - int error = glGetError(); - if (error != GL_NO_ERROR) { - throw new IllegalStateException("OpenGL error 0x" + Integer.toHexString(error)); - } - } - - /** - * Clears to the views' background, and sets up for opaque drawing with depth. - */ - static void clearToBackground() { - int background = StudioTheme.EDITOR_BACKGROUND.getRGB(); - glClearColor(channel(background, 16), channel(background, 8), channel(background, 0), 1F); - glClearDepth(1D); - glDepthMask(true); - glEnable(GL_DEPTH_TEST); - glDepthFunc(GL_LESS); - glDisable(GL_BLEND); - glDisable(GL_CULL_FACE); - glDisable(GL_POLYGON_OFFSET_FILL); - glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); - } - - static float channel(int color, int shift) { - return (float) (((color >>> shift) & 0xFF) / COLOR_CHANNEL_MAX); - } - - private static GpuFramebuffer offScreenFramebuffer() { - if (offScreen == null) { - offScreen = new GpuFramebuffer(); - } - return offScreen; - } - - private static Optional onCard(CardWork work) { - if (failed) { - return Optional.empty(); - } - Optional gpu = GpuContext.shared(); - if (gpu.isEmpty()) { - return Optional.empty(); - } - try { - return gpu.get().call(() -> work.drawOn(gpu.get())); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return Optional.empty(); - } catch (RuntimeException failure) { - stopUsingCard(failure); - return Optional.empty(); - } - } - - private static void stopUsingCard(RuntimeException failure) { - failed = true; - IrisLogging.reportError(failure); - IrisLogging.warn("3D views draw without a graphics card from now on: %s", failure.getCause() == null ? failure : failure.getCause()); - } - - @FunctionalInterface - private interface CardWork { - Optional drawOn(GpuContext gpu); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/GpuLibrary.java b/core/src/main/java/art/arcane/iris/studio/map/GpuLibrary.java deleted file mode 100644 index 266b2d198..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/GpuLibrary.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.spi.IrisLogging; - -import java.util.List; - -/** - * Whether the graphics card library the 3D views draw with and its native bindings can load. Mod loaders get it from the game, - * which ships only part of it, so the views check here before touching any class that links against it. - */ -final class GpuLibrary { - private static final List REQUIRED_CLASSES = List.of( - "org.lwjgl.system.MemoryStack", - "org.lwjgl.opengl.GL", - "org.lwjgl.egl.EGL", - "org.lwjgl.system.jawt.JAWT" - ); - private static final boolean LOADED = findRequiredClasses(); - - private GpuLibrary() { - } - - static boolean isLoaded() { - return LOADED; - } - - private static boolean findRequiredClasses() { - ClassLoader loader = GpuLibrary.class.getClassLoader(); - for (String className : REQUIRED_CLASSES) { - try { - Class.forName(className, false, loader); - } catch (ClassNotFoundException | LinkageError missing) { - IrisLogging.info("3D views draw without a graphics card: %s isn't on the classpath", className); - return false; - } - } - try { - Class.forName("org.lwjgl.system.jawt.JAWTFunctions", true, loader); - return true; - } catch (ClassNotFoundException | LinkageError | SecurityException unavailable) { - IrisLogging.info("3D views draw without a graphics card: native bindings are unavailable (%s)", unavailable); - return false; - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/GpuObjectMesh.java b/core/src/main/java/art/arcane/iris/studio/map/GpuObjectMesh.java deleted file mode 100644 index e79cd113b..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/GpuObjectMesh.java +++ /dev/null @@ -1,293 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.studio.map.BlockModel.Face; -import art.arcane.iris.studio.map.BlockModel.TextureMapping; -import art.arcane.iris.studio.map.BlockTextures.BlockTexture; -import org.lwjgl.system.MemoryUtil; - -import java.nio.FloatBuffer; -import java.nio.IntBuffer; -import java.util.Arrays; -import java.util.IdentityHashMap; -import java.util.List; -import java.util.Map; - -import static org.lwjgl.opengl.GL33.GL_R32I; -import static org.lwjgl.opengl.GL33.GL_RGBA32F; -import static org.lwjgl.opengl.GL33.GL_RGBA8; -import static org.lwjgl.opengl.GL33.GL_STATIC_DRAW; -import static org.lwjgl.opengl.GL33.GL_STREAM_DRAW; -import static org.lwjgl.opengl.GL33.GL_TEXTURE_BUFFER; -import static org.lwjgl.opengl.GL33.glBindBuffer; -import static org.lwjgl.opengl.GL33.glBindTexture; -import static org.lwjgl.opengl.GL33.glBufferData; -import static org.lwjgl.opengl.GL33.glBufferSubData; -import static org.lwjgl.opengl.GL33.glDeleteBuffers; -import static org.lwjgl.opengl.GL33.glDeleteTextures; -import static org.lwjgl.opengl.GL33.glGenBuffers; -import static org.lwjgl.opengl.GL33.glGenTextures; -import static org.lwjgl.opengl.GL33.glTexBuffer; - -/** - * An object mesh's quads and the texels of their textures on the graphics card, each in a buffer texture the shaders - * read from. Quads come solid first, then the cut-away ghost, then the see-through ones, whose drawing order is sent - * again every frame, farthest first. Only for the GPU thread. - */ -final class GpuObjectMesh implements GpuCache.Upload { - static final int TEXELS_PER_QUAD = 7; - private static final int FLOATS_PER_QUAD = TEXELS_PER_QUAD * 4; - private static final int OPAQUE_ALPHA = 0xFF; - - private final Vec3 anchor; - private final int solidCount; - private final int ghostCount; - private final int seeThroughCount; - private final float[] seeThroughCenters; - private final long bytes; - private final int quadBuffer = glGenBuffers(); - private final int quadTexture = glGenTextures(); - private final int texelBuffer = glGenBuffers(); - private final int texelTexture = glGenTextures(); - private final int orderBuffer = glGenBuffers(); - private final int orderTexture = glGenTextures(); - - private GpuObjectMesh(ObjectMesh mesh, int texelCount) { - ObjectMesh.Bounds bounds = mesh.bounds(); - anchor = new Vec3(bounds.minX(), bounds.minY(), bounds.minZ()); - solidCount = mesh.solidQuads().size(); - ghostCount = mesh.cutAwayQuads().size(); - seeThroughCount = mesh.translucentQuads().size(); - seeThroughCenters = centersOf(mesh.translucentQuads()); - bytes = (long) quadCount() * FLOATS_PER_QUAD * Float.BYTES + (long) texelCount * Integer.BYTES + (long) seeThroughCount * Integer.BYTES; - } - - /** - * @param mostTexels the card's GL_MAX_TEXTURE_BUFFER_SIZE - * @return the uploaded mesh, or null when it is more than the card's buffer textures hold - */ - static GpuObjectMesh upload(ObjectMesh mesh, int mostTexels) { - Map textureOffsets = new IdentityHashMap<>(); - int texelCount = placeTextures(mesh, textureOffsets); - long quadTexels = (long) (mesh.solidQuads().size() + mesh.cutAwayQuads().size() + mesh.translucentQuads().size()) * TEXELS_PER_QUAD; - if (quadTexels > mostTexels || texelCount > mostTexels || quadTexels * 6L > Integer.MAX_VALUE) { - return null; - } - GpuObjectMesh uploaded = new GpuObjectMesh(mesh, texelCount); - try { - uploaded.fillQuads(mesh, textureOffsets); - uploaded.fillTexels(textureOffsets, texelCount); - uploaded.prepareOrder(); - } catch (RuntimeException failure) { - uploaded.delete(); - throw failure; - } - return uploaded; - } - - private static int placeTextures(ObjectMesh mesh, Map offsets) { - int texelCount = 0; - for (List quads : List.of(mesh.solidQuads(), mesh.cutAwayQuads(), mesh.translucentQuads())) { - for (ObjectMesh.Quad quad : quads) { - BlockTexture texture = quad.face().texture(); - if (!offsets.containsKey(texture)) { - offsets.put(texture, texelCount); - texelCount += texture.width() * texture.height(); - } - } - } - return texelCount; - } - - private float[] centersOf(List quads) { - float[] centers = new float[quads.size() * 3]; - for (int index = 0; index < quads.size(); index++) { - ObjectMesh.Quad quad = quads.get(index); - Face face = quad.face(); - centers[index * 3] = (float) (quad.originX() - anchor.x() + (face.edgeU().x() + face.edgeV().x()) / 2D); - centers[index * 3 + 1] = (float) (quad.originY() - anchor.y() + (face.edgeU().y() + face.edgeV().y()) / 2D); - centers[index * 3 + 2] = (float) (quad.originZ() - anchor.z() + (face.edgeU().z() + face.edgeV().z()) / 2D); - } - return centers; - } - - private void fillQuads(ObjectMesh mesh, Map textureOffsets) { - FloatBuffer packed = MemoryUtil.memAllocFloat(Math.max(1, quadCount()) * FLOATS_PER_QUAD); - try { - for (List quads : List.of(mesh.solidQuads(), mesh.cutAwayQuads(), mesh.translucentQuads())) { - for (ObjectMesh.Quad quad : quads) { - pack(quad, textureOffsets.get(quad.face().texture()), packed); - } - } - packed.flip(); - glBindBuffer(GL_TEXTURE_BUFFER, quadBuffer); - glBufferData(GL_TEXTURE_BUFFER, packed, GL_STATIC_DRAW); - } finally { - MemoryUtil.memFree(packed); - } - glBindTexture(GL_TEXTURE_BUFFER, quadTexture); - glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA32F, quadBuffer); - } - - // Whole numbers ride along as float bits, read back exactly by the shader. - private void pack(ObjectMesh.Quad quad, int textureOffset, FloatBuffer packed) { - Face face = quad.face(); - BlockTexture texture = face.texture(); - TextureMapping mapping = face.mapping(); - ObjectRenderer.TexelRange columns = ObjectRenderer.TexelRange.of(mapping.u(), mapping.uAlongU(), mapping.uAlongV(), texture.width()); - ObjectRenderer.TexelRange rows = ObjectRenderer.TexelRange.of(mapping.v(), mapping.vAlongU(), mapping.vAlongV(), texture.height()); - put(packed, quad.originX() - anchor.x(), quad.originY() - anchor.y(), quad.originZ() - anchor.z()).put((float) face.shade()); - put(packed, face.edgeU()).put((float) quad.opacity()); - put(packed, face.edgeV()).put(Float.intBitsToFloat(textureOffset)); - put(packed, face.normal()).put(Float.intBitsToFloat(texture.width())); - put(packed, mapping.u(), mapping.uAlongU(), mapping.uAlongV()).put(Float.intBitsToFloat(texture.height())); - put(packed, mapping.v(), mapping.vAlongU(), mapping.vAlongV()).put(0F); - packed.put(Float.intBitsToFloat(columns.first())).put(Float.intBitsToFloat(columns.last())) - .put(Float.intBitsToFloat(rows.first())).put(Float.intBitsToFloat(rows.last())); - } - - private static FloatBuffer put(FloatBuffer packed, Vec3 vector) { - return put(packed, vector.x(), vector.y(), vector.z()); - } - - private static FloatBuffer put(FloatBuffer packed, double x, double y, double z) { - return packed.put((float) x).put((float) y).put((float) z); - } - - // Texels the game doesn't draw are fully transparent, so the shader skips them. - private void fillTexels(Map textureOffsets, int texelCount) { - IntBuffer packed = MemoryUtil.memAllocInt(Math.max(1, texelCount)); - try { - textureOffsets.forEach((texture, offset) -> { - int[] alphas = texture.alphas(); - for (int texel = 0; texel < texture.width() * texture.height(); texel++) { - int alpha = !texture.opaque()[texel] ? 0 : alphas == null ? OPAQUE_ALPHA : alphas[texel]; - packed.put(offset + texel, rgba(texture.pixels()[texel], alpha)); - } - }); - glBindBuffer(GL_TEXTURE_BUFFER, texelBuffer); - glBufferData(GL_TEXTURE_BUFFER, packed, GL_STATIC_DRAW); - } finally { - MemoryUtil.memFree(packed); - } - glBindTexture(GL_TEXTURE_BUFFER, texelTexture); - glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA8, texelBuffer); - } - - // GL_RGBA8 takes red from the lowest byte, which is the first in memory on the little-endian machines LWJGL runs on. - private static int rgba(int rgb, int alpha) { - return ((rgb >>> 16) & 0xFF) | (rgb & 0xFF00) | ((rgb & 0xFF) << 16) | (alpha << 24); - } - - private void prepareOrder() { - glBindBuffer(GL_TEXTURE_BUFFER, orderBuffer); - glBufferData(GL_TEXTURE_BUFFER, (long) Math.max(1, seeThroughCount) * Integer.BYTES, GL_STREAM_DRAW); - glBindTexture(GL_TEXTURE_BUFFER, orderTexture); - glTexBuffer(GL_TEXTURE_BUFFER, GL_R32I, orderBuffer); - } - - /** - * Sends the see-through quads' drawing order, farthest from the camera first, keeping the mesh's order between - * quads at the same depth. - * - * @param towardCamera how far each block along x, y and z brings a point toward the camera - */ - void sortSeeThroughFarthestFirst(Vec3 towardCamera) { - if (seeThroughCount == 0) { - return; - } - long[] depthThenIndex = new long[seeThroughCount]; - for (int index = 0; index < seeThroughCount; index++) { - float depth = (float) (seeThroughCenters[index * 3] * towardCamera.x() + seeThroughCenters[index * 3 + 1] * towardCamera.y() - + seeThroughCenters[index * 3 + 2] * towardCamera.z()); - depthThenIndex[index] = (long) sortableBits(depth) << 32 | index; - } - Arrays.sort(depthThenIndex); - IntBuffer order = MemoryUtil.memAllocInt(seeThroughCount); - try { - int firstSeeThrough = firstSeeThrough(); - for (long entry : depthThenIndex) { - order.put(firstSeeThrough + (int) entry); - } - order.flip(); - glBindBuffer(GL_TEXTURE_BUFFER, orderBuffer); - glBufferSubData(GL_TEXTURE_BUFFER, 0L, order); - } finally { - MemoryUtil.memFree(order); - } - } - - // Ordered as signed ints the way the floats are ordered. - private static int sortableBits(float value) { - int bits = Float.floatToIntBits(value); - return bits < 0 ? bits ^ Integer.MAX_VALUE : bits; - } - - void bindQuads() { - glBindTexture(GL_TEXTURE_BUFFER, quadTexture); - } - - void bindTexels() { - glBindTexture(GL_TEXTURE_BUFFER, texelTexture); - } - - void bindOrder() { - glBindTexture(GL_TEXTURE_BUFFER, orderTexture); - } - - Vec3 anchor() { - return anchor; - } - - int solidCount() { - return solidCount; - } - - int firstGhost() { - return solidCount; - } - - int ghostCount() { - return ghostCount; - } - - int firstSeeThrough() { - return solidCount + ghostCount; - } - - int seeThroughCount() { - return seeThroughCount; - } - - private int quadCount() { - return solidCount + ghostCount + seeThroughCount; - } - - @Override - public long bytes() { - return bytes; - } - - @Override - public void delete() { - glDeleteTextures(new int[]{quadTexture, texelTexture, orderTexture}); - glDeleteBuffers(new int[]{quadBuffer, texelBuffer, orderBuffer}); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/GpuObjectRenderer.java b/core/src/main/java/art/arcane/iris/studio/map/GpuObjectRenderer.java deleted file mode 100644 index ab4aae1c1..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/GpuObjectRenderer.java +++ /dev/null @@ -1,300 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.util.Optional; -import java.util.Set; - -import static org.lwjgl.opengl.GL33.GL_BLEND; -import static org.lwjgl.opengl.GL33.GL_LEQUAL; -import static org.lwjgl.opengl.GL33.GL_LINES; -import static org.lwjgl.opengl.GL33.GL_MAX_TEXTURE_BUFFER_SIZE; -import static org.lwjgl.opengl.GL33.GL_ONE; -import static org.lwjgl.opengl.GL33.GL_ONE_MINUS_SRC_ALPHA; -import static org.lwjgl.opengl.GL33.GL_SRC_ALPHA; -import static org.lwjgl.opengl.GL33.GL_TEXTURE0; -import static org.lwjgl.opengl.GL33.GL_TEXTURE1; -import static org.lwjgl.opengl.GL33.GL_TEXTURE2; -import static org.lwjgl.opengl.GL33.GL_TRIANGLES; -import static org.lwjgl.opengl.GL33.GL_ZERO; -import static org.lwjgl.opengl.GL33.glActiveTexture; -import static org.lwjgl.opengl.GL33.glBindVertexArray; -import static org.lwjgl.opengl.GL33.glBlendFuncSeparate; -import static org.lwjgl.opengl.GL33.glDepthFunc; -import static org.lwjgl.opengl.GL33.glDepthMask; -import static org.lwjgl.opengl.GL33.glDisable; -import static org.lwjgl.opengl.GL33.glDrawArrays; -import static org.lwjgl.opengl.GL33.glEnable; -import static org.lwjgl.opengl.GL33.glGenVertexArrays; -import static org.lwjgl.opengl.GL33.glGetInteger; - -/** - * Draws an object mesh on the graphics card, looking the way {@link ObjectRenderer} draws it. That one still draws on - * machines without a card, and the thumbnails. The mesh stays on the card while it is shown, so a frame only sends the - * camera and the see-through quads' order. - */ -final class GpuObjectRenderer { - private static final double DEPTH_MARGIN_BLOCKS = 4D; - // Several large objects, well within what any card able to draw them has. - private static final long MOST_UPLOADED_BYTES = 256L << 20; - private static final int CORNERS_PER_QUAD = 6; - private static final int ENDS_PER_LINE = 2; - private static final int GRID_DIRECTIONS = 2; - - private static final String QUAD_VERTEX_SHADER = """ - #version 330 core - const int[6] CORNERS = int[6](0, 1, 2, 2, 1, 3); - const int TEXELS_PER_QUAD = %d; - uniform samplerBuffer quads; - uniform isamplerBuffer order; - uniform bool inOrder; - uniform int firstQuad; - uniform mat4 toClip; - uniform vec3 anchorFromCenter; - uniform vec3 towardCamera; - out vec2 texturePosition; - flat out int firstTexel; - flat out ivec2 textureSize; - flat out ivec4 texelRange; - flat out float shade; - flat out float opacity; - - // Faces looking away from the camera are hidden behind the ones looking toward it, so every corner of - // theirs is put in the same spot outside the view, which draws nothing. - void main() { - int index = gl_VertexID / 6; - int quad = inOrder ? texelFetch(order, index).r : firstQuad + index; - int base = quad * TEXELS_PER_QUAD; - vec4 origin = texelFetch(quads, base); - vec4 edgeU = texelFetch(quads, base + 1); - vec4 edgeV = texelFetch(quads, base + 2); - vec4 normal = texelFetch(quads, base + 3); - if (dot(normal.xyz, towardCamera) <= 0.0) { - gl_Position = vec4(2.0, 2.0, 2.0, 1.0); - return; - } - vec4 mappingU = texelFetch(quads, base + 4); - vec4 mappingV = texelFetch(quads, base + 5); - int corner = CORNERS[gl_VertexID %% 6]; - float alongU = float(corner & 1); - float alongV = float(corner >> 1); - gl_Position = toClip * vec4(anchorFromCenter + origin.xyz + alongU * edgeU.xyz + alongV * edgeV.xyz, 1.0); - texturePosition = vec2(mappingU.x + alongU * mappingU.y + alongV * mappingU.z, - mappingV.x + alongU * mappingV.y + alongV * mappingV.z); - firstTexel = floatBitsToInt(edgeV.w); - textureSize = ivec2(floatBitsToInt(normal.w), floatBitsToInt(mappingU.w)); - texelRange = floatBitsToInt(texelFetch(quads, base + 6)); - shade = origin.w; - opacity = edgeU.w; - } - """.formatted(GpuObjectMesh.TEXELS_PER_QUAD); - - private static final String QUAD_FRAGMENT_SHADER = """ - #version 330 core - uniform samplerBuffer texels; - uniform bool blended; - in vec2 texturePosition; - flat in int firstTexel; - flat in ivec2 textureSize; - flat in ivec4 texelRange; - flat in float shade; - flat in float opacity; - out vec4 fragment; - - void main() { - int column = clamp(int(floor(texturePosition.x * float(textureSize.x))), texelRange.x, texelRange.y); - int row = clamp(int(floor(texturePosition.y * float(textureSize.y))), texelRange.z, texelRange.w); - vec4 texel = texelFetch(texels, firstTexel + row * textureSize.x + column); - if (texel.a == 0.0) { - discard; - } - fragment = vec4(min(texel.rgb * shade, vec3(1.0)), blended ? texel.a * opacity : 1.0); - } - """; - - private static final String GRID_VERTEX_SHADER = """ - #version 330 core - uniform mat4 toClip; - uniform vec3 gridCenter; - uniform int reach; - uniform int step; - uniform int linesPerDirection; - - void main() { - int line = gl_VertexID / 2; - float across = float(-reach + (line % linesPerDirection) * step); - float along = float((gl_VertexID % 2) * 2 - 1) * float(reach); - vec3 offset = line < linesPerDirection ? vec3(across, 0.0, along) : vec3(along, 0.0, across); - gl_Position = toClip * vec4(gridCenter + offset, 1.0); - } - """; - - private static final String FLAT_FRAGMENT_SHADER = """ - #version 330 core - uniform vec4 color; - out vec4 fragment; - - void main() { - fragment = color; - } - """; - - private static GpuObjectRenderer onCard; - - private final GpuProgram quadProgram = GpuProgram.of(QUAD_VERTEX_SHADER, QUAD_FRAGMENT_SHADER); - private final GpuProgram gridProgram = GpuProgram.of(GRID_VERTEX_SHADER, FLAT_FRAGMENT_SHADER); - private final int attributelessVertexArray = glGenVertexArrays(); - // Asked once: asking the card waits for everything sent to it so far. - private final int mostBufferTexels = glGetInteger(GL_MAX_TEXTURE_BUFFER_SIZE); - private final GpuCache uploadedMeshes = new GpuCache<>(); - - /** - * @return the picture, or nothing when the card can't draw this mesh and the caller should draw it without one - */ - static Optional render(ObjectMesh mesh, OrbitCamera camera, int width, int height, int coveredLeftWidth) { - return GpuFrames.drawPicture(target -> onCard().draw(mesh, camera, width, height, coveredLeftWidth, target)); - } - - /** - * @return the frame, or nothing when it can't go straight into the window and the caller should draw a picture - */ - static Optional renderOnScreen(ObjectMesh mesh, ScreenTarget screen, OrbitCamera camera, int width, int height, - int coveredLeftWidth) { - return GpuFrames.drawOnScreen(screen, target -> onCard().draw(mesh, camera, width, height, coveredLeftWidth, target)); - } - - private static GpuObjectRenderer onCard() { - if (onCard == null) { - onCard = new GpuObjectRenderer(); - } - return onCard; - } - - private Optional draw(ObjectMesh mesh, OrbitCamera camera, int width, int height, int coveredLeftWidth, - GpuFrameTarget target) { - GpuObjectMesh uploaded = uploaded(mesh); - if (uploaded == null) { - return Optional.empty(); - } - OrbitProjection projection = ObjectRenderer.projection(mesh, camera, width, height, coveredLeftWidth); - ObjectRenderer.FloorGrid grid = ObjectRenderer.FloorGrid.under(mesh.bounds()); - double depthRange = farthestFrom(projection.center(), mesh.bounds(), grid) + DEPTH_MARGIN_BLOCKS; - float[] toClip = projection.clipMatrix(width, height, depthRange); - target.bindSized(width, height); - GpuFrames.clearToBackground(); - glDepthFunc(GL_LEQUAL); - glBindVertexArray(attributelessVertexArray); - drawGrid(grid, projection, toClip); - drawMesh(uploaded, projection, toClip); - GpuFrames.failOnError(); - return Optional.of(target.finish(projection, depthRange)); - } - - private GpuObjectMesh uploaded(ObjectMesh mesh) { - uploadedMeshes.forgetCollected(); - GpuObjectMesh uploaded = uploadedMeshes.get(mesh); - if (uploaded == null) { - uploaded = GpuObjectMesh.upload(mesh, mostBufferTexels); - if (uploaded == null) { - return null; - } - uploadedMeshes.put(mesh, uploaded); - } - uploadedMeshes.forgetBeyond(MOST_UPLOADED_BYTES, Set.of(mesh)); - return uploaded; - } - - // No point of the scene is further from the projection's centre than the farthest corner of a box around it all. - private static double farthestFrom(Vec3 center, ObjectMesh.Bounds bounds, ObjectRenderer.FloorGrid grid) { - double reachX = Math.max(Math.abs(bounds.minX() - center.x()), Math.abs(bounds.maxX() - center.x())); - double reachZ = Math.max(Math.abs(bounds.minZ() - center.z()), Math.abs(bounds.maxZ() - center.z())); - double gridReachX = Math.abs(grid.centerX() - center.x()) + grid.reach(); - double gridReachZ = Math.abs(grid.centerZ() - center.z()) + grid.reach(); - double reachY = Math.max(Math.abs(Math.min(bounds.minY(), grid.floorY()) - center.y()), Math.abs(bounds.maxY() - center.y())); - return Math.sqrt(square(Math.max(reachX, gridReachX)) + square(reachY) + square(Math.max(reachZ, gridReachZ))); - } - - private static double square(double value) { - return value * value; - } - - private void drawGrid(ObjectRenderer.FloorGrid grid, OrbitProjection projection, float[] toClip) { - Vec3 center = projection.center(); - int color = grid.color(); - gridProgram.use(); - gridProgram.setMatrix("toClip", toClip); - gridProgram.set("gridCenter", new Vec3(grid.centerX() - center.x(), grid.floorY() - center.y(), grid.centerZ() - center.z())); - gridProgram.set("reach", grid.reach()); - gridProgram.set("step", grid.step()); - gridProgram.set("linesPerDirection", grid.linesPerDirection()); - gridProgram.set("color", GpuFrames.channel(color, 16), GpuFrames.channel(color, 8), GpuFrames.channel(color, 0), 1D); - glDrawArrays(GL_LINES, 0, grid.linesPerDirection() * GRID_DIRECTIONS * ENDS_PER_LINE); - } - - /** - * The cut-away ghost is drawn first, hiding nothing, so the solid quads drawn over it replace it wherever the object - * shows. Later quads win ties, so an overlay on the same box, like grass on a grass block's side, shows on top. - */ - private void drawMesh(GpuObjectMesh mesh, OrbitProjection projection, float[] toClip) { - Vec3 towardCamera = new Vec3(projection.depthStep(1D, 0D, 0D), projection.depthStep(0D, 1D, 0D), projection.depthStep(0D, 0D, 1D)); - Vec3 anchor = mesh.anchor(); - Vec3 center = projection.center(); - quadProgram.use(); - quadProgram.setMatrix("toClip", toClip); - quadProgram.set("anchorFromCenter", new Vec3(anchor.x() - center.x(), anchor.y() - center.y(), anchor.z() - center.z())); - quadProgram.set("towardCamera", towardCamera); - quadProgram.set("quads", 0); - quadProgram.set("texels", 1); - quadProgram.set("order", 2); - glActiveTexture(GL_TEXTURE0); - mesh.bindQuads(); - glActiveTexture(GL_TEXTURE1); - mesh.bindTexels(); - glActiveTexture(GL_TEXTURE2); - mesh.bindOrder(); - glActiveTexture(GL_TEXTURE0); - - startBlending(); - drawQuads(mesh.firstGhost(), mesh.ghostCount(), true); - glDisable(GL_BLEND); - glDepthMask(true); - drawQuads(0, mesh.solidCount(), false); - startBlending(); - mesh.sortSeeThroughFarthestFirst(towardCamera); - quadProgram.set("inOrder", 1); - drawQuads(0, mesh.seeThroughCount(), true); - quadProgram.set("inOrder", 0); - } - - // Blended quads hide nothing behind them. The window's own alpha is left whole, so nothing behind it shows through. - private static void startBlending() { - glEnable(GL_BLEND); - glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ZERO, GL_ONE); - glDepthMask(false); - } - - private void drawQuads(int firstQuad, int count, boolean blended) { - if (count == 0) { - return; - } - quadProgram.set("firstQuad", firstQuad); - quadProgram.set("blended", blended ? 1 : 0); - glDrawArrays(GL_TRIANGLES, 0, count * CORNERS_PER_QUAD); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/GpuProgram.java b/core/src/main/java/art/arcane/iris/studio/map/GpuProgram.java deleted file mode 100644 index 6765244ce..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/GpuProgram.java +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.util.HashMap; -import java.util.Map; - -import static org.lwjgl.opengl.GL20.GL_COMPILE_STATUS; -import static org.lwjgl.opengl.GL20.GL_FALSE; -import static org.lwjgl.opengl.GL20.GL_FRAGMENT_SHADER; -import static org.lwjgl.opengl.GL20.GL_LINK_STATUS; -import static org.lwjgl.opengl.GL20.GL_VERTEX_SHADER; -import static org.lwjgl.opengl.GL20.glAttachShader; -import static org.lwjgl.opengl.GL20.glCompileShader; -import static org.lwjgl.opengl.GL20.glCreateProgram; -import static org.lwjgl.opengl.GL20.glCreateShader; -import static org.lwjgl.opengl.GL20.glDeleteProgram; -import static org.lwjgl.opengl.GL20.glDeleteShader; -import static org.lwjgl.opengl.GL20.glGetProgramInfoLog; -import static org.lwjgl.opengl.GL20.glGetProgrami; -import static org.lwjgl.opengl.GL20.glGetShaderInfoLog; -import static org.lwjgl.opengl.GL20.glGetShaderi; -import static org.lwjgl.opengl.GL20.glGetUniformLocation; -import static org.lwjgl.opengl.GL20.glLinkProgram; -import static org.lwjgl.opengl.GL20.glShaderSource; -import static org.lwjgl.opengl.GL20.glUniform1f; -import static org.lwjgl.opengl.GL20.glUniform1i; -import static org.lwjgl.opengl.GL20.glUniform1iv; -import static org.lwjgl.opengl.GL20.glUniform2i; -import static org.lwjgl.opengl.GL20.glUniform3f; -import static org.lwjgl.opengl.GL20.glUniform3i; -import static org.lwjgl.opengl.GL20.glUniform4f; -import static org.lwjgl.opengl.GL20.glUniformMatrix4fv; -import static org.lwjgl.opengl.GL20.glUseProgram; - -/** - * A vertex and a fragment shader linked into one program, with its uniforms set by name. Only for the GPU thread. - */ -final class GpuProgram { - private final int id; - private final Map uniformLocations = new HashMap<>(); - - private GpuProgram(int id) { - this.id = id; - } - - static GpuProgram of(String vertexSource, String fragmentSource) { - int vertexShader = compile(GL_VERTEX_SHADER, vertexSource); - int fragmentShader = compile(GL_FRAGMENT_SHADER, fragmentSource); - int program = glCreateProgram(); - glAttachShader(program, vertexShader); - glAttachShader(program, fragmentShader); - glLinkProgram(program); - glDeleteShader(vertexShader); - glDeleteShader(fragmentShader); - if (glGetProgrami(program, GL_LINK_STATUS) == GL_FALSE) { - String log = glGetProgramInfoLog(program); - glDeleteProgram(program); - throw new IllegalStateException("Linking a shader program failed: " + log); - } - return new GpuProgram(program); - } - - private static int compile(int type, String source) { - int shader = glCreateShader(type); - glShaderSource(shader, source); - glCompileShader(shader); - if (glGetShaderi(shader, GL_COMPILE_STATUS) == GL_FALSE) { - String log = glGetShaderInfoLog(shader); - glDeleteShader(shader); - throw new IllegalStateException("Compiling a shader failed: " + log); - } - return shader; - } - - void use() { - glUseProgram(id); - } - - void set(String name, int value) { - glUniform1i(location(name), value); - } - - void set(String name, int x, int y) { - glUniform2i(location(name), x, y); - } - - void set(String name, int x, int y, int z) { - glUniform3i(location(name), x, y, z); - } - - void set(String name, int[] values) { - glUniform1iv(location(name), values); - } - - void set(String name, double value) { - glUniform1f(location(name), (float) value); - } - - void set(String name, Vec3 value) { - glUniform3f(location(name), (float) value.x(), (float) value.y(), (float) value.z()); - } - - void set(String name, double red, double green, double blue, double alpha) { - glUniform4f(location(name), (float) red, (float) green, (float) blue, (float) alpha); - } - - void setMatrix(String name, float[] columnMajor) { - glUniformMatrix4fv(location(name), false, columnMajor); - } - - private int location(String name) { - return uniformLocations.computeIfAbsent(name, uniform -> glGetUniformLocation(id, uniform)); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/GpuTerrainRenderer.java b/core/src/main/java/art/arcane/iris/studio/map/GpuTerrainRenderer.java deleted file mode 100644 index 094e558ed..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/GpuTerrainRenderer.java +++ /dev/null @@ -1,400 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; - -import static org.lwjgl.opengl.GL33.GL_BLEND; -import static org.lwjgl.opengl.GL33.GL_MAX_TEXTURE_BUFFER_SIZE; -import static org.lwjgl.opengl.GL33.GL_MAX_TEXTURE_SIZE; -import static org.lwjgl.opengl.GL33.GL_ONE_MINUS_SRC_ALPHA; -import static org.lwjgl.opengl.GL33.GL_POLYGON_OFFSET_FILL; -import static org.lwjgl.opengl.GL33.GL_SRC_ALPHA; -import static org.lwjgl.opengl.GL33.GL_TEXTURE0; -import static org.lwjgl.opengl.GL33.GL_TEXTURE1; -import static org.lwjgl.opengl.GL33.GL_TRIANGLES; -import static org.lwjgl.opengl.GL33.GL_TRIANGLE_STRIP; -import static org.lwjgl.opengl.GL33.glActiveTexture; -import static org.lwjgl.opengl.GL33.glBindVertexArray; -import static org.lwjgl.opengl.GL33.glBlendFunc; -import static org.lwjgl.opengl.GL33.glDepthMask; -import static org.lwjgl.opengl.GL33.glDrawArrays; -import static org.lwjgl.opengl.GL33.glEnable; -import static org.lwjgl.opengl.GL33.glGenVertexArrays; -import static org.lwjgl.opengl.GL33.glGetInteger; -import static org.lwjgl.opengl.GL33.glPolygonOffset; - -/** - * Draws noise terrain as block columns on the graphics card, looking the way {@link NoiseTerrainRenderer} draws them. - * That one still draws on machines without a card. Faces and colours stay on the card while the scene shows them, so - * a frame only sends the camera. - */ -final class GpuTerrainRenderer { - private static final double DEPTH_MARGIN_BLOCKS = 16D; - // A few full views' worth, well within what any card able to draw them has. - private static final long MOST_UPLOADED_BYTES = 768L << 20; - // Half a frame at 60 frames a second. - private static final long UPLOAD_NANOS_PER_FRAME = 8_000_000L; - private static final double FACE_OVERLAP_PIXELS = 0.05D; - - private static final String FACE_VERTEX_SHADER = """ - #version 330 core - const int[6] CORNERS = int[6](0, 1, 2, 2, 1, 3); - uniform isamplerBuffer faces; - uniform int firstFace; - uniform mat4 toClip; - uniform ivec3 layerOrigin; - uniform vec3 centerFraction; - uniform int step; - uniform ivec3 normal; - uniform float overlap; - uniform int hiddenCells[%1$d]; - uniform bool holeWall; - out vec2 units; - flat out ivec2 firstCell; - flat out int run; - - bool hides(ivec2 column) { - if (any(lessThan(column, ivec2(0))) || any(greaterThanEqual(column, ivec2(%2$d)))) { - return false; - } - int cell = column.y / %3$d * %4$d + column.x / %3$d; - return (hiddenCells[cell / 32] & (1 << (cell %% 32))) != 0; - } - - // The same as TerrainHole.shows: no face of a hidden column, and beside the hole its wall instead of the - // usual side. No face crosses a cell's edge, so its first column decides for all of it. - bool showsWithHole(ivec2 column) { - if (hides(column)) { - return false; - } - return normal.y == 1 || holeWall == hides(column + normal.xz); - } - - // Corners are worked out in whole blocks relative to the view centre, so far from the world's origin - // nothing is lost to float precision. Faces meeting the middle of a longer face's edge leave hairline - // cracks along it, so every face reaches a little past its edges. Faces the hole leaves out land outside - // the view, where they're clipped away before any pixel is drawn. - void main() { - ivec4 face = texelFetch(faces, firstFace + gl_VertexID / 6); - if (!showsWithHole(face.xy)) { - gl_Position = vec4(2.0, 2.0, 2.0, 1.0); - units = vec2(0.0); - firstCell = ivec2(0); - run = 1; - return; - } - int corner = CORNERS[gl_VertexID %% 6]; - int alongRun = corner & 1; - int alongReach = corner >> 1; - run = face.w & 0xFFFF; - int reach = (face.w >> 16) & 0xFFFF; - bool runsAlongX = normal.x == 0; - bool isTop = normal.y == 1; - ivec3 origin = ivec3((face.x + max(normal.x, 0)) * step, face.z, (face.y + max(normal.z, 0)) * step); - ivec3 runEdge = runsAlongX ? ivec3(run * step, 0, 0) : ivec3(0, 0, run * step); - ivec3 reachEdge = isTop ? ivec3(0, 0, reach * step) : ivec3(0, reach, 0); - ivec3 position = layerOrigin + origin + alongRun * runEdge + alongReach * reachEdge; - vec3 runDirection = runsAlongX ? vec3(1.0, 0.0, 0.0) : vec3(0.0, 0.0, 1.0); - vec3 reachDirection = isTop ? vec3(0.0, 0.0, 1.0) : vec3(0.0, 1.0, 0.0); - vec3 outward = (float(alongRun) * 2.0 - 1.0) * runDirection + (float(alongReach) * 2.0 - 1.0) * reachDirection; - gl_Position = toClip * vec4(vec3(position) - centerFraction + outward * overlap, 1.0); - units = vec2(alongRun * run, alongReach * reach); - firstCell = face.xy; - } - """.formatted(TerrainHole.WORDS, TerrainTile.COLUMNS, TerrainHole.CELL_COLUMNS, TerrainHole.CELLS_ACROSS); - - private static final String FACE_FRAGMENT_SHADER = """ - #version 330 core - uniform sampler2D colors; - uniform ivec2 runDirection; - uniform float shade; - in vec2 units; - flat in ivec2 firstCell; - flat in int run; - out vec4 fragment; - - float outlineStrength(float pixelsPerUnit) { - return clamp((pixelsPerUnit - %1$s) / (%2$s - %1$s), 0.0, 1.0); - } - - float lineStrength(float along, float unitsPerPixel) { - float pixelsPerUnit = 1.0 / max(unitsPerPixel, 1e-6); - if (pixelsPerUnit < %1$s || abs(along - round(along)) * pixelsPerUnit >= %3$s) { - return 0.0; - } - return outlineStrength(pixelsPerUnit); - } - - void main() { - int along = clamp(int(floor(units.x)), 0, run - 1); - vec3 color = min(texelFetch(colors, firstCell + runDirection * along, 0).rgb * shade, vec3(1.0)); - vec2 unitsPerPixel = fwidth(units); - float strength = lineStrength(units.x, unitsPerPixel.x); - if (strength == 0.0) { - strength = lineStrength(units.y, unitsPerPixel.y); - } - float luminance = dot(color, vec3(0.3, 0.59, 0.11)) * 255.0; - vec3 outline = luminance < %4$s ? mix(color, vec3(1.0), %5$s) : color * %6$s; - fragment = vec4(mix(color, outline, strength), 1.0); - } - """.formatted(NoiseTerrainRenderer.LEAST_OUTLINE_SPACING_PIXELS, NoiseTerrainRenderer.FULL_OUTLINE_SPACING_PIXELS, - NoiseTerrainRenderer.OUTLINE_HALF_WIDTH_PIXELS, NoiseTerrainRenderer.DARK_LUMINANCE, - NoiseTerrainRenderer.OUTLINE_LIGHTENING, NoiseTerrainRenderer.OUTLINE_SHADE); - - private static final String FLAT_VERTEX_SHADER = """ - #version 330 core - uniform mat4 toClip; - uniform vec3 corner; - uniform vec3 edgeU; - uniform vec3 edgeV; - - void main() { - float alongU = float(gl_VertexID & 1); - float alongV = float(gl_VertexID >> 1); - gl_Position = toClip * vec4(corner + alongU * edgeU + alongV * edgeV, 1.0); - } - """; - - private static final String FLAT_FRAGMENT_SHADER = """ - #version 330 core - uniform vec4 color; - out vec4 fragment; - - void main() { - fragment = color; - } - """; - - private static GpuTerrainRenderer onCard; - - private final GpuProgram facesProgram = GpuProgram.of(FACE_VERTEX_SHADER, FACE_FRAGMENT_SHADER); - private final GpuProgram flatProgram = GpuProgram.of(FLAT_VERTEX_SHADER, FLAT_FRAGMENT_SHADER); - private final int attributelessVertexArray = glGenVertexArrays(); - // Asked once: asking the card waits for everything sent to it so far. - private final int mostFacesPerLayer = glGetInteger(GL_MAX_TEXTURE_BUFFER_SIZE); - private final int largestColorsSide = glGetInteger(GL_MAX_TEXTURE_SIZE); - private final GpuTileCache uploadedTiles = new GpuTileCache(); - - /** - * @return the picture, or nothing when the card can't draw this scene and the caller should draw it without one - */ - static Optional render(NoiseTerrainScene scene, OrbitCamera camera, int width, int height, int coveredLeftWidth) { - return GpuFrames.drawPicture(target -> onCard().draw(scene, camera, width, height, coveredLeftWidth, target)); - } - - /** - * @return the frame, or nothing when it can't go straight into the window and the caller should draw a picture - */ - static Optional renderOnScreen(NoiseTerrainScene scene, ScreenTarget screen, OrbitCamera camera, int width, int height, - int coveredLeftWidth) { - return GpuFrames.drawOnScreen(screen, target -> onCard().draw(scene, camera, width, height, coveredLeftWidth, target)); - } - - private static GpuTerrainRenderer onCard() { - if (onCard == null) { - onCard = new GpuTerrainRenderer(); - } - return onCard; - } - - /** - * Draws what of the scene is on the card. What isn't yet is put there over the next frames, as the picture asks to - * be drawn again, so turning the camera never waits on new ground being put on the card. - */ - private Optional draw(NoiseTerrainScene scene, OrbitCamera camera, int width, int height, int coveredLeftWidth, - GpuFrameTarget target) { - Uploads uploads = uploadWithinBudget(scene); - if (uploads == null) { - return Optional.empty(); - } - OrbitPicture picture = drawLayers(scene, uploads.layers(), camera, width, height, coveredLeftWidth, target); - return Optional.of(uploads.complete() ? picture : picture.stillCatchingUp()); - } - - private OrbitPicture drawLayers(NoiseTerrainScene scene, List layers, OrbitCamera camera, int width, int height, - int coveredLeftWidth, GpuFrameTarget target) { - OrbitProjection projection = scene.projection(camera, width, height, coveredLeftWidth); - NoiseTerrainScene.Extent extent = scene.extent(); - double depthRange = extent.farthestFrom(projection.center()) + DEPTH_MARGIN_BLOCKS; - float[] toClip = projection.clipMatrix(width, height, depthRange); - target.bindSized(width, height); - GpuFrames.clearToBackground(); - for (UploadedLayer layer : layers) { - drawFaces(layer, projection, toClip); - } - if (scene.hasWater()) { - drawWater(extent, BlockFaces.blockTop(scene.waterLevel()), projection, toClip); - } - GpuFrames.failOnError(); - return target.finish(projection, depthRange); - } - - /** - * Puts as many of the scene's layers on the card as fit in one frame's time, reusing what is already there, and - * says how to draw what is there. A place whose newest ground isn't on the card yet is drawn with what is, such as - * the ground from before the heights changed. Tiles the scene doesn't show stay on the card while they fit and are - * still in memory, as turning back to them is likely. - * - * @return the layers on the card, or null when one is too large for it - */ - private Uploads uploadWithinBudget(NoiseTerrainScene scene) { - UploadProgress progress = uploadCoarsestFirst(scene.layers()); - if (progress == UploadProgress.TOO_LARGE) { - return null; - } - List layers = layersOnCard(scene.layers()); - Set shown = new HashSet<>(); - for (HoledLayer layer : scene.layers()) { - shown.add(GpuTileCache.Place.of(layer.terrain())); - } - uploadedTiles.forgetBeyond(MOST_UPLOADED_BYTES, shown); - return new Uploads(layers, progress == UploadProgress.COMPLETE); - } - - // Coarse tiles cover the most ground for their upload, so they go first; finer ones then only cut their holes. - private UploadProgress uploadCoarsestFirst(List layers) { - long deadline = System.nanoTime() + UPLOAD_NANOS_PER_FRAME; - List coarsestFirst = new ArrayList<>(layers); - coarsestFirst.sort(Comparator.comparingInt((HoledLayer layer) -> layer.terrain().step()).reversed()); - UploadProgress progress = UploadProgress.COMPLETE; - for (HoledLayer layer : coarsestFirst) { - GpuTileCache.Place place = GpuTileCache.Place.of(layer.terrain()); - GpuTile tile = uploadedTiles.get(place); - if (tile != null && tile.shows(layer.layer())) { - continue; - } - if (System.nanoTime() > deadline) { - progress = UploadProgress.CATCHING_UP; - continue; - } - if (upload(layer.layer(), place, tile) == null) { - return UploadProgress.TOO_LARGE; - } - } - return progress; - } - - // A hole is only cut where what fills it is on the card, so no ground is ever left out with nothing in its place. - // Tiles whose fillers are all on the card show nothing, so they aren't drawn at all. - private List layersOnCard(List layers) { - List onCard = new ArrayList<>(layers.size()); - for (HoledLayer layer : layers) { - GpuTile tile = uploadedTiles.get(GpuTileCache.Place.of(layer.terrain())); - if (tile == null) { - continue; - } - TerrainHole hole = layer.holeAmong(filler -> uploadedTiles.get(GpuTileCache.Place.of(filler)) != null); - if (!hole.hidesAll()) { - onCard.add(new UploadedLayer(layer.terrain(), tile.faces(), tile.colors(), hole)); - } - } - return onCard; - } - - private GpuTile upload(TerrainLayer layer, GpuTileCache.Place place, GpuTile previous) { - if (previous != null) { - return previous.showInstead(layer, largestColorsSide, mostFacesPerLayer) ? previous : null; - } - GpuTile tile = GpuTile.upload(layer, largestColorsSide, mostFacesPerLayer); - if (tile != null) { - uploadedTiles.put(place, tile); - } - return tile; - } - - // Faces looking away from the camera are hidden behind the ones looking toward it, so they're never drawn. - private void drawFaces(UploadedLayer layer, OrbitProjection projection, float[] toClip) { - Vec3 center = projection.center(); - int wholeX = (int) Math.floor(center.x()); - int wholeY = (int) Math.floor(center.y()); - int wholeZ = (int) Math.floor(center.z()); - facesProgram.use(); - facesProgram.setMatrix("toClip", toClip); - facesProgram.set("colors", 0); - facesProgram.set("faces", 1); - facesProgram.set("layerOrigin", layer.terrain().originX() - wholeX, -wholeY, layer.terrain().originZ() - wholeZ); - facesProgram.set("centerFraction", new Vec3(center.x() - wholeX, center.y() - wholeY, center.z() - wholeZ)); - facesProgram.set("step", layer.terrain().step()); - facesProgram.set("overlap", FACE_OVERLAP_PIXELS / projection.pixelsPerBlock()); - facesProgram.set("hiddenCells", layer.hole().hiddenCells()); - glActiveTexture(GL_TEXTURE0); - layer.colors().bind(); - glActiveTexture(GL_TEXTURE1); - layer.faces().bind(); - glBindVertexArray(attributelessVertexArray); - for (BlockFaces.Kind kind : BlockFaces.Kind.values()) { - facesProgram.set("holeWall", kind == BlockFaces.Kind.HOLE_WALL ? 1 : 0); - for (BlockFaces.Facing facing : BlockFaces.Facing.values()) { - drawFacing(layer.faces(), kind, facing, projection); - } - } - glActiveTexture(GL_TEXTURE0); - } - - private void drawFacing(GpuFaces faces, BlockFaces.Kind kind, BlockFaces.Facing facing, OrbitProjection projection) { - int count = faces.count(kind, facing); - if (count == 0 || !projection.facesCamera(facing.normalX, facing.normalY, facing.normalZ)) { - return; - } - facesProgram.set("firstFace", faces.first(kind, facing)); - facesProgram.set("normal", facing.normalX, facing.normalY, facing.normalZ); - facesProgram.set("runDirection", facing.runsAlongX() ? 1 : 0, facing.runsAlongX() ? 0 : 1); - facesProgram.set("shade", NoiseTerrainRenderer.faceShadeAt(facing, projection.pixelsPerBlock())); - glDrawArrays(GL_TRIANGLES, 0, count * GpuFaces.CORNERS_PER_FACE); - } - - // Water is blended over what lies below its surface, and hides nothing behind it. Ground level with the water's - // surface stays dry rather than flickering between the two. - private void drawWater(NoiseTerrainScene.Extent extent, int level, OrbitProjection projection, float[] toClip) { - glEnable(GL_BLEND); - glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); - glDepthMask(false); - glEnable(GL_POLYGON_OFFSET_FILL); - glPolygonOffset(1F, 1F); - Vec3 center = projection.center(); - flatProgram.use(); - flatProgram.setMatrix("toClip", toClip); - flatProgram.set("corner", new Vec3(extent.minX() - center.x(), level - center.y(), extent.minZ() - center.z())); - flatProgram.set("edgeU", new Vec3(extent.sizeX(), 0D, 0D)); - flatProgram.set("edgeV", new Vec3(0D, 0D, extent.sizeZ())); - int color = NoiseTerrainRenderer.WATER_COLOR; - flatProgram.set("color", GpuFrames.channel(color, 16), GpuFrames.channel(color, 8), GpuFrames.channel(color, 0), - NoiseTerrainRenderer.WATER_OPACITY); - glBindVertexArray(attributelessVertexArray); - glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); - } - - private record Uploads(List layers, boolean complete) { - } - - private enum UploadProgress { - COMPLETE, - CATCHING_UP, - TOO_LARGE - } - - private record UploadedLayer(NoiseTerrain terrain, GpuFaces faces, GpuColors colors, TerrainHole hole) { - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/GpuTile.java b/core/src/main/java/art/arcane/iris/studio/map/GpuTile.java deleted file mode 100644 index e0dad7359..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/GpuTile.java +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.lang.ref.WeakReference; - -/** - * A place on the ground on the graphics card: the colours and faces of the terrain last sampled there. They're put on - * the card once, whole, and stay as finer tiles inside come and go, since the face shader leaves out whatever hole they - * cut. When the noise or its heights change, the place is sampled anew; until the newest terrain is on the card, the - * older one still covers the place. Only for the GPU thread. - */ -final class GpuTile implements GpuCache.Upload { - private GpuColors colors; - private GpuFaces faces; - // Held weakly, so ground no longer drawn can be dropped from memory while its upload still stands in for it. - private WeakReference source; - - private GpuTile(GpuColors colors, GpuFaces faces, TerrainLayer source) { - this.colors = colors; - this.faces = faces; - this.source = new WeakReference<>(source); - } - - /** - * @param largestSide the card's GL_MAX_TEXTURE_SIZE - * @param mostFaces the card's GL_MAX_TEXTURE_BUFFER_SIZE - * @return the tile, or null when its terrain has more columns or rows than the card's textures can hold - */ - static GpuTile upload(TerrainLayer layer, int largestSide, int mostFaces) { - GpuColors colors = GpuColors.upload(layer.terrain(), largestSide); - if (colors == null) { - return null; - } - try { - return new GpuTile(colors, GpuFaces.upload(layer.faces(), mostFaces), layer); - } catch (RuntimeException failure) { - colors.delete(); - throw failure; - } - } - - boolean shows(TerrainLayer wanted) { - return source.get() == wanted; - } - - // Ground whose terrain is gone from memory is drawn only while nothing newer for its place is on the card. - boolean showsForgottenTerrain() { - return source.get() == null; - } - - /** - * @return false when the layer's terrain has more columns or rows than the card's textures can hold - */ - boolean showInstead(TerrainLayer wanted, int largestSide, int mostFaces) { - GpuTile next = upload(wanted, largestSide, mostFaces); - if (next == null) { - return false; - } - delete(); - colors = next.colors; - faces = next.faces; - source = next.source; - return true; - } - - GpuColors colors() { - return colors; - } - - GpuFaces faces() { - return faces; - } - - @Override - public long bytes() { - return colors.bytes() + faces.bytes(); - } - - @Override - public void delete() { - colors.delete(); - faces.delete(); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/GpuTileCache.java b/core/src/main/java/art/arcane/iris/studio/map/GpuTileCache.java deleted file mode 100644 index 63698660f..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/GpuTileCache.java +++ /dev/null @@ -1,82 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.Map; -import java.util.Set; - -/** - * The ground on the graphics card by where it lies, so ground sampled anew for a place replaces what was there, which - * covers the place until then. Only for the GPU thread. - */ -final class GpuTileCache { - private final LinkedHashMap leastRecentlyUsedFirst = new LinkedHashMap<>(16, 0.75F, true); - - GpuTile get(Place place) { - return leastRecentlyUsedFirst.get(place); - } - - void put(Place place, GpuTile tile) { - leastRecentlyUsedFirst.put(place, tile); - } - - /** - * Deletes ground not shown whose terrain is gone from memory, as it can never be drawn again, then the least - * recently used until the cache fits, sparing what is shown. - */ - void forgetBeyond(long mostBytes, Set shown) { - long bytes = 0L; - Iterator> oldestFirst = leastRecentlyUsedFirst.entrySet().iterator(); - while (oldestFirst.hasNext()) { - Map.Entry entry = oldestFirst.next(); - if (!shown.contains(entry.getKey()) && entry.getValue().showsForgottenTerrain()) { - entry.getValue().delete(); - oldestFirst.remove(); - } else { - bytes += entry.getValue().bytes(); - } - } - oldestFirst = leastRecentlyUsedFirst.entrySet().iterator(); - while (bytes > mostBytes && oldestFirst.hasNext()) { - Map.Entry entry = oldestFirst.next(); - if (!shown.contains(entry.getKey())) { - bytes -= entry.getValue().bytes(); - entry.getValue().delete(); - oldestFirst.remove(); - } - } - } - - /** - * Where a tile's ground lies, and how coarse it is. - */ - record Place(int originX, int originZ, int step) { - static Place of(NoiseTerrain terrain) { - return new Place(terrain.originX(), terrain.originZ(), terrain.step()); - } - - // The same place as the tile's terrain once sampled. - static Place of(TerrainTile tile) { - TerrainGrid grid = tile.grid(); - return new Place(grid.originX(), grid.originZ(), grid.step()); - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/GpuWindowFrame.java b/core/src/main/java/art/arcane/iris/studio/map/GpuWindowFrame.java deleted file mode 100644 index 9739a02ff..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/GpuWindowFrame.java +++ /dev/null @@ -1,96 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.awt.Rectangle; -import java.awt.image.BufferedImage; -import java.awt.image.DataBufferInt; -import java.util.ArrayList; -import java.util.List; - -import static org.lwjgl.opengl.GL30.GL_BACK; -import static org.lwjgl.opengl.GL30.GL_BGRA; -import static org.lwjgl.opengl.GL30.GL_FRAMEBUFFER; -import static org.lwjgl.opengl.GL30.GL_UNSIGNED_INT_8_8_8_8_REV; -import static org.lwjgl.opengl.GL30.glBindFramebuffer; -import static org.lwjgl.opengl.GL30.glDrawBuffer; -import static org.lwjgl.opengl.GL30.glReadBuffer; -import static org.lwjgl.opengl.GL30.glReadPixels; -import static org.lwjgl.opengl.GL30.glViewport; - -/** - * A frame drawn straight into a view's window. Of what was drawn, only the patches Swing paints where panels float - * over the window are read back. The frame waits in the window's back buffer until {@link GpuFrames#showOnScreen}, - * so it can go on screen together with its patches. Only for the GPU thread. - */ -final class GpuWindowFrame implements GpuFrameTarget { - private static final int WINDOW_FRAMEBUFFER = 0; - - private final List seeThrough; - private int width; - private int height; - - /** - * @param seeThrough the parts of the view panels float over, which Swing paints instead of the window - */ - GpuWindowFrame(List seeThrough) { - this.seeThrough = seeThrough; - } - - // The context was first made current without any window, which left it drawing into no buffer; NVIDIA's driver - // keeps that once a window comes along. - @Override - public void bindSized(int nextWidth, int nextHeight) { - width = nextWidth; - height = nextHeight; - glBindFramebuffer(GL_FRAMEBUFFER, WINDOW_FRAMEBUFFER); - glDrawBuffer(GL_BACK); - glReadBuffer(GL_BACK); - glViewport(0, 0, width, height); - } - - @Override - public OrbitPicture finish(OrbitProjection projection, double depthRange) { - return OrbitPicture.onScreen(width, height, readPatches(), GpuFrameTarget.depthInMiddle(projection, depthRange, width, height)); - } - - private List readPatches() { - Rectangle frame = new Rectangle(0, 0, width, height); - List patches = new ArrayList<>(seeThrough.size()); - for (Rectangle part : seeThrough) { - Rectangle inFrame = part.intersection(frame); - if (!inFrame.isEmpty()) { - patches.add(read(inFrame)); - } - } - return patches; - } - - // Rows come bottom up. - private PicturePatch read(Rectangle area) { - int[] rows = new int[area.width * area.height]; - glReadPixels(area.x, height - area.y - area.height, area.width, area.height, GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, rows); - BufferedImage image = new BufferedImage(area.width, area.height, BufferedImage.TYPE_INT_RGB); - int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); - for (int row = 0; row < area.height; row++) { - System.arraycopy(rows, (area.height - 1 - row) * area.width, pixels, row * area.width, area.width); - } - return new PicturePatch(area.x, area.y, image); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/GroundSight.java b/core/src/main/java/art/arcane/iris/studio/map/GroundSight.java deleted file mode 100644 index cc5bbff93..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/GroundSight.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.util.ArrayList; -import java.util.List; -import java.util.Optional; -import java.util.function.DoubleBinaryOperator; - -/** - * How the 3D terrain view looks at the ground for one camera: which ground lies under a pixel, and which ground is on - * screen. The ground's height is asked for anew, so it holds wherever tiles are still coarse or missing. - * - * @param left where the part of the view no panel floats over starts - * @param floorY the lowest the ground goes, as far as the view knows - * @param topY the highest the ground goes, as far as the view knows - */ -record GroundSight(OrbitProjection projection, int left, int width, int height, int floorY, int topY) { - // Across the ground per step along a line of sight, so no column is stepped over. - private static final double MARCH_STEP_BLOCKS = 1D; - private static final int REFINE_STEPS = 10; - - /** - * The ground drawn at a pixel: the first point down the line of sight that lies below the surface. - * - * @param surfaceY the ground's height at a spot, or the water's where that is higher - */ - Optional groundAt(double screenX, double screenY, DoubleBinaryOperator surfaceY) { - double sinPitch = projection.towardCamera().y(); - double stepY = MARCH_STEP_BLOCKS * sinPitch / Math.sqrt(Math.max(1E-6, 1D - sinPitch * sinPitch)); - double aboveY = topY; - for (double y = topY; y >= floorY; y -= stepY) { - Vec3 point = projection.pointAt(screenX, screenY, y); - if (surfaceY.applyAsDouble(point.x(), point.z()) >= y) { - return Optional.of(refine(screenX, screenY, aboveY, y, surfaceY)); - } - aboveY = y; - } - return Optional.empty(); - } - - // Halves the stretch of the line of sight where it passes into the ground until the point sits on the surface. - private Vec3 refine(double screenX, double screenY, double aboveY, double belowY, DoubleBinaryOperator surfaceY) { - double above = aboveY; - double below = belowY; - for (int step = 0; step < REFINE_STEPS; step++) { - double middle = (above + below) / 2D; - Vec3 point = projection.pointAt(screenX, screenY, middle); - if (surfaceY.applyAsDouble(point.x(), point.z()) >= middle) { - below = middle; - } else { - above = middle; - } - } - Vec3 point = projection.pointAt(screenX, screenY, below); - return new Vec3(point.x(), surfaceY.applyAsDouble(point.x(), point.z()), point.z()); - } - - /** - * Spots spread evenly over the ground on screen, about {@code most} of them over the stretch the view can reach. The - * view looks along parallel lines, so even on the ground is even on screen, but for slopes and hidden valleys. The - * spots keep to a grid fixed in the world, so turning the view a little doesn't change which spots are counted. - */ - List groundInView(int most, DoubleBinaryOperator surfaceY) { - Reach reach = reach(); - double spacing = gridSpacing(reach, most); - List spots = new ArrayList<>(); - for (double z = Math.floor(reach.minZ() / spacing) * spacing; z <= reach.maxZ(); z += spacing) { - for (double x = Math.floor(reach.minX() / spacing) * spacing; x <= reach.maxX(); x += spacing) { - double y = surfaceY.applyAsDouble(x, z); - if (isOnScreen(x, y, z)) { - spots.add(new Vec3(x, y, z)); - } - } - } - return spots; - } - - private boolean isOnScreen(double x, double y, double z) { - double screenX = projection.screenX(x, y, z); - double screenY = projection.screenY(x, y, z); - return screenX >= left && screenX < width && screenY >= 0D && screenY < height; - } - - // The ground the view's corners look at, from the floor to the top. - private Reach reach() { - double minX = Double.POSITIVE_INFINITY; - double minZ = Double.POSITIVE_INFINITY; - double maxX = Double.NEGATIVE_INFINITY; - double maxZ = Double.NEGATIVE_INFINITY; - for (double screenX : new double[]{left, width}) { - for (double screenY : new double[]{0D, height}) { - for (double groundY : new double[]{floorY, topY}) { - Vec3 point = projection.pointAt(screenX, screenY, groundY); - minX = Math.min(minX, point.x()); - minZ = Math.min(minZ, point.z()); - maxX = Math.max(maxX, point.x()); - maxZ = Math.max(maxZ, point.z()); - } - } - } - return new Reach(minX, minZ, maxX, maxZ); - } - - // A whole power of two, so zooming only changes the grid when the spacing has doubled or halved. - private static double gridSpacing(Reach reach, int most) { - double area = Math.max(1D, (reach.maxX() - reach.minX()) * (reach.maxZ() - reach.minZ())); - double spacing = Math.sqrt(area / Math.max(1, most)); - return Math.pow(2D, Math.ceil(Math.log(Math.max(1D, spacing)) / Math.log(2D))); - } - - private record Reach(double minX, double minZ, double maxX, double maxZ) { - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/HoledLayer.java b/core/src/main/java/art/arcane/iris/studio/map/HoledLayer.java deleted file mode 100644 index 351d3f59e..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/HoledLayer.java +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.util.List; -import java.util.function.Predicate; - -/** - * A tile's ground as the 3D noise view shows it, less the finer tiles inside it that are ready to fill their part. The - * hole is cut when drawing, from the fillers that are drawable by then, so ground is never left out before what fills - * it can be drawn. - */ -record HoledLayer(TerrainTile tile, TerrainLayer layer, List fillers) { - TerrainHole holeAmong(Predicate drawable) { - return TerrainHole.of(tile, fillers.stream().filter(drawable).toList()); - } - - TerrainHole holeOfAllFillers() { - return TerrainHole.of(tile, fillers); - } - - NoiseTerrain terrain() { - return layer.terrain(); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/ImageMapExplorer.java b/core/src/main/java/art/arcane/iris/studio/map/ImageMapExplorer.java deleted file mode 100644 index f6be87580..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/ImageMapExplorer.java +++ /dev/null @@ -1,1041 +0,0 @@ -package art.arcane.iris.studio.map; - -import art.arcane.iris.pack.loading.IrisData; -import art.arcane.iris.localization.DesktopUiMessages; -import art.arcane.iris.localization.IrisLanguage; -import art.arcane.iris.studio.workspace.ImageMapStudioExporter; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.generation.terrain.IrisDimension; -import art.arcane.iris.generation.image.IrisImageMap; -import art.arcane.iris.generation.image.IrisImageMapAlpha; -import art.arcane.iris.generation.image.IrisImageMapApplication; -import art.arcane.iris.generation.image.IrisImageMapBinding; -import art.arcane.iris.generation.image.IrisImageMapMask; -import art.arcane.iris.generation.image.IrisImageMapMaskOperation; -import art.arcane.iris.generation.image.IrisImageMapOrigin; -import art.arcane.iris.generation.image.IrisImageMapOutOfBounds; -import art.arcane.iris.generation.image.IrisImageMapRotation; -import art.arcane.iris.generation.image.IrisImageMapSampling; -import art.arcane.iris.generation.image.IrisImageMapType; -import art.arcane.iris.generation.image.IrisImageMapUnknownColor; -import art.arcane.iris.world.IrisWorldBoundary; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.volmlib.util.collection.KMap; -import art.arcane.volmlib.util.localization.TextKey; - -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.DefaultComboBoxModel; -import javax.swing.DefaultCellEditor; -import javax.swing.JButton; -import javax.swing.JCheckBox; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JFileChooser; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JSplitPane; -import javax.swing.JTable; -import javax.swing.JTextArea; -import javax.swing.JTextField; -import javax.swing.ListSelectionModel; -import javax.swing.SwingWorker; -import javax.swing.filechooser.FileNameExtensionFilter; -import javax.swing.table.DefaultTableModel; -import java.awt.BorderLayout; -import java.awt.CardLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.FlowLayout; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.GridLayout; -import java.awt.Insets; -import java.io.File; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Objects; -import java.util.function.DoubleBinaryOperator; - -/** - * The map window's Image maps view: turns a PNG into terrain height, biomes or a mask, previews it on the world and - * exports it into the pack. - */ -final class ImageMapExplorer { - private static final int EDITOR_WIDTH = 470; - private static final int OVERLAY_COLUMNS = 2; - private static final int TABLE_ROW_HEIGHT = 23; - private static final String STATUS_SEPARATOR = " · "; - - private final Engine engine; - private final File packFolder; - private final String dimensionKey; - private final ImageMapStudioPreviewPanel previewPanel = new ImageMapStudioPreviewPanel(); - private final StudioStatusBar statusBar = new StudioStatusBar(); - private final List controls = new ArrayList<>(); - private final JSplitPane view; - private final JComboBox presetPicker = new JComboBox<>(); - private final JTextField bindingKeyField = field("image-map"); - private final JTextField mapKeyField = field("image-map"); - private final JTextField imageKeyField = field("image-map"); - private final JComboBox typePicker = combo(IrisImageMapType.values()); - private final JComboBox applicationPicker = combo(IrisImageMapApplication.values()); - private final JTextField blocksPerPixelField = field("1"); - private final JTextField originXField = field("0"); - private final JTextField originZField = field("0"); - private final JTextField sourceOriginXField = field("0"); - private final JTextField sourceOriginZField = field("0"); - private final JComboBox rotationPicker = combo(IrisImageMapRotation.values()); - private final JCheckBox mirrorXCheck = check(); - private final JCheckBox mirrorZCheck = check(); - private final JComboBox samplingPicker = combo(IrisImageMapSampling.values()); - private final JComboBox outOfBoundsPicker = combo(IrisImageMapOutOfBounds.values()); - private final JTextField fallbackValueField = field("0"); - private final JTextField fallbackTargetField = field(""); - private final JComboBox alphaPicker = combo(IrisImageMapAlpha.values()); - private final JTextField minimumHeightField = field("-64"); - private final JTextField maximumHeightField = field("320"); - private final JTextField verticalOffsetField = field("0"); - private final JCheckBox clampCheck = check(); - private final JCheckBox heightInvertedCheck = check(); - private final JTextField heightCurveExponentField = field("1"); - private final JTextField heightSmoothingRadiusField = field("0"); - private final JCheckBox maskInvertedCheck = check(); - private final JTextField maskCurveExponentField = field("1"); - private final JTextField maskSmoothingRadiusField = field("0"); - private final JTextField thresholdField = field("0.5"); - private final JTextField falloffField = field("0"); - private final JTextField toleranceField = field("0"); - private final JComboBox unknownColorPicker = combo(IrisImageMapUnknownColor.values()); - private final DefaultTableModel legendModel = new DefaultTableModel(new Object[]{"#RRGGBB", "Target"}, 0); - private final JTable legendTable = new JTable(legendModel); - private final DefaultTableModel composedMaskModel = new DefaultTableModel( - new Object[]{"Binding", "Operation", "Invert", "Threshold", "Falloff"}, 0 - ) { - @Override - public Class getColumnClass(int columnIndex) { - return columnIndex == 2 ? Boolean.class : Object.class; - } - }; - private final JTable composedMaskTable = new JTable(composedMaskModel); - private final JPanel typeCards = new JPanel(new CardLayout()); - private final JTextArea metadataArea = area(3); - private final JTextArea diagnosticsArea = area(5); - private final JCheckBox chunksOverlay = selectedCheck(); - private final JCheckBox regionsOverlay = selectedCheck(); - private final JCheckBox boundaryOverlay = selectedCheck(); - private final JCheckBox coverageOverlay = selectedCheck(); - private Path sourcePath; - private IrisWorldBoundary boundary; - private boolean controlsUpdating; - - ImageMapExplorer(Engine engine) { - this.engine = Objects.requireNonNull(engine, "Image Map Studio engine"); - this.packFolder = engine.getPackSource().toFile(); - this.dimensionKey = engine.getDimension().getLoadKey(); - this.boundary = engine.getDimension().getWorldBoundary() == null - ? null - : IrisWorldBoundary.snapshot(engine.getDimension().getWorldBoundary()); - buildControls(); - this.view = buildWorkspace(); - setStatus(DesktopUiMessages.IMAGEMAP_READY); - configureControls(); - refreshPresets(); - } - - static void reloadActiveEngine(Engine engine) { - engine.hotloadSilently(); - } - - JComponent view() { - return view; - } - - JComponent statusBar() { - return statusBar; - } - - /** - * Starts the editor right of the floating view list instead of under it. - */ - void setCoveredLeftWidth(int width) { - view.setBorder(BorderFactory.createEmptyBorder(0, width, 0, 0)); - view.setDividerLocation(width + StudioTheme.scale(EDITOR_WIDTH)); - view.revalidate(); - } - - /** - * The toolbar buttons that belong to this view. - */ - List controls() { - return controls; - } - - /** - * Loads the first preset, once the view is on screen for the first time. - */ - void open() { - String selected = (String) presetPicker.getSelectedItem(); - if (selected != null && !selected.isBlank()) { - loadPreset(selected); - } - } - - void close() { - previewPanel.close(); - } - - private void configureControls() { - clampCheck.setSelected(true); - typePicker.setSelectedItem(IrisImageMapType.GRAYSCALE_HEIGHT); - applicationPicker.setSelectedItem(IrisImageMapApplication.TERRAIN_HEIGHT); - samplingPicker.setSelectedItem(IrisImageMapSampling.NEAREST); - outOfBoundsPicker.setSelectedItem(IrisImageMapOutOfBounds.FALLBACK); - alphaPicker.setSelectedItem(IrisImageMapAlpha.IGNORE); - unknownColorPicker.setSelectedItem(IrisImageMapUnknownColor.ERROR); - typePicker.addActionListener(event -> updateTypeControls()); - for (JCheckBox overlay : List.of(chunksOverlay, regionsOverlay, boundaryOverlay, coverageOverlay)) { - overlay.addActionListener(event -> updateOverlays()); - } - previewPanel.setDiagnosticConsumer(this::appendDiagnostic); - configureComposedMaskTable(); - updateTypeControls(); - updateOverlays(); - } - - private void buildControls() { - presetPicker.setPrototypeDisplayValue("terrain/example-long-preset"); - presetPicker.setToolTipText("Image maps already in the pack"); - presetPicker.setFocusable(false); - presetPicker.setMaximumSize(presetPicker.getPreferredSize()); - controls.add(StudioToolbar.label(text(DesktopUiMessages.IMAGEMAP_PRESET))); - controls.add(presetPicker); - controls.add(StudioToolbar.button(text(DesktopUiMessages.IMAGEMAP_LOAD), "Load the chosen image map", () -> { - String selected = (String) presetPicker.getSelectedItem(); - if (selected != null) { - loadPreset(selected); - } - })); - controls.add(StudioToolbar.button(text(DesktopUiMessages.IMAGEMAP_IMPORT_PNG), "Start a new image map from a PNG", - () -> chooseSource(false))); - controls.add(StudioToolbar.button(text(DesktopUiMessages.IMAGEMAP_REPLACE_PNG), "Swap the PNG behind this image map", - () -> chooseSource(true))); - controls.add(StudioToolbar.button(text(DesktopUiMessages.IMAGEMAP_PREVIEW), "Preview the image map on the world", - this::preview)); - controls.add(StudioToolbar.button(text(DesktopUiMessages.IMAGEMAP_EXPORT), "Write the image map into the pack and hotload", - this::export)); - } - - private JSplitPane buildWorkspace() { - JScrollPane editorScroll = new JScrollPane(buildEditor()); - editorScroll.setBorder(BorderFactory.createEmptyBorder()); - editorScroll.getVerticalScrollBar().setUnitIncrement(StudioTheme.scale(18)); - editorScroll.setPreferredSize(StudioTheme.scaledSize(EDITOR_WIDTH, 760)); - JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, editorScroll, previewPanel); - split.setBorder(BorderFactory.createEmptyBorder()); - split.setResizeWeight(0D); - split.setDividerLocation(StudioTheme.scale(EDITOR_WIDTH)); - split.putClientProperty("FlatLaf.style", "style: grip"); - return split; - } - - private JPanel buildEditor() { - JPanel editor = new ViewportWidthPanel(); - editor.setLayout(new BoxLayout(editor, BoxLayout.Y_AXIS)); - editor.setBackground(StudioTheme.PANEL_BACKGROUND); - editor.setBorder(StudioTheme.emptyBorder(10, 10, 10, 10)); - editor.add(section(DesktopUiMessages.IMAGEMAP_METADATA, metadataPanel())); - editor.add(Box.createVerticalStrut(StudioTheme.scale(9))); - editor.add(section(DesktopUiMessages.IMAGEMAP_RESOURCE, resourcePanel())); - editor.add(Box.createVerticalStrut(StudioTheme.scale(9))); - editor.add(section(DesktopUiMessages.IMAGEMAP_COORDINATES, coordinatePanel())); - editor.add(Box.createVerticalStrut(StudioTheme.scale(9))); - typeCards.add(heightPanel(), "HEIGHT"); - typeCards.add(colorPanel(), "COLOR"); - typeCards.add(maskPanel(), "MASK"); - typeCards.setOpaque(false); - typeCards.setAlignmentX(Component.LEFT_ALIGNMENT); - editor.add(typeCards); - editor.add(Box.createVerticalStrut(StudioTheme.scale(9))); - editor.add(section(DesktopUiMessages.IMAGEMAP_COMPOSED_MASKS, composedMaskPanel())); - editor.add(Box.createVerticalStrut(StudioTheme.scale(9))); - editor.add(section(DesktopUiMessages.IMAGEMAP_OVERLAYS, overlayPanel())); - editor.add(Box.createVerticalStrut(StudioTheme.scale(9))); - editor.add(section(DesktopUiMessages.IMAGEMAP_DIAGNOSTICS, diagnosticsPanel())); - return editor; - } - - private JPanel metadataPanel() { - metadataArea.setText(text(DesktopUiMessages.IMAGEMAP_NO_SOURCE)); - return single(metadataArea); - } - - private JPanel resourcePanel() { - JPanel panel = form(); - addRow(panel, 0, DesktopUiMessages.IMAGEMAP_BINDING_KEY, bindingKeyField); - addRow(panel, 1, DesktopUiMessages.IMAGEMAP_MAP_KEY, mapKeyField); - addRow(panel, 2, DesktopUiMessages.IMAGEMAP_IMAGE_KEY, imageKeyField); - addRow(panel, 3, DesktopUiMessages.IMAGEMAP_TYPE, typePicker); - addRow(panel, 4, DesktopUiMessages.IMAGEMAP_APPLICATION, applicationPicker); - return panel; - } - - private JPanel coordinatePanel() { - JPanel panel = form(); - addRow(panel, 0, DesktopUiMessages.IMAGEMAP_BLOCKS_PER_PIXEL, blocksPerPixelField); - addRow(panel, 1, DesktopUiMessages.IMAGEMAP_ORIGIN_X, originXField); - addRow(panel, 2, DesktopUiMessages.IMAGEMAP_ORIGIN_Z, originZField); - addRow(panel, 3, DesktopUiMessages.IMAGEMAP_SOURCE_ORIGIN_X, sourceOriginXField); - addRow(panel, 4, DesktopUiMessages.IMAGEMAP_SOURCE_ORIGIN_Z, sourceOriginZField); - addRow(panel, 5, DesktopUiMessages.IMAGEMAP_ROTATION, rotationPicker); - addRow(panel, 6, DesktopUiMessages.IMAGEMAP_MIRROR_X, mirrorXCheck); - addRow(panel, 7, DesktopUiMessages.IMAGEMAP_MIRROR_Z, mirrorZCheck); - addRow(panel, 8, DesktopUiMessages.IMAGEMAP_SAMPLING, samplingPicker); - addRow(panel, 9, DesktopUiMessages.IMAGEMAP_OUT_OF_BOUNDS, outOfBoundsPicker); - addRow(panel, 10, DesktopUiMessages.IMAGEMAP_ALPHA, alphaPicker); - addRow(panel, 11, DesktopUiMessages.IMAGEMAP_FALLBACK_VALUE, fallbackValueField); - addRow(panel, 12, DesktopUiMessages.IMAGEMAP_FALLBACK_TARGET, fallbackTargetField); - return panel; - } - - private JPanel heightPanel() { - JPanel panel = form(); - addRow(panel, 0, DesktopUiMessages.IMAGEMAP_MINIMUM_HEIGHT, minimumHeightField); - addRow(panel, 1, DesktopUiMessages.IMAGEMAP_MAXIMUM_HEIGHT, maximumHeightField); - addRow(panel, 2, DesktopUiMessages.IMAGEMAP_VERTICAL_OFFSET, verticalOffsetField); - addRow(panel, 3, DesktopUiMessages.IMAGEMAP_CLAMP, clampCheck); - addRow(panel, 4, DesktopUiMessages.IMAGEMAP_INVERTED, heightInvertedCheck); - addRow(panel, 5, DesktopUiMessages.IMAGEMAP_CURVE_EXPONENT, heightCurveExponentField); - addRow(panel, 6, DesktopUiMessages.IMAGEMAP_SMOOTHING_RADIUS, heightSmoothingRadiusField); - return section(DesktopUiMessages.IMAGEMAP_HEIGHT, panel); - } - - private JPanel maskPanel() { - JPanel panel = form(); - addRow(panel, 0, DesktopUiMessages.IMAGEMAP_THRESHOLD, thresholdField); - addRow(panel, 1, DesktopUiMessages.IMAGEMAP_FALLOFF, falloffField); - addRow(panel, 2, DesktopUiMessages.IMAGEMAP_INVERTED, maskInvertedCheck); - addRow(panel, 3, DesktopUiMessages.IMAGEMAP_CURVE_EXPONENT, maskCurveExponentField); - addRow(panel, 4, DesktopUiMessages.IMAGEMAP_SMOOTHING_RADIUS, maskSmoothingRadiusField); - return section(DesktopUiMessages.IMAGEMAP_MASK, panel); - } - - private JPanel colorPanel() { - JPanel panel = new JPanel(new BorderLayout(0, StudioTheme.scale(7))); - panel.setOpaque(false); - JPanel settings = form(); - addRow(settings, 0, DesktopUiMessages.IMAGEMAP_COLOR_TOLERANCE, toleranceField); - addRow(settings, 1, DesktopUiMessages.IMAGEMAP_UNKNOWN_COLOR, unknownColorPicker); - panel.add(settings, BorderLayout.NORTH); - configureTable(legendTable); - panel.add(tableScroll(legendTable, 160), BorderLayout.CENTER); - JPanel actions = new JPanel(new FlowLayout(FlowLayout.LEFT, StudioTheme.scale(6), 0)); - actions.setOpaque(false); - JButton add = button(DesktopUiMessages.IMAGEMAP_ADD_COLOR); - add.addActionListener(event -> legendModel.addRow(new Object[]{"#000000", "iris:"})); - actions.add(add); - JButton remove = button(DesktopUiMessages.IMAGEMAP_REMOVE_COLOR); - remove.addActionListener(event -> removeLegendRows()); - actions.add(remove); - panel.add(actions, BorderLayout.SOUTH); - return section(DesktopUiMessages.IMAGEMAP_COLOR_MAP, panel); - } - - private JPanel overlayPanel() { - JPanel panel = new JPanel(new GridLayout(0, OVERLAY_COLUMNS, StudioTheme.scale(9), StudioTheme.scale(2))); - panel.setOpaque(false); - chunksOverlay.setText(text(DesktopUiMessages.IMAGEMAP_CHUNKS)); - regionsOverlay.setText(text(DesktopUiMessages.IMAGEMAP_REGIONS)); - boundaryOverlay.setText(text(DesktopUiMessages.IMAGEMAP_BOUNDARY)); - coverageOverlay.setText(text(DesktopUiMessages.IMAGEMAP_COVERAGE)); - panel.add(chunksOverlay); - panel.add(regionsOverlay); - panel.add(boundaryOverlay); - panel.add(coverageOverlay); - return panel; - } - - private JPanel composedMaskPanel() { - JPanel panel = new JPanel(new BorderLayout(0, StudioTheme.scale(7))); - panel.setOpaque(false); - panel.add(tableScroll(composedMaskTable, 120), BorderLayout.CENTER); - JPanel actions = new JPanel(new FlowLayout(FlowLayout.LEFT, StudioTheme.scale(6), 0)); - actions.setOpaque(false); - JButton add = button(DesktopUiMessages.IMAGEMAP_ADD_MASK); - add.addActionListener(event -> composedMaskModel.addRow(new Object[]{ - "", IrisImageMapMaskOperation.MULTIPLY, false, "0", "0" - })); - actions.add(add); - JButton remove = button(DesktopUiMessages.IMAGEMAP_REMOVE_COLOR); - remove.addActionListener(event -> removeRows(composedMaskTable, composedMaskModel)); - actions.add(remove); - panel.add(actions, BorderLayout.SOUTH); - return panel; - } - - private JPanel diagnosticsPanel() { - diagnosticsArea.setText(text(DesktopUiMessages.IMAGEMAP_READY)); - return single(diagnosticsArea); - } - - private void refreshPresets() { - IrisData data = IrisData.openRuntime(packFolder); - try { - String[] keys = data.getImageMapLoader().getPossibleKeys(); - Arrays.sort(keys); - presetPicker.setModel(new DefaultComboBoxModel<>(keys)); - } finally { - data.close(); - } - } - - private void loadPreset(String key) { - setStatus(DesktopUiMessages.IMAGEMAP_LOADING); - new SwingWorker() { - @Override - protected PresetState doInBackground() throws Exception { - IrisData data = IrisData.openRuntime(packFolder); - try { - IrisImageMap loaded = data.getImageMapLoader().load(key); - if (loaded == null) { - throw new IllegalArgumentException("Image-map preset '" + key + "' could not be loaded"); - } - IrisImageMap definition = data.getGson().fromJson(data.getGson().toJson(loaded), IrisImageMap.class); - IrisDimension dimension = data.getDimensionLoader().load(dimensionKey); - String bindingKey = key; - IrisImageMapApplication application = suggestedApplication(definition.getType()); - List masks = List.of(); - if (dimension != null) { - for (IrisImageMapBinding binding : dimension.getImageMaps()) { - if (binding != null && key.equals(binding.getMap())) { - bindingKey = binding.getKey(); - application = binding.getApplication(); - masks = binding.getMasks() == null - ? List.of() - : List.copyOf(binding.getMasks()); - break; - } - } - } - File image = data.getImageLoader().findFile(definition.getSource()); - if (image == null || !image.isFile()) { - throw new IllegalArgumentException("Preset source PNG is missing: " + definition.getSource()); - } - IrisWorldBoundary loadedBoundary = dimension == null || dimension.getWorldBoundary() == null - ? null - : IrisWorldBoundary.snapshot(dimension.getWorldBoundary()); - return new PresetState( - definition, image.toPath(), key, bindingKey, application, masks, loadedBoundary - ); - } finally { - data.close(); - } - } - - @Override - protected void done() { - try { - PresetState state = get(); - boundary = state.boundary(); - sourcePath = state.source(); - controlsUpdating = true; - applyDefinition(state.definition()); - mapKeyField.setText(state.mapKey()); - bindingKeyField.setText(state.bindingKey()); - applicationPicker.setSelectedItem(state.application()); - applyMasks(state.masks()); - controlsUpdating = false; - preview(); - } catch (Exception exception) { - controlsUpdating = false; - showFailure(text(DesktopUiMessages.IMAGEMAP_LOAD_FAILED), exception); - } - } - }.execute(); - } - - private void chooseSource(boolean replacement) { - JFileChooser chooser = new JFileChooser(sourcePath == null ? packFolder : sourcePath.toFile().getParentFile()); - chooser.setDialogTitle(text(replacement - ? DesktopUiMessages.IMAGEMAP_REPLACE_PNG - : DesktopUiMessages.IMAGEMAP_IMPORT_PNG)); - chooser.setFileFilter(new FileNameExtensionFilter("PNG", "png")); - if (chooser.showOpenDialog(view) != JFileChooser.APPROVE_OPTION) { - return; - } - sourcePath = chooser.getSelectedFile().toPath().toAbsolutePath().normalize(); - if (!replacement) { - String key = ImageMapStudioModel.safeKey(chooser.getSelectedFile().getName()); - bindingKeyField.setText(key); - mapKeyField.setText(key); - imageKeyField.setText(key); - } - inspectSourceAndPreview(); - } - - private void inspectSourceAndPreview() { - Path inspectedPath = sourcePath; - setStatus(DesktopUiMessages.IMAGEMAP_PREVIEWING); - new SwingWorker() { - @Override - protected ImageMapStudioExporter.SourceInspection doInBackground() throws Exception { - return ImageMapStudioExporter.inspectSource(inspectedPath); - } - - @Override - protected void done() { - try { - ImageMapStudioExporter.SourceInspection inspection = get(); - ImageMapStudioModel.SourceMetadata metadata = ImageMapStudioModel.inspect( - inspectedPath, - inspection.source(), - inspection.format(), - inspection.colorProfile(), - inspection.minimumAlpha(), - inspection.maximumAlpha() - ); - metadataArea.setText(metadata.path() + "\n" + metadata.summary()); - previewPanel.setSource(inspection.source()); - preview(); - } catch (Exception exception) { - showFailure(text(DesktopUiMessages.IMAGEMAP_PREVIEW_FAILED), exception); - } - } - }.execute(); - } - - private void preview() { - IrisImageMap definition; - List currentMasks; - try { - definition = readDefinition(); - requireSource(); - currentMasks = readMasks(); - validateMaskApplication(currentMasks); - } catch (RuntimeException exception) { - showFailure(text(DesktopUiMessages.IMAGEMAP_PREVIEW_FAILED), exception); - return; - } - setStatus(DesktopUiMessages.IMAGEMAP_PREVIEWING); - diagnosticsArea.setText(""); - Path currentSource = sourcePath; - IrisImageMapApplication currentApplication = selected(applicationPicker, "application"); - DoubleBinaryOperator proceduralHeightSampler = null; - if (currentApplication == IrisImageMapApplication.TERRAIN_HEIGHT - && !engine.isClosed() - && engine.getComplex() != null) { - proceduralHeightSampler = (worldX, worldZ) -> engine.getComplex() - .sampleProceduralTerrainHeight(worldX, worldZ); - } - DoubleBinaryOperator currentProceduralHeightSampler = proceduralHeightSampler; - new SwingWorker() { - @Override - protected ImageMapStudioExporter.PreviewResult doInBackground() throws Exception { - return ImageMapStudioExporter.preview( - currentSource, definition, packFolder, dimensionKey, currentMasks - ); - } - - @Override - protected void done() { - try { - ImageMapStudioExporter.PreviewResult result = get(); - ImageMapStudioModel.SourceMetadata metadata = ImageMapStudioModel.inspect( - currentSource, - result.source(), - result.compiled().getSourceMetadata().format(), - result.colorProfile(), - result.compiled().getSourceMetadata().minimumAlpha(), - result.compiled().getSourceMetadata().maximumAlpha() - ); - metadataArea.setText(metadata.path() + "\n" + metadata.summary()); - previewPanel.setPreview( - result.source(), result.compiled(), result.maskSampler(), boundary, - currentApplication, engine.getMinHeight(), currentProceduralHeightSampler - ); - List warnings = ImageMapStudioModel.warnings( - definition, metadata.width(), metadata.height(), boundary - ); - warnings = new ArrayList<>(warnings); - if (result.compiled().getClippedPixelCount() > 0) { - warnings.add(result.compiled().getClippedPixelCount() - + " source height pixel(s) are clipped to the configured vertical range."); - } - if (result.compiled().getUnknownColorPixelCount() > 0) { - warnings.add(result.compiled().getUnknownColorPixelCount() - + " source color pixel(s) are absent from the legend and use the unknown-color policy."); - } - diagnosticsArea.setText(warnings.isEmpty() - ? text(DesktopUiMessages.IMAGEMAP_PREVIEW_VALID) - : String.join("\n", warnings)); - diagnosticsArea.setForeground(warnings.isEmpty() ? StudioTheme.SUCCESS : StudioTheme.TEXT); - setStatus(DesktopUiMessages.IMAGEMAP_READY); - } catch (Exception exception) { - showFailure(text(DesktopUiMessages.IMAGEMAP_PREVIEW_FAILED), exception); - } - } - }.execute(); - } - - private void export() { - IrisImageMap definition; - List masks; - try { - definition = readDefinition(); - requireSource(); - masks = readMasks(); - validateMaskApplication(masks); - } catch (RuntimeException exception) { - showFailure(text(DesktopUiMessages.IMAGEMAP_EXPORT_FAILED), exception); - return; - } - String bindingKey = bindingKeyField.getText().trim(); - String mapKey = mapKeyField.getText().trim(); - String imageKey = imageKeyField.getText().trim(); - IrisImageMapApplication application = selected(applicationPicker, "application"); - ImageMapStudioExporter.ExportRequest request = new ImageMapStudioExporter.ExportRequest( - packFolder, - dimensionKey, - bindingKey, - application, - mapKey, - imageKey, - definition, - sourcePath, - masks - ); - setStatus(DesktopUiMessages.IMAGEMAP_EXPORTING); - new SwingWorker() { - @Override - protected ImageMapStudioExporter.ExportResult doInBackground() throws Exception { - ImageMapStudioExporter.ExportResult result = ImageMapStudioExporter.export(request); - reloadActiveEngine(engine); - return result; - } - - @Override - protected void done() { - try { - ImageMapStudioExporter.ExportResult result = get(); - StringBuilder message = new StringBuilder(text(DesktopUiMessages.IMAGEMAP_EXPORTED)); - message.append('\n').append(result.imageMapFile()); - message.append('\n').append(result.imageFile()); - message.append('\n').append(result.dimensionFile()); - for (String warning : result.warnings()) { - message.append('\n').append(warning); - } - diagnosticsArea.setForeground(StudioTheme.SUCCESS); - diagnosticsArea.setText(message.toString()); - setStatus(DesktopUiMessages.IMAGEMAP_EXPORTED); - refreshPresets(); - presetPicker.setSelectedItem(mapKey); - } catch (Exception exception) { - showFailure(text(DesktopUiMessages.IMAGEMAP_EXPORT_FAILED), exception); - } - } - }.execute(); - } - - private IrisImageMap readDefinition() { - IrisImageMapType type = selected(typePicker, "type"); - IrisImageMap defaults = new IrisImageMap(); - boolean heightType = type == IrisImageMapType.GRAYSCALE_HEIGHT || type == IrisImageMapType.RGB_HEIGHT; - boolean maskType = type == IrisImageMapType.BINARY_MASK - || type == IrisImageMapType.GRAYSCALE_MASK - || type == IrisImageMapType.ALPHA_MASK; - boolean colorType = type == IrisImageMapType.COLOR_MAP; - IrisImageMap definition = new IrisImageMap() - .setSource(requiredText(imageKeyField, "Image key")) - .setType(type) - .setBlocksPerPixel(number(blocksPerPixelField, "Blocks per pixel")) - .setOrigin(new IrisImageMapOrigin( - number(originXField, "Origin X"), - number(originZField, "Origin Z") - )) - .setSourceOrigin(new IrisImageMapOrigin( - number(sourceOriginXField, "Source origin X"), - number(sourceOriginZField, "Source origin Z") - )) - .setRotation(selected(rotationPicker, "rotation")) - .setMirrorX(mirrorXCheck.isSelected()) - .setMirrorZ(mirrorZCheck.isSelected()) - .setSampling(selected(samplingPicker, "sampling")) - .setOutOfBounds(selected(outOfBoundsPicker, "out-of-bounds policy")) - .setFallbackValue(number(fallbackValueField, "Fallback value")) - .setFallbackTarget(fallbackTargetField.getText().trim()) - .setAlpha(selected(alphaPicker, "alpha policy")) - .setMinimumHeight(heightType - ? number(minimumHeightField, "Minimum height") : defaults.getMinimumHeight()) - .setMaximumHeight(heightType - ? number(maximumHeightField, "Maximum height") : defaults.getMaximumHeight()) - .setVerticalOffset(heightType - ? number(verticalOffsetField, "Vertical offset") : defaults.getVerticalOffset()) - .setClamp(heightType ? clampCheck.isSelected() : defaults.isClamp()) - .setInverted(heightType - ? heightInvertedCheck.isSelected() - : maskType && maskInvertedCheck.isSelected()) - .setCurveExponent(heightType - ? number(heightCurveExponentField, "Curve exponent") - : maskType - ? number(maskCurveExponentField, "Curve exponent") - : defaults.getCurveExponent()) - .setSmoothingRadius(heightType - ? integer(heightSmoothingRadiusField, "Smoothing radius") - : maskType - ? integer(maskSmoothingRadiusField, "Smoothing radius") - : defaults.getSmoothingRadius()) - .setThreshold(type == IrisImageMapType.BINARY_MASK - ? number(thresholdField, "Threshold") : defaults.getThreshold()) - .setFalloff(type == IrisImageMapType.BINARY_MASK - ? number(falloffField, "Falloff") : defaults.getFalloff()) - .setColorTolerance(colorType - ? number(toleranceField, "Color tolerance") : defaults.getColorTolerance()) - .setUnknownColor(colorType - ? selected(unknownColorPicker, "unknown-color policy") - : defaults.getUnknownColor()); - if (colorType) { - List rows = new ArrayList<>(); - for (int row = 0; row < legendModel.getRowCount(); row++) { - rows.add(new ImageMapStudioModel.LegendRow( - String.valueOf(legendModel.getValueAt(row, 0)), - String.valueOf(legendModel.getValueAt(row, 1)) - )); - } - KMap colors = ImageMapStudioModel.legend(rows); - definition.setColors(colors); - } - requiredText(bindingKeyField, "Binding key"); - requiredText(mapKeyField, "Image-map key"); - return ImageMapStudioModel.normalizeTypeSettings(definition); - } - - private void applyDefinition(IrisImageMap definition) { - imageKeyField.setText(definition.getSource()); - typePicker.setSelectedItem(definition.getType()); - blocksPerPixelField.setText(Double.toString(definition.getBlocksPerPixel())); - originXField.setText(Double.toString(definition.getOrigin().getX())); - originZField.setText(Double.toString(definition.getOrigin().getZ())); - sourceOriginXField.setText(Double.toString(definition.getSourceOrigin().getX())); - sourceOriginZField.setText(Double.toString(definition.getSourceOrigin().getZ())); - rotationPicker.setSelectedItem(definition.getRotation()); - mirrorXCheck.setSelected(definition.isMirrorX()); - mirrorZCheck.setSelected(definition.isMirrorZ()); - samplingPicker.setSelectedItem(definition.getSampling()); - outOfBoundsPicker.setSelectedItem(definition.getOutOfBounds()); - fallbackValueField.setText(Double.toString(definition.getFallbackValue())); - fallbackTargetField.setText(definition.getFallbackTarget()); - alphaPicker.setSelectedItem(definition.getAlpha()); - minimumHeightField.setText(Double.toString(definition.getMinimumHeight())); - maximumHeightField.setText(Double.toString(definition.getMaximumHeight())); - verticalOffsetField.setText(Double.toString(definition.getVerticalOffset())); - clampCheck.setSelected(definition.isClamp()); - heightInvertedCheck.setSelected(definition.isInverted()); - heightCurveExponentField.setText(Double.toString(definition.getCurveExponent())); - heightSmoothingRadiusField.setText(Integer.toString(definition.getSmoothingRadius())); - maskInvertedCheck.setSelected(definition.isInverted()); - maskCurveExponentField.setText(Double.toString(definition.getCurveExponent())); - maskSmoothingRadiusField.setText(Integer.toString(definition.getSmoothingRadius())); - thresholdField.setText(Double.toString(definition.getThreshold())); - falloffField.setText(Double.toString(definition.getFalloff())); - toleranceField.setText(Double.toString(definition.getColorTolerance())); - unknownColorPicker.setSelectedItem(definition.getUnknownColor()); - legendModel.setRowCount(0); - for (ImageMapStudioModel.LegendRow row : ImageMapStudioModel.legendRows(definition)) { - legendModel.addRow(new Object[]{row.color(), row.target()}); - } - updateTypeControls(); - } - - private void updateTypeControls() { - IrisImageMapType type = (IrisImageMapType) typePicker.getSelectedItem(); - if (type == null) { - return; - } - CardLayout layout = (CardLayout) typeCards.getLayout(); - layout.show(typeCards, typeCard(type)); - thresholdField.setEnabled(type == IrisImageMapType.BINARY_MASK); - falloffField.setEnabled(type == IrisImageMapType.BINARY_MASK); - if (controlsUpdating) { - return; - } - if (type == IrisImageMapType.COLOR_MAP || type == IrisImageMapType.BINARY_MASK) { - samplingPicker.setSelectedItem(IrisImageMapSampling.NEAREST); - } - if (type == IrisImageMapType.ALPHA_MASK) { - alphaPicker.setSelectedItem(IrisImageMapAlpha.IGNORE); - } - applicationPicker.setSelectedItem(suggestedApplication(type)); - } - - private static IrisImageMapApplication suggestedApplication(IrisImageMapType type) { - if (type == null) { - return IrisImageMapApplication.CUSTOM; - } - return switch (type) { - case GRAYSCALE_HEIGHT, RGB_HEIGHT -> IrisImageMapApplication.TERRAIN_HEIGHT; - case COLOR_MAP -> IrisImageMapApplication.BIOME; - case BINARY_MASK, GRAYSCALE_MASK, ALPHA_MASK -> IrisImageMapApplication.MASK; - }; - } - - private static String typeCard(IrisImageMapType type) { - return switch (type) { - case GRAYSCALE_HEIGHT, RGB_HEIGHT -> "HEIGHT"; - case COLOR_MAP -> "COLOR"; - case BINARY_MASK, GRAYSCALE_MASK, ALPHA_MASK -> "MASK"; - }; - } - - private void updateOverlays() { - previewPanel.setOverlays( - chunksOverlay.isSelected(), - regionsOverlay.isSelected(), - boundaryOverlay.isSelected(), - coverageOverlay.isSelected() - ); - } - - private static void configureTable(JTable table) { - table.setRowHeight(StudioTheme.scale(TABLE_ROW_HEIGHT)); - table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION); - } - - private void configureComposedMaskTable() { - configureTable(composedMaskTable); - composedMaskTable.getColumnModel().getColumn(1).setCellEditor( - new DefaultCellEditor(new JComboBox<>(IrisImageMapMaskOperation.values())) - ); - } - - private static JScrollPane tableScroll(JTable table, int height) { - JScrollPane scroll = new JScrollPane(table); - scroll.setPreferredSize(StudioTheme.scaledSize(390, height)); - scroll.setBorder(BorderFactory.createLineBorder(StudioTheme.CONTROL_BORDER)); - return scroll; - } - - private void removeLegendRows() { - removeRows(legendTable, legendModel); - } - - private static void removeRows(JTable table, DefaultTableModel model) { - int[] selected = table.getSelectedRows(); - for (int index = selected.length - 1; index >= 0; index--) { - model.removeRow(selected[index]); - } - } - - private List readMasks() { - List rows = new ArrayList<>(); - for (int row = 0; row < composedMaskModel.getRowCount(); row++) { - rows.add(ImageMapStudioModel.maskRow( - String.valueOf(composedMaskModel.getValueAt(row, 0)), - composedMaskModel.getValueAt(row, 1), - Boolean.TRUE.equals(composedMaskModel.getValueAt(row, 2)), - composedMaskModel.getValueAt(row, 3), - composedMaskModel.getValueAt(row, 4) - )); - } - return ImageMapStudioModel.masks(rows); - } - - private void applyMasks(List masks) { - composedMaskModel.setRowCount(0); - for (ImageMapStudioModel.MaskRow row : ImageMapStudioModel.maskRows(masks)) { - composedMaskModel.addRow(new Object[]{ - row.map(), row.operation(), row.inverted(), row.threshold(), row.falloff() - }); - } - } - - private void validateMaskApplication(List masks) { - if (selected(applicationPicker, "application") == IrisImageMapApplication.MASK && !masks.isEmpty()) { - throw new IllegalArgumentException("A MASK binding cannot reference composed masks"); - } - } - - private void appendDiagnostic(String diagnostic) { - if (diagnostic == null || diagnostic.isBlank()) { - return; - } - String current = diagnosticsArea.getText(); - diagnosticsArea.setForeground(StudioTheme.ERROR); - diagnosticsArea.setText(current.isBlank() ? diagnostic : current + "\n" + diagnostic); - } - - private void showFailure(String prefix, Exception exception) { - Throwable cause = exception; - while (cause.getCause() != null && cause != cause.getCause()) { - cause = cause.getCause(); - } - if (!(cause instanceof IllegalArgumentException)) { - IrisLogging.reportError(cause); - } - diagnosticsArea.setForeground(StudioTheme.ERROR); - diagnosticsArea.setText(prefix + ": " + String.valueOf(cause.getMessage())); - statusBar.showError(prefix); - } - - private void setStatus(TextKey key) { - statusBar.showSummary(packFolder.getName() + STATUS_SEPARATOR + dimensionKey + STATUS_SEPARATOR + text(key)); - } - - private void requireSource() { - if (sourcePath == null) { - throw new IllegalArgumentException(text(DesktopUiMessages.IMAGEMAP_NO_SOURCE)); - } - } - - private static JPanel form() { - JPanel panel = new JPanel(new GridBagLayout()); - panel.setOpaque(false); - return panel; - } - - private static void addRow(JPanel panel, int row, TextKey key, Component component) { - int rowGap = StudioTheme.scale(3); - GridBagConstraints labelConstraints = new GridBagConstraints(); - labelConstraints.gridx = 0; - labelConstraints.gridy = row; - labelConstraints.anchor = GridBagConstraints.WEST; - labelConstraints.insets = new Insets(rowGap, 0, rowGap, StudioTheme.scale(8)); - panel.add(label(key), labelConstraints); - - GridBagConstraints componentConstraints = new GridBagConstraints(); - componentConstraints.gridx = 1; - componentConstraints.gridy = row; - componentConstraints.weightx = 1D; - componentConstraints.fill = GridBagConstraints.HORIZONTAL; - componentConstraints.insets = new Insets(rowGap, 0, rowGap, 0); - panel.add(component, componentConstraints); - } - - private static JPanel section(TextKey title, Component content) { - JPanel panel = new JPanel(new BorderLayout()); - panel.setAlignmentX(Component.LEFT_ALIGNMENT); - panel.setOpaque(false); - panel.setBorder(BorderFactory.createLineBorder(StudioTheme.CONTROL_BORDER)); - JLabel heading = new JLabel(text(title)); - heading.setFont(StudioTheme.sectionFont()); - heading.setBorder(BorderFactory.createCompoundBorder( - BorderFactory.createMatteBorder(0, 0, 1, 0, StudioTheme.CONTROL_BORDER), - StudioTheme.emptyBorder(7, 9, 7, 9) - )); - panel.add(heading, BorderLayout.NORTH); - JPanel body = new JPanel(new BorderLayout()); - body.setOpaque(false); - body.setBorder(StudioTheme.emptyBorder(8, 9, 9, 9)); - body.add(content, BorderLayout.CENTER); - panel.add(body, BorderLayout.CENTER); - panel.setMaximumSize(new Dimension(Integer.MAX_VALUE, panel.getPreferredSize().height + StudioTheme.scale(300))); - return panel; - } - - private static JPanel single(Component component) { - JPanel panel = new JPanel(new BorderLayout()); - panel.setOpaque(false); - panel.add(component, BorderLayout.CENTER); - return panel; - } - - private static JLabel label(TextKey key) { - JLabel label = new JLabel(text(key)); - label.setForeground(StudioTheme.SECONDARY_TEXT); - label.setFont(StudioTheme.smallFont()); - return label; - } - - private static JButton button(TextKey key) { - JButton button = new JButton(text(key)); - button.setFocusable(false); - return button; - } - - private static JTextField field(String value) { - return new JTextField(value); - } - - private static JTextArea area(int rows) { - JTextArea area = new JTextArea(rows, 20); - area.setEditable(false); - area.setLineWrap(true); - area.setWrapStyleWord(true); - area.setBorder(StudioTheme.emptyBorder(6, 7, 6, 7)); - return area; - } - - private static JCheckBox check() { - JCheckBox check = new JCheckBox(); - check.setOpaque(false); - check.setFocusable(false); - return check; - } - - private static JCheckBox selectedCheck() { - JCheckBox check = check(); - check.setSelected(true); - return check; - } - - private static JComboBox combo(T[] values) { - JComboBox combo = new JComboBox<>(values); - combo.setFocusable(false); - return combo; - } - - private static double number(JTextField field, String name) { - double value; - try { - value = Double.parseDouble(field.getText().trim()); - } catch (NumberFormatException exception) { - throw new IllegalArgumentException(name + " must be a number", exception); - } - if (!Double.isFinite(value)) { - throw new IllegalArgumentException(name + " must be finite"); - } - return value; - } - - private static int integer(JTextField field, String name) { - try { - return Integer.parseInt(field.getText().trim()); - } catch (NumberFormatException exception) { - throw new IllegalArgumentException(name + " must be an integer", exception); - } - } - - private static String requiredText(JTextField field, String name) { - String value = field.getText().trim(); - if (value.isEmpty()) { - throw new IllegalArgumentException(name + " must not be blank"); - } - return value; - } - - private static T selected(JComboBox combo, String name) { - int index = combo.getSelectedIndex(); - if (index < 0) { - throw new IllegalArgumentException("A " + name + " is required"); - } - return combo.getItemAt(index); - } - - private static String text(TextKey key) { - return IrisLanguage.plain(key); - } - - private record PresetState( - IrisImageMap definition, - Path source, - String mapKey, - String bindingKey, - IrisImageMapApplication application, - List masks, - IrisWorldBoundary boundary - ) { - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/ImageMapStudioModel.java b/core/src/main/java/art/arcane/iris/studio/map/ImageMapStudioModel.java deleted file mode 100644 index d581de6ec..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/ImageMapStudioModel.java +++ /dev/null @@ -1,411 +0,0 @@ -package art.arcane.iris.studio.map; - -import art.arcane.iris.generation.image.IrisImage; -import art.arcane.iris.generation.image.IrisImageMap; -import art.arcane.iris.generation.image.IrisImageMapOrigin; -import art.arcane.iris.generation.image.IrisImageMapMask; -import art.arcane.iris.generation.image.IrisImageMapMaskOperation; -import art.arcane.iris.generation.image.IrisImageMapRotation; -import art.arcane.iris.generation.image.IrisImageMapType; -import art.arcane.iris.generation.image.IrisImageMapUnknownColor; -import art.arcane.iris.world.IrisWorldBoundary; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.collection.KMap; - -import java.awt.geom.Line2D; -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; -import java.nio.file.Path; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.regex.Pattern; - -public final class ImageMapStudioModel { - private static final Pattern COLOR = Pattern.compile("#[0-9a-fA-F]{6}"); - private static final Pattern KEY_CHARACTER = Pattern.compile("[^a-z0-9/._-]"); - - private ImageMapStudioModel() { - } - - public static SourceMetadata inspect(Path path, BufferedImage image, String format) { - return inspect(path, image, format, "not inspected", 1D, 1D); - } - - public static SourceMetadata inspect( - Path path, - BufferedImage image, - String format, - String colorProfile, - double minimumAlpha, - double maximumAlpha - ) { - IrisImage irisImage = new IrisImage(image, format); - return new SourceMetadata( - path.toAbsolutePath().normalize(), - irisImage.getFormat(), - irisImage.getWidth(), - irisImage.getHeight(), - (long) irisImage.getWidth() * irisImage.getHeight(), - irisImage.getColorMode().name(), - irisImage.getColorComponentCount(), - irisImage.getChannelCount(), - irisImage.getBitDepth(), - irisImage.hasAlpha(), - minimumAlpha, - maximumAlpha, - colorProfile - ); - } - - public static KMap legend(List rows) { - KMap colors = new KMap<>(); - for (LegendRow row : rows) { - String color = row.color() == null ? "" : row.color().trim().toUpperCase(Locale.ROOT); - String target = row.target() == null ? "" : row.target().trim(); - if (color.isEmpty() && target.isEmpty()) { - continue; - } - if (!COLOR.matcher(color).matches()) { - throw new IllegalArgumentException("Legend color must use #RRGGBB syntax: " + color); - } - if (target.isEmpty()) { - throw new IllegalArgumentException("Legend target must not be blank for " + color); - } - String previous = colors.put(color, target); - if (previous != null) { - throw new IllegalArgumentException("Legend contains duplicate color " + color); - } - } - return colors; - } - - public static List legendRows(IrisImageMap definition) { - List rows = new ArrayList<>(); - if (definition.getColors() == null) { - return rows; - } - for (Map.Entry entry : definition.getColors().entrySet()) { - rows.add(new LegendRow(entry.getKey().toUpperCase(Locale.ROOT), entry.getValue())); - } - rows.sort(Comparator.comparing(LegendRow::color)); - return rows; - } - - public static IrisImageMap normalizeTypeSettings(IrisImageMap definition) { - IrisImageMapType type = definition.getType(); - if (type == null) { - return definition; - } - IrisImageMap defaults = new IrisImageMap(); - switch (type) { - case GRAYSCALE_HEIGHT, RGB_HEIGHT -> definition - .setThreshold(defaults.getThreshold()) - .setFalloff(defaults.getFalloff()) - .setColorTolerance(defaults.getColorTolerance()) - .setUnknownColor(IrisImageMapUnknownColor.ERROR) - .setColors(new KMap<>()); - case COLOR_MAP -> definition - .setMinimumHeight(defaults.getMinimumHeight()) - .setMaximumHeight(defaults.getMaximumHeight()) - .setVerticalOffset(defaults.getVerticalOffset()) - .setClamp(defaults.isClamp()) - .setInverted(defaults.isInverted()) - .setCurveExponent(defaults.getCurveExponent()) - .setSmoothingRadius(defaults.getSmoothingRadius()) - .setThreshold(defaults.getThreshold()) - .setFalloff(defaults.getFalloff()); - case BINARY_MASK, GRAYSCALE_MASK, ALPHA_MASK -> { - definition - .setMinimumHeight(defaults.getMinimumHeight()) - .setMaximumHeight(defaults.getMaximumHeight()) - .setVerticalOffset(defaults.getVerticalOffset()) - .setClamp(defaults.isClamp()) - .setColorTolerance(defaults.getColorTolerance()) - .setUnknownColor(IrisImageMapUnknownColor.ERROR) - .setColors(new KMap<>()); - if (type != IrisImageMapType.BINARY_MASK) { - definition - .setThreshold(defaults.getThreshold()) - .setFalloff(defaults.getFalloff()); - } - } - } - return definition; - } - - public static KList masks(List rows) { - KList masks = new KList<>(); - for (MaskRow row : rows) { - masks.add(new IrisImageMapMask() - .setMap(row.map()) - .setOperation(row.operation()) - .setInverted(row.inverted()) - .setThreshold(row.threshold()) - .setFalloff(row.falloff())); - } - return masks; - } - - public static MaskRow maskRow( - String mapValue, - Object operationValue, - boolean inverted, - Object thresholdValue, - Object falloffValue - ) { - String map = mapValue == null ? "" : mapValue.trim(); - if (map.isBlank()) { - throw new IllegalArgumentException("Composed mask binding key must not be blank"); - } - IrisImageMapMaskOperation operation; - try { - operation = IrisImageMapMaskOperation.valueOf( - String.valueOf(operationValue).trim().toUpperCase(Locale.ROOT) - ); - } catch (IllegalArgumentException exception) { - throw new IllegalArgumentException("Unknown mask operation for '" + map + "'", exception); - } - double threshold = unitValue(thresholdValue, "Mask threshold for '" + map + "'"); - double falloff = unitValue(falloffValue, "Mask falloff for '" + map + "'"); - return new MaskRow(map, operation, inverted, threshold, falloff); - } - - public static List maskRows(List masks) { - List rows = new ArrayList<>(); - if (masks == null) { - return rows; - } - for (IrisImageMapMask mask : masks) { - if (mask != null) { - rows.add(new MaskRow( - mask.getMap(), - mask.getOperation(), - mask.isInverted(), - mask.getThreshold(), - mask.getFalloff() - )); - } - } - return rows; - } - - public static String safeKey(String fileName) { - String normalized = fileName == null ? "image-map" : fileName.trim().toLowerCase(Locale.ROOT); - if (normalized.endsWith(".png")) { - normalized = normalized.substring(0, normalized.length() - 4); - } - normalized = KEY_CHARACTER.matcher(normalized).replaceAll("-"); - while (normalized.contains("--")) { - normalized = normalized.replace("--", "-"); - } - normalized = normalized.replaceAll("^[./_-]+|[./_-]+$", ""); - return normalized.isBlank() ? "image-map" : normalized; - } - - public static List warnings( - IrisImageMap definition, - int sourceWidth, - int sourceHeight, - IrisWorldBoundary boundary - ) { - List warnings = new ArrayList<>(); - double blocksPerPixel = definition.getBlocksPerPixel(); - if (Double.isFinite(blocksPerPixel)) { - if (blocksPerPixel < 1D) { - warnings.add("Sub-block source scale will discard detail during block generation."); - } else if (blocksPerPixel > 512D) { - warnings.add("Each source pixel spans more than one Minecraft region (512 blocks)."); - } - } - long worldWidth = Math.round(sourceWidth * blocksPerPixel); - long worldHeight = Math.round(sourceHeight * blocksPerPixel); - if (worldWidth < 16L || worldHeight < 16L) { - warnings.add("The transformed source covers less than one complete chunk on at least one axis."); - } - if (boundary != null) { - Point2D.Double[] polygon = sourceWorldCorners(definition, sourceWidth, sourceHeight); - Point2D.Double[] borderCorners = new Point2D.Double[]{ - new Point2D.Double(boundary.minimumX(), boundary.minimumZ()), - new Point2D.Double(boundary.maximumX(), boundary.minimumZ()), - new Point2D.Double(boundary.maximumX(), boundary.maximumZ()), - new Point2D.Double(boundary.minimumX(), boundary.maximumZ()) - }; - for (Point2D.Double corner : borderCorners) { - if (!contains(polygon, corner)) { - warnings.add("The configured world boundary is not fully covered by the source image."); - break; - } - } - double minimumX = Double.POSITIVE_INFINITY; - double maximumX = Double.NEGATIVE_INFINITY; - double minimumZ = Double.POSITIVE_INFINITY; - double maximumZ = Double.NEGATIVE_INFINITY; - boolean outsideBoundary = false; - for (Point2D.Double corner : polygon) { - minimumX = Math.min(minimumX, corner.x); - maximumX = Math.max(maximumX, corner.x); - minimumZ = Math.min(minimumZ, corner.y); - maximumZ = Math.max(maximumZ, corner.y); - if (corner.x < boundary.minimumX() || corner.x > boundary.maximumX() - || corner.y < boundary.minimumZ() || corner.y > boundary.maximumZ()) { - outsideBoundary = true; - } - } - if (outsideBoundary) { - warnings.add("The source image extends outside the world boundary; mapped content there is not playable."); - } - double footprintWidth = maximumX - minimumX; - double footprintHeight = maximumZ - minimumZ; - if (footprintWidth > boundary.getSize() * 2D || footprintHeight > boundary.getSize() * 2D) { - warnings.add("The transformed source is substantially larger than the playable boundary."); - } else if (footprintWidth < boundary.getSize() * 0.5D - || footprintHeight < boundary.getSize() * 0.5D) { - warnings.add("The transformed source is substantially smaller than the playable boundary."); - } - } - return List.copyOf(warnings); - } - - public static Point2D.Double[] sourceWorldCorners(IrisImageMap definition, int width, int height) { - return new Point2D.Double[]{ - sourceToWorld(definition, 0D, 0D), - sourceToWorld(definition, width, 0D), - sourceToWorld(definition, width, height), - sourceToWorld(definition, 0D, height) - }; - } - - public static Point2D.Double sourceToWorld(IrisImageMap definition, double sourceX, double sourceZ) { - IrisImageMapOrigin origin = definition.getOrigin(); - IrisImageMapOrigin sourceOrigin = definition.getSourceOrigin(); - double x = sourceX - sourceOrigin.getX(); - double z = sourceZ - sourceOrigin.getZ(); - if (definition.isMirrorX()) { - x = -x; - } - if (definition.isMirrorZ()) { - z = -z; - } - Point2D.Double rotated = rotateForward(x, z, definition.getRotation()); - return new Point2D.Double( - origin.getX() + (rotated.x * definition.getBlocksPerPixel()), - origin.getZ() + (rotated.y * definition.getBlocksPerPixel()) - ); - } - - public static int targetColor(String target) { - if (target == null) { - return 0xFF252936; - } - int hash = target.hashCode(); - int red = 72 + Math.floorMod(hash, 152); - int green = 72 + Math.floorMod(hash >>> 8, 152); - int blue = 72 + Math.floorMod(hash >>> 16, 152); - return 0xFF000000 | (red << 16) | (green << 8) | blue; - } - - public static int heightColor(double height, double minimum, double maximum) { - double range = maximum - minimum; - double normalized = range == 0D ? 0.5D : Math.max(0D, Math.min(1D, (height - minimum) / range)); - double red; - double green; - double blue; - if (normalized < 0.5D) { - double factor = normalized * 2D; - red = 38D + (45D * factor); - green = 77D + (111D * factor); - blue = 132D - (42D * factor); - } else { - double factor = (normalized - 0.5D) * 2D; - red = 83D + (169D * factor); - green = 188D + (58D * factor); - blue = 90D + (150D * factor); - } - return 0xFF000000 | ((int) red << 16) | ((int) green << 8) | (int) blue; - } - - private static Point2D.Double rotateForward(double x, double z, IrisImageMapRotation rotation) { - return switch (rotation) { - case DEG_0 -> new Point2D.Double(x, z); - case DEG_90 -> new Point2D.Double(-z, x); - case DEG_180 -> new Point2D.Double(-x, -z); - case DEG_270 -> new Point2D.Double(z, -x); - }; - } - - private static boolean contains(Point2D.Double[] polygon, Point2D.Double point) { - boolean inside = false; - int previous = polygon.length - 1; - for (int index = 0; index < polygon.length; index++) { - Point2D.Double current = polygon[index]; - Point2D.Double before = polygon[previous]; - if (Line2D.ptSegDist(before.x, before.y, current.x, current.y, point.x, point.y) <= 0.0000001D) { - return true; - } - boolean crosses = (current.y > point.y) != (before.y > point.y); - if (crosses) { - double intersection = ((before.x - current.x) * (point.y - current.y) - / (before.y - current.y)) + current.x; - if (point.x < intersection) { - inside = !inside; - } - } - previous = index; - } - return inside; - } - - private static double unitValue(Object value, String name) { - double number; - try { - number = Double.parseDouble(String.valueOf(value).trim()); - } catch (NumberFormatException exception) { - throw new IllegalArgumentException(name + " must be a number", exception); - } - if (!Double.isFinite(number) || number < 0D || number > 1D) { - throw new IllegalArgumentException(name + " must be finite and within 0..1"); - } - return number; - } - - public record SourceMetadata( - Path path, - String format, - int width, - int height, - long pixels, - String colorMode, - int colorComponents, - int channels, - int bitDepth, - boolean alpha, - double minimumAlpha, - double maximumAlpha, - String colorProfile - ) { - public String summary() { - String alphaSummary = alpha - ? String.format(Locale.ROOT, "yes (%.1f%%..%.1f%%)", minimumAlpha * 100D, maximumAlpha * 100D) - : "no"; - return format.toUpperCase(Locale.ROOT) + " | " + width + " × " + height - + " | " + pixels + " pixels | " + colorMode - + " | " + bitDepth + "-bit | " + channels + " channel(s) | alpha " - + alphaSummary + " | profile " + colorProfile; - } - } - - public record LegendRow(String color, String target) { - } - - public record MaskRow( - String map, - IrisImageMapMaskOperation operation, - boolean inverted, - double threshold, - double falloff - ) { - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/ImageMapStudioPreviewPanel.java b/core/src/main/java/art/arcane/iris/studio/map/ImageMapStudioPreviewPanel.java deleted file mode 100644 index fc9746532..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/ImageMapStudioPreviewPanel.java +++ /dev/null @@ -1,626 +0,0 @@ -package art.arcane.iris.studio.map; - -import art.arcane.iris.localization.DesktopUiMessages; -import art.arcane.iris.localization.IrisLanguage; -import art.arcane.iris.generation.image.CompiledIrisImageMap; -import art.arcane.iris.generation.image.IrisImageMapRuntime; -import art.arcane.iris.generation.image.IrisImageMapMaskSampler; -import art.arcane.iris.generation.image.IrisImageMap; -import art.arcane.iris.generation.image.IrisImageMapApplication; -import art.arcane.iris.generation.image.IrisImageMapType; -import art.arcane.iris.world.IrisWorldBoundary; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.volmlib.util.localization.MessageArgument; - -import javax.swing.BorderFactory; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JSplitPane; -import javax.swing.SwingWorker; -import java.awt.BasicStroke; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Polygon; -import java.awt.RenderingHints; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseWheelEvent; -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; -import java.util.concurrent.CancellationException; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.Consumer; -import java.util.function.DoubleBinaryOperator; - -final class ImageMapStudioPreviewPanel extends JPanel implements AutoCloseable { - // The images and their overlay lines are drawn for a dark backdrop, in either theme. - private static final Color CANVAS_BACKGROUND = new Color(12, 15, 22); - private static final Color CANVAS_TEXT = new Color(151, 160, 178); - - private final SourceCanvas sourceCanvas = new SourceCanvas(); - private final WorldCanvas worldCanvas = new WorldCanvas(); - private final JLabel statusLabel = new JLabel(" "); - - ImageMapStudioPreviewPanel() { - super(new BorderLayout()); - setBackground(StudioTheme.PANEL_BACKGROUND); - JPanel source = wrap(IrisLanguage.plain(DesktopUiMessages.IMAGEMAP_SOURCE), sourceCanvas); - JPanel interpreted = wrap(IrisLanguage.plain(DesktopUiMessages.IMAGEMAP_INTERPRETED), worldCanvas); - JSplitPane split = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, source, interpreted); - split.setBorder(BorderFactory.createEmptyBorder()); - split.setResizeWeight(0.42D); - split.putClientProperty("FlatLaf.style", "style: grip"); - add(split, BorderLayout.CENTER); - statusLabel.setForeground(StudioTheme.SECONDARY_TEXT); - statusLabel.setFont(StudioTheme.smallFont()); - statusLabel.setBorder(BorderFactory.createCompoundBorder( - BorderFactory.createMatteBorder(1, 0, 0, 0, StudioTheme.SEPARATOR), - StudioTheme.emptyBorder(5, 9, 5, 9) - )); - add(statusLabel, BorderLayout.SOUTH); - worldCanvas.setHoverConsumer(statusLabel::setText); - } - - void setPreview( - BufferedImage source, - CompiledIrisImageMap compiled, - IrisImageMapMaskSampler maskSampler, - IrisWorldBoundary boundary, - IrisImageMapApplication application, - int minimumWorldHeight, - DoubleBinaryOperator proceduralHeightSampler - ) { - sourceCanvas.setSource(source); - worldCanvas.setPreview( - compiled, maskSampler, boundary, application, minimumWorldHeight, proceduralHeightSampler - ); - } - - void setSource(BufferedImage source) { - sourceCanvas.setSource(source); - worldCanvas.clear(); - } - - void setDiagnosticConsumer(Consumer diagnosticConsumer) { - worldCanvas.setDiagnosticConsumer(diagnosticConsumer); - } - - void setOverlays(boolean chunks, boolean regions, boolean boundary, boolean coverage) { - worldCanvas.setOverlays(chunks, regions, boundary, coverage); - } - - BufferedImage renderInterpretedSnapshot(int width, int height) { - return worldCanvas.renderSnapshot(width, height).image(); - } - - BufferedImage renderSourceSnapshot(int width, int height) { - sourceCanvas.setSize(width, height); - BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - Graphics2D graphics = image.createGraphics(); - try { - sourceCanvas.paint(graphics); - } finally { - graphics.dispose(); - } - return image; - } - - @Override - public void close() { - worldCanvas.close(); - } - - private static JPanel wrap(String title, JPanel canvas) { - JPanel panel = new JPanel(new BorderLayout()); - panel.setOpaque(false); - panel.setBorder(BorderFactory.createLineBorder(StudioTheme.SEPARATOR)); - JLabel label = new JLabel(title); - label.setFont(StudioTheme.sectionFont()); - label.setBorder(BorderFactory.createCompoundBorder( - BorderFactory.createMatteBorder(0, 0, 1, 0, StudioTheme.SEPARATOR), - StudioTheme.emptyBorder(6, 9, 6, 9) - )); - panel.add(label, BorderLayout.NORTH); - panel.add(canvas, BorderLayout.CENTER); - return panel; - } - - private static final class SourceCanvas extends JPanel { - private BufferedImage source; - - private SourceCanvas() { - setBackground(CANVAS_BACKGROUND); - setPreferredSize(new Dimension(420, 520)); - } - - private void setSource(BufferedImage source) { - this.source = source; - repaint(); - } - - @Override - protected void paintComponent(Graphics graphics) { - super.paintComponent(graphics); - if (source == null) { - drawEmpty(graphics, IrisLanguage.plain(DesktopUiMessages.IMAGEMAP_NO_SOURCE)); - return; - } - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - canvas.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); - int padding = 16; - double scale = Math.min( - (getWidth() - (padding * 2D)) / source.getWidth(), - (getHeight() - (padding * 2D)) / source.getHeight() - ); - scale = Math.max(0.0001D, scale); - int width = Math.max(1, (int) Math.round(source.getWidth() * scale)); - int height = Math.max(1, (int) Math.round(source.getHeight() * scale)); - int x = (getWidth() - width) / 2; - int y = (getHeight() - height) / 2; - canvas.drawImage(source, x, y, width, height, null); - canvas.setColor(new Color(255, 255, 255, 64)); - canvas.drawRect(x, y, width - 1, height - 1); - if (scale >= 8D && source.getWidth() <= 256 && source.getHeight() <= 256) { - canvas.setColor(new Color(255, 255, 255, 25)); - for (int sourceX = 1; sourceX < source.getWidth(); sourceX++) { - int lineX = x + (int) Math.round(sourceX * scale); - canvas.drawLine(lineX, y, lineX, y + height); - } - for (int sourceZ = 1; sourceZ < source.getHeight(); sourceZ++) { - int lineY = y + (int) Math.round(sourceZ * scale); - canvas.drawLine(x, lineY, x + width, lineY); - } - } - } finally { - canvas.dispose(); - } - } - } - - private static final class WorldCanvas extends JPanel implements AutoCloseable { - private final AtomicLong revision = new AtomicLong(); - private CompiledIrisImageMap compiled; - private IrisImageMapMaskSampler maskSampler = IrisImageMapMaskSampler.empty(); - private IrisWorldBoundary boundary; - private IrisImageMapApplication application = IrisImageMapApplication.CUSTOM; - private int minimumWorldHeight; - private DoubleBinaryOperator proceduralHeightSampler; - private BufferedImage rendered; - private SwingWorker worker; - private Consumer diagnosticConsumer = ignored -> { - }; - private Consumer hoverConsumer = ignored -> { - }; - private double centerX; - private double centerZ; - private double blocksPerScreenPixel = 1D; - private boolean showChunks = true; - private boolean showRegions = true; - private boolean showBoundary = true; - private boolean showCoverage = true; - private Point dragOrigin; - private double dragCenterX; - private double dragCenterZ; - - private WorldCanvas() { - setBackground(CANVAS_BACKGROUND); - setPreferredSize(new Dimension(620, 520)); - MouseAdapter mouse = new MouseAdapter() { - @Override - public void mousePressed(MouseEvent event) { - dragOrigin = event.getPoint(); - dragCenterX = centerX; - dragCenterZ = centerZ; - } - - @Override - public void mouseDragged(MouseEvent event) { - if (dragOrigin == null) { - return; - } - centerX = dragCenterX - ((event.getX() - dragOrigin.x) * blocksPerScreenPixel); - centerZ = dragCenterZ - ((event.getY() - dragOrigin.y) * blocksPerScreenPixel); - requestRender(); - } - - @Override - public void mouseReleased(MouseEvent event) { - dragOrigin = null; - } - - @Override - public void mouseMoved(MouseEvent event) { - publishHover(event.getX(), event.getY()); - } - - @Override - public void mouseWheelMoved(MouseWheelEvent event) { - double beforeX = screenToWorldX(event.getX()); - double beforeZ = screenToWorldZ(event.getY()); - double factor = Math.pow(1.12D, event.getPreciseWheelRotation()); - blocksPerScreenPixel = Math.max(0.01D, Math.min(1_000_000D, blocksPerScreenPixel * factor)); - centerX += beforeX - screenToWorldX(event.getX()); - centerZ += beforeZ - screenToWorldZ(event.getY()); - requestRender(); - } - }; - addMouseListener(mouse); - addMouseMotionListener(mouse); - addMouseWheelListener(mouse); - addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent event) { - requestRender(); - } - }); - } - - private void setPreview( - CompiledIrisImageMap compiled, - IrisImageMapMaskSampler maskSampler, - IrisWorldBoundary boundary, - IrisImageMapApplication application, - int minimumWorldHeight, - DoubleBinaryOperator proceduralHeightSampler - ) { - this.compiled = compiled; - this.maskSampler = maskSampler == null ? IrisImageMapMaskSampler.empty() : maskSampler; - this.boundary = boundary; - this.application = application == null ? IrisImageMapApplication.CUSTOM : application; - this.minimumWorldHeight = minimumWorldHeight; - this.proceduralHeightSampler = proceduralHeightSampler; - IrisImageMap definition = compiled.getDefinition(); - centerX = definition.getOrigin().getX(); - centerZ = definition.getOrigin().getZ(); - fitSource(); - requestRender(); - } - - private void clear() { - revision.incrementAndGet(); - if (worker != null) { - worker.cancel(true); - worker = null; - } - compiled = null; - rendered = null; - repaint(); - } - - private void setDiagnosticConsumer(Consumer diagnosticConsumer) { - this.diagnosticConsumer = diagnosticConsumer == null ? ignored -> { - } : diagnosticConsumer; - } - - private void setHoverConsumer(Consumer hoverConsumer) { - this.hoverConsumer = hoverConsumer == null ? ignored -> { - } : hoverConsumer; - } - - private void setOverlays(boolean chunks, boolean regions, boolean boundary, boolean coverage) { - showChunks = chunks; - showRegions = regions; - showBoundary = boundary; - showCoverage = coverage; - requestRender(); - } - - private void fitSource() { - if (compiled == null) { - return; - } - Point2D.Double[] corners = ImageMapStudioModel.sourceWorldCorners( - compiled.getDefinition(), compiled.getSourceWidth(), compiled.getSourceHeight() - ); - double minimumX = Double.POSITIVE_INFINITY; - double maximumX = Double.NEGATIVE_INFINITY; - double minimumZ = Double.POSITIVE_INFINITY; - double maximumZ = Double.NEGATIVE_INFINITY; - for (Point2D.Double corner : corners) { - minimumX = Math.min(minimumX, corner.x); - maximumX = Math.max(maximumX, corner.x); - minimumZ = Math.min(minimumZ, corner.y); - maximumZ = Math.max(maximumZ, corner.y); - } - centerX = (minimumX + maximumX) / 2D; - centerZ = (minimumZ + maximumZ) / 2D; - int width = Math.max(320, getWidth()); - int height = Math.max(320, getHeight()); - blocksPerScreenPixel = Math.max( - (maximumX - minimumX) / (width * 0.82D), - (maximumZ - minimumZ) / (height * 0.82D) - ); - blocksPerScreenPixel = Math.max(0.01D, blocksPerScreenPixel); - } - - private void requestRender() { - if (compiled == null || getWidth() <= 0 || getHeight() <= 0) { - repaint(); - return; - } - long currentRevision = revision.incrementAndGet(); - if (worker != null) { - worker.cancel(true); - } - int width = Math.max(1, getWidth()); - int height = Math.max(1, getHeight()); - worker = new SwingWorker<>() { - @Override - protected RenderResult doInBackground() { - return renderSnapshot(width, height); - } - - @Override - protected void done() { - if (isCancelled() || currentRevision != revision.get()) { - return; - } - try { - RenderResult result = get(); - rendered = result.image(); - if (result.errors() > 0) { - diagnosticConsumer.accept(result.errors() + " preview sample(s) failed; invalid pixels are magenta."); - } - repaint(); - } catch (CancellationException ignored) { - } catch (InterruptedException exception) { - Thread.currentThread().interrupt(); - } catch (ExecutionException exception) { - IrisLogging.reportError(exception.getCause()); - diagnosticConsumer.accept("Preview render failed: " + exception.getCause().getMessage()); - } - } - }; - worker.execute(); - } - - private RenderResult renderSnapshot(int width, int height) { - BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB); - if (compiled == null) { - return new RenderResult(image, 0); - } - int errors = 0; - IrisImageMapType type = compiled.getType(); - IrisImageMap definition = compiled.getDefinition(); - for (int screenZ = 0; screenZ < height; screenZ++) { - if (Thread.currentThread().isInterrupted()) { - break; - } - double worldZ = centerZ + ((screenZ - (height / 2D)) * blocksPerScreenPixel); - for (int screenX = 0; screenX < width; screenX++) { - double worldX = centerX + ((screenX - (width / 2D)) * blocksPerScreenPixel); - int color; - try { - double maskWeight = maskSampler.sample(worldX, worldZ); - color = switch (type) { - case GRAYSCALE_HEIGHT, RGB_HEIGHT -> ImageMapStudioModel.heightColor( - interpretedHeight(worldX, worldZ, maskWeight), - definition.getMinimumHeight(), - definition.getMaximumHeight() - ); - case COLOR_MAP -> categoricalApplication() - && !IrisImageMapRuntime.selectCategorical(maskWeight) - ? CANVAS_BACKGROUND.getRGB() - : ImageMapStudioModel.targetColor(compiled.sampleTarget(worldX, worldZ)); - case BINARY_MASK, GRAYSCALE_MASK, ALPHA_MASK -> grayscale( - compiled.sampleNormalized(worldX, worldZ) - ); - }; - } catch (RuntimeException exception) { - color = 0xFFFF3DA8; - errors++; - } - if (showCoverage && !compiled.containsWorld(worldX, worldZ) - && ((screenX + screenZ) & 7) < 3) { - color = blend(color, 0xFF090B10, 0.48D); - } - image.setRGB(screenX, screenZ, color); - } - } - return new RenderResult(image, errors); - } - - @Override - protected void paintComponent(Graphics graphics) { - super.paintComponent(graphics); - if (compiled == null) { - drawEmpty(graphics, IrisLanguage.plain(DesktopUiMessages.IMAGEMAP_NO_PREVIEW)); - return; - } - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - if (rendered != null) { - canvas.drawImage(rendered, 0, 0, getWidth(), getHeight(), null); - } - drawWorldGrid(canvas, 16D, new Color(255, 255, 255, 28), showChunks); - drawWorldGrid(canvas, 512D, new Color(99, 161, 255, 96), showRegions); - if (showCoverage) { - drawCoverage(canvas); - } - if (showBoundary && boundary != null) { - drawBoundary(canvas); - } - drawOrigin(canvas); - } finally { - canvas.dispose(); - } - } - - private void drawWorldGrid(Graphics2D canvas, double spacing, Color color, boolean enabled) { - if (!enabled || spacing / blocksPerScreenPixel < 7D) { - return; - } - canvas.setColor(color); - double minimumX = screenToWorldX(0); - double maximumX = screenToWorldX(getWidth()); - double minimumZ = screenToWorldZ(0); - double maximumZ = screenToWorldZ(getHeight()); - double firstX = Math.floor(minimumX / spacing) * spacing; - double firstZ = Math.floor(minimumZ / spacing) * spacing; - for (double worldX = firstX; worldX <= maximumX; worldX += spacing) { - int screenX = worldToScreenX(worldX); - canvas.drawLine(screenX, 0, screenX, getHeight()); - } - for (double worldZ = firstZ; worldZ <= maximumZ; worldZ += spacing) { - int screenZ = worldToScreenZ(worldZ); - canvas.drawLine(0, screenZ, getWidth(), screenZ); - } - } - - private void drawCoverage(Graphics2D canvas) { - Point2D.Double[] corners = ImageMapStudioModel.sourceWorldCorners( - compiled.getDefinition(), compiled.getSourceWidth(), compiled.getSourceHeight() - ); - Polygon polygon = new Polygon(); - for (Point2D.Double corner : corners) { - polygon.addPoint(worldToScreenX(corner.x), worldToScreenZ(corner.y)); - } - canvas.setStroke(new BasicStroke(2F)); - canvas.setColor(new Color(99, 161, 255, 205)); - canvas.drawPolygon(polygon); - } - - private void drawBoundary(Graphics2D canvas) { - int minimumX = worldToScreenX(boundary.minimumX()); - int maximumX = worldToScreenX(boundary.maximumX()); - int minimumZ = worldToScreenZ(boundary.minimumZ()); - int maximumZ = worldToScreenZ(boundary.maximumZ()); - int x = Math.min(minimumX, maximumX); - int z = Math.min(minimumZ, maximumZ); - int width = Math.abs(maximumX - minimumX); - int height = Math.abs(maximumZ - minimumZ); - canvas.setColor(new Color(255, 188, 82, 220)); - canvas.setStroke(new BasicStroke(2F)); - canvas.drawRect(x, z, width, height); - } - - private void drawOrigin(Graphics2D canvas) { - IrisImageMap definition = compiled.getDefinition(); - int x = worldToScreenX(definition.getOrigin().getX()); - int z = worldToScreenZ(definition.getOrigin().getZ()); - canvas.setColor(new Color(255, 255, 255, 190)); - canvas.drawLine(x - 7, z, x + 7, z); - canvas.drawLine(x, z - 7, x, z + 7); - } - - private void publishHover(int screenX, int screenZ) { - if (compiled == null) { - return; - } - double worldX = screenToWorldX(screenX); - double worldZ = screenToWorldZ(screenZ); - String value; - try { - double maskWeight = maskSampler.sample(worldX, worldZ); - value = switch (compiled.getType()) { - case GRAYSCALE_HEIGHT, RGB_HEIGHT -> String.format( - "Y %.3f", interpretedHeight(worldX, worldZ, maskWeight) - ); - case COLOR_MAP -> categoricalApplication() - && !IrisImageMapRuntime.selectCategorical(maskWeight) - ? "procedural" - : String.valueOf(compiled.sampleTarget(worldX, worldZ)); - case BINARY_MASK, GRAYSCALE_MASK, ALPHA_MASK -> String.format( - "%.4f", compiled.sampleNormalized(worldX, worldZ) - ); - }; - if (!maskSampler.isEmpty()) { - value += String.format(" | mask %.4f", maskWeight); - } - } catch (RuntimeException exception) { - value = exception.getMessage(); - } - hoverConsumer.accept(IrisLanguage.plain( - DesktopUiMessages.IMAGEMAP_PREVIEW_STATUS, - MessageArgument.untrusted("x", String.format("%.2f", worldX)), - MessageArgument.untrusted("z", String.format("%.2f", worldZ)), - MessageArgument.untrusted("value", value), - MessageArgument.untrusted("scale", String.format("%.3f", blocksPerScreenPixel)) - )); - } - - private double interpretedHeight(double worldX, double worldZ, double maskWeight) { - double mappedHeight = compiled.sampleHeight(worldX, worldZ); - if (application != IrisImageMapApplication.TERRAIN_HEIGHT || maskSampler.isEmpty()) { - return mappedHeight; - } - IrisImageMap definition = compiled.getDefinition(); - double proceduralLocalHeight = proceduralHeightSampler == null - ? definition.getMinimumHeight() - minimumWorldHeight - : proceduralHeightSampler.applyAsDouble(worldX, worldZ); - double mappedLocalHeight = mappedHeight - minimumWorldHeight; - return minimumWorldHeight + IrisImageMapRuntime.blendTerrainHeight( - mappedLocalHeight, proceduralLocalHeight, maskWeight - ); - } - - private boolean categoricalApplication() { - return application == IrisImageMapApplication.BIOME - || application == IrisImageMapApplication.REGION - || application == IrisImageMapApplication.SURFACE_BLOCK; - } - - private int worldToScreenX(double worldX) { - return (int) Math.round((getWidth() / 2D) + ((worldX - centerX) / blocksPerScreenPixel)); - } - - private int worldToScreenZ(double worldZ) { - return (int) Math.round((getHeight() / 2D) + ((worldZ - centerZ) / blocksPerScreenPixel)); - } - - private double screenToWorldX(double screenX) { - return centerX + ((screenX - (getWidth() / 2D)) * blocksPerScreenPixel); - } - - private double screenToWorldZ(double screenZ) { - return centerZ + ((screenZ - (getHeight() / 2D)) * blocksPerScreenPixel); - } - - @Override - public void close() { - revision.incrementAndGet(); - if (worker != null) { - worker.cancel(true); - } - } - } - - private static void drawEmpty(Graphics graphics, String text) { - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - canvas.setColor(CANVAS_TEXT); - canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - int width = canvas.getFontMetrics().stringWidth(text); - int x = Math.max(8, (graphics.getClipBounds() == null ? 0 : graphics.getClipBounds().width - width) / 2); - int y = Math.max(20, graphics.getClipBounds() == null ? 20 : graphics.getClipBounds().height / 2); - canvas.drawString(text, x, y); - } finally { - canvas.dispose(); - } - } - - private static int grayscale(double value) { - int level = (int) Math.round(Math.max(0D, Math.min(1D, value)) * 255D); - return 0xFF000000 | (level << 16) | (level << 8) | level; - } - - private static int blend(int first, int second, double secondWeight) { - double firstWeight = 1D - secondWeight; - int red = (int) ((((first >>> 16) & 0xFF) * firstWeight) + (((second >>> 16) & 0xFF) * secondWeight)); - int green = (int) ((((first >>> 8) & 0xFF) * firstWeight) + (((second >>> 8) & 0xFF) * secondWeight)); - int blue = (int) (((first & 0xFF) * firstWeight) + ((second & 0xFF) * secondWeight)); - return 0xFF000000 | (red << 16) | (green << 8) | blue; - } - - private record RenderResult(BufferedImage image, int errors) { - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/IslandOverlay.java b/core/src/main/java/art/arcane/iris/studio/map/IslandOverlay.java deleted file mode 100644 index aa3c048e4..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/IslandOverlay.java +++ /dev/null @@ -1,105 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -package art.arcane.iris.studio.map; - -import javax.swing.JComponent; -import javax.swing.JLayeredPane; -import java.awt.Cursor; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; - -/** - * Lays an island over content that fills the whole area behind it. Dragging the island's right edge resizes it, - * always leaving the content some room beside it. - */ -public final class IslandOverlay extends JLayeredPane { - private static final long serialVersionUID = -4182209135360718342L; - - private final IslandPanel island; - private final JComponent background; - private final int minimumIslandWidth; - private final int minimumUncoveredWidth; - private int islandWidth; - - public IslandOverlay(IslandPanel island, JComponent background, int islandWidth, int minimumIslandWidth, int minimumUncoveredWidth) { - this.island = island; - this.background = background; - this.islandWidth = islandWidth; - this.minimumIslandWidth = minimumIslandWidth; - this.minimumUncoveredWidth = minimumUncoveredWidth; - add(background, JLayeredPane.DEFAULT_LAYER); - add(island, JLayeredPane.PALETTE_LAYER); - installResizing(); - } - - @Override - public void doLayout() { - background.setBounds(0, 0, getWidth(), getHeight()); - island.setBounds(0, 0, clampedIslandWidth(), getHeight()); - } - - private int clampedIslandWidth() { - int widest = Math.max(minimumIslandWidth, getWidth() - minimumUncoveredWidth); - return Math.clamp(islandWidth, minimumIslandWidth, widest); - } - - private void installResizing() { - MouseAdapter resizer = new MouseAdapter() { - private boolean dragging; - - @Override - public void mouseMoved(MouseEvent event) { - island.setCursor(island.isOnResizeEdge(event.getX(), event.getY()) - ? Cursor.getPredefinedCursor(Cursor.E_RESIZE_CURSOR) - : Cursor.getDefaultCursor()); - } - - @Override - public void mouseExited(MouseEvent event) { - if (!dragging) { - island.setCursor(Cursor.getDefaultCursor()); - } - } - - @Override - public void mousePressed(MouseEvent event) { - dragging = island.isOnResizeEdge(event.getX(), event.getY()); - } - - @Override - public void mouseDragged(MouseEvent event) { - if (!dragging) { - return; - } - islandWidth = event.getX(); - islandWidth = clampedIslandWidth(); - revalidate(); - repaint(); - } - - @Override - public void mouseReleased(MouseEvent event) { - dragging = false; - } - }; - island.addMouseListener(resizer); - island.addMouseMotionListener(resizer); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/IslandPanel.java b/core/src/main/java/art/arcane/iris/studio/map/IslandPanel.java deleted file mode 100644 index d0a3728c2..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/IslandPanel.java +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -package art.arcane.iris.studio.map; - -import javax.swing.JComponent; -import javax.swing.JPanel; -import java.awt.BorderLayout; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.geom.RoundRectangle2D; -import java.util.List; - -/** - * A rounded panel floating over the window content with a gap all around it, like the tool windows of IntelliJ's - * islands theme. The gap belongs to the content behind it, except for the strip along the right edge, which grabs the - * island to resize it. - */ -public final class IslandPanel extends JPanel implements FloatingPanels.PartlySeeThrough { - private static final long serialVersionUID = 7313084027614358519L; - private static final int GAP = 6; - private static final int CORNER_ARC = 12; - private static final int INNER_PADDING = 4; - - public IslandPanel(JComponent content) { - super(new BorderLayout()); - setOpaque(false); - int inset = GAP + INNER_PADDING; - setBorder(StudioTheme.emptyBorder(inset, inset, inset, inset)); - add(content, BorderLayout.CENTER); - } - - boolean isOnResizeEdge(int x, int y) { - int edgeWidth = StudioTheme.scale(GAP + INNER_PADDING); - return x >= getWidth() - edgeWidth && x < getWidth() && y >= 0 && y < getHeight(); - } - - // Clicks in the gap reach the content behind the island instead of the island itself. - @Override - public boolean contains(int x, int y) { - return island().contains(x, y) || isOnResizeEdge(x, y); - } - - // The gap all around, reaching in as far as the rounded corners do. - @Override - public List seeThroughParts() { - int width = getWidth(); - int height = getHeight(); - int gap = StudioTheme.scale(GAP); - int edge = gap + (int) Math.ceil(StudioTheme.scale((double) CORNER_ARC) / 2D); - return List.of( - new Rectangle(0, 0, width, edge), - new Rectangle(0, height - edge, width, edge), - new Rectangle(0, edge, gap, height - edge * 2), - new Rectangle(width - gap, edge, gap, height - edge * 2)); - } - - @Override - protected void paintComponent(Graphics graphics) { - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - canvas.setColor(StudioTheme.PANEL_BACKGROUND); - canvas.fill(island()); - } finally { - canvas.dispose(); - } - } - - private RoundRectangle2D island() { - double gap = StudioTheme.scale(GAP); - double arc = StudioTheme.scale(CORNER_ARC); - return new RoundRectangle2D.Double(gap, gap, getWidth() - gap * 2D, getHeight() - gap * 2D, arc, arc); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/LatestMeasurement.java b/core/src/main/java/art/arcane/iris/studio/map/LatestMeasurement.java deleted file mode 100644 index 6dbffa27b..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/LatestMeasurement.java +++ /dev/null @@ -1,92 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.spi.IrisLogging; - -import java.awt.EventQueue; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.BooleanSupplier; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Supplier; - -/** - * Measures off the Swing thread, one measurement at a time, and only hands back the newest one asked for. - */ -final class LatestMeasurement { - private final ThreadPoolExecutor worker; - private final AtomicLong generation = new AtomicLong(); - - LatestMeasurement(String threadName) { - this.worker = new ThreadPoolExecutor(1, 1, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(1), task -> { - Thread thread = new Thread(task, threadName); - thread.setDaemon(true); - return thread; - }, new ThreadPoolExecutor.DiscardOldestPolicy()); - } - - /** - * Runs the measurement and shows its result on the Swing thread, unless another was asked for meanwhile or it - * measured nothing. - */ - void measure(Supplier measurement, Consumer show) { - measureUntilSuperseded(stillWanted -> measurement.get(), show); - } - - /** - * Like {@link #measure}, for long measurements that ask {@code stillWanted} between steps and give up once another - * measurement was asked for. - */ - void measureUntilSuperseded(Function measurement, Consumer show) { - long requested = generation.incrementAndGet(); - BooleanSupplier stillWanted = () -> requested == generation.get(); - worker.execute(() -> { - T result = measureSafely(() -> measurement.apply(stillWanted)); - EventQueue.invokeLater(() -> { - if (requested == generation.get() && result != null) { - show.accept(result); - } - }); - }); - } - - /** - * Drops the measurement under way, whose result no longer fits. - */ - void discardPending() { - generation.incrementAndGet(); - } - - void close() { - worker.shutdownNow(); - } - - private static T measureSafely(Supplier measurement) { - try { - return measurement.get(); - } catch (Throwable error) { - IrisLogging.reportError(error); - return null; - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/LoadingAnimation.java b/core/src/main/java/art/arcane/iris/studio/map/LoadingAnimation.java deleted file mode 100644 index 5367a3611..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/LoadingAnimation.java +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package art.arcane.iris.studio.map; - -import java.awt.AlphaComposite; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.geom.Path2D; -import java.awt.image.BufferedImage; - -/** - * A little cube of blocks building itself while something loads: the blocks drop in one by one, the cube holds a - * moment, fades, and starts over. Loads shorter than {@link #SHOW_AFTER_MILLIS} never show it, and once it shows it - * stays for {@link #SHOW_AT_LEAST_MILLIS}, so it never flashes. - */ -final class LoadingAnimation { - static final int SHOW_AFTER_MILLIS = 300; - static final int SHOW_AT_LEAST_MILLIS = 700; - static final int FRAME_MILLIS = 33; - - // Back to front, so each block lands on or beside ones already there. - private static final int[][] BUILD_ORDER = { - {0, 0, 0}, {1, 0, 0}, {0, 0, 1}, {1, 0, 1}, - {0, 1, 0}, {1, 1, 0}, {0, 1, 1}, {1, 1, 1}}; - private static final int STEP_MILLIS = 140; - private static final int DROP_MILLIS = 260; - private static final int HOLD_MILLIS = 450; - private static final int FADE_MILLIS = 320; - private static final int CYCLE_MILLIS = STEP_MILLIS * (BUILD_ORDER.length - 1) + DROP_MILLIS + HOLD_MILLIS + FADE_MILLIS; - private static final double DROP_HEIGHT_BLOCKS = 1.6D; - private static final double ISOMETRIC_WIDTH = Math.cos(Math.PI / 6D); - private static final double ISOMETRIC_DEPTH = 0.5D; - private static final float SIDE_SHADE = 0.78F; - private static final float FAR_SIDE_SHADE = 0.6F; - - private LoadingAnimation() { - } - - /** - * Whether a load that began at {@code loadingSinceMillis} has taken long enough to show the animation. - */ - static boolean isDue(long loadingSinceMillis) { - return System.currentTimeMillis() - loadingSinceMillis >= SHOW_AFTER_MILLIS; - } - - /** - * How much longer the animation of a load that began at {@code loadingSinceMillis} has to stay up once the load is - * done; zero when it never showed or has shown long enough. - */ - static long remainingShowMillis(long loadingSinceMillis) { - if (!isDue(loadingSinceMillis)) { - return 0L; - } - long shownMillis = System.currentTimeMillis() - loadingSinceMillis - SHOW_AFTER_MILLIS; - return Math.max(0L, SHOW_AT_LEAST_MILLIS - shownMillis); - } - - /** - * Draws the cube centred on a point, {@code blockSize} pixels to a block edge, as it looks - * {@code elapsedMillis} after it first showed. - */ - static void paint(Graphics2D graphics, double centerX, double centerY, double blockSize, long elapsedMillis) { - long time = Math.floorMod(elapsedMillis, CYCLE_MILLIS); - long fadeStart = CYCLE_MILLIS - FADE_MILLIS; - if (time < fadeStart) { - drawCube(graphics, centerX, centerY, blockSize, time); - return; - } - fadeCube(graphics, centerX, centerY, blockSize, time, 1F - (time - fadeStart) / (float) FADE_MILLIS); - } - - // Faded block by block, the blocks behind would show through; the whole cube is drawn first and faded as one. - private static void fadeCube(Graphics2D graphics, double centerX, double centerY, double blockSize, long time, float opacity) { - int extent = (int) Math.ceil(blockSize * (2D + DROP_HEIGHT_BLOCKS) * 2D); - BufferedImage cube = new BufferedImage(extent, extent, BufferedImage.TYPE_INT_ARGB); - Graphics2D cubeCanvas = cube.createGraphics(); - drawCube(cubeCanvas, extent / 2D, extent / 2D, blockSize, time); - cubeCanvas.dispose(); - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - canvas.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, Math.max(0F, opacity))); - canvas.drawImage(cube, (int) Math.round(centerX - extent / 2D), (int) Math.round(centerY - extent / 2D), null); - } finally { - canvas.dispose(); - } - } - - private static void drawCube(Graphics2D graphics, double centerX, double centerY, double blockSize, long time) { - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - for (int index = 0; index < BUILD_ORDER.length; index++) { - long sinceDropStart = time - (long) index * STEP_MILLIS; - if (sinceDropStart < 0) { - break; - } - double fallen = easeOut(Math.min(1D, sinceDropStart / (double) DROP_MILLIS)); - int[] block = BUILD_ORDER[index]; - drawBlock(canvas, centerX, centerY, blockSize, block[0], block[1] + DROP_HEIGHT_BLOCKS * (1D - fallen), block[2]); - } - } finally { - canvas.dispose(); - } - } - - private static double easeOut(double progress) { - double remaining = 1D - progress; - return 1D - remaining * remaining * remaining; - } - - // The cube's middle, (1, 1, 1), lands on the centre point; the top and the two sides facing the viewer show. - private static void drawBlock(Graphics2D canvas, double centerX, double centerY, double size, double x, double y, double z) { - Color top = StudioTheme.ACCENT; - canvas.setColor(top); - canvas.fill(face(centerX, centerY, size, x, y, z, new double[][]{{0, 1, 0}, {1, 1, 0}, {1, 1, 1}, {0, 1, 1}})); - canvas.setColor(shaded(top, SIDE_SHADE)); - canvas.fill(face(centerX, centerY, size, x, y, z, new double[][]{{1, 0, 0}, {1, 1, 0}, {1, 1, 1}, {1, 0, 1}})); - canvas.setColor(shaded(top, FAR_SIDE_SHADE)); - canvas.fill(face(centerX, centerY, size, x, y, z, new double[][]{{0, 0, 1}, {1, 0, 1}, {1, 1, 1}, {0, 1, 1}})); - } - - private static Path2D face(double centerX, double centerY, double size, double x, double y, double z, double[][] corners) { - Path2D path = new Path2D.Double(); - for (int corner = 0; corner < corners.length; corner++) { - double cornerX = x + corners[corner][0] - 1D; - double cornerY = y + corners[corner][1] - 1D; - double cornerZ = z + corners[corner][2] - 1D; - double screenX = centerX + (cornerX - cornerZ) * ISOMETRIC_WIDTH * size; - double screenY = centerY + (cornerX + cornerZ) * ISOMETRIC_DEPTH * size - cornerY * size; - if (corner == 0) { - path.moveTo(screenX, screenY); - } else { - path.lineTo(screenX, screenY); - } - } - path.closePath(); - return path; - } - - private static Color shaded(Color color, float shade) { - return new Color(Math.round(color.getRed() * shade), Math.round(color.getGreen() * shade), Math.round(color.getBlue() * shade)); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/MapCanvas.java b/core/src/main/java/art/arcane/iris/studio/map/MapCanvas.java deleted file mode 100644 index d3b61c9cd..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/MapCanvas.java +++ /dev/null @@ -1,1343 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.studio.map.components.MapTileRenderer; -import art.arcane.iris.studio.map.components.MapLabels; -import art.arcane.iris.studio.map.components.MapLayer; -import art.arcane.iris.studio.map.components.MapStyle; -import art.arcane.iris.studio.map.components.PickDisplay; -import art.arcane.iris.studio.map.components.TileType; -import art.arcane.iris.studio.view.GuiMarker; -import art.arcane.iris.studio.view.GuiOverlay; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.generation.biome.IrisBiome; -import art.arcane.volmlib.util.format.Form; - -import javax.swing.JMenuItem; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.SwingUtilities; -import javax.swing.Timer; -import java.awt.Color; -import java.awt.EventQueue; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.RenderingHints; -import java.awt.Toolkit; -import java.awt.datatransfer.StringSelection; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseWheelEvent; -import java.awt.image.BufferedImage; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import java.util.UUID; -import java.util.function.Consumer; - -/** - * The tile map of the map window: draws the chosen view of the world and lets you drag, zoom and inspect it. - */ -final class MapCanvas extends JPanel { - private static final long serialVersionUID = 2094606939770332040L; - private static final Color MOB_COLOR = StudioTheme.ERROR; - private static final Color GRID_MINOR = new Color(255, 255, 255, 18); - private static final Color GRID_MAJOR = new Color(255, 255, 255, 38); - private static final Color TILE_EMPTY_A = new ThemeColor(0xF0F1F3, 0x232427); - private static final Color TILE_EMPTY_B = new ThemeColor(0xEBECEF, 0x26272B); - private static final int CARD_PADDING = 12; - private static final int RIVER_KEY_SWATCH = 12; - private static final int RIVER_KEY_SWATCH_GAP = 8; - private static final int EMPTY_ICON_SIZE = 40; - private static final int NOTIFICATION_MILLIS = 2_500; - private static final double DEFAULT_BLOCKS_PER_PIXEL = 4D; - private static final double WHEEL_ZOOM_EXPONENT = 0.08D; - private static final double KEYBOARD_ZOOM_FACTOR = 1.189207115002721D; - private static final int LEGEND_REFRESH_MILLIS = 200; - - private final UUID worldId; - private final UUID openerId; - private final Listener listener; - private final VisionRenderController controller; - private final StudioStatusBar statusBar = new StudioStatusBar(); - private final Runnable hotloadHook; - private final Timer hoverTimer; - private final Timer markerTimer; - private final Timer notificationTimer; - private final Timer provisionalTimer; - private final Timer legendTimer; - private final Map notifications = new LinkedHashMap<>(); - - private Engine engine; - private MapTileRenderer renderer; - private GuiOverlay overlay; - private boolean waterOverlay = true; - private VisionRenderController.Frame renderFrame; - private BufferedImage tileLayer; - private boolean tileLayerStale = true; - private MapStyle style = MapStyle.PLAIN; - private TileType currentType = TileType.BIOME; - private String previewRegionKey; - private PickDisplay pickDisplay = PickDisplay.PICKS; - private String viewLabel = MapView.BIOMES.label(); - private List players = List.of(); - private List entities = List.of(); - private QuickHover quickHover; - private MapHoverProbe.Details hoverDetails; - private Point cursor; - private Point dragOrigin; - private double centerX; - private double centerZ; - private long contentRevision = 1L; - private long previousPaintStartedNanos; - private double blocksPerPixel = DEFAULT_BLOCKS_PER_PIXEL; - private int paintCadenceFps; - private boolean grid; - private boolean entitiesVisible; - private boolean follow; - private boolean help; - private int coveredLeftWidth; - private boolean debug; - private boolean detailedHover; - private boolean active = true; - private boolean closed; - - MapCanvas(Engine engine, UUID worldId, UUID openerId, Listener listener) { - this.engine = Objects.requireNonNull(engine, "engine"); - this.worldId = worldId; - this.openerId = openerId; - this.listener = Objects.requireNonNull(listener, "listener"); - this.renderer = new MapTileRenderer(engine); - this.overlay = MapHost.overlayFor(engine, openerId); - this.controller = new VisionRenderController(this::onTilesChanged); - this.hotloadHook = () -> EventQueue.invokeLater(this::refreshContent); - - setBackground(StudioTheme.EDITOR_BACKGROUND); - setFocusable(true); - installMouseHandlers(); - addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent event) { - requestRender(); - } - }); - - this.hoverTimer = singleShotTimer(90, this::requestHover); - this.legendTimer = singleShotTimer(LEGEND_REFRESH_MILLIS, this::publishLegend); - this.markerTimer = new Timer(650, event -> refreshMarkers()); - this.markerTimer.setCoalesce(true); - this.notificationTimer = new Timer(200, event -> expireNotifications()); - this.notificationTimer.setCoalesce(true); - this.provisionalTimer = new Timer(500, event -> { - if (!closed && active) { - controller.retryProvisional(renderFrame); - } - }); - MapHost.registerHotloadHook(hotloadHook); - markerTimer.start(); - notificationTimer.start(); - provisionalTimer.start(); - } - - StudioStatusBar statusBar() { - return statusBar; - } - - Engine engine() { - return engine; - } - - double centerX() { - return centerX; - } - - double centerZ() { - return centerZ; - } - - boolean isGridVisible() { - return grid; - } - - boolean areEntitiesVisible() { - return entitiesVisible; - } - - boolean isFollowing() { - return follow; - } - - MapStyle style() { - return style; - } - - void start() { - refreshMarkers(); - requestRender(); - } - - void centerOn(double worldX, double worldZ) { - centerX = worldX; - centerZ = worldZ; - requestRender(); - } - - void showView(MapView view) { - if (!view.isTileMap()) { - return; - } - viewLabel = view.label(); - TileType nextType = view == MapView.REGIONS && previewRegionKey != null ? TileType.REGION_PREVIEW : view.renderType(); - if (nextType == currentType) { - return; - } - currentType = nextType; - if (currentType != TileType.HEIGHT) { - style = style.withHeightRange(null); - } - requestRender(); - } - - /** - * Shows the given region's biomes everywhere in the region view, as if every spot belonged to it; null shows the - * regions themselves again. - */ - void previewRegion(String regionKey) { - if (Objects.equals(regionKey, previewRegionKey)) { - return; - } - previewRegionKey = regionKey; - if (currentType.isRegionView()) { - currentType = regionKey == null ? TileType.REGION : TileType.REGION_PREVIEW; - requestRender(); - } - } - - PickDisplay pickDisplay() { - return pickDisplay; - } - - /** - * Draws the region or biome view's picks, the noise that picks them, or both. - */ - void showPicksAs(PickDisplay display) { - if (display == pickDisplay) { - return; - } - pickDisplay = display; - if (currentType.drawsPickNoise()) { - requestRender(); - } - } - - MapCensus.ViewArea viewArea() { - return new MapCensus.ViewArea(screenToWorldX(0D), screenToWorldZ(0D), screenToWorldX(getWidth()), - screenToWorldZ(getHeight())); - } - - private MapLayer currentLayer() { - return switch (currentType) { - case BIOME -> MapLayer.biomes(pickDisplay, waterOverlay); - case REGION -> MapLayer.regions(pickDisplay); - case REGION_PREVIEW -> MapLayer.regionPreview(previewRegionKey, pickDisplay); - default -> MapLayer.of(currentType); - }; - } - - String legendTitle() { - return currentType == TileType.REGION ? "Regions in view" : "Biomes in view"; - } - - // Tiles keep loading in the background only for the view on screen; a hidden canvas stops asking for new ones. - void setActive(boolean nextActive) { - if (closed || active == nextActive) { - return; - } - active = nextActive; - if (active) { - markerTimer.start(); - provisionalTimer.start(); - requestRender(); - } else { - controller.suspend(); - hoverTimer.stop(); - legendTimer.stop(); - markerTimer.stop(); - provisionalTimer.stop(); - clearHover(); - } - } - - void refreshContent() { - if (closed) { - return; - } - if (!ensureEngine()) { - notifyUser("No active Iris engine"); - return; - } - renderer = new MapTileRenderer(engine); - overlay = MapHost.overlayFor(engine, openerId); - contentRevision++; - requestRender(); - notifyUser("Refreshing"); - listener.onTogglesChanged(); - listener.onContentRefreshed(); - } - - void toggleShading() { - applyStyle(style.withShading(!style.shading())); - notifyUser(style.shading() ? "Terrain shading on" : "Terrain shading off"); - listener.onTogglesChanged(); - } - - boolean isWaterOverlayEnabled() { - return waterOverlay; - } - - void toggleWaterOverlay() { - waterOverlay = !waterOverlay; - if (currentType == TileType.BIOME) { - requestRender(); - } - listener.onTogglesChanged(); - } - - void toggleRegionBorders() { - applyStyle(style.withRegionBorders(!style.regionBorders())); - notifyUser(style.regionBorders() ? "Region borders on" : "Region borders off"); - listener.onTogglesChanged(); - } - - /** - * Highlights the biome or region, or clears the highlight when it is the one already highlighted. - */ - void toggleHighlight(MapLabels.Label label) { - if (label == null) { - return; - } - MapStyle.Highlight current = style.highlight(); - if (current != null && current.kind() == label.kind() && current.key().equals(label.key())) { - clearHighlight(); - return; - } - applyStyle(style.withHighlight(new MapStyle.Highlight(label.kind(), label.key(), label.name()))); - notifyUser("Highlighting " + label.name() + " · Esc clears"); - } - - void highlightUnderCursor() { - VisionRenderController.TilePixel pixel = cursor == null ? null : tilePixelAt(cursor); - if (pixel == null) { - notifyUser("Point at the map to highlight what is there"); - return; - } - toggleHighlight(pixel.subject()); - } - - /** - * Esc steps back one layer of emphasis: the highlight first, then the help. - */ - void dismissEmphasis() { - if (style.highlight() != null) { - clearHighlight(); - } else if (help) { - toggleHelp(); - } - } - - private void clearHighlight() { - applyStyle(style.withHighlight(null)); - notifyUser("Highlight cleared"); - } - - private void applyStyle(MapStyle next) { - boolean heightsWereNeeded = needsHeights(); - style = next; - if (needsHeights() != heightsWereNeeded) { - requestRender(); - } else { - tileLayerStale = true; - repaint(); - } - scheduleLegendUpdate(); - } - - private boolean needsHeights() { - return style.shading() || currentType == TileType.HEIGHT; - } - - void toggleGrid() { - grid = !grid; - repaint(); - notifyUser(grid ? "Grid on" : "Grid off"); - listener.onTogglesChanged(); - } - - void toggleEntities() { - entitiesVisible = !entitiesVisible; - if (entitiesVisible) { - refreshMarkers(); - } else { - entities = List.of(); - repaint(); - } - notifyUser(entitiesVisible ? "Entities on" : "Entities off"); - listener.onTogglesChanged(); - } - - void toggleFollow() { - follow = !follow; - if (follow && players.isEmpty()) { - follow = false; - notifyUser("No player in this world"); - } else if (follow) { - GuiMarker player = players.get(0); - centerOn(player.worldX(), player.worldZ()); - notifyUser("Following " + player.label()); - } else { - notifyUser("Stopped following"); - } - listener.onTogglesChanged(); - } - - /** - * Keeps the help, debug and notification cards clear of a panel floating over the map's left side. - */ - void setCoveredLeftWidth(int width) { - if (width == coveredLeftWidth) { - return; - } - coveredLeftWidth = width; - repaint(); - } - - void toggleHelp() { - help = !help; - repaint(); - } - - void toggleDebug() { - debug = !debug; - repaint(); - } - - void setDetailedHover(boolean detailed) { - if (detailedHover != detailed) { - detailedHover = detailed; - repaint(); - } - } - - void zoomIn() { - changeZoom(1D / KEYBOARD_ZOOM_FACTOR, cursor); - } - - void zoomOut() { - changeZoom(KEYBOARD_ZOOM_FACTOR, cursor); - } - - void resetZoom() { - changeZoom(DEFAULT_BLOCKS_PER_PIXEL / blocksPerPixel, null); - notifyUser("Zoom reset"); - } - - void close() { - if (closed) { - return; - } - closed = true; - hoverTimer.stop(); - legendTimer.stop(); - markerTimer.stop(); - notificationTimer.stop(); - provisionalTimer.stop(); - MapHost.unregisterHotloadHook(hotloadHook); - controller.close(); - } - - private static Timer singleShotTimer(int delay, Runnable task) { - Timer timer = new Timer(delay, event -> task.run()); - timer.setRepeats(false); - timer.setCoalesce(true); - return timer; - } - - private void installMouseHandlers() { - MouseAdapter handler = new MouseAdapter() { - @Override - public void mouseMoved(MouseEvent event) { - cursor = event.getPoint(); - setDetailedHover(event.isShiftDown()); - showQuickHover(); - hoverTimer.restart(); - refreshStatus(); - } - - @Override - public void mouseDragged(MouseEvent event) { - cursor = event.getPoint(); - if (dragOrigin == null) { - return; - } - centerX += (dragOrigin.x - event.getX()) * blocksPerPixel; - centerZ += (dragOrigin.y - event.getY()) * blocksPerPixel; - dragOrigin = event.getPoint(); - stopFollowing(); - clearHover(); - requestRender(); - } - - @Override - public void mouseWheelMoved(MouseWheelEvent event) { - cursor = event.getPoint(); - changeZoom(Math.pow(2D, event.getPreciseWheelRotation() * WHEEL_ZOOM_EXPONENT), cursor); - event.consume(); - } - - @Override - public void mousePressed(MouseEvent event) { - requestFocusInWindow(); - cursor = event.getPoint(); - if (event.isPopupTrigger()) { - showContextMenu(event); - } else if (SwingUtilities.isLeftMouseButton(event)) { - dragOrigin = event.getPoint(); - } - } - - @Override - public void mouseReleased(MouseEvent event) { - dragOrigin = null; - if (event.isPopupTrigger()) { - showContextMenu(event); - } - } - - @Override - public void mouseClicked(MouseEvent event) { - cursor = event.getPoint(); - if (!SwingUtilities.isLeftMouseButton(event)) { - return; - } - if (event.isControlDown()) { - teleportTo(event.getPoint()); - } else if (event.isAltDown()) { - openInEditor(event.getPoint()); - } else if (event.getClickCount() == 2) { - showPalettesAt(event.getPoint()); - } - } - - @Override - public void mouseEntered(MouseEvent event) { - cursor = event.getPoint(); - } - - @Override - public void mouseExited(MouseEvent event) { - cursor = null; - clearHover(); - hoverTimer.stop(); - refreshStatus(); - repaint(); - } - }; - addMouseListener(handler); - addMouseMotionListener(handler); - addMouseWheelListener(handler); - } - - private void showContextMenu(MouseEvent event) { - Point point = event.getPoint(); - int blockX = floorWorldCoordinate(screenToWorldX(point.x)); - int blockZ = floorWorldCoordinate(screenToWorldZ(point.y)); - JPopupMenu menu = new JPopupMenu(); - addHighlightItems(menu, tilePixelAt(point)); - menu.add(menuItem("Show palettes here", () -> showPalettesAt(point))); - menu.add(menuItem("Teleport here", () -> teleportTo(point))); - menu.add(menuItem(currentType == TileType.REGION ? "Open region file" : "Open biome file", () -> openInEditor(point))); - menu.addSeparator(); - menu.add(menuItem("Copy coordinates (" + blockX + ", " + blockZ + ")", () -> copyCoordinates(blockX, blockZ))); - menu.show(this, point.x, point.y); - } - - private void addHighlightItems(JPopupMenu menu, VisionRenderController.TilePixel pixel) { - MapLabels.Label subject = pixel == null ? null : pixel.subject(); - MapLabels.Label region = pixel == null ? null : pixel.region(); - if (subject != null) { - menu.add(menuItem(highlightText(subject), () -> toggleHighlight(subject))); - } - if (region != null && subject != null && subject.kind() != MapLabels.Kind.REGION) { - menu.add(menuItem(highlightText(region), () -> toggleHighlight(region))); - } - if (style.highlight() != null) { - menu.add(menuItem("Clear highlight", this::clearHighlight)); - } - if (menu.getComponentCount() > 0) { - menu.addSeparator(); - } - } - - private String highlightText(MapLabels.Label label) { - MapStyle.Highlight current = style.highlight(); - boolean highlighted = current != null && current.kind() == label.kind() && current.key().equals(label.key()); - String kind = label.kind() == MapLabels.Kind.REGION ? "region " : ""; - return (highlighted ? "Stop highlighting " : "Highlight ") + kind + label.name(); - } - - private static JMenuItem menuItem(String text, Runnable action) { - JMenuItem item = new JMenuItem(text); - item.addActionListener(event -> action.run()); - return item; - } - - private void copyCoordinates(int blockX, int blockZ) { - Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(blockX + " " + blockZ), null); - notifyUser("Copied " + blockX + ", " + blockZ); - } - - private void showPalettesAt(Point point) { - listener.onShowPalettesAt(screenToWorldX(point.x), screenToWorldZ(point.y)); - } - - void findSurfaceBiome(double worldX, double worldZ, Consumer onFound) { - Engine probeEngine = engine; - controller.submitProbe(renderFrame, () -> { - IrisBiome biome = probeEngine.getSurfaceBiome(floorWorldCoordinate(worldX), floorWorldCoordinate(worldZ)); - return biome == null ? null : biome.getLoadKey(); - }, onFound); - } - - @Override - protected void paintComponent(Graphics graphics) { - long started = System.nanoTime(); - if (previousPaintStartedNanos > 0L) { - long interval = started - previousPaintStartedNanos; - paintCadenceFps = interval > 2_000_000_000L - ? 0 - : (int) Math.min(240L, Math.round(1_000_000_000D / Math.max(1L, interval))); - } - previousPaintStartedNanos = started; - super.paintComponent(graphics); - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - if (showsRiversWithoutHydrology()) { - renderNoHydrology(canvas); - return; - } - renderTiles(canvas); - if (grid) { - renderGrid(canvas); - } - canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - renderMarkers(canvas); - renderLegend(canvas); - if (help) { - renderHelp(canvas); - } else if (debug) { - renderDebug(canvas); - } - renderHover(canvas); - renderNotifications(canvas); - } catch (Throwable error) { - IrisLogging.debug("Vision paint failed: " + error.getClass().getSimpleName() + ": " + error.getMessage()); - } finally { - canvas.dispose(); - } - } - - private boolean showsRiversWithoutHydrology() { - return currentType == TileType.RIVER && !engine.getComplex().getHydrologyRuntime().enabled(); - } - - private void renderNoHydrology(Graphics2D canvas) { - canvas.setColor(StudioTheme.EDITOR_BACKGROUND); - canvas.fillRect(0, 0, getWidth(), getHeight()); - EmptyState empty = new EmptyState(MapViewIcon.large(MapView.RIVERS, EMPTY_ICON_SIZE), "No rivers planned", - "Enable hydrology in", "dimensions/" + engine.getDimension().getLoadKey() + ".json", - "They appear here once the pack reloads."); - empty.paint(canvas, this, coveredLeftWidth + (getWidth() - coveredLeftWidth) / 2, getHeight() / 2); - } - - // The display server gets one finished picture per paint: handing it every tile separately made the map lag. - private void renderTiles(Graphics2D canvas) { - canvas.drawImage(currentTileLayer(), 0, 0, null); - } - - // The theme changed: the cached layer holds the old theme's background. - @Override - public void updateUI() { - super.updateUI(); - tileLayerStale = true; - } - - private BufferedImage currentTileLayer() { - int width = Math.max(1, getWidth()); - int height = Math.max(1, getHeight()); - if (tileLayer == null || tileLayer.getWidth() != width || tileLayer.getHeight() != height) { - tileLayer = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - tileLayer.setAccelerationPriority(0F); - tileLayerStale = true; - } - if (tileLayerStale) { - Graphics2D layer = tileLayer.createGraphics(); - try { - composeTiles(layer); - } finally { - layer.dispose(); - } - tileLayerStale = false; - } - return tileLayer; - } - - private void composeTiles(Graphics2D canvas) { - VisionRenderController.Frame frame = renderFrame; - canvas.setColor(StudioTheme.EDITOR_BACKGROUND); - canvas.fillRect(0, 0, getWidth(), getHeight()); - if (frame == null) { - return; - } - canvas.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); - double frameTileSpan = VisionRenderController.TILE_PIXELS * frame.renderBlocksPerPixel(); - for (VisionRenderController.VisibleTile tile : frame.tiles()) { - double worldX = tile.tileX() * frameTileSpan; - double worldZ = tile.tileZ() * frameTileSpan; - int screenX = (int) Math.round(worldToScreenX(worldX)); - int screenY = (int) Math.round(worldToScreenZ(worldZ)); - int tileWidth = Math.max(1, (int) Math.round(worldToScreenX(worldX + frameTileSpan)) - screenX); - int tileHeight = Math.max(1, (int) Math.round(worldToScreenZ(worldZ + frameTileSpan)) - screenY); - if (tile.tile() != null) { - canvas.drawImage(tile.tile().image(style), screenX, screenY, tileWidth, tileHeight, null); - if (!tile.provisional()) { - continue; - } - } else { - canvas.setColor(((tile.tileX() ^ tile.tileZ()) & 1L) == 0L ? TILE_EMPTY_A : TILE_EMPTY_B); - canvas.fillRect(screenX, screenY, tileWidth, tileHeight); - } - drawFallback(canvas, controller.fallback(frame, tile), screenX, screenY, tileWidth, tileHeight); - } - } - - private void drawFallback(Graphics2D canvas, VisionRenderController.Fallback fallback, int screenX, int screenY, - int tileWidth, int tileHeight) { - if (fallback == null) { - return; - } - for (VisionRenderController.FallbackPiece piece : fallback.pieces()) { - int left = screenX + (int) Math.round(piece.offsetX() * tileWidth); - int top = screenY + (int) Math.round(piece.offsetZ() * tileHeight); - int right = screenX + (int) Math.round((piece.offsetX() + piece.size()) * tileWidth); - int bottom = screenY + (int) Math.round((piece.offsetZ() + piece.size()) * tileHeight); - canvas.drawImage(piece.tile().image(style), left, top, right, bottom, - piece.sourceX(), piece.sourceZ(), piece.sourceX() + piece.sourceSize(), piece.sourceZ() + piece.sourceSize(), null); - } - } - - private void renderGrid(Graphics2D canvas) { - double chunkPixels = 16D / blocksPerPixel; - if (chunkPixels >= 8D) { - canvas.setColor(GRID_MINOR); - drawWorldGrid(canvas, 16D, chunkPixels); - } - canvas.setColor(GRID_MAJOR); - double regionPixels = 512D / blocksPerPixel; - if (regionPixels >= 8D) { - drawWorldGrid(canvas, 512D, regionPixels); - } - } - - private void drawWorldGrid(Graphics2D canvas, double blockSpacing, double pixelSpacing) { - double firstX = Math.floor(screenToWorldX(0D) / blockSpacing) * blockSpacing; - double firstZ = Math.floor(screenToWorldZ(0D) / blockSpacing) * blockSpacing; - for (double screen = worldToScreenX(firstX); screen <= getWidth(); screen += pixelSpacing) { - int screenX = (int) Math.round(screen); - canvas.drawLine(screenX, 0, screenX, getHeight()); - } - for (double screen = worldToScreenZ(firstZ); screen <= getHeight(); screen += pixelSpacing) { - int screenY = (int) Math.round(screen); - canvas.drawLine(0, screenY, getWidth(), screenY); - } - } - - private void renderMarkers(Graphics2D canvas) { - if (entitiesVisible) { - canvas.setColor(MOB_COLOR); - for (GuiMarker marker : entities) { - int screenX = (int) Math.round(worldToScreenX(marker.worldX())); - int screenY = (int) Math.round(worldToScreenZ(marker.worldZ())); - fillDot(canvas, screenX, screenY, 3); - } - } - - for (GuiMarker marker : players) { - int screenX = (int) Math.round(worldToScreenX(marker.worldX())); - int screenY = (int) Math.round(worldToScreenZ(marker.worldZ())); - PlayerMarker.paint(canvas, screenX, screenY, marker); - } - if (entitiesVisible && detailedHover) { - renderNearestEntity(canvas); - } - } - - private static void fillDot(Graphics2D canvas, int centerX, int centerY, int logicalRadius) { - int radius = StudioTheme.scale(logicalRadius); - canvas.fillOval(centerX - radius, centerY - radius, radius * 2, radius * 2); - } - - private void renderNearestEntity(Graphics2D canvas) { - Point point = cursor; - if (point == null || entities.isEmpty()) { - return; - } - double worldX = screenToWorldX(point.x); - double worldZ = screenToWorldZ(point.y); - GuiMarker nearest = null; - double nearestDistance = Double.MAX_VALUE; - for (GuiMarker marker : entities) { - double deltaX = marker.worldX() - worldX; - double deltaZ = marker.worldZ() - worldZ; - double distance = deltaX * deltaX + deltaZ * deltaZ; - if (distance < nearestDistance) { - nearestDistance = distance; - nearest = marker; - } - } - if (nearest == null) { - return; - } - ArrayList lines = new ArrayList<>(); - lines.add(nearest.label()); - lines.add("Position " + ((int) nearest.worldX()) + ", " + ((int) nearest.worldY()) + ", " + ((int) nearest.worldZ())); - if (nearest.maxHealth() > 0D) { - lines.add("Health " + Form.f(nearest.health(), 1) + " / " + Form.f(nearest.maxHealth(), 1)); - } - int padding = StudioTheme.scale(CARD_PADDING); - drawCard(canvas, getWidth() - padding, padding, 1D, 0D, lines); - } - - private void renderLegend(Graphics2D canvas) { - switch (currentType) { - case HEIGHT -> renderHeightKey(canvas); - case RIVER -> renderRiverKey(canvas); - default -> { - } - } - } - - private void renderRiverKey(Graphics2D canvas) { - canvas.setFont(StudioTheme.smallFont()); - FontMetrics metrics = canvas.getFontMetrics(); - int padding = StudioTheme.scale(CARD_PADDING); - int swatch = StudioTheme.scale(RIVER_KEY_SWATCH); - int swatchGap = StudioTheme.scale(RIVER_KEY_SWATCH_GAP); - int rowHeight = Math.max(swatch, metrics.getHeight()); - List rows = RiverKey.rows(); - int widestLabel = rows.stream().mapToInt(row -> metrics.stringWidth(row.label())).max().orElse(0); - int width = padding * 2 + swatch + swatchGap + widestLabel; - int height = padding * 2 + rowHeight * rows.size(); - int x = getWidth() - width - padding; - int y = getHeight() - height - padding; - StudioOverlay.drawCard(canvas, x, y, width, height); - for (int index = 0; index < rows.size(); index++) { - RiverKey.Row row = rows.get(index); - int rowY = y + padding + index * rowHeight; - canvas.setColor(new Color(row.color())); - canvas.fillRect(x + padding, rowY + (rowHeight - swatch) / 2, swatch, swatch); - canvas.setColor(StudioTheme.SECONDARY_TEXT); - canvas.drawString(row.label(), x + padding + swatch + swatchGap, - rowY + (rowHeight - metrics.getHeight()) / 2 + metrics.getAscent()); - } - } - - private void renderHeightKey(Graphics2D canvas) { - MapStyle.HeightRange range = currentHeightRange(); - canvas.setFont(StudioTheme.smallFont()); - int padding = StudioTheme.scale(CARD_PADDING); - int gradientHeight = StudioTheme.scale(14); - int labelGap = StudioTheme.scale(4); - int width = StudioTheme.scale(244); - int height = padding * 2 + gradientHeight + labelGap + canvas.getFontMetrics().getHeight(); - int x = getWidth() - width - padding; - int y = getHeight() - height - padding; - StudioOverlay.drawCard(canvas, x, y, width, height); - int gradientX = x + padding; - int gradientY = y + padding; - int gradientWidth = width - padding * 2; - double span = Math.max(1D, range.highest() - range.lowest()); - for (int pixel = 0; pixel < gradientWidth; pixel++) { - double sampleHeight = range.lowest() + span * pixel / Math.max(1D, gradientWidth - 1D); - canvas.setColor(new Color(MapTileRenderer.heightColor(sampleHeight, range))); - canvas.drawLine(gradientX + pixel, gradientY, gradientX + pixel, gradientY + gradientHeight); - } - canvas.setColor(StudioTheme.SECONDARY_TEXT); - int labelBaseline = gradientY + gradientHeight + labelGap + canvas.getFontMetrics().getAscent(); - String minimum = Integer.toString((int) Math.round(range.lowest())); - String sea = "sea " + Math.round(range.seaLevel()); - String maximum = Integer.toString((int) Math.round(range.highest())); - int minimumRight = gradientX + canvas.getFontMetrics().stringWidth(minimum); - int maximumX = gradientX + gradientWidth - canvas.getFontMetrics().stringWidth(maximum); - int seaWidth = canvas.getFontMetrics().stringWidth(sea); - int seaX = gradientX + (int) Math.round(gradientWidth * (range.seaLevel() - range.lowest()) / span) - seaWidth / 2; - canvas.drawString(minimum, gradientX, labelBaseline); - if (seaX > minimumRight + labelGap && seaX + seaWidth < maximumX - labelGap) { - canvas.drawString(sea, seaX, labelBaseline); - } - canvas.drawString(maximum, maximumX, labelBaseline); - } - - private void renderHover(Graphics2D canvas) { - QuickHover quick = quickHover; - if (quick == null) { - return; - } - MapHoverProbe.Details details = hoverDetails; - MapHoverCard card = MapHoverCard.of(quick.subject(), quick.region(), details, currentType, detailedHover, - quick.worldX(), quick.worldZ()); - int screenX = (int) Math.round(worldToScreenX(quick.worldX())) + StudioTheme.scale(16); - int screenY = (int) Math.round(worldToScreenZ(quick.worldZ())); - card.paint(canvas, screenX, screenY, getWidth(), getHeight()); - } - - private void renderHelp(Graphics2D canvas) { - List keys = List.of("Drag", "Wheel / + -", "\\", "Double-click", "Right-click", "Ctrl+Click", "Alt+Click", - "Shift", "H", "Esc", "S", "B", "R", "F", "G", "E", "M", "1 to 0, P", "/"); - List descriptions = List.of( - "Move the map", - "Zoom in and out", - "Reset zoom", - "Show the palettes of that spot", - "More actions for that spot", - "Teleport there", - "Open the biome file", - "More details while hovering", - "Highlight what is under the cursor", - "Clear the highlight", - "Terrain shading", - "Region borders", - "Redraw the map", - "Follow your player", - "Chunk and region grid", - "Show entities", - "Next view", - "Pick a view", - "Hide this help" - ); - canvas.setFont(StudioTheme.boldFont()); - int keyWidth = 0; - for (String key : keys) { - keyWidth = Math.max(keyWidth, canvas.getFontMetrics().stringWidth(key)); - } - canvas.setFont(StudioTheme.font()); - int descriptionWidth = 0; - for (String description : descriptions) { - descriptionWidth = Math.max(descriptionWidth, canvas.getFontMetrics().stringWidth(description)); - } - int padding = StudioTheme.scale(CARD_PADDING); - int columnGap = StudioTheme.scale(18); - int lineHeight = canvas.getFontMetrics().getHeight() + StudioTheme.scale(4); - int width = keyWidth + columnGap + descriptionWidth + padding * 2; - int height = keys.size() * lineHeight + padding * 2; - int left = coveredLeftWidth + padding; - StudioOverlay.drawCard(canvas, left, padding, width, height); - for (int index = 0; index < keys.size(); index++) { - int y = padding * 2 + canvas.getFontMetrics().getAscent() + index * lineHeight; - canvas.setFont(StudioTheme.boldFont()); - canvas.setColor(StudioTheme.LINK); - canvas.drawString(keys.get(index), left + padding, y); - canvas.setFont(StudioTheme.font()); - canvas.setColor(StudioTheme.SECONDARY_TEXT); - canvas.drawString(descriptions.get(index), left + padding + keyWidth + columnGap, y); - } - } - - private void renderDebug(Graphics2D canvas) { - VisionRenderController.Progress progress = controller.progress(renderFrame); - VisionRenderController.Frame frame = renderFrame; - ArrayList lines = new ArrayList<>(); - lines.add("Tiles " + progress.ready() + " / " + progress.total() + " drawn"); - lines.add("Render threads busy " + progress.activeWorkers()); - lines.add("Tile scale " + (frame == null ? "-" : Form.f(frame.renderBlocksPerPixel(), 0)) + " blocks/px"); - lines.add(paintCadenceFps + " paints per second"); - int padding = StudioTheme.scale(CARD_PADDING); - drawCard(canvas, coveredLeftWidth + padding, getHeight() - padding, 0D, 1D, lines); - } - - private void renderNotifications(Graphics2D canvas) { - if (notifications.isEmpty()) { - return; - } - String text = String.join(" · ", notifications.keySet()); - canvas.setFont(StudioTheme.font()); - int textWidth = canvas.getFontMetrics().stringWidth(text); - int padding = StudioTheme.scale(CARD_PADDING); - int width = textWidth + padding * 2; - int height = canvas.getFontMetrics().getHeight() + padding; - int x = coveredLeftWidth + (getWidth() - coveredLeftWidth - width) / 2; - int y = getHeight() - height - StudioTheme.scale(16); - StudioOverlay.drawCard(canvas, x, y, width, height); - canvas.setColor(StudioTheme.TEXT); - canvas.drawString(text, x + padding, y + padding / 2 + canvas.getFontMetrics().getAscent()); - } - - private void drawCard(Graphics2D canvas, int anchorX, int anchorY, double pushX, double pushY, List lines) { - canvas.setFont(StudioTheme.font()); - int lineHeight = canvas.getFontMetrics().getHeight(); - int width = 0; - for (int index = 0; index < lines.size(); index++) { - canvas.setFont(index == 0 ? StudioTheme.boldFont() : StudioTheme.font()); - width = Math.max(width, canvas.getFontMetrics().stringWidth(lines.get(index))); - } - int padding = StudioTheme.scale(CARD_PADDING); - width += padding * 2; - int height = lines.size() * lineHeight + padding * 2; - int x = (int) Math.round(anchorX - width * pushX); - int y = (int) Math.round(anchorY - height * pushY); - x = Math.max(padding, Math.min(getWidth() - width - padding, x)); - y = Math.max(padding, Math.min(getHeight() - height - padding, y)); - StudioOverlay.drawCard(canvas, x, y, width, height); - for (int index = 0; index < lines.size(); index++) { - boolean title = index == 0; - canvas.setFont(title ? StudioTheme.boldFont() : StudioTheme.font()); - canvas.setColor(title ? StudioTheme.TEXT : StudioTheme.SECONDARY_TEXT); - canvas.drawString(lines.get(index), x + padding, y + padding + canvas.getFontMetrics().getAscent() + index * lineHeight); - } - } - - private void onTilesChanged() { - if (closed || !active) { - return; - } - tileLayerStale = true; - repaint(); - refreshStatus(); - scheduleLegendUpdate(); - if (quickHover != null && quickHover.subject() == null) { - showQuickHover(); - } - } - - // At most one count per interval however fast tiles arrive, so the legend stays live without costing frames. - private void scheduleLegendUpdate() { - if (!legendTimer.isRunning()) { - legendTimer.start(); - } - } - - private void publishLegend() { - if (closed || !active) { - return; - } - MapTileRenderer legendRenderer = renderer; - TileType type = currentType; - MapCensus.ViewArea area = viewArea(); - List shares = MapCensus.count(renderFrame, area, label -> legendRenderer.legendColor(label, type)); - listener.onLegendChanged(legendTitle(), shares, style.highlight()); - if (type == TileType.HEIGHT) { - fitHeightColorsToView(area); - } - } - - // The height colours stretch over the heights on screen, so plains and mountains don't share one shade of green. - private void fitHeightColorsToView(MapCensus.ViewArea area) { - MapStyle.HeightRange measured = MapCensus.heightRange(renderFrame, area, renderer.defaultHeightRange().seaLevel()); - if (measured != null && !measured.equals(style.heightRange())) { - applyStyle(style.withHeightRange(measured)); - } - } - - private MapStyle.HeightRange currentHeightRange() { - return style.heightRange() == null ? renderer.defaultHeightRange() : style.heightRange(); - } - - private void requestRender() { - tileLayerStale = true; - if (closed || !active || getWidth() < 1 || getHeight() < 1 || !ensureEngine()) { - repaint(); - return; - } - clearHover(); - VisionRenderController.RenderSpec spec = new VisionRenderController.RenderSpec( - renderer, - currentLayer(), - contentRevision, - centerX, - centerZ, - blocksPerPixel, - getWidth(), - getHeight(), - needsHeights() - ); - renderFrame = controller.request(spec); - repaint(); - refreshStatus(); - scheduleLegendUpdate(); - } - - private void refreshStatus() { - int viewWidthBlocks = (int) (blocksPerPixel * getWidth()); - int viewHeightBlocks = (int) (blocksPerPixel * getHeight()); - statusBar.showSummary(viewLabel + " " + formatScale(blocksPerPixel) + " blocks/px " - + Form.f(viewWidthBlocks) + " × " + Form.f(viewHeightBlocks) + " blocks"); - VisionRenderController.Progress progress = controller.progress(renderFrame); - boolean drawing = progress.completion() < 1D; - statusBar.showActivity(drawing ? "Drawing " + progress.ready() + " of " + progress.total() + " tiles" : ""); - statusBar.showProgress(progress.completion()); - Point point = cursor; - double worldX = point == null ? centerX : screenToWorldX(point.x); - double worldZ = point == null ? centerZ : screenToWorldZ(point.y); - statusBar.showPosition("X " + Form.f(floorWorldCoordinate(worldX)) + " Z " + Form.f(floorWorldCoordinate(worldZ))); - } - - private static String formatScale(double blocksPerPixel) { - if (blocksPerPixel >= 1D) { - return Form.f(blocksPerPixel, 1); - } - return "1/" + String.format(Locale.ROOT, "%.0f", 1D / blocksPerPixel); - } - - private boolean ensureEngine() { - Engine activeEngine = engine; - if (activeEngine != null && !activeEngine.isClosed() && activeEngine.getComplex() != null) { - return true; - } - try { - Engine reacquired = MapHost.findEngine(worldId); - if (reacquired == null || reacquired.isClosed() || reacquired.getComplex() == null) { - return false; - } - engine = reacquired; - renderer = new MapTileRenderer(reacquired); - overlay = MapHost.overlayFor(reacquired, openerId); - contentRevision++; - return true; - } catch (Throwable error) { - IrisLogging.debug("Vision engine reacquisition failed: " + error.getClass().getSimpleName() + ": " + error.getMessage()); - return false; - } - } - - private void refreshMarkers() { - if (closed || overlay == null) { - return; - } - try { - List nextPlayers = overlay.players(); - players = nextPlayers == null ? List.of() : List.copyOf(nextPlayers); - if (entitiesVisible) { - overlay.requestEntities(next -> EventQueue.invokeLater(() -> { - if (!closed && entitiesVisible) { - entities = next == null ? List.of() : List.copyOf(next); - repaint(); - } - })); - } else if (!entities.isEmpty()) { - entities = List.of(); - } - if (follow && !players.isEmpty()) { - GuiMarker player = players.get(0); - if (Math.abs(centerX - player.worldX()) > 0.5D || Math.abs(centerZ - player.worldZ()) > 0.5D) { - centerOn(player.worldX(), player.worldZ()); - } - } - if (active) { - repaint(); - } - } catch (Throwable error) { - IrisLogging.debug("Vision marker refresh failed: " + error.getClass().getSimpleName() + ": " + error.getMessage()); - } - } - - private void requestHover() { - Point point = cursor; - VisionRenderController.Frame frame = renderFrame; - Engine probeEngine = engine; - if (closed || !active || point == null || frame == null || probeEngine == null || probeEngine.getComplex() == null) { - return; - } - double worldX = screenToWorldX(point.x); - double worldZ = screenToWorldZ(point.y); - controller.submitProbe( - frame, - () -> MapHoverProbe.sample(probeEngine, worldX, worldZ, previewedRegion(), hoverExplainsBiomePick()), - details -> { - QuickHover quick = quickHover; - if (quick != null && quick.worldX() == details.worldX() && quick.worldZ() == details.worldZ()) { - hoverDetails = details; - repaint(); - } - } - ); - } - - // These views' hover card names the surface biome, so the whole way to it is worth looking up. - private boolean hoverExplainsBiomePick() { - return currentType.drawsPickNoise() || currentType == TileType.HEIGHT; - } - - private String previewedRegion() { - return currentType == TileType.REGION_PREVIEW ? previewRegionKey : null; - } - - // The drawn tiles already know the biome and region under the cursor, so the card follows the mouse without waiting. - private void showQuickHover() { - Point point = cursor; - if (point == null || dragOrigin != null) { - return; - } - double worldX = screenToWorldX(point.x); - double worldZ = screenToWorldZ(point.y); - VisionRenderController.TilePixel pixel = tilePixelAt(point); - quickHover = new QuickHover(worldX, worldZ, pixel == null ? null : pixel.subject(), pixel == null ? null : pixel.region()); - repaint(); - } - - private void clearHover() { - quickHover = null; - hoverDetails = null; - } - - private VisionRenderController.TilePixel tilePixelAt(Point point) { - VisionRenderController.Frame frame = renderFrame; - return frame == null ? null : frame.pixelAt(screenToWorldX(point.x), screenToWorldZ(point.y)); - } - - private void stopFollowing() { - if (follow) { - follow = false; - listener.onTogglesChanged(); - } - } - - private void notifyUser(String message) { - notifications.put(message, System.currentTimeMillis() + NOTIFICATION_MILLIS); - repaint(); - } - - private void expireNotifications() { - long now = System.currentTimeMillis(); - boolean changed = false; - Iterator> iterator = notifications.entrySet().iterator(); - while (iterator.hasNext()) { - if (iterator.next().getValue() <= now) { - iterator.remove(); - changed = true; - } - } - if (changed) { - repaint(); - } - } - - private void changeZoom(double factor, Point anchor) { - if (!Double.isFinite(factor) || factor <= 0D) { - return; - } - Point effectiveAnchor = anchor == null ? new Point(getWidth() / 2, getHeight() / 2) : anchor; - VisionViewport next = new VisionViewport(centerX, centerZ, blocksPerPixel).zoomAt( - effectiveAnchor.x, - effectiveAnchor.y, - getWidth(), - getHeight(), - factor, - VisionRenderController.MINIMUM_VIEW_BLOCKS_PER_PIXEL, - VisionRenderController.MAXIMUM_BLOCKS_PER_PIXEL - ); - if (next.blocksPerPixel() == blocksPerPixel) { - return; - } - centerX = next.centerX(); - centerZ = next.centerZ(); - blocksPerPixel = next.blocksPerPixel(); - stopFollowing(); - clearHover(); - requestRender(); - } - - private double screenToWorldX(double screenX) { - return centerX + (screenX - getWidth() * 0.5D) * blocksPerPixel; - } - - private double screenToWorldZ(double screenY) { - return centerZ + (screenY - getHeight() * 0.5D) * blocksPerPixel; - } - - private double worldToScreenX(double worldX) { - return getWidth() * 0.5D + (worldX - centerX) / blocksPerPixel; - } - - private double worldToScreenZ(double worldZ) { - return getHeight() * 0.5D + (worldZ - centerZ) / blocksPerPixel; - } - - private void openInEditor(Point point) { - Engine activeEngine = engine; - if (activeEngine == null || point == null) { - return; - } - double worldX = screenToWorldX(point.x); - double worldZ = screenToWorldZ(point.y); - MapLayer layer = currentLayer(); - controller.submitProbe( - renderFrame, - () -> PackFileOpener.openAt(activeEngine, worldX, worldZ, layer), - opened -> opened.ifPresent(fileName -> notifyUser("Opened " + fileName)) - ); - } - - private void teleportTo(Point point) { - if (overlay == null || point == null) { - notifyUser("No player in this world"); - return; - } - int worldX = floorWorldCoordinate(screenToWorldX(point.x)); - int worldZ = floorWorldCoordinate(screenToWorldZ(point.y)); - overlay.teleport(worldX, worldZ); - notifyUser("Teleporting to " + worldX + ", " + worldZ); - } - - static int floorWorldCoordinate(double coordinate) { - return (int) StrictMath.floor(coordinate); - } - - interface Listener { - void onTogglesChanged(); - - void onContentRefreshed(); - - void onShowPalettesAt(double worldX, double worldZ); - - void onLegendChanged(String title, List shares, MapStyle.Highlight highlight); - } - - private record QuickHover(double worldX, double worldZ, MapLabels.Label subject, MapLabels.Label region) { - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/MapCensus.java b/core/src/main/java/art/arcane/iris/studio/map/MapCensus.java deleted file mode 100644 index a8283a4ba..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/MapCensus.java +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.studio.map.components.MapLabels; -import art.arcane.iris.studio.map.components.MapStyle; -import art.arcane.iris.studio.map.components.MapTile; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.ToIntFunction; - -/** - * Measures the visible part of the map from the tiles already drawn: how much each biome or region covers, and which - * heights it spans. - */ -final class MapCensus { - private static final long MAXIMUM_COUNTED_PIXELS = 250_000L; - private static final int MINIMUM_HEIGHT_SAMPLES = 64; - private static final double LOW_HEIGHT_PERCENTILE = 0.01D; - private static final double HIGH_HEIGHT_PERCENTILE = 0.99D; - private static final double HEIGHT_RANGE_STEP_BLOCKS = 8D; - private static final double MINIMUM_WATER_DEPTH_BLOCKS = 8D; - private static final double MINIMUM_LAND_HEIGHT_BLOCKS = 16D; - - private MapCensus() { - } - - static List count(VisionRenderController.Frame frame, ViewArea area, ToIntFunction colorOf) { - Map counts = new HashMap<>(); - MapLabels[] labels = new MapLabels[1]; - long counted = visitVisiblePixels(frame, area, (tile, pixelX, pixelZ) -> { - labels[0] = tile.labels(); - counts.computeIfAbsent(tile.subjectAt(pixelX, pixelZ), id -> new long[1])[0]++; - }); - return shares(counts, labels[0], counted, colorOf); - } - - /** - * The heights on screen, ignoring the highest and lowest few percent so one spike doesn't wash out every colour. - * Rounded to whole steps, so panning around doesn't recolour the map for every small change. - * - * @return the range, or null until enough of the map is drawn to tell - */ - static MapStyle.HeightRange heightRange(VisionRenderController.Frame frame, ViewArea area, double seaLevel) { - DoubleList heights = new DoubleList(); - visitVisiblePixels(frame, area, (tile, pixelX, pixelZ) -> { - if (tile.hasHeights()) { - heights.add(tile.heightAt(pixelX, pixelZ)); - } - }); - if (heights.size() < MINIMUM_HEIGHT_SAMPLES) { - return null; - } - double[] sorted = heights.sorted(); - double low = sorted[(int) ((sorted.length - 1) * LOW_HEIGHT_PERCENTILE)]; - double high = sorted[(int) ((sorted.length - 1) * HIGH_HEIGHT_PERCENTILE)]; - double lowest = Math.floor(Math.min(low, seaLevel - MINIMUM_WATER_DEPTH_BLOCKS) / HEIGHT_RANGE_STEP_BLOCKS) - * HEIGHT_RANGE_STEP_BLOCKS; - double highest = Math.ceil(Math.max(high, seaLevel + MINIMUM_LAND_HEIGHT_BLOCKS) / HEIGHT_RANGE_STEP_BLOCKS) - * HEIGHT_RANGE_STEP_BLOCKS; - return new MapStyle.HeightRange(lowest, seaLevel, highest); - } - - private static long visitVisiblePixels(VisionRenderController.Frame frame, ViewArea area, PixelVisitor visitor) { - if (frame == null) { - return 0L; - } - double blocksPerPixel = frame.renderBlocksPerPixel(); - int stride = countingStride(area.maximumX() - area.minimumX(), area.maximumZ() - area.minimumZ(), blocksPerPixel); - double tileSpan = VisionRenderController.TILE_PIXELS * blocksPerPixel; - long visited = 0L; - for (VisionRenderController.VisibleTile visible : frame.tiles()) { - MapTile tile = visible.tile(); - if (tile == null) { - continue; - } - double originX = visible.tileX() * tileSpan; - double originZ = visible.tileZ() * tileSpan; - int firstX = firstPixel(area.minimumX() - originX, blocksPerPixel, stride, visible.tileX()); - int firstZ = firstPixel(area.minimumZ() - originZ, blocksPerPixel, stride, visible.tileZ()); - int endX = endPixel(area.maximumX() - originX, blocksPerPixel, tile.size()); - int endZ = endPixel(area.maximumZ() - originZ, blocksPerPixel, tile.size()); - for (int pixelZ = firstZ; pixelZ < endZ; pixelZ += stride) { - for (int pixelX = firstX; pixelX < endX; pixelX += stride) { - visitor.visit(tile, pixelX, pixelZ); - visited++; - } - } - } - return visited; - } - - private static List shares(Map counts, MapLabels labels, long counted, - ToIntFunction colorOf) { - if (labels == null || counted == 0L) { - return List.of(); - } - List shares = new ArrayList<>(counts.size()); - for (Map.Entry entry : counts.entrySet()) { - MapLabels.Label label = labels.label(entry.getKey()); - if (label != null) { - shares.add(new Share(label, colorOf.applyAsInt(label), entry.getValue()[0] / (double) counted)); - } - } - shares.sort(Comparator.comparingDouble(Share::fraction).reversed().thenComparing(share -> share.label().name())); - return List.copyOf(shares); - } - - // Counting every pixel of a big screen is wasted work; an evenly spread sample gives the same percentages. - private static int countingStride(double widthBlocks, double heightBlocks, double blocksPerPixel) { - double pixels = (widthBlocks / blocksPerPixel) * (heightBlocks / blocksPerPixel); - return Math.max(1, (int) Math.ceil(Math.sqrt(pixels / MAXIMUM_COUNTED_PIXELS))); - } - - // Starting on the global stride grid keeps neighbouring tiles from sampling the same columns twice as densely. - private static int firstPixel(double offsetBlocks, double blocksPerPixel, int stride, long tileIndex) { - int first = Math.max(0, (int) Math.ceil(offsetBlocks / blocksPerPixel)); - long globalPixel = tileIndex * VisionRenderController.TILE_PIXELS + first; - int misalignment = (int) Math.floorMod(globalPixel, (long) stride); - return misalignment == 0 ? first : first + stride - misalignment; - } - - private static int endPixel(double offsetBlocks, double blocksPerPixel, int size) { - return Math.min(size, (int) Math.ceil(offsetBlocks / blocksPerPixel)); - } - - record Share(MapLabels.Label label, int color, double fraction) { - } - - /** - * The world area the screen shows, in blocks. - */ - record ViewArea(double minimumX, double minimumZ, double maximumX, double maximumZ) { - } - - @FunctionalInterface - private interface PixelVisitor { - void visit(MapTile tile, int pixelX, int pixelZ); - } - - private static final class DoubleList { - private double[] values = new double[1024]; - private int size; - - void add(double value) { - if (size == values.length) { - values = Arrays.copyOf(values, size * 2); - } - values[size++] = value; - } - - int size() { - return size; - } - - double[] sorted() { - double[] sorted = Arrays.copyOf(values, size); - Arrays.sort(sorted); - return sorted; - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/MapHost.java b/core/src/main/java/art/arcane/iris/studio/map/MapHost.java deleted file mode 100644 index 1f568be65..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/MapHost.java +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.generation.runtime.PreservationRegistry; -import art.arcane.iris.spi.IrisServices; -import art.arcane.iris.studio.view.GuiHost; -import art.arcane.iris.studio.view.GuiOverlay; - -import javax.swing.JFrame; -import java.awt.Dimension; -import java.awt.GraphicsEnvironment; -import java.awt.Rectangle; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.awt.image.BufferedImage; -import java.util.UUID; -import java.util.concurrent.ExecutorService; - -/** - * What the studio windows need from the server they run in: frames it closes on shutdown, engines and hotload - * notices from the platform's {@link GuiHost.Provider}, and threads it stops with the plugin. - */ -public final class MapHost { - private MapHost() { - } - - static boolean isAvailable() { - return GuiHost.isAvailable(); - } - - public static JFrame createFrame(String title) { - XwaylandWindowManagerHint.apply(); - StudioTheme.install(); - JFrame frame = new JFrame(title); - GuiHost.prepareFrame(frame); - frame.addWindowListener(new WindowAdapter() { - @Override - public void windowActivated(WindowEvent event) { - StudioTheme.followSystem(); - } - }); - return frame; - } - - /** - * Wraps rendered pixels in an image Java2D draws straight from memory. Left to itself Java2D copies every image it - * draws into a texture inside the display server; with a map's hundreds of tiles that crashed Xwayland's Intel driver - * and took every X window on the desktop down with it. - */ - public static BufferedImage uncachedImage(int[] pixels, int width, int height) { - BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); - image.getRaster().setDataElements(0, 0, width, height, pixels); - image.setAccelerationPriority(0F); - return image; - } - - // A scaled-up default size can be bigger than a small or low resolution screen. - public static Dimension fitToScreen(Dimension preferred) { - Rectangle usable = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds(); - return new Dimension(Math.min(preferred.width, usable.width), Math.min(preferred.height, usable.height)); - } - - static Engine findActiveEngine() { - return usable(GuiHost.get().findActiveEngine()); - } - - /** - * The engine of the world the window was opened for, or the active one on platforms that can't look worlds up. - */ - static Engine findEngine(UUID worldId) { - Engine engine = worldId == null ? null : usable(GuiHost.get().findEngine(worldId)); - return engine != null ? engine : findActiveEngine(); - } - - static GuiOverlay overlayFor(Engine engine, UUID openerId) { - return engine == null ? null : GuiHost.get().overlayFor(engine, openerId); - } - - static void registerHotloadHook(Runnable onHotload) { - GuiHost.get().registerHotloadHook(onHotload); - } - - static void unregisterHotloadHook(Runnable onHotload) { - GuiHost.get().unregisterHotloadHook(onHotload); - } - - static void interruptOnPluginShutdown(ExecutorService executor) { - PreservationRegistry preservation = IrisServices.getOrNull(PreservationRegistry.class); - if (preservation != null) { - preservation.register(executor); - } - } - - static void interruptOnPluginShutdown(Thread thread) { - PreservationRegistry preservation = IrisServices.getOrNull(PreservationRegistry.class); - if (preservation != null) { - preservation.register(thread); - } - } - - private static Engine usable(Engine engine) { - return engine == null || engine.isClosed() || engine.isClosing() ? null : engine; - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/MapHoverCard.java b/core/src/main/java/art/arcane/iris/studio/map/MapHoverCard.java deleted file mode 100644 index af10fb530..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/MapHoverCard.java +++ /dev/null @@ -1,538 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.studio.map.MapHoverProbe.PickStep; -import art.arcane.iris.studio.map.MapHoverProbe.StepKind; -import art.arcane.iris.studio.map.NoisePickSpread.Band; -import art.arcane.iris.studio.map.components.MapLabels; -import art.arcane.iris.studio.map.components.TileType; -import art.arcane.iris.pack.loading.IrisRegistrant; -import art.arcane.iris.generation.biome.IrisBiome; - -import java.awt.Color; -import java.awt.Font; -import java.awt.FontMetrics; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.io.File; -import java.util.ArrayList; -import java.util.List; -import java.util.Locale; -import java.util.Optional; - -/** - * The card that follows the cursor: the biome and its region, the ground's height, and a row per noise that picked - * them, each split into one segment per option with the picked one lit and a line at the spot's value. Shift adds the - * terrain, location and pack files; a footer bar lists the shortcuts. - */ -record MapHoverCard(Header header, String subtitle, List noiseRows, List groups, List hints) { - private static final int MINIMUM_CONTENT_WIDTH = 240; - private static final int MINIMUM_SEGMENTS_WIDTH = 120; - private static final int PADDING_X = 12; - private static final int PADDING_TOP = 9; - private static final int PADDING_BOTTOM = 11; - private static final int ICON_SIZE = 12; - private static final int ICON_GAP = 8; - private static final int REGION_GAP = 16; - private static final int ROWS_GAP = 9; - private static final int ROW_HEIGHT = 18; - private static final int COLUMN_GAP = 8; - private static final int SEGMENT_HEIGHT = 6; - private static final int WIDE_SEGMENT_GAP = 2; - private static final int NARROW_SEGMENT_GAP = 1; - private static final int WIDE_SEGMENT_WIDTH = 8; - private static final int NARROW_SEGMENT_WIDTH = 3; - private static final int MARKER_WIDTH = 2; - private static final int MARKER_HEIGHT = 12; - private static final int GROUP_GAP = 8; - private static final int GROUP_TITLE_GAP = 4; - private static final int DETAIL_COLUMN_GAP = 14; - private static final int DETAIL_ROW_GAP = 3; - private static final int FOOTER_PADDING_Y = 7; - private static final int KEY_PADDING_X = 4; - private static final int KEY_GAP = 4; - private static final int HINT_GAP = 14; - private static final Color ICON_EDGE = new ThemeColor(new Color(0, 0, 0, 38), new Color(255, 255, 255, 38)); - - /** - * @param subject the biome, or region in the region view, the drawn tile shows; null while that tile is drawing - * @param region the region the drawn tile shows - * @param details the probed facts about the spot, or null until they arrive - * @param detailed whether Shift is held, which adds the terrain, location and pack files - */ - static MapHoverCard of(MapLabels.Label subject, MapLabels.Label region, MapHoverProbe.Details details, - TileType type, boolean detailed, double worldX, double worldZ) { - List path = details == null ? List.of() : details.pickPath(); - IrisBiome biome = cardBiome(subject, details, type); - List groups = new ArrayList<>(); - if (detailed) { - addTerrainGroup(groups, details, type); - groups.add(locationGroup(worldX, worldZ)); - addFilesGroup(groups, biome, details != null ? details.region() : region == null ? null : region.subject()); - } - return new MapHoverCard(header(subject, region, biome, path), subtitle(details, path), noiseRows(path), groups, - hints(detailed)); - } - - /** - * Draws the card with its top left corner as close to the given point as fits inside the bounds. - */ - void paint(Graphics2D canvas, int anchorX, int anchorY, int boundsWidth, int boundsHeight) { - Graphics2D card = (Graphics2D) canvas.create(); - card.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - card.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - int paddingX = StudioTheme.scale(PADDING_X); - int contentWidth = contentWidth(card); - int width = contentWidth + paddingX * 2; - int footerHeight = footerHeight(card); - int height = StudioTheme.scale(PADDING_TOP) + headerHeight(card) + rowsHeight() + groupsHeight(card) - + StudioTheme.scale(PADDING_BOTTOM) + footerHeight; - int x = Math.max(paddingX, Math.min(boundsWidth - width - paddingX, anchorX)); - int y = Math.max(paddingX, Math.min(boundsHeight - height - paddingX, anchorY)); - StudioOverlay.drawCard(card, x, y, width, height, footerHeight); - - int left = x + paddingX; - int top = y + StudioTheme.scale(PADDING_TOP); - top = drawHeader(card, left, top, contentWidth); - top = drawNoiseRows(card, left, top, contentWidth); - drawGroups(card, left, top); - drawFooter(card, left, y + height - footerHeight); - card.dispose(); - } - - private int contentWidth(Graphics2D canvas) { - int width = Math.max(headerWidth(canvas), rowsWidth(canvas)); - width = Math.max(width, groupsWidth(canvas)); - width = Math.max(width, footerWidth(canvas)); - return Math.max(StudioTheme.scale(MINIMUM_CONTENT_WIDTH), width); - } - - // Header: the biome's colour and name with its region on the right, and the ground below. - private int headerTextOffset() { - return header.color() == null ? 0 : StudioTheme.scale(ICON_SIZE + ICON_GAP); - } - - private int headerWidth(Graphics2D canvas) { - FontMetrics small = canvas.getFontMetrics(StudioTheme.smallFont()); - int width = headerTextOffset() + canvas.getFontMetrics(StudioTheme.boldFont()).stringWidth(header.name()); - if (header.region() != null) { - width += StudioTheme.scale(REGION_GAP) + small.stringWidth(header.region()); - } - if (subtitle != null) { - width = Math.max(width, headerTextOffset() + small.stringWidth(subtitle)); - } - return width; - } - - private int headerHeight(Graphics2D canvas) { - int height = canvas.getFontMetrics(StudioTheme.boldFont()).getHeight(); - if (subtitle != null) { - height += canvas.getFontMetrics(StudioTheme.smallFont()).getHeight(); - } - return height; - } - - private int drawHeader(Graphics2D canvas, int left, int top, int contentWidth) { - FontMetrics bold = canvas.getFontMetrics(StudioTheme.boldFont()); - FontMetrics small = canvas.getFontMetrics(StudioTheme.smallFont()); - if (header.color() != null) { - int iconSize = StudioTheme.scale(ICON_SIZE); - drawIcon(canvas, header.color(), left, top + (bold.getHeight() - iconSize) / 2, iconSize); - } - int textLeft = left + headerTextOffset(); - int baseline = top + bold.getAscent(); - drawText(canvas, header.name(), StudioTheme.boldFont(), StudioTheme.TEXT, textLeft, baseline); - if (header.region() != null) { - drawText(canvas, header.region(), StudioTheme.smallFont(), StudioTheme.MUTED_TEXT, - left + contentWidth - small.stringWidth(header.region()), baseline); - } - top += bold.getHeight(); - if (subtitle != null) { - drawText(canvas, subtitle, StudioTheme.smallFont(), StudioTheme.SECONDARY_TEXT, textLeft, top + small.getAscent()); - top += small.getHeight(); - } - return top; - } - - private static void drawIcon(Graphics2D canvas, int rgb, int left, int top, int size) { - int arc = Math.max(2, size / 2); - canvas.setColor(new Color(rgb)); - canvas.fillRoundRect(left, top, size, size, arc, arc); - canvas.setColor(ICON_EDGE); - canvas.drawRoundRect(left, top, size - 1, size - 1, arc, arc); - } - - // Noise rows: a muted label, the segments (or in hybrid terrain how the biome won), and the value on the right. - private int labelColumnWidth(Graphics2D canvas) { - FontMetrics small = canvas.getFontMetrics(StudioTheme.smallFont()); - return noiseRows.stream().mapToInt(row -> small.stringWidth(row.label())).max().orElse(0); - } - - private int valueColumnWidth(Graphics2D canvas) { - FontMetrics value = canvas.getFontMetrics(valueFont()); - return noiseRows.stream().mapToInt(row -> value.stringWidth(row.value())).max().orElse(0); - } - - private int rowsWidth(Graphics2D canvas) { - if (noiseRows.isEmpty()) { - return 0; - } - FontMetrics small = canvas.getFontMetrics(StudioTheme.smallFont()); - int middle = noiseRows.stream() - .mapToInt(row -> row.showsSegments() ? StudioTheme.scale(MINIMUM_SEGMENTS_WIDTH) : small.stringWidth(row.note())) - .max().orElse(0); - return labelColumnWidth(canvas) + valueColumnWidth(canvas) + middle + StudioTheme.scale(COLUMN_GAP) * 2; - } - - private int rowsHeight() { - return noiseRows.isEmpty() ? 0 : StudioTheme.scale(ROWS_GAP) + noiseRows.size() * StudioTheme.scale(ROW_HEIGHT); - } - - private int drawNoiseRows(Graphics2D canvas, int left, int top, int contentWidth) { - if (noiseRows.isEmpty()) { - return top; - } - top += StudioTheme.scale(ROWS_GAP); - int rowHeight = StudioTheme.scale(ROW_HEIGHT); - int columnGap = StudioTheme.scale(COLUMN_GAP); - int middleLeft = left + labelColumnWidth(canvas) + columnGap; - int valueRight = left + contentWidth; - int middleWidth = valueRight - valueColumnWidth(canvas) - columnGap - middleLeft; - FontMetrics small = canvas.getFontMetrics(StudioTheme.smallFont()); - FontMetrics value = canvas.getFontMetrics(valueFont()); - for (NoiseRow row : noiseRows) { - int baseline = top + (rowHeight - small.getHeight()) / 2 + small.getAscent(); - drawText(canvas, row.label(), StudioTheme.smallFont(), StudioTheme.MUTED_TEXT, left, baseline); - if (row.showsSegments()) { - drawSegments(canvas, row, middleLeft, top + (rowHeight - StudioTheme.scale(SEGMENT_HEIGHT)) / 2, middleWidth); - } else { - drawText(canvas, row.note(), StudioTheme.smallFont(), StudioTheme.SECONDARY_TEXT, middleLeft, baseline); - } - drawText(canvas, row.value(), valueFont(), StudioTheme.SECONDARY_TEXT, valueRight - value.stringWidth(row.value()), - baseline); - top += rowHeight; - } - return top; - } - - // One segment per band, as wide as the band's share of the noise; the picked one in its option's colour. - private static void drawSegments(Graphics2D canvas, NoiseRow row, int left, int top, int width) { - List bands = row.bands(); - int height = StudioTheme.scale(SEGMENT_HEIGHT); - int gap = segmentGap(width, bands.size()); - int picked = pickedBandIndex(bands, row.noise()); - int arc = StudioTheme.scale(2); - for (int index = 0; index < bands.size(); index++) { - Band band = bands.get(index); - int from = left + (int) Math.round(band.fromNoise() * width); - int to = left + (int) Math.round(band.toNoise() * width); - int segmentWidth = Math.max(1, to - from - (index == bands.size() - 1 ? 0 : gap)); - canvas.setColor(index == picked ? new Color(band.option().color()) : StudioTheme.OVERLAY_BORDER); - canvas.fillRoundRect(from, top, segmentWidth, height, arc, arc); - } - drawMarker(canvas, left + (int) Math.round(Math.clamp(row.noise(), 0D, 1D) * width), top + height / 2); - } - - private static int segmentGap(int width, int segmentCount) { - int averageWidth = width / Math.max(1, segmentCount); - if (averageWidth >= StudioTheme.scale(WIDE_SEGMENT_WIDTH)) { - return StudioTheme.scale(WIDE_SEGMENT_GAP); - } - return averageWidth >= StudioTheme.scale(NARROW_SEGMENT_WIDTH) ? StudioTheme.scale(NARROW_SEGMENT_GAP) : 0; - } - - // The engine gives values below 0 the first option and values above 1 the last, the same as this. - private static int pickedBandIndex(List bands, double noise) { - for (int index = 0; index < bands.size(); index++) { - if (noise <= bands.get(index).toNoise()) { - return index; - } - } - return bands.size() - 1; - } - - private static void drawMarker(Graphics2D canvas, int centerX, int centerY) { - int width = StudioTheme.scale(MARKER_WIDTH); - int height = StudioTheme.scale(MARKER_HEIGHT); - int left = centerX - width / 2; - int top = centerY - height / 2; - canvas.setColor(StudioTheme.PANEL_BACKGROUND); - canvas.fillRect(left - 1, top - 1, width + 2, height + 2); - canvas.setColor(StudioTheme.TEXT); - canvas.fillRect(left, top, width, height); - } - - private static Font valueFont() { - return StudioTheme.monospacedFont().deriveFont(StudioTheme.smallFont().getSize2D()); - } - - // Groups: sentence-case titles over rows of muted labels and values, all labels in one column. - private int detailLabelWidth(Graphics2D canvas) { - FontMetrics metrics = canvas.getFontMetrics(StudioTheme.font()); - return groups.stream().flatMap(group -> group.rows().stream()) - .mapToInt(row -> metrics.stringWidth(row.label())).max().orElse(0); - } - - private int groupsWidth(Graphics2D canvas) { - if (groups.isEmpty()) { - return 0; - } - FontMetrics metrics = canvas.getFontMetrics(StudioTheme.font()); - int valueWidth = groups.stream().flatMap(group -> group.rows().stream()) - .mapToInt(row -> metrics.stringWidth(row.value())).max().orElse(0); - return detailLabelWidth(canvas) + StudioTheme.scale(DETAIL_COLUMN_GAP) + valueWidth; - } - - private int groupsHeight(Graphics2D canvas) { - int rowHeight = canvas.getFontMetrics(StudioTheme.font()).getHeight() + StudioTheme.scale(DETAIL_ROW_GAP); - return groups.stream().mapToInt(group -> groupTitleHeight(canvas) + group.rows().size() * rowHeight).sum(); - } - - private void drawGroups(Graphics2D canvas, int left, int top) { - FontMetrics regular = canvas.getFontMetrics(StudioTheme.font()); - int valueLeft = left + detailLabelWidth(canvas) + StudioTheme.scale(DETAIL_COLUMN_GAP); - for (Group group : groups) { - top = drawGroupTitle(canvas, group.title(), left, top); - for (Row row : group.rows()) { - int baseline = top + regular.getAscent(); - drawText(canvas, row.label(), StudioTheme.font(), StudioTheme.SECONDARY_TEXT, left, baseline); - drawText(canvas, row.value(), StudioTheme.font(), row.link() ? StudioTheme.LINK : StudioTheme.TEXT, valueLeft, - baseline); - top += regular.getHeight() + StudioTheme.scale(DETAIL_ROW_GAP); - } - } - } - - private static int groupTitleHeight(Graphics2D canvas) { - return StudioTheme.scale(GROUP_GAP) + canvas.getFontMetrics(StudioTheme.smallFont()).getHeight() - + StudioTheme.scale(GROUP_TITLE_GAP); - } - - private static int drawGroupTitle(Graphics2D canvas, String title, int left, int top) { - FontMetrics small = canvas.getFontMetrics(StudioTheme.smallFont()); - top += StudioTheme.scale(GROUP_GAP); - drawText(canvas, title, StudioTheme.smallFont(), StudioTheme.MUTED_TEXT, left, top + small.getAscent()); - return top + small.getHeight() + StudioTheme.scale(GROUP_TITLE_GAP); - } - - // Footer: the shortcuts as key caps, each followed by what it does. - private int footerWidth(Graphics2D canvas) { - FontMetrics small = canvas.getFontMetrics(StudioTheme.smallFont()); - int width = 0; - for (Hint hint : hints) { - width += keyWidth(small, hint.key()) + StudioTheme.scale(KEY_GAP) + small.stringWidth(hint.action()); - } - return width + StudioTheme.scale(HINT_GAP) * Math.max(0, hints.size() - 1); - } - - private static int footerHeight(Graphics2D canvas) { - return canvas.getFontMetrics(StudioTheme.smallFont()).getHeight() + StudioTheme.scale(FOOTER_PADDING_Y) * 2; - } - - private static int keyWidth(FontMetrics small, String key) { - return small.stringWidth(key) + StudioTheme.scale(KEY_PADDING_X) * 2; - } - - private void drawFooter(Graphics2D canvas, int left, int top) { - FontMetrics small = canvas.getFontMetrics(StudioTheme.smallFont()); - int textTop = top + StudioTheme.scale(FOOTER_PADDING_Y); - int baseline = textTop + small.getAscent(); - int arc = StudioTheme.scale(6); - for (Hint hint : hints) { - int keyWidth = keyWidth(small, hint.key()); - canvas.setColor(StudioTheme.HOVER_BACKGROUND); - canvas.fillRoundRect(left, textTop, keyWidth, small.getHeight(), arc, arc); - drawText(canvas, hint.key(), StudioTheme.smallFont(), StudioTheme.SECONDARY_TEXT, - left + StudioTheme.scale(KEY_PADDING_X), baseline); - left += keyWidth + StudioTheme.scale(KEY_GAP); - drawText(canvas, hint.action(), StudioTheme.smallFont(), StudioTheme.MUTED_TEXT, left, baseline); - left += small.stringWidth(hint.action()) + StudioTheme.scale(HINT_GAP); - } - } - - private static void drawText(Graphics2D canvas, String text, Font font, Color color, int left, int baseline) { - canvas.setFont(font); - canvas.setColor(color); - canvas.drawString(text, left, baseline); - } - - // The card is about a biome; the region view's tiles only know the region until the probe finds the biome. - private static IrisBiome cardBiome(MapLabels.Label subject, MapHoverProbe.Details details, TileType type) { - if (subject != null && subject.subject() instanceof IrisBiome biome) { - return biome; - } - if (details == null) { - return null; - } - return type == TileType.CAVE_LAND ? details.caveBiome() : details.surfaceBiome(); - } - - private static Header header(MapLabels.Label subject, MapLabels.Label region, IrisBiome biome, List path) { - String regionName = path.stream() - .filter(step -> step.kind() == StepKind.REGION_NOISE || step.kind() == StepKind.PREVIEWED_REGION) - .map(step -> step.picked().name()) - .findFirst() - .orElse(region == null ? null : region.name()); - if (biome != null) { - return new Header(biome.getName(), colorOf(biome, path), regionName); - } - if (subject != null) { - return new Header(subject.name(), null, subject.kind() == MapLabels.Kind.REGION ? null : regionName); - } - return new Header("Drawing…", null, null); - } - - private static Integer colorOf(IrisBiome biome, List path) { - return path.stream() - .filter(step -> step.picked().key().equals(biome.getLoadKey())) - .reduce((first, last) -> last) - .map(step -> step.picked().color()) - .orElse(null); - } - - private static String subtitle(MapHoverProbe.Details details, List path) { - if (details == null) { - return null; - } - String ground = Math.round(details.height()) + " · " + signedHeight(details.height() - details.fluidHeight()) - + " · " + Math.round(details.slopeDegrees()) + "°"; - return parentOfChild(path).map(parent -> "child of " + parent + " · " + ground).orElse(ground); - } - - // A child biome took the spot from the biome the noise picked, which is the step before it. - private static Optional parentOfChild(List path) { - for (int index = 1; index < path.size(); index++) { - if (path.get(index).kind() == StepKind.CHILD) { - return Optional.of(path.get(index - 1).picked().name()); - } - } - return Optional.empty(); - } - - private static List noiseRows(List path) { - List rows = new ArrayList<>(); - for (PickStep step : path) { - switch (step.kind()) { - case REGION_NOISE -> rows.add(new NoiseRow("Region", step.bands(), step.noise(), null, step.value())); - case BIOME_NOISE -> rows.add(new NoiseRow(capitalize(step.detail()), step.bands(), step.noise(), null, - step.value())); - case PREVIEWED_REGION, CHILD -> { - } - } - } - return rows; - } - - private static void addTerrainGroup(List groups, MapHoverProbe.Details details, TileType type) { - if (details == null) { - return; - } - List rows = new ArrayList<>(); - IrisBiome surface = details.surfaceBiome(); - IrisBiome cave = details.caveBiome(); - if (type == TileType.CAVE_LAND && surface != null) { - rows.add(new Row("Surface biome", surface.getName(), false)); - } else if (type != TileType.CAVE_LAND && cave != null && cave != surface) { - rows.add(new Row("Cave biome", cave.getName(), false)); - } - if (details.vanillaBiome() != null) { - rows.add(new Row("Minecraft", details.vanillaBiome().replace('_', ' '), false)); - } - if (!rows.isEmpty()) { - groups.add(new Group("Terrain", rows)); - } - } - - private static Group locationGroup(double worldX, double worldZ) { - int blockX = MapCanvas.floorWorldCoordinate(worldX); - int blockZ = MapCanvas.floorWorldCoordinate(worldZ); - return new Group("Location", List.of( - new Row("Block", blockX + ", " + blockZ, false), - new Row("Chunk", (blockX >> 4) + ", " + (blockZ >> 4), false), - new Row("Region file", "r." + (blockX >> 9) + "." + (blockZ >> 9) + ".mca", false))); - } - - private static void addFilesGroup(List groups, IrisBiome biome, Object region) { - List rows = new ArrayList<>(); - if (biome != null) { - rows.add(new Row("Biome", packPath(biome), true)); - } - if (region instanceof IrisRegistrant registrant) { - rows.add(new Row("Region", packPath(registrant), true)); - } - if (!rows.isEmpty()) { - groups.add(new Group("Files", rows)); - } - } - - // The key is the path under the type's folder, so folder, key and extension give the file within the pack. - private static String packPath(IrisRegistrant registrant) { - File file = registrant.getLoadFile(); - String fileName = file == null ? "" : file.getName(); - int extensionStart = fileName.lastIndexOf('.'); - String extension = extensionStart < 0 ? "" : fileName.substring(extensionStart); - return registrant.getFolderName() + "/" + registrant.getLoadKey() + extension; - } - - private static List hints(boolean detailed) { - List hints = new ArrayList<>(); - if (!detailed) { - hints.add(new Hint("Shift", "More")); - } - hints.add(new Hint("H", "Highlight")); - hints.add(new Hint("Alt+Click", "Open file")); - return hints; - } - - private static String signedHeight(double height) { - long rounded = Math.round(height); - return rounded < 0 ? "−" + -rounded : "+" + rounded; - } - - private static String capitalize(String text) { - return text.substring(0, 1).toUpperCase(Locale.ROOT) + text.substring(1); - } - - /** - * @param color the biome's map colour, or null when no step of the path tells it - * @param region the region's name, or null when the title already is the region - */ - record Header(String name, Integer color, String region) { - } - - /** - * @param bands the bands the noise splits into, empty when no noise picked the step - * @param note how the step was picked when no noise did, or null - */ - record NoiseRow(String label, List bands, double noise, String note, String value) { - boolean showsSegments() { - return !bands.isEmpty(); - } - } - - record Group(String title, List rows) { - } - - record Row(String label, String value, boolean link) { - } - - record Hint(String key, String action) { - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/MapLegendPanel.java b/core/src/main/java/art/arcane/iris/studio/map/MapLegendPanel.java deleted file mode 100644 index 261970f36..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/MapLegendPanel.java +++ /dev/null @@ -1,244 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.studio.map.components.MapStyle; - -import javax.swing.BorderFactory; -import javax.swing.DefaultListCellRenderer; -import javax.swing.DefaultListModel; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.ListSelectionModel; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Component; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import java.util.function.Consumer; - -/** - * The biomes or regions on screen with how much of it each covers; clicking one highlights it on the map. - */ -final class MapLegendPanel extends JPanel { - private static final long serialVersionUID = 4471297416386034128L; - private static final int PANEL_WIDTH = 250; - private static final int ROW_HEIGHT = 26; - private static final int SWATCH_SIZE = 12; - private static final int SWATCH_GAP = 8; - private static final int ROW_PADDING = 10; - private static final int PERCENT_WIDTH = 42; - private static final String DRAWING_MESSAGE = "Drawing the map…"; - - private final JLabel title = new JLabel(); - private final DefaultListModel rows = new DefaultListModel<>(); - private final JList list = new JList<>(rows) { - // Long names shorten with an ellipsis instead of pushing the percentages out of sight. - @Override - public boolean getScrollableTracksViewportWidth() { - return true; - } - }; - private final Set sharedNames = new HashSet<>(); - private MapStyle.Highlight highlight; - - MapLegendPanel(Consumer onRowClicked) { - this(); - highlightOnClick(onRowClicked); - } - - /** - * A legend whose rows only tell what is on screen; clicking them does nothing. - */ - static MapLegendPanel listingOnly() { - return new MapLegendPanel(); - } - - private MapLegendPanel() { - super(new BorderLayout()); - setPreferredSize(StudioTheme.scaledSize(PANEL_WIDTH, 0)); - setBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, StudioTheme.SEPARATOR)); - setBackground(StudioTheme.PANEL_BACKGROUND); - - title.setFont(StudioTheme.sectionFont()); - title.setForeground(StudioTheme.MUTED_TEXT); - title.setBorder(StudioTheme.emptyBorder(10, 16, 6, 16)); - add(title, BorderLayout.NORTH); - - list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - list.setFocusable(false); - list.setFixedCellHeight(StudioTheme.scale(ROW_HEIGHT)); - list.setCellRenderer(new ShareRenderer()); - list.setBackground(StudioTheme.PANEL_BACKGROUND); - list.setBorder(StudioTheme.emptyBorder(0, 6, 4, 6)); - add(StudioToolbar.scroll(list), BorderLayout.CENTER); - } - - private void highlightOnClick(Consumer onRowClicked) { - list.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent event) { - MapCensus.Share share = shareAt(event.getPoint()); - if (share != null) { - onRowClicked.accept(share); - } - } - }); - JLabel hint = new JLabel("Click to highlight · Esc clears"); - hint.setFont(StudioTheme.smallFont()); - hint.setForeground(StudioTheme.MUTED_TEXT); - hint.setBorder(StudioTheme.emptyBorder(6, 16, 8, 16)); - add(hint, BorderLayout.SOUTH); - } - - void show(String subjectTitle, List shares, MapStyle.Highlight nextHighlight) { - title.setText(subjectTitle.toUpperCase(Locale.ROOT)); - highlight = nextHighlight; - rememberSharedNames(shares); - if (!sameRows(shares)) { - rows.clear(); - rows.addAll(shares); - } - list.repaint(); - } - - // Two biomes can share a display name; those rows show their key so they can be told apart. - private void rememberSharedNames(List shares) { - Set seen = new HashSet<>(); - sharedNames.clear(); - for (MapCensus.Share share : shares) { - if (!seen.add(share.label().name())) { - sharedNames.add(share.label().name()); - } - } - } - - private String rowText(MapCensus.Share share) { - String name = share.label().name(); - return sharedNames.contains(name) ? name + " (" + share.label().key() + ")" : name; - } - - private boolean sameRows(List shares) { - if (rows.size() != shares.size()) { - return false; - } - for (int index = 0; index < shares.size(); index++) { - if (!rows.get(index).equals(shares.get(index))) { - return false; - } - } - return true; - } - - private MapCensus.Share shareAt(Point point) { - int index = list.locationToIndex(point); - if (index < 0) { - return null; - } - Rectangle bounds = list.getCellBounds(index, index); - return bounds != null && bounds.contains(point) ? rows.get(index) : null; - } - - private boolean isHighlighted(MapCensus.Share share) { - return highlight != null - && highlight.kind() == share.label().kind() - && highlight.key().equals(share.label().key()); - } - - @Override - protected void paintChildren(Graphics graphics) { - super.paintChildren(graphics); - if (!rows.isEmpty()) { - return; - } - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - canvas.setFont(StudioTheme.font()); - canvas.setColor(StudioTheme.MUTED_TEXT); - canvas.drawString(DRAWING_MESSAGE, StudioTheme.scale(16), - title.getHeight() + StudioTheme.scale(4) + canvas.getFontMetrics().getAscent()); - } finally { - canvas.dispose(); - } - } - - private final class ShareRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = -2350212934617052618L; - private Color swatch = Color.BLACK; - private String percent = ""; - - @Override - public Component getListCellRendererComponent(JList owner, Object value, int index, boolean selected, boolean focused) { - MapCensus.Share share = (MapCensus.Share) value; - super.getListCellRendererComponent(owner, rowText(share), index, isHighlighted(share), false); - setFont(StudioTheme.font()); - setBorder(StudioTheme.emptyBorder(0, ROW_PADDING + SWATCH_SIZE + SWATCH_GAP, 0, ROW_PADDING + PERCENT_WIDTH)); - setToolTipText(share.label().key()); - swatch = new Color(share.color()); - percent = formatPercent(share.fraction()); - return this; - } - - @Override - protected void paintComponent(Graphics graphics) { - super.paintComponent(graphics); - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - int size = StudioTheme.scale(SWATCH_SIZE); - int swatchX = StudioTheme.scale(ROW_PADDING); - int swatchY = (getHeight() - size) / 2; - int arc = StudioTheme.scale(4); - canvas.setColor(swatch); - canvas.fillRoundRect(swatchX, swatchY, size, size, arc, arc); - canvas.setColor(StudioTheme.CONTROL_BORDER); - canvas.drawRoundRect(swatchX, swatchY, size - 1, size - 1, arc, arc); - canvas.setFont(StudioTheme.smallFont()); - canvas.setColor(StudioTheme.SECONDARY_TEXT); - int textWidth = canvas.getFontMetrics().stringWidth(percent); - int baseline = (getHeight() + canvas.getFontMetrics().getAscent() - canvas.getFontMetrics().getDescent()) / 2; - canvas.drawString(percent, getWidth() - StudioTheme.scale(ROW_PADDING) - textWidth, baseline); - } finally { - canvas.dispose(); - } - } - } - - private static String formatPercent(double fraction) { - double percent = fraction * 100D; - if (percent < 0.1D) { - return "<0.1%"; - } - return percent < 10D - ? String.format(Locale.ROOT, "%.1f%%", percent) - : String.format(Locale.ROOT, "%.0f%%", percent); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/MapView.java b/core/src/main/java/art/arcane/iris/studio/map/MapView.java deleted file mode 100644 index aa02188b5..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/MapView.java +++ /dev/null @@ -1,130 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.studio.map.components.TileType; - -import java.awt.event.KeyEvent; - -/** - * Everything the map window can show, in the order and groups of its view list. - */ -enum MapView { - BIOMES("Biomes", "The biome at each spot, in the biome's colour", Group.WORLD, TileType.BIOME, KeyEvent.VK_1), - REGIONS("Regions", "The region each spot belongs to; pick one to see the biomes it places", - Group.WORLD, TileType.REGION, KeyEvent.VK_2), - HEIGHT("Height", "Terrain height, from deep water to snowy peaks", Group.WORLD, TileType.HEIGHT, KeyEvent.VK_3), - RIVERS("Rivers", "Streams, rivers, falls, ponds, lakes, sea inlets, grottos and cave pools from the hydrology", - Group.WORLD, TileType.RIVER, KeyEvent.VK_4), - WORLD_3D("3D world", "The terrain in 3D, coloured by biome or region", Group.WORLD, null, KeyEvent.VK_5), - LAND_BIOMES("Land biomes", "The land biome each spot would get, also where the sea is", - Group.BIOME_STREAMS, TileType.BIOME_LAND, KeyEvent.VK_6), - SEA_BIOMES("Sea biomes", "The sea biome each spot would get, also where the land is", - Group.BIOME_STREAMS, TileType.BIOME_SEA, KeyEvent.VK_7), - CAVE_BIOMES("Cave land","The cave biome under each spot", Group.BIOME_STREAMS, TileType.CAVE_LAND, KeyEvent.VK_8), - PALETTES("Palettes", "The blocks each biome's palette layers place, with their textures", - Group.BLOCKS, null, KeyEvent.VK_P), - OBJECTS("Objects", "Every object in the pack in 3D, with the blocks it is made of", - Group.BLOCKS, null, KeyEvent.VK_O), - PROCEDURAL("Procedural", "Trees, rock formations and more that Iris generates from settings, every variant in 3D", - Group.BLOCKS, null, KeyEvent.VK_T), - NOISE("Noise", "The pack's noise generators and Iris' built-in noise styles", - Group.GENERATORS, null, KeyEvent.VK_N), - IMAGE_MAPS("Image maps", "Terrain height, biomes or masks painted from a PNG, previewed and exported into the pack", - Group.GENERATORS, null, KeyEvent.VK_I), - OBJECT_LOAD("Object Load", "Configuration estimate of object density and chance, not measured performance", - Group.DIAGNOSTICS, TileType.OBJECT_LOAD, KeyEvent.VK_F6), - DECORATOR_LOAD("Decorator Load", "Configuration estimate of decorator chance and stacks, not measured performance", - Group.DIAGNOSTICS, TileType.DECORATOR_LOAD, KeyEvent.VK_F7), - LAYER_LOAD("Layer Load", "Configuration estimate of biome layer count, not measured performance", - Group.DIAGNOSTICS, TileType.LAYER_LOAD, KeyEvent.VK_F8); - - private final String label; - private final String description; - private final Group group; - private final TileType renderType; - private final int shortcutKey; - - MapView(String label, String description, Group group, TileType renderType, int shortcutKey) { - this.label = label; - this.description = description; - this.group = group; - this.renderType = renderType; - this.shortcutKey = shortcutKey; - } - - String label() { - return label; - } - - String description() { - return description; - } - - Group group() { - return group; - } - - /** - * The tile renderer's mode for this view, or null for the 3D world, palette, object, procedural, noise and image map - * views, which draw themselves. - */ - TileType renderType() { - return renderType; - } - - int shortcutKey() { - return shortcutKey; - } - - String shortcutText() { - return KeyEvent.getKeyText(shortcutKey); - } - - boolean isTileMap() { - return renderType != null; - } - - static MapView forShortcut(int keyCode) { - for (MapView view : values()) { - if (view.shortcutKey == keyCode) { - return view; - } - } - return null; - } - - enum Group { - WORLD("World"), - BIOME_STREAMS("Biome layers"), - BLOCKS("Blocks"), - GENERATORS("Generators"), - DIAGNOSTICS("Diagnostics"); - - private final String label; - - Group(String label) { - this.label = label; - } - - String label() { - return label; - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/MapViewIcon.java b/core/src/main/java/art/arcane/iris/studio/map/MapViewIcon.java deleted file mode 100644 index dd6a555cb..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/MapViewIcon.java +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import com.formdev.flatlaf.extras.FlatSVGIcon; - -import javax.swing.Icon; -import java.util.EnumMap; -import java.util.Locale; -import java.util.Map; - -/** - * The icon of each map view, taken from IntelliJ's new UI icon set (see the NOTICE in iris/icons). - */ -final class MapViewIcon { - private static final String ICON_FOLDER = "iris/icons/views/"; - private static final int SIZE = 16; - private static final Map LOADED = new EnumMap<>(MapView.class); - - private MapViewIcon() { - } - - static Icon of(MapView view) { - return LOADED.computeIfAbsent(view, shown -> load(shown, SIZE)); - } - - /** - * The view's icon drawn larger, for an empty view. - */ - static Icon large(MapView view, int size) { - return load(view, size); - } - - private static Icon load(MapView view, int size) { - if (view.group() == MapView.Group.DIAGNOSTICS) { - return new FlatSVGIcon("iris/icons/profiler.svg", size, size, MapViewIcon.class.getClassLoader()); - } - String fileName = view.name().toLowerCase(Locale.ROOT).replace('_', '-') + ".svg"; - return new FlatSVGIcon(ICON_FOLDER + fileName, size, size, MapViewIcon.class.getClassLoader()); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/MapViewList.java b/core/src/main/java/art/arcane/iris/studio/map/MapViewList.java deleted file mode 100644 index 1c320c8c4..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/MapViewList.java +++ /dev/null @@ -1,246 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import javax.swing.DefaultListCellRenderer; -import javax.swing.DefaultListModel; -import javax.swing.JList; -import javax.swing.ListSelectionModel; -import javax.swing.UIManager; -import java.awt.Component; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Insets; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.Locale; -import java.util.function.Consumer; - -/** - * The map window's list of views, grouped under headers, each row with a picture of the view and the key that opens - * it. - */ -final class MapViewList extends JList { - private static final long serialVersionUID = -4130872409914437415L; - private static final int ROW_HEIGHT = 28; - private static final int NO_ROW = -1; - - private final DefaultListModel rows = new DefaultListModel<>(); - private int lastViewRow; - private int hoveredRow = NO_ROW; - - MapViewList(Consumer onViewChosen) { - fillRows(); - setModel(rows); - setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - setFixedCellHeight(StudioTheme.scale(ROW_HEIGHT)); - setCellRenderer(new RowRenderer()); - setBorder(StudioTheme.emptyBorder(4, 6, 4, 6)); - addListSelectionListener(event -> { - if (event.getValueIsAdjusting() || skipHeaderRow()) { - return; - } - Row selected = getSelectedValue(); - if (selected == null) { - return; - } - lastViewRow = getSelectedIndex(); - onViewChosen.accept(selected.view()); - }); - MouseAdapter hover = new MouseAdapter() { - @Override - public void mouseMoved(MouseEvent event) { - hover(viewRowAt(event)); - } - - @Override - public void mouseExited(MouseEvent event) { - hover(NO_ROW); - } - }; - addMouseListener(hover); - addMouseMotionListener(hover); - } - - private int viewRowAt(MouseEvent event) { - int row = locationToIndex(event.getPoint()); - if (row < 0 || rows.get(row).isHeader() || !getCellBounds(row, row).contains(event.getPoint())) { - return NO_ROW; - } - return row; - } - - private void hover(int row) { - if (row == hoveredRow) { - return; - } - repaintRow(hoveredRow); - hoveredRow = row; - repaintRow(hoveredRow); - } - - private void repaintRow(int row) { - Rectangle bounds = row == NO_ROW ? null : getCellBounds(row, row); - if (bounds != null) { - repaint(bounds); - } - } - - void select(MapView view) { - for (int row = 0; row < rows.size(); row++) { - if (rows.get(row).view() == view) { - lastViewRow = row; - setSelectedIndex(row); - ensureIndexIsVisible(row); - return; - } - } - } - - private void fillRows() { - MapView.Group currentGroup = null; - for (MapView view : MapView.values()) { - if (view.group() != currentGroup) { - currentGroup = view.group(); - rows.addElement(Row.header(currentGroup)); - } - rows.addElement(Row.of(view)); - } - } - - // Headers can't be chosen: clicking one keeps the current view, and the arrow keys carry on past it. - private boolean skipHeaderRow() { - int row = getSelectedIndex(); - if (row < 0 || !rows.get(row).isHeader()) { - return false; - } - int step = row >= lastViewRow ? 1 : -1; - int next = nextViewRow(row, step); - if (next < 0) { - next = nextViewRow(row, -step); - } - setSelectedIndex(next < 0 ? lastViewRow : next); - ensureIndexIsVisible(getSelectedIndex()); - return true; - } - - private int nextViewRow(int from, int step) { - for (int row = from + step; row >= 0 && row < rows.size(); row += step) { - if (!rows.get(row).isHeader()) { - return row; - } - } - return -1; - } - - record Row(MapView.Group group, MapView view) { - static Row header(MapView.Group group) { - return new Row(group, null); - } - - static Row of(MapView view) { - return new Row(view.group(), view); - } - - boolean isHeader() { - return view == null; - } - } - - private static final class RowRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 6302156810211578474L; - private static final int ICON_TEXT_GAP = 8; - private static final int KEYCAP_SIZE = 17; - private static final int KEYCAP_ARC = 5; - private String shortcut; - private boolean hovered; - - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, boolean selected, boolean focused) { - Row row = (Row) value; - super.getListCellRendererComponent(list, row.isHeader() ? "" : row.view().label(), index, selected && !row.isHeader(), false); - if (row.isHeader()) { - setText(row.group().label().toUpperCase(Locale.ROOT)); - setFont(StudioTheme.sectionFont()); - setForeground(StudioTheme.MUTED_TEXT); - setBorder(StudioTheme.emptyBorder(index == 0 ? 2 : 10, 8, 0, 6)); - setIcon(null); - setToolTipText(null); - shortcut = null; - hovered = false; - setOpaque(true); - return this; - } - setFont(StudioTheme.font()); - setBorder(StudioTheme.emptyBorder(0, 8, 0, 8)); - setIcon(MapViewIcon.of(row.view())); - setIconTextGap(StudioTheme.scale(ICON_TEXT_GAP)); - setToolTipText(row.view().description()); - shortcut = row.view().shortcutText(); - hovered = !selected && list instanceof MapViewList viewList && viewList.hoveredRow == index; - setOpaque(!hovered); - return this; - } - - @Override - protected void paintComponent(Graphics graphics) { - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - if (hovered) { - paintHoverBackground(canvas); - } - super.paintComponent(graphics); - if (shortcut != null) { - paintKeycap(canvas); - } - } finally { - canvas.dispose(); - } - } - - // Shaped like the selection the look and feel paints, so moving between them doesn't jump. - private void paintHoverBackground(Graphics2D canvas) { - Insets inset = UIManager.getInsets("List.selectionInsets"); - int left = inset == null ? 0 : StudioTheme.scale(inset.left); - int right = inset == null ? 0 : StudioTheme.scale(inset.right); - int arc = StudioTheme.scale(UIManager.getInt("List.selectionArc")); - canvas.setColor(StudioTheme.HOVER_BACKGROUND); - canvas.fillRoundRect(left, 0, getWidth() - left - right, getHeight(), arc, arc); - } - - private void paintKeycap(Graphics2D canvas) { - canvas.setFont(StudioTheme.smallFont()); - int textWidth = canvas.getFontMetrics().stringWidth(shortcut); - int height = StudioTheme.scale(KEYCAP_SIZE); - int width = Math.max(height, textWidth + StudioTheme.scale(8)); - int x = getWidth() - getInsets().right - width; - int y = (getHeight() - height) / 2; - int arc = StudioTheme.scale(KEYCAP_ARC); - canvas.setColor(StudioTheme.CONTROL_BORDER); - canvas.drawRoundRect(x, y, width - 1, height - 1, arc, arc); - canvas.setColor(StudioTheme.SECONDARY_TEXT); - int baseline = y + (height + canvas.getFontMetrics().getAscent() - canvas.getFontMetrics().getDescent()) / 2; - canvas.drawString(shortcut, x + (width - textWidth) / 2, baseline); - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/MapWindow.java b/core/src/main/java/art/arcane/iris/studio/map/MapWindow.java deleted file mode 100644 index 9f04edd1e..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/MapWindow.java +++ /dev/null @@ -1,719 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.generation.noise.IrisGenerator; -import art.arcane.iris.studio.map.components.MapStyle; - -import javax.swing.AbstractAction; -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.JComponent; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JRootPane; -import javax.swing.JSplitPane; -import javax.swing.JToggleButton; -import javax.swing.JToolBar; -import javax.swing.KeyStroke; -import javax.swing.SwingConstants; -import javax.swing.text.JTextComponent; -import java.awt.BorderLayout; -import java.awt.CardLayout; -import java.awt.Dimension; -import java.awt.EventQueue; -import java.awt.KeyboardFocusManager; -import java.awt.event.ActionEvent; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.KeyEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.List; -import java.util.Map; -import java.util.function.IntConsumer; - -/** - * The studio map: one window showing the world as tiles in several views, with the palette, object, noise and image map - * explorers as its Palettes, Objects, Noise and Image maps views. - */ -public final class MapWindow implements MapCanvas.Listener { - private static final String MAP_CARD = "map"; - private static final String PALETTES_CARD = "palettes"; - private static final String NOISE_CARD = "noise"; - private static final String WORLD_CARD = "world"; - private static final String IMAGE_MAPS_CARD = "image maps"; - private static final int SIDEBAR_WIDTH = 270; - private static final int SIDEBAR_MINIMUM_WIDTH = 200; - private static final int CONTENT_MINIMUM_WIDTH = 320; - private static final double PALETTE_RECENTER_DISTANCE_BLOCKS = 1D; - private static final double WORLD_RECENTER_DISTANCE_BLOCKS = 1D; - private static final int VIEW_LIST_SCROLL_INSETS = 4; - private static final int EXPLORER_DIVIDER_HEIGHT = 7; - - private final JFrame frame; - private final PaletteExplorerStart start; - private final NoiseSelection noiseSelection; - private final MapCanvas canvas; - private final MapViewList viewList; - private final JLabel viewTitle = new JLabel(); - private final JPanel content = new JPanel(new CardLayout()); - private final JPanel statusBars = new JPanel(new CardLayout()); - private final JPanel sidebar = new JPanel(new BorderLayout()); - private final IslandPanel sidebarIsland = new IslandPanel(sidebar); - private final JPanel inspectorSlot = new JPanel(new BorderLayout()); - private final JComponent viewListScroll; - private final JSplitPane explorerSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT); - private final JSplitPane pickInspectorSplit = new JSplitPane(JSplitPane.VERTICAL_SPLIT); - private final List mapControls = new ArrayList<>(); - private final List explorerControls = new ArrayList<>(); - private final List noiseControls = new ArrayList<>(); - private final List worldControls = new ArrayList<>(); - private final List imageMapControls = new ArrayList<>(); - private final JToolBar toolbar = StudioToolbar.create(); - private final JComponent resetViewButton = StudioToolbar.button("Reset view", "Go back to the starting position and zoom (R)", - this::resetExplorerView); - private final JToggleButton gridToggle = StudioToolbar.toggle("Grid", "Show chunk and region borders (G)"); - private final JToggleButton entitiesToggle = StudioToolbar.toggle("Entities", "Show mobs and other entities (E)"); - private final JToggleButton followToggle = StudioToolbar.toggle("Follow", "Keep your player in the middle (F)"); - private final JToggleButton shadingToggle = StudioToolbar.toggle("Shading", "Shade hills and valleys on every view (S)"); - private final JToggleButton bordersToggle = StudioToolbar.toggle("Borders", "Outline the regions on every view (B)"); - private final JToggleButton waterToggle = StudioToolbar.toggle("Water", "Overlay water on biome picks (W)"); - private final ResourceUsage resourceUsage = new ResourceUsage(); - private final MapLegendPanel legendPanel; - private final RegionExplorer regionExplorer; - private final BiomeExplorer biomeExplorer; - - private NoiseExplorerGUI paletteExplorer; - private final Map objectExplorers = new EnumMap<>(MapView.class); - private NoiseExplorerGUI noiseExplorer; - private JComponent noiseSidebar; - private WorldExplorer worldExplorer; - private ImageMapExplorer imageMapExplorer; - private double worldCenterX; - private double worldCenterZ; - private MapView currentView; - private boolean windowVisible = true; - private double paletteCenterX; - private double paletteCenterZ; - - private MapWindow(PaletteExplorerStart start, NoiseSelection noiseSelection) { - this.start = start; - this.noiseSelection = noiseSelection; - this.frame = MapHost.createFrame("Iris Map"); - this.canvas = new MapCanvas(start.engine(), start.worldId(), start.playerId(), this); - this.viewList = new MapViewList(this::showView); - this.viewListScroll = StudioToolbar.scroll(viewList); - this.legendPanel = new MapLegendPanel(share -> canvas.toggleHighlight(share.label())); - this.regionExplorer = new RegionExplorer(canvas::engine, canvas::previewRegion, canvas::showPicksAs); - this.biomeExplorer = new BiomeExplorer(canvas::engine, canvas::showPicksAs); - canvas.centerOn(start.centerX(), start.centerZ()); - buildFrame(); - } - - public static void openMap(PaletteExplorerStart start) { - openLater(start, MapView.BIOMES); - } - - public static void openPalettes(PaletteExplorerStart start) { - openLater(start, MapView.PALETTES); - } - - public static void openNoise(PaletteExplorerStart start) { - openLater(start, MapView.NOISE); - } - - public static void openNoise(PaletteExplorerStart start, NoiseSelection selection) { - if (!MapHost.isAvailable()) { - return; - } - EventQueue.invokeLater(() -> open(start, MapView.NOISE, selection)); - } - - public static void openImageMaps(PaletteExplorerStart start) { - openLater(start, MapView.IMAGE_MAPS); - } - - private static void openLater(PaletteExplorerStart start, MapView initialView) { - if (!MapHost.isAvailable()) { - return; - } - EventQueue.invokeLater(() -> open(start, initialView, null)); - } - - private static void open(PaletteExplorerStart start, MapView initialView, NoiseSelection selection) { - if (!MapHost.isAvailable()) { - return; - } - StudioTheme.install(); - MapWindow window = new MapWindow(start, selection); - window.frame.setVisible(true); - window.canvas.start(); - window.resourceUsage.start(); - window.showView(initialView); - } - - private void buildFrame() { - styleExplorerSplit(); - stylePickInspectorSplit(); - content.add(canvas, MAP_CARD); - statusBars.add(canvas.statusBar(), MAP_CARD); - sidebar.add(viewListScroll, BorderLayout.CENTER); - - frame.setLayout(new BorderLayout()); - frame.add(buildToolbar(), BorderLayout.NORTH); - frame.add(new IslandOverlay(sidebarIsland, content, StudioTheme.scale(SIDEBAR_WIDTH), - StudioTheme.scale(SIDEBAR_MINIMUM_WIDTH), StudioTheme.scale(CONTENT_MINIMUM_WIDTH)), BorderLayout.CENTER); - frame.add(inspectorSlot, BorderLayout.EAST); - frame.add(statusBars, BorderLayout.SOUTH); - installShortcuts(frame.getRootPane()); - keepClearOfIsland(canvas::setCoveredLeftWidth); - frame.setSize(MapHost.fitToScreen(StudioTheme.scaledSize(1440, 880))); - frame.setMinimumSize(StudioTheme.scaledSize(820, 520)); - frame.setLocationRelativeTo(null); - frame.addWindowListener(new WindowAdapter() { - @Override - public void windowIconified(WindowEvent event) { - updateWindowVisibility(); - } - - @Override - public void windowDeiconified(WindowEvent event) { - updateWindowVisibility(); - } - - @Override - public void windowClosed(WindowEvent event) { - close(); - } - }); - frame.addComponentListener(new ComponentAdapter() { - @Override - public void componentShown(ComponentEvent event) { - updateWindowVisibility(); - } - - @Override - public void componentHidden(ComponentEvent event) { - updateWindowVisibility(); - } - }); - } - - private void updateWindowVisibility() { - boolean visible = isWindowVisible(); - boolean wasVisible = windowVisible; - windowVisible = visible; - canvas.setActive(visible && currentView != null && currentView.isTileMap()); - if (currentView == MapView.WORLD_3D && worldExplorer != null) { - if (visible && !wasVisible) { - worldExplorer.show(worldCenterX, worldCenterZ, false); - } else if (!visible) { - worldExplorer.hide(); - } - } - if (visible) { - resourceUsage.start(); - } else { - resourceUsage.stop(); - } - } - - private boolean isWindowVisible() { - return frame.isShowing() && (frame.getExtendedState() & JFrame.ICONIFIED) == 0; - } - - private JToolBar buildToolbar() { - viewTitle.setFont(StudioTheme.titleFont()); - viewTitle.setBorder(StudioTheme.emptyBorder(0, 6, 0, 14)); - toolbar.add(viewTitle); - - mapControls.add(StudioToolbar.button("Refresh", "Redraw the map with the latest pack files (R)", canvas::refreshContent)); - mapControls.add(StudioToolbar.button("Reset zoom", "Go back to the default zoom (\\)", canvas::resetZoom)); - mapControls.add(gridToggle); - mapControls.add(entitiesToggle); - mapControls.add(followToggle); - mapControls.add(toolbarSeparator()); - mapControls.add(shadingToggle); - mapControls.add(bordersToggle); - mapControls.add(waterToggle); - gridToggle.addActionListener(event -> canvas.toggleGrid()); - entitiesToggle.addActionListener(event -> canvas.toggleEntities()); - followToggle.addActionListener(event -> canvas.toggleFollow()); - shadingToggle.addActionListener(event -> canvas.toggleShading()); - bordersToggle.addActionListener(event -> canvas.toggleRegionBorders()); - waterToggle.addActionListener(event -> canvas.toggleWaterOverlay()); - mapControls.forEach(toolbar::add); - - explorerControls.add(resetViewButton); - explorerControls.forEach(toolbar::add); - - toolbar.add(Box.createHorizontalGlue()); - toolbar.add(resourceUsage); - toolbar.add(StudioToolbar.themeButton()); - JComponent help = StudioToolbar.button("Shortcuts", "Show every mouse and key shortcut (/)", canvas::toggleHelp); - mapControls.add(help); - toolbar.add(help); - onTogglesChanged(); - return toolbar; - } - - private static JComponent toolbarSeparator() { - JToolBar.Separator separator = new JToolBar.Separator(); - separator.setOrientation(SwingConstants.VERTICAL); - return separator; - } - - private void showView(MapView view) { - if (view == null || view == currentView) { - return; - } - MapView previousView = currentView; - currentView = view; - viewList.select(view); - viewTitle.setText(view.label()); - viewTitle.setToolTipText(view.description()); - if (previousView == MapView.WORLD_3D) { - worldExplorer.hide(); - } - if (view.isTileMap()) { - showMap(previousView, view); - } else if (view == MapView.WORLD_3D) { - showWorld(); - } else if (view == MapView.PALETTES) { - showPalettes(previousView); - } else if (view == MapView.OBJECTS || view == MapView.PROCEDURAL) { - showObjectExplorer(view); - } else if (view == MapView.IMAGE_MAPS) { - showImageMaps(); - } else { - showNoise(); - } - frame.getRootPane().revalidate(); - frame.getRootPane().repaint(); - updateWindowVisibility(); - } - - private void showMap(MapView previousView, MapView view) { - if (previousView == MapView.PALETTES && paletteExplorer != null) { - canvas.centerOn(paletteExplorer.centerX(), paletteExplorer.centerZ()); - } - canvas.showView(view); - canvas.setActive(isWindowVisible()); - showControls(mapControls); - waterToggle.setVisible(view == MapView.BIOMES); - if (view == MapView.REGIONS) { - showRegionExplorer(previousView); - } else if (view == MapView.BIOMES) { - showBiomeExplorer(); - } else { - useSidebar(viewListScroll); - useInspector(legendPanel); - } - showCard(MAP_CARD); - canvas.requestFocusInWindow(); - } - - // The region inspector sits above the legend, which then lists the chosen region's biomes on the map. - private void showRegionExplorer(MapView previousView) { - if (previousView != MapView.REGIONS) { - regionExplorer.loadRegions(); - } - useSidebar(viewListAbove(regionExplorer.navigator())); - showPickInspector(regionExplorer.inspector()); - EventQueue.invokeLater(() -> viewList.select(currentView)); - regionExplorer.measure(canvas.viewArea()); - } - - private void showBiomeExplorer() { - useSidebar(viewListScroll); - showPickInspector(biomeExplorer.inspector()); - biomeExplorer.measure(canvas.viewArea()); - } - - // The region and biome views share how the map draws its picks, so their switches show the same choice. - private void showPickInspector(PickInspectorPanel inspector) { - inspector.selectDisplay(canvas.pickDisplay()); - pickInspectorSplit.setTopComponent(StudioTheme.matchTheme(inspector)); - pickInspectorSplit.setBottomComponent(StudioTheme.matchTheme(legendPanel)); - useInspector(pickInspectorSplit); - } - - private void stylePickInspectorSplit() { - pickInspectorSplit.setBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, StudioTheme.SEPARATOR)); - pickInspectorSplit.setResizeWeight(0.7D); - pickInspectorSplit.setBackground(StudioTheme.PANEL_BACKGROUND); - pickInspectorSplit.setDividerSize(StudioTheme.scale(EXPLORER_DIVIDER_HEIGHT)); - pickInspectorSplit.putClientProperty("FlatLaf.style", "style: grip"); - } - - private void showPalettes(MapView previousView) { - boolean firstOpen = paletteExplorer == null; - if (firstOpen) { - createPaletteExplorer(previousView == null); - } else { - followMapIntoPalettes(); - } - canvas.setActive(false); - showControls(explorerControls); - useSidebar(viewListAbove(paletteExplorer.paletteSidebar())); - useInspector(paletteExplorer.paletteInspector()); - showCard(PALETTES_CARD); - EventQueue.invokeLater(() -> viewList.select(currentView)); - if (firstOpen) { - paletteExplorer.openViewer(); - } - } - - private void showObjectExplorer(MapView view) { - boolean firstOpen = !objectExplorers.containsKey(view); - ObjectExplorer explorer = objectExplorers.computeIfAbsent(view, this::createObjectExplorer); - canvas.setActive(false); - showControls(explorerControls); - useSidebar(viewListAbove(explorer.browser())); - useInspector(explorer.overview()); - showCard(view.name()); - EventQueue.invokeLater(() -> viewList.select(currentView)); - if (firstOpen) { - explorer.open(); - } - } - - // The 3D world keeps its camera unless the map was moved since; then it turns around the map's middle. - private void showWorld() { - boolean firstOpen = worldExplorer == null; - if (firstOpen) { - createWorldExplorer(); - } - boolean mapMoved = Math.hypot(canvas.centerX() - worldCenterX, canvas.centerZ() - worldCenterZ) >= WORLD_RECENTER_DISTANCE_BLOCKS; - worldCenterX = canvas.centerX(); - worldCenterZ = canvas.centerZ(); - canvas.setActive(false); - showControls(worldControls, explorerControls); - useSidebar(viewListScroll); - useInspector(worldExplorer.legend()); - showCard(WORLD_CARD); - worldExplorer.show(worldCenterX, worldCenterZ, firstOpen || mapMoved); - } - - private void createWorldExplorer() { - worldExplorer = new WorldExplorer(canvas::engine); - keepClearOfIsland(worldExplorer::setCoveredLeftWidth); - worldControls.addAll(worldExplorer.controls()); - worldControls.forEach(control -> toolbar.add(control, toolbar.getComponentIndex(resetViewButton))); - content.add(worldExplorer.view(), WORLD_CARD); - statusBars.add(worldExplorer.statusBar(), WORLD_CARD); - } - - private void keepClearOfIsland(IntConsumer setCoveredLeftWidth) { - setCoveredLeftWidth.accept(sidebarIsland.getWidth()); - sidebarIsland.addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent event) { - setCoveredLeftWidth.accept(sidebarIsland.getWidth()); - } - }); - } - - private ObjectExplorer createObjectExplorer(MapView view) { - ObjectSource source = view == MapView.PROCEDURAL ? new ProceduralObjectSource() : new PackObjectSource(); - ObjectExplorer explorer = new ObjectExplorer(start.engine(), start.worldId(), source); - keepClearOfIsland(explorer::setCoveredLeftWidth); - content.add(explorer.view(), view.name()); - statusBars.add(explorer.statusBar(), view.name()); - return explorer; - } - - private void showNoise() { - boolean firstOpen = noiseExplorer == null; - if (firstOpen) { - createNoiseExplorer(); - } - canvas.setActive(false); - showControls(noiseControls, explorerControls); - useSidebar(viewListAbove(noiseSidebar)); - inspectorSlot.removeAll(); - showCard(NOISE_CARD); - EventQueue.invokeLater(() -> viewList.select(currentView)); - if (firstOpen) { - noiseExplorer.openViewer(); - } - } - - private void showImageMaps() { - boolean firstOpen = imageMapExplorer == null; - if (firstOpen) { - createImageMapExplorer(); - } - canvas.setActive(false); - showControls(imageMapControls); - useSidebar(viewListScroll); - inspectorSlot.removeAll(); - showCard(IMAGE_MAPS_CARD); - if (firstOpen) { - imageMapExplorer.open(); - } - } - - private void createImageMapExplorer() { - imageMapExplorer = new ImageMapExplorer(start.engine()); - keepClearOfIsland(imageMapExplorer::setCoveredLeftWidth); - imageMapControls.addAll(imageMapExplorer.controls()); - imageMapControls.forEach(control -> toolbar.add(control, toolbar.getComponentIndex(resetViewButton))); - content.add(imageMapExplorer.view(), IMAGE_MAPS_CARD); - statusBars.add(imageMapExplorer.statusBar(), IMAGE_MAPS_CARD); - } - - // Both explorers share one split, so the divider stays where it was dragged when switching between them. - private JSplitPane viewListAbove(JComponent explorerSidebar) { - boolean firstUse = explorerSplit.getBottomComponent() == null; - explorerSplit.setTopComponent(viewListScroll); - explorerSplit.setBottomComponent(StudioTheme.matchTheme(explorerSidebar)); - if (firstUse) { - EventQueue.invokeLater(this::fitViewListAboveExplorer); - } - return explorerSplit; - } - - private void styleExplorerSplit() { - explorerSplit.setBorder(BorderFactory.createEmptyBorder()); - explorerSplit.setResizeWeight(0D); - explorerSplit.setBackground(StudioTheme.PANEL_BACKGROUND); - explorerSplit.setDividerSize(StudioTheme.scale(EXPLORER_DIVIDER_HEIGHT)); - explorerSplit.putClientProperty("FlatLaf.style", "style: grip"); - } - - // Every view stays in sight, so the divider starts below the last one and can only be dragged further down. Measured - // once the sidebar is laid out, since the list's rows are taller before they know their width. - private void fitViewListAboveExplorer() { - int fullHeight = viewList.getPreferredSize().height + VIEW_LIST_SCROLL_INSETS; - viewListScroll.setMinimumSize(new Dimension(0, fullHeight)); - explorerSplit.setDividerLocation(fullHeight); - } - - private void createNoiseExplorer() { - noiseExplorer = noiseSelection == null - ? NoiseExplorerGUI.createNoiseExplorer(start) - : NoiseExplorerGUI.createGeneratorExplorer(start, noiseSelection); - keepClearOfIsland(noiseExplorer::setCoveredLeftWidth); - noiseSidebar = noiseExplorer.noiseSidebar(); - noiseControls.addAll(noiseExplorer.noiseControls()); - noiseControls.forEach(control -> toolbar.add(control, toolbar.getComponentIndex(resetViewButton))); - content.add(noiseExplorer, NOISE_CARD); - statusBars.add(noiseExplorer.statusBar(), NOISE_CARD); - } - - private void createPaletteExplorer(boolean openedOnPalettes) { - PaletteExplorerStart explorerStart = openedOnPalettes - ? start - : new PaletteExplorerStart(start.engine(), start.worldId(), start.playerId(), null, canvas.centerX(), canvas.centerZ()); - paletteExplorer = NoiseExplorerGUI.createPaletteExplorer(explorerStart); - content.add(paletteExplorer, PALETTES_CARD); - statusBars.add(paletteExplorer.statusBar(), PALETTES_CARD); - rememberPaletteCenter(explorerStart.centerX(), explorerStart.centerZ()); - if (!openedOnPalettes) { - showSurfaceBiomePalettes(explorerStart.centerX(), explorerStart.centerZ()); - } - } - - // Coming back from the map only moves the palettes when the map was moved, so a chosen layer survives a quick look. - private void followMapIntoPalettes() { - double movedX = canvas.centerX() - paletteCenterX; - double movedZ = canvas.centerZ() - paletteCenterZ; - if (Math.hypot(movedX, movedZ) < PALETTE_RECENTER_DISTANCE_BLOCKS) { - return; - } - paletteExplorer.centerOn(canvas.centerX(), canvas.centerZ()); - rememberPaletteCenter(canvas.centerX(), canvas.centerZ()); - showSurfaceBiomePalettes(canvas.centerX(), canvas.centerZ()); - } - - @Override - public void onShowPalettesAt(double worldX, double worldZ) { - canvas.centerOn(worldX, worldZ); - showView(MapView.PALETTES); - } - - private void showSurfaceBiomePalettes(double worldX, double worldZ) { - canvas.findSurfaceBiome(worldX, worldZ, biomeKey -> { - if (paletteExplorer != null) { - paletteExplorer.showPalettesAt(worldX, worldZ, biomeKey); - } - }); - } - - private void rememberPaletteCenter(double worldX, double worldZ) { - paletteCenterX = worldX; - paletteCenterZ = worldZ; - } - - @Override - public void onTogglesChanged() { - gridToggle.setSelected(canvas.isGridVisible()); - entitiesToggle.setSelected(canvas.areEntitiesVisible()); - followToggle.setSelected(canvas.isFollowing()); - shadingToggle.setSelected(canvas.style().shading()); - bordersToggle.setSelected(canvas.style().regionBorders()); - waterToggle.setSelected(canvas.isWaterOverlayEnabled()); - } - - @Override - public void onLegendChanged(String title, List shares, MapStyle.Highlight highlight) { - legendPanel.show(title, shares, highlight); - if (currentView == MapView.REGIONS) { - regionExplorer.measure(canvas.viewArea()); - } else if (currentView == MapView.BIOMES) { - biomeExplorer.measure(canvas.viewArea()); - } - } - - @Override - public void onContentRefreshed() { - regionExplorer.refresh(); - biomeExplorer.refresh(); - if (worldExplorer != null) { - worldExplorer.refresh(worldCenterX, worldCenterZ); - } - } - - // Only called for the view on screen, whose explorer exists by then. - private void resetExplorerView() { - switch (currentView) { - case WORLD_3D -> worldExplorer.resetCamera(); - case OBJECTS, PROCEDURAL -> objectExplorers.get(currentView).resetCamera(); - case NOISE -> noiseExplorer.resetViewport(); - case PALETTES -> paletteExplorer.resetViewport(); - default -> { - } - } - } - - private void useSidebar(JComponent component) { - sidebar.removeAll(); - sidebar.add(StudioTheme.matchTheme(component), BorderLayout.CENTER); - } - - private void useInspector(JComponent component) { - inspectorSlot.removeAll(); - inspectorSlot.add(StudioTheme.matchTheme(component), BorderLayout.CENTER); - } - - private void showCard(String card) { - ((CardLayout) content.getLayout()).show(content, card); - ((CardLayout) statusBars.getLayout()).show(statusBars, card); - } - - @SafeVarargs - private void showControls(List... visibleControls) { - for (List controls : List.of(mapControls, explorerControls, noiseControls, worldControls, imageMapControls)) { - controls.forEach(control -> control.setVisible(false)); - } - for (List controls : visibleControls) { - controls.forEach(control -> control.setVisible(true)); - } - } - - private void installShortcuts(JRootPane rootPane) { - for (MapView view : MapView.values()) { - bind(rootPane, KeyStroke.getKeyStroke(view.shortcutKey(), 0), "view-" + view.name(), () -> showView(view)); - } - bind(rootPane, KeyStroke.getKeyStroke(KeyEvent.VK_M, 0), "next-view", this::showNextView); - bind(rootPane, KeyStroke.getKeyStroke(KeyEvent.VK_R, 0), "refresh", this::refreshOrReset); - bindMap(rootPane, KeyEvent.VK_F, 0, "follow", canvas::toggleFollow); - bindMap(rootPane, KeyEvent.VK_G, 0, "grid", canvas::toggleGrid); - bindMap(rootPane, KeyEvent.VK_E, 0, "entities", canvas::toggleEntities); - bindMap(rootPane, KeyEvent.VK_F3, 0, "debug", canvas::toggleDebug); - bindMap(rootPane, KeyEvent.VK_H, 0, "highlight", canvas::highlightUnderCursor); - bindMap(rootPane, KeyEvent.VK_ESCAPE, 0, "dismiss", canvas::dismissEmphasis); - bindMap(rootPane, KeyEvent.VK_S, 0, "shading", canvas::toggleShading); - bindMap(rootPane, KeyEvent.VK_B, 0, "borders", canvas::toggleRegionBorders); - bindMap(rootPane, KeyEvent.VK_W, 0, "water", canvas::toggleWaterOverlay); - bindMap(rootPane, KeyEvent.VK_EQUALS, 0, "zoom-in", canvas::zoomIn); - bindMap(rootPane, KeyEvent.VK_EQUALS, KeyEvent.SHIFT_DOWN_MASK, "zoom-in-plus", canvas::zoomIn); - bindMap(rootPane, KeyEvent.VK_ADD, 0, "zoom-in-keypad", canvas::zoomIn); - bindMap(rootPane, KeyEvent.VK_MINUS, 0, "zoom-out", canvas::zoomOut); - bindMap(rootPane, KeyEvent.VK_SUBTRACT, 0, "zoom-out-keypad", canvas::zoomOut); - bindMap(rootPane, KeyEvent.VK_BACK_SLASH, 0, "reset-zoom", canvas::resetZoom); - bindMap(rootPane, KeyEvent.VK_SLASH, 0, "help", canvas::toggleHelp); - bindMap(rootPane, KeyEvent.VK_SLASH, KeyEvent.SHIFT_DOWN_MASK, "help-question", canvas::toggleHelp); - bind(rootPane, KeyStroke.getKeyStroke(KeyEvent.VK_SHIFT, KeyEvent.SHIFT_DOWN_MASK, false), "details-on", - () -> canvas.setDetailedHover(true)); - bind(rootPane, KeyStroke.getKeyStroke(KeyEvent.VK_SHIFT, 0, true), "details-off", () -> canvas.setDetailedHover(false)); - } - - private void bindMap(JRootPane rootPane, int keyCode, int modifiers, String name, Runnable action) { - bind(rootPane, KeyStroke.getKeyStroke(keyCode, modifiers), name, () -> { - if (currentView != null && currentView.isTileMap()) { - action.run(); - } - }); - } - - // Keys typed into a search box belong to that box, not to the window's shortcuts. - private static void bind(JRootPane rootPane, KeyStroke keyStroke, String name, Runnable action) { - rootPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(keyStroke, name); - rootPane.getActionMap().put(name, new AbstractAction() { - @Override - public void actionPerformed(ActionEvent event) { - if (!(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() instanceof JTextComponent)) { - action.run(); - } - } - }); - } - - private void showNextView() { - MapView[] views = MapView.values(); - showView(views[(currentView.ordinal() + 1) % views.length]); - } - - private void refreshOrReset() { - if (currentView.isTileMap()) { - canvas.refreshContent(); - } else { - resetExplorerView(); - } - } - - private void close() { - resourceUsage.stop(); - canvas.close(); - regionExplorer.close(); - biomeExplorer.close(); - if (paletteExplorer != null) { - paletteExplorer.close(); - } - objectExplorers.values().forEach(ObjectExplorer::close); - if (noiseExplorer != null) { - noiseExplorer.close(); - } - if (worldExplorer != null) { - worldExplorer.close(); - } - if (imageMapExplorer != null) { - imageMapExplorer.close(); - } - } - - public record NoiseSelection(String generatorKey, IrisGenerator generator, long seed) { - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/NoiseColorScale.java b/core/src/main/java/art/arcane/iris/studio/map/NoiseColorScale.java deleted file mode 100644 index 67a05d2af..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/NoiseColorScale.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.awt.Color; - -interface NoiseColorScale { - int colorFinite(double value); - - default int colorAt(double value, double worldX, double worldZ) { - return colorFinite(value); - } - - int colorInvalid(); - - default int colorInvalidAt(double worldX, double worldZ) { - return colorInvalid(); - } - - Color displayColorNormalized(double normalized); - - String label(); - - double minimum(); - - double maximum(); -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/NoiseColumns.java b/core/src/main/java/art/arcane/iris/studio/map/NoiseColumns.java deleted file mode 100644 index 835e7563e..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/NoiseColumns.java +++ /dev/null @@ -1,42 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.volmlib.util.function.NoiseProvider; - -import java.util.function.DoubleUnaryOperator; - -/** - * Noise as terrain columns: each value raised to a height and coloured by the noise's colour scale. - * - * @param heightOf turns a noise value into a height in blocks - */ -record NoiseColumns(NoiseProvider noise, DoubleUnaryOperator heightOf, NoiseColorScale colorScale) implements TerrainColumns { - @Override - public void sampleRow(TerrainGrid grid, int row, float[] heights, int[] colors) { - double worldZ = grid.originZ() + (double) row * grid.step(); - for (int column = 0; column < grid.columns(); column++) { - double worldX = grid.originX() + (double) column * grid.step(); - double value = noise.noise(worldX, worldZ); - int index = row * grid.columns() + column; - heights[index] = Double.isFinite(value) ? (float) heightOf.applyAsDouble(value) : Float.NaN; - colors[index] = Double.isFinite(value) ? colorScale.colorAt(value, worldX, worldZ) : 0; - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/NoiseExplorerGUI.java b/core/src/main/java/art/arcane/iris/studio/map/NoiseExplorerGUI.java deleted file mode 100644 index f7ed1dab9..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/NoiseExplorerGUI.java +++ /dev/null @@ -1,1766 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import com.formdev.flatlaf.FlatClientProperties; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.configuration.IrisSettings; -import art.arcane.iris.pack.loading.IrisData; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.generation.biome.IrisBiome; -import art.arcane.iris.generation.noise.IrisGenerator; -import art.arcane.iris.generation.noise.IrisShapedGeneratorStyle; -import art.arcane.iris.generation.noise.NoiseStyle; -import art.arcane.volmlib.util.function.NoiseProvider; -import art.arcane.volmlib.util.math.RNG; -import art.arcane.volmlib.util.noise.CNG; -import art.arcane.volmlib.util.stream.ProceduralStream; - -import javax.swing.AbstractAction; -import javax.swing.BorderFactory; -import javax.swing.ButtonGroup; -import javax.swing.DefaultListCellRenderer; -import javax.swing.DefaultListModel; -import javax.swing.JComboBox; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextField; -import javax.swing.JToggleButton; -import javax.swing.JToolBar; -import javax.swing.KeyStroke; -import javax.swing.ListSelectionModel; -import javax.swing.SwingConstants; -import javax.swing.Timer; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import java.awt.BasicStroke; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.EventQueue; -import java.awt.Graphics; -import java.awt.AlphaComposite; -import java.awt.Composite; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.RenderingHints; -import java.awt.event.ActionEvent; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseWheelEvent; -import java.awt.image.BufferedImage; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.EnumMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.DoubleUnaryOperator; -import java.util.function.LongFunction; - -public final class NoiseExplorerGUI extends JPanel { - private static final long serialVersionUID = 2094606939770332040L; - private static final Color GRID = new Color(255, 255, 255, 12); - private static final Color CROSSHAIR = new Color(255, 255, 255, 125); - private static final int LEGEND_WIDTH = 190; - private static final int REFINEMENT_DELAY_MILLIS = 180; - private static final long DEFAULT_SEED = 12345L; - private static final double TEXTURE_PIXELS_MAX_BLOCKS_PER_PIXEL = 0.25D; - private static final int FULL_DETAIL_SAMPLE_STEP = 1; - private static final double PALETTE_START_BLOCKS_PER_PIXEL = 1D / 16D; - private static final long COARSE_SAMPLE_BUDGET = 4_096L; - private static final double REFINEMENT_TARGET_MILLIS = 250D; - private static final double PALETTE_REFINEMENT_TARGET_MILLIS = 2_000D; - private static final double INTERACTIVE_FRAME_TARGET_MILLIS = 33D; - private static final int RESIZE_SETTLE_MILLIS = 45; - private static final double WHEEL_ZOOM_EXPONENT = 0.08D; - private static final int MOST_TERRAIN_WORKERS = 8; - private static final String OVERLAY_NOISE_ID = "dimension:overlay"; - private static final String TERRAIN_CAMERA_HINT = "Drag to orbit · Right-drag to pan · Scroll to zoom · R resets"; - private static final NoiseCategory[] CATEGORY_ORDER = { - NoiseCategory.CUSTOM, - NoiseCategory.PACK_GENERATORS, - NoiseCategory.PACK_PALETTES, - NoiseCategory.SIMPLEX, - NoiseCategory.PERLIN, - NoiseCategory.CELLULAR, - NoiseCategory.IRIS, - NoiseCategory.CLOVER, - NoiseCategory.HEXAGON, - NoiseCategory.VASCULAR, - NoiseCategory.GLOBE, - NoiseCategory.CUBIC, - NoiseCategory.FRACTAL, - NoiseCategory.STATIC, - NoiseCategory.NOWHERE, - NoiseCategory.SIERPINSKI, - NoiseCategory.UTILITY, - NoiseCategory.OTHER - }; - - private final ExplorerMode mode; - private final PaletteExplorerStart paletteStart; - private final NoiseViewport initialViewport; - private volatile Engine activeEngine; - private final LongFunction customFactory; - private final String customName; - private final List fixedSources; - private final ThreadPoolExecutor sourceExecutor; - private final ThreadPoolExecutor catalogExecutor; - private final NoiseRenderCoordinator renderCoordinator; - private final Timer refinementTimer; - private final Timer resizeTimer; - private final FrameCrossfade crossfade; - private final AtomicLong sourceLoadRevision = new AtomicLong(); - private final AtomicLong catalogLoadRevision = new AtomicLong(); - private final Runnable hotloadHook = this::handleHotload; - private final DefaultListModel sourceModel = new DefaultListModel<>(); - private final JList sourceList = new JList<>(sourceModel); - private final JTextField searchField = new JTextField(); - private final JTextField seedField = new JTextField(9); - private final JLabel selectedLabel = new JLabel("No source selected"); - private final JLabel catalogLabel = new JLabel("Pack catalog waiting"); - private final JComboBox palettePicker = new JComboBox<>(NoisePalette.values()); - private final StudioStatusBar statusBar = new StudioStatusBar(); - private final PaletteInspectorPanel paletteInspector = new PaletteInspectorPanel(new PaletteInspectorListener()); - private final PaletteNavigator paletteNavigator; - private final OrbitViewport terrainViewport = new OrbitViewport("Iris Noise Terrain Viewer", null); - private final int terrainWorkerCount = Math.min(MOST_TERRAIN_WORKERS, Math.max(1, Runtime.getRuntime().availableProcessors() / 2)); - private final ThreadPoolExecutor terrainWorkers; - private final ThreadPoolExecutor terrainSamplers; - private final NoiseTerrainView terrainView; - private final Map displayButtons = new EnumMap<>(NoiseDisplay.class); - private final TerrainHeightSlider heightSlider = new TerrainHeightSlider(heightBlocks -> requestTerrain()); - private final JComponent terrainPane = heightSlider.floatingOver(terrainViewport); - private PlayerLocationTracker locationTracker; - private volatile BlockTextures blockTextures; - - private List packSources = List.of(); - private NoiseViewport viewport; - private NoisePalette palette; - private SourceItem selectedSource; - private NoiseProvider sampler; - private BlockRange samplerBlockRange; - private NoiseDisplay display = NoiseDisplay.FLAT; - private PaletteLayerPreview palettePreview; - private int paletteDepth; - private NoiseRenderCoordinator.Result renderResult; - private NoiseRenderCoordinator.Result lastTimedFrame; - private NoiseRenderCoordinator.Request interactiveFrame; - private boolean interactiveFramePending; - private Point pointer; - private Point dragPoint; - private long seed; - private long viewRevision; - private int lastSourceRow = -1; - private boolean catalogLoading; - private boolean sourceLoading; - private boolean rendering; - private boolean disposed; - private boolean awaitingInitialPackSource; - private String requestedPaletteBiome; - private String errorMessage; - - private NoiseExplorerGUI(ExplorerMode mode, Engine engine, String customGeneratorKey, IrisGenerator fallbackGenerator, - String customName, long initialSeed, PaletteExplorerStart paletteStart) { - this.mode = mode; - this.paletteStart = paletteStart; - this.paletteNavigator = new PaletteNavigator(this::selectPalette); - this.awaitingInitialPackSource = mode == ExplorerMode.PALETTES; - this.requestedPaletteBiome = mode == ExplorerMode.PALETTES && paletteStart != null ? paletteStart.biomeKey() : null; - this.initialViewport = mode != ExplorerMode.PALETTES || paletteStart == null - ? new NoiseViewport(0D, 0D, 1D) - : new NoiseViewport(paletteStart.centerX(), paletteStart.centerZ(), PALETTE_START_BLOCKS_PER_PIXEL); - this.viewport = initialViewport; - this.activeEngine = engine; - this.customFactory = fallbackGenerator == null - ? null - : sourceSeed -> createGeneratorSampler(customGeneratorKey, fallbackGenerator, sourceSeed); - this.customName = customName; - this.seed = initialSeed; - this.seedField.setText(Long.toString(initialSeed)); - this.palette = IrisSettings.get().getGui().colorMode && mode == ExplorerMode.NOISE ? NoisePalette.TERRAIN : NoisePalette.GRAYSCALE; - this.sourceExecutor = createExecutor("Iris Noise Source Loader"); - this.catalogExecutor = createExecutor("Iris Noise Catalog Loader"); - this.renderCoordinator = new NoiseRenderCoordinator(new RenderListener()); - this.terrainWorkers = createWorkers("Iris Noise Terrain Worker", terrainWorkerCount); - this.terrainSamplers = createWorkers("Iris Noise Terrain Sampler", terrainWorkerCount); - this.terrainView = new NoiseTerrainView(terrainViewport, terrainWorkers, terrainSamplers, terrainWorkerCount); - this.terrainView.onProgress(this::refreshStatus); - MapHost.interruptOnPluginShutdown(sourceExecutor); - MapHost.interruptOnPluginShutdown(catalogExecutor); - MapHost.interruptOnPluginShutdown(terrainWorkers); - MapHost.interruptOnPluginShutdown(terrainSamplers); - this.refinementTimer = new Timer(REFINEMENT_DELAY_MILLIS, event -> requestRefinement()); - this.refinementTimer.setRepeats(false); - this.resizeTimer = new Timer(RESIZE_SETTLE_MILLIS, event -> requestPreview()); - this.resizeTimer.setRepeats(false); - this.crossfade = new FrameCrossfade(this::repaint); - this.fixedSources = buildFixedSources(); - setBackground(StudioTheme.EDITOR_BACKGROUND); - setFocusable(true); - setLayout(new BorderLayout()); - terrainPane.setVisible(false); - add(terrainPane, BorderLayout.CENTER); - installInputHandlers(); - catalogLabel.setFont(StudioTheme.smallFont()); - catalogLabel.setForeground(StudioTheme.SECONDARY_TEXT); - statusBar.showActivity(mode == ExplorerMode.PALETTES ? "Opening palettes..." : "Opening noise explorer..."); - MapHost.registerHotloadHook(hotloadHook); - } - - // The palette explorer has no window of its own: the map window shows it as its Palettes view. - static NoiseExplorerGUI createPaletteExplorer(PaletteExplorerStart start) { - return new NoiseExplorerGUI(ExplorerMode.PALETTES, start.engine(), null, null, null, DEFAULT_SEED, start); - } - - // The map window shows the noise explorer as its Noise view. - static NoiseExplorerGUI createNoiseExplorer(PaletteExplorerStart start) { - return new NoiseExplorerGUI(ExplorerMode.NOISE, start == null ? null : start.engine(), null, null, null, DEFAULT_SEED, start); - } - - static NoiseExplorerGUI createGeneratorExplorer(PaletteExplorerStart start, MapWindow.NoiseSelection selection) { - String generatorKey = selection.generatorKey(); - String displayName = generatorKey == null || generatorKey.isBlank() ? "Custom Generator" : generatorKey; - return new NoiseExplorerGUI(ExplorerMode.NOISE, start.engine(), generatorKey, selection.generator(), displayName, - selection.seed(), start); - } - - private static ThreadPoolExecutor createExecutor(String name) { - AtomicInteger threadId = new AtomicInteger(); - ThreadFactory threadFactory = runnable -> { - Thread thread = new Thread(runnable, name + " " + threadId.incrementAndGet()); - thread.setDaemon(true); - thread.setPriority(Thread.MIN_PRIORITY); - return thread; - }; - ThreadPoolExecutor executor = new ThreadPoolExecutor( - 1, - 1, - 30L, - TimeUnit.SECONDS, - new ArrayBlockingQueue<>(1), - threadFactory, - new ThreadPoolExecutor.DiscardOldestPolicy() - ); - executor.allowCoreThreadTimeOut(true); - return executor; - } - - static ThreadPoolExecutor createWorkers(String name, int count) { - AtomicInteger threadId = new AtomicInteger(); - ThreadFactory threadFactory = runnable -> { - Thread thread = new Thread(runnable, name + " " + threadId.incrementAndGet()); - thread.setDaemon(true); - thread.setPriority(Thread.MIN_PRIORITY); - return thread; - }; - ThreadPoolExecutor workers = new ThreadPoolExecutor(count, count, 30L, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), threadFactory); - workers.allowCoreThreadTimeOut(true); - return workers; - } - - List noiseControls() { - selectedLabel.setFont(StudioTheme.boldFont()); - selectedLabel.setBorder(StudioTheme.emptyBorder(0, 4, 0, 10)); - seedField.setMaximumSize(seedField.getPreferredSize()); - seedField.addActionListener(event -> applySeed()); - palettePicker.setSelectedItem(palette); - palettePicker.setMaximumSize(palettePicker.getPreferredSize()); - palettePicker.addActionListener(event -> { - NoisePalette nextPalette = (NoisePalette) palettePicker.getSelectedItem(); - if (nextPalette != null && nextPalette != palette) { - palette = nextPalette; - requestPreview(); - } - }); - List controls = new ArrayList<>(List.of( - selectedLabel, - new JToolBar.Separator(), - StudioToolbar.label("Seed"), - seedField, - StudioToolbar.button("Apply", "Use this seed", this::applySeed), - new JToolBar.Separator(), - StudioToolbar.label("Colours"), - palettePicker, - new JToolBar.Separator() - )); - controls.addAll(displayButtons()); - refreshTerrainControls(); - return controls; - } - - private List displayButtons() { - ButtonGroup group = new ButtonGroup(); - for (NoiseDisplay choice : NoiseDisplay.values()) { - JToggleButton button = StudioToolbar.toggle(choice.label(), choice.description()); - button.setSelected(choice == display); - button.addActionListener(event -> showAs(choice)); - group.add(button); - displayButtons.put(choice, button); - } - return List.copyOf(displayButtons.values()); - } - - // Noise already measured in blocks keeps its own heights, so only the 3D views of other noise can be raised. - private void refreshTerrainControls() { - heightSlider.setUsable(samplerBlockRange == null); - } - - JComponent noiseSidebar() { - JPanel sidebar = new JPanel(new BorderLayout()); - StudioToolbar.makeSearchField(searchField, "Search noise..."); - searchField.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void insertUpdate(DocumentEvent event) { - populateSourceList(); - } - - @Override - public void removeUpdate(DocumentEvent event) { - populateSourceList(); - } - - @Override - public void changedUpdate(DocumentEvent event) { - populateSourceList(); - } - }); - // Down or Enter in the search box jumps to the results, so the list can be searched without the mouse. - searchField.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "focus-results"); - searchField.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "focus-results"); - searchField.getActionMap().put("focus-results", new AbstractAction() { - @Override - public void actionPerformed(ActionEvent event) { - focusFirstSource(); - } - }); - - sourceList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - sourceList.setCellRenderer(new SourceCellRenderer()); - sourceList.addListSelectionListener(event -> { - if (event.getValueIsAdjusting()) { - return; - } - if (skipHeaderRow()) { - return; - } - ListItem item = sourceList.getSelectedValue(); - lastSourceRow = sourceList.getSelectedIndex(); - if (item != null && item.source() != null) { - selectSource(item.source()); - } - }); - - sidebar.add(StudioToolbar.padded(searchField, 8, 8, 8, 8), BorderLayout.NORTH); - sidebar.add(StudioToolbar.scroll(sourceList), BorderLayout.CENTER); - sidebar.add(StudioToolbar.padded(catalogLabel, 6, 12, 8, 12), BorderLayout.SOUTH); - populateSourceList(); - return sidebar; - } - - JComponent paletteSidebar() { - JPanel sidebar = new JPanel(new BorderLayout()); - sidebar.add(paletteNavigator, BorderLayout.CENTER); - sidebar.add(StudioToolbar.padded(catalogLabel, 6, 12, 8, 12), BorderLayout.SOUTH); - return sidebar; - } - - PaletteInspectorPanel paletteInspector() { - return paletteInspector; - } - - StudioStatusBar statusBar() { - return statusBar; - } - - double centerX() { - return viewport.centerX(); - } - - double centerZ() { - return viewport.centerZ(); - } - - void centerOn(double worldX, double worldZ) { - viewport = new NoiseViewport(worldX, worldZ, viewport.blocksPerPixel()); - requestPreview(); - } - - // Jumps to a spot and opens the palette of the biome there, once the catalog has loaded if it hasn't yet. - void showPalettesAt(double worldX, double worldZ, String biomeKey) { - centerOn(worldX, worldZ); - if (biomeKey == null) { - return; - } - requestedPaletteBiome = biomeKey; - SourceItem firstPalette = firstPaletteOf(biomeKey, packSources); - if (firstPalette != null && firstPalette != selectedSource) { - selectSource(firstPalette); - } - } - - // Header rows can't be chosen, so moving onto one with the arrow keys carries on to the next real source. - private boolean skipHeaderRow() { - int row = sourceList.getSelectedIndex(); - if (row < 0 || sourceModel.get(row).source() != null) { - return false; - } - int step = row >= lastSourceRow ? 1 : -1; - int next = nextSourceRow(row, step); - if (next < 0) { - next = nextSourceRow(row, -step); - } - if (next < 0) { - sourceList.clearSelection(); - } else { - sourceList.setSelectedIndex(next); - sourceList.ensureIndexIsVisible(next); - } - return true; - } - - private int nextSourceRow(int from, int step) { - for (int row = from + step; row >= 0 && row < sourceModel.size(); row += step) { - if (sourceModel.get(row).source() != null) { - return row; - } - } - return -1; - } - - private void focusFirstSource() { - int row = sourceList.getSelectedIndex() >= 0 ? sourceList.getSelectedIndex() : nextSourceRow(-1, 1); - if (row < 0) { - return; - } - sourceList.setSelectedIndex(row); - sourceList.ensureIndexIsVisible(row); - sourceList.requestFocusInWindow(); - } - - void openViewer() { - loadCatalog(); - if (mode == ExplorerMode.PALETTES) { - loadBlockTextures(); - if (paletteStart != null && paletteStart.playerId() != null) { - locationTracker = PlayerLocationTracker.follow(() -> activeEngine, - MapHost.overlayFor(activeEngine, paletteStart.playerId()), paletteNavigator::showLocation); - } else { - paletteNavigator.showUntracked(); - } - } - SourceItem initial = findInitialSource(); - if (initial != null && !selectSourceInList(initial.id())) { - selectSource(initial); - } - } - - private SourceItem findInitialSource() { - if (customFactory != null) { - for (SourceItem source : fixedSources) { - if (source.category() == NoiseCategory.CUSTOM) { - return source; - } - } - } - for (SourceItem source : fixedSources) { - if (source.id().equals("style:SIMPLEX")) { - return source; - } - } - return fixedSources.isEmpty() ? null : fixedSources.get(0); - } - - private List buildFixedSources() { - if (mode == ExplorerMode.PALETTES) { - return List.of(); - } - List sources = new ArrayList<>(); - if (customFactory != null && customName != null) { - sources.add(new SourceItem( - "custom:" + customName, - customName, - customName, - NoiseCategory.CUSTOM, - true, - (sourceSeed, depth) -> LoadedSource.of(customFactory.apply(sourceSeed)) - )); - } - for (NoiseStyle style : NoiseStyle.values()) { - sources.add(new SourceItem( - "style:" + style.name(), - formatName(style.name()), - style.name(), - categorize(style), - true, - (sourceSeed, depth) -> { - CNG noise = style.create(new RNG(sourceSeed)); - return LoadedSource.of((x, z) -> noise.noise(x, z)); - } - )); - } - return List.copyOf(sources); - } - - private void loadCatalog() { - if (disposed) { - return; - } - long revision = catalogLoadRevision.incrementAndGet(); - catalogLoading = true; - catalogLabel.setForeground(StudioTheme.SECONDARY_TEXT); - catalogLabel.setText("Loading pack catalog..."); - submitLatest(catalogExecutor, () -> { - try { - Engine engine = resolveEngine(); - List loadedSources = loadPackSources(engine); - PaletteCatalog paletteCatalog = mode == ExplorerMode.PALETTES && engine != null ? PaletteCatalog.load(engine) : null; - EventQueue.invokeLater(() -> applyCatalog(revision, loadedSources, paletteCatalog, null)); - } catch (Throwable error) { - IrisLogging.reportError(error); - EventQueue.invokeLater(() -> applyCatalog(revision, List.of(), null, error)); - } - }); - } - - private Engine resolveEngine() { - Engine engine = activeEngine; - return engine != null && !engine.isClosed() ? engine : null; - } - - private NoiseProvider createGeneratorSampler(String generatorKey, IrisGenerator fallback, long sourceSeed) { - IrisGenerator generator = fallback; - Engine engine = resolveEngine(); - if (engine != null && generatorKey != null && !generatorKey.isBlank()) { - IrisGenerator refreshedGenerator = engine.getData().getGeneratorLoader().load(generatorKey); - if (refreshedGenerator != null) { - generator = refreshedGenerator; - } - } - long mixedSeed = new RNG(sourceSeed).nextParallelRNG(3245).lmax(); - IrisGenerator selectedGenerator = generator; - return (x, z) -> selectedGenerator.getHeight(x, z, mixedSeed); - } - - private List loadPackSources(Engine engine) { - if (engine == null) { - return List.of(); - } - return switch (mode) { - case NOISE -> loadPackGeneratorSources(engine); - case PALETTES -> loadPackPaletteSources(engine); - }; - } - - private static List loadPackGeneratorSources(Engine engine) { - List sources = new ArrayList<>(); - SourceItem overlayNoise = overlayNoiseSource(engine); - if (overlayNoise != null) { - sources.add(overlayNoise); - } - IrisData data = engine.getData(); - String[] keys = data.getGeneratorLoader().getPossibleKeys(); - if (keys == null || keys.length == 0) { - return List.copyOf(sources); - } - Arrays.sort(keys); - for (String key : keys) { - sources.add(new SourceItem( - "pack:" + key, - formatName(key), - key, - NoiseCategory.PACK_GENERATORS, - true, - (sourceSeed, depth) -> { - IrisGenerator generator = data.getGeneratorLoader().load(key); - if (generator == null) { - throw new IllegalStateException("Pack generator not found: " + key); - } - long mixedSeed = new RNG(sourceSeed).nextParallelRNG(3245).lmax(); - return LoadedSource.of((x, z) -> generator.getHeight(x, z, mixedSeed)); - } - )); - } - return List.copyOf(sources); - } - - /** - * The dimension's overlay noise, summed the way the world adds it: heights in blocks above the fluid, with the - * world's own seed. In hybrid terrain it is the base terrain itself. - */ - private static SourceItem overlayNoiseSource(Engine engine) { - List overlay = engine.getDimension().getOverlayNoise(); - if (overlay.isEmpty()) { - return null; - } - BlockRange range = new BlockRange( - overlay.stream().mapToInt(IrisShapedGeneratorStyle::getMin).sum(), - overlay.stream().mapToInt(IrisShapedGeneratorStyle::getMax).sum()); - return new SourceItem(OVERLAY_NOISE_ID, "Overlay noise", "overlay noise", NoiseCategory.PACK_GENERATORS, false, - (sourceSeed, depth) -> { - ProceduralStream stream = engine.getComplex().getOverlayStream(); - return new LoadedSource(stream::get, null, range); - }); - } - - // Palette layers always use the world's terrain seed: they share their cached noise with the running world. - private List loadPackPaletteSources(Engine engine) { - IrisData data = engine.getData(); - String[] keys = data.getBiomeLoader().getPossibleKeys(); - if (keys == null || keys.length == 0) { - return List.of(); - } - Arrays.sort(keys); - List sources = new ArrayList<>(); - for (String key : keys) { - IrisBiome biome = data.getBiomeLoader().load(key); - if (biome == null) { - continue; - } - for (PaletteCatalog.PaletteSummary summary : PaletteCatalog.summarizePalettes(key, biome)) { - BiomePalette palette = summary.palette(); - sources.add(new SourceItem( - palette.id(), - summary.text(), - key, - NoiseCategory.PACK_PALETTES, - false, - (sourceSeed, depth) -> { - PaletteLayerPreview preview = PaletteLayerPreview.load(engine, palette, depth, blockTextures); - return new LoadedSource(preview::sample, preview, null); - } - )); - } - } - return List.copyOf(sources); - } - - private static SourceItem firstPaletteOf(String biomeKey, List sources) { - return sources.stream().filter(source -> BiomePalette.belongsTo(source.id(), biomeKey)).findFirst().orElse(null); - } - - private void selectPalette(BiomePalette palette) { - SourceItem source = findSourceById(palette.id(), packSources); - if (source != null && source != selectedSource) { - selectSource(source); - } - } - - private static BiomePalette paletteOf(SourceItem source) { - return BiomePalette.fromId(source.id()); - } - - private void loadBlockTextures() { - statusBar.showActivity(MinecraftClientJar.isCached() ? "Loading block textures..." : "Downloading block textures..."); - BlockTextures.shared().whenComplete((textures, error) -> EventQueue.invokeLater(() -> applyBlockTextures(textures, error))); - } - - private void applyBlockTextures(BlockTextures textures, Throwable error) { - if (disposed) { - return; - } - if (error != null) { - Throwable reason = error.getCause() == null ? error : error.getCause(); - statusBar.showError("Block textures unavailable: " + readableError(reason)); - return; - } - blockTextures = textures; - statusBar.showActivity(""); - // The first layer may still be loading without textures, so it has to be reloaded even before it shows. - if (selectedSource != null) { - loadSelectedSource(); - } - } - - private void applyCatalog(long revision, List sources, PaletteCatalog paletteCatalog, Throwable error) { - if (disposed || revision != catalogLoadRevision.get()) { - return; - } - catalogLoading = false; - packSources = sources; - if (paletteCatalog != null) { - paletteNavigator.showCatalog(paletteCatalog); - } - if (error != null) { - catalogLabel.setForeground(StudioTheme.ERROR); - catalogLabel.setText("Pack catalog unavailable"); - } else { - catalogLabel.setForeground(StudioTheme.SECONDARY_TEXT); - catalogLabel.setText(catalogSummary(sources)); - } - boolean reloadSelectedPack = false; - if (error == null - && selectedSource != null - && selectedSource.category().isFromPack()) { - SourceItem replacement = findSourceById(selectedSource.id(), sources); - if (replacement == null) { - failRemovedPackSource(selectedSource); - } else { - selectedSource = replacement; - reloadSelectedPack = true; - } - } - populateSourceList(); - if (reloadSelectedPack) { - loadSelectedSource(); - } - if (error == null && awaitingInitialPackSource && !sources.isEmpty()) { - awaitingInitialPackSource = false; - selectInitialPackSource(sources); - } - } - - private void selectInitialPackSource(List sources) { - SourceItem requested = requestedPaletteBiome == null ? null : firstPaletteOf(requestedPaletteBiome, sources); - SourceItem initial = requested == null ? sources.get(0) : requested; - if (!selectSourceInList(initial.id())) { - selectSource(initial); - } - } - - private String catalogSummary(List sources) { - if (mode == ExplorerMode.NOISE) { - return sources.isEmpty() ? "No active pack generators" : sources.size() + " pack generators"; - } - if (resolveEngine() == null) { - return "Open a studio world to see its palettes"; - } - long biomes = sources.stream().map(SourceItem::rawName).distinct().count(); - return sources.size() + " palettes in " + biomes + " biomes"; - } - - private void failRemovedPackSource(SourceItem removedSource) { - sourceLoadRevision.incrementAndGet(); - refinementTimer.stop(); - viewRevision++; - renderCoordinator.cancel(viewRevision); - selectedSource = null; - clearSampler(); - renderResult = null; - crossfade.clear(); - sourceLoading = false; - rendering = false; - errorMessage = "Pack source removed during hotload: " + removedSource.text(); - selectedLabel.setText("No source selected"); - sourceList.clearSelection(); - refreshStatus(); - repaint(); - } - - private void populateSourceList() { - if (!EventQueue.isDispatchThread()) { - EventQueue.invokeLater(this::populateSourceList); - return; - } - if (mode == ExplorerMode.PALETTES) { - return; - } - String selectedId = selectedSource == null ? null : selectedSource.id(); - String filter = searchField.getText().trim().toLowerCase(Locale.ROOT); - sourceModel.clear(); - for (NoiseCategory category : CATEGORY_ORDER) { - List matching = matchingSources(category, filter); - if (matching.isEmpty()) { - continue; - } - sourceModel.addElement(new ListItem(categoryLabel(category), null)); - for (SourceItem source : matching) { - sourceModel.addElement(new ListItem(source.text(), source)); - } - } - if (selectedId != null) { - selectSourceInList(selectedId); - } - } - - private List matchingSources(NoiseCategory category, String filter) { - List matching = new ArrayList<>(); - addMatchingSources(matching, fixedSources, category, filter); - addMatchingSources(matching, packSources, category, filter); - return matching; - } - - private static void addMatchingSources(List destination, List sources, - NoiseCategory category, String filter) { - for (SourceItem source : sources) { - if (source.category() != category) { - continue; - } - String searchable = (source.text() + " " + source.rawName()).toLowerCase(Locale.ROOT); - if (filter.isEmpty() || searchable.contains(filter)) { - destination.add(source); - } - } - } - - private boolean selectSourceInList(String sourceId) { - for (int index = 0; index < sourceModel.size(); index++) { - ListItem item = sourceModel.get(index); - if (item.source() != null && item.source().id().equals(sourceId)) { - sourceList.setSelectedIndex(index); - sourceList.ensureIndexIsVisible(index); - return true; - } - } - return false; - } - - private void selectSource(SourceItem source) { - if (disposed || source == null || (source == selectedSource && (sampler != null || sourceLoading))) { - return; - } - selectedSource = source; - paletteDepth = 0; - selectedLabel.setText(source.category() == NoiseCategory.PACK_PALETTES ? source.rawName() : source.text()); - if (source.category() == NoiseCategory.PACK_PALETTES) { - paletteNavigator.markSelected(paletteOf(source)); - } - loadSelectedSource(); - } - - private void loadSelectedSource() { - SourceItem source = selectedSource; - if (disposed || source == null) { - return; - } - long revision = sourceLoadRevision.incrementAndGet(); - long requestedSeed = seed; - int requestedDepth = paletteDepth; - refinementTimer.stop(); - viewRevision++; - renderCoordinator.cancel(viewRevision); - sampler = null; - crossfade.hold(renderResult); - renderResult = null; - sourceLoading = true; - rendering = false; - errorMessage = null; - if (display.showsTerrain()) { - terrainView.hide(); - terrainViewport.showLoading("Loading " + source.text()); - } - refreshStatus(); - repaint(); - submitLatest(sourceExecutor, () -> { - try { - LoadedSource loaded = source.factory().create(requestedSeed, requestedDepth); - if (loaded == null || loaded.sampler() == null) { - throw new IllegalStateException("Noise source returned no sampler: " + source.rawName()); - } - EventQueue.invokeLater(() -> applyLoadedSource(revision, source, loaded)); - } catch (Throwable error) { - IrisLogging.reportError(error); - EventQueue.invokeLater(() -> applySourceError(revision, source, error)); - } - }); - } - - private void applyLoadedSource(long revision, SourceItem source, LoadedSource loaded) { - if (disposed || revision != sourceLoadRevision.get() || selectedSource != source) { - return; - } - sampler = loaded.sampler(); - samplerBlockRange = loaded.blockRange(); - palettePreview = loaded.palettePreview(); - refreshTerrainControls(); - showPaletteInspector(); - sourceLoading = false; - errorMessage = null; - renderResult = null; - refreshStatus(); - requestPreview(); - } - - private void applySourceError(long revision, SourceItem source, Throwable error) { - if (disposed || revision != sourceLoadRevision.get() || selectedSource != source) { - return; - } - clearSampler(); - crossfade.clear(); - sourceLoading = false; - rendering = false; - errorMessage = readableError(error); - if (display.showsTerrain()) { - terrainViewport.showMessage("Could not load " + source.text()); - } - refreshStatus(); - repaint(); - } - - private void clearSampler() { - sampler = null; - samplerBlockRange = null; - palettePreview = null; - refreshTerrainControls(); - showPaletteInspector(); - } - - private void showPaletteInspector() { - if (palettePreview == null) { - paletteInspector.hideInspector(); - } else { - paletteInspector.showPreview(palettePreview); - } - if (paletteInspector.getParent() != null) { - paletteInspector.getParent().revalidate(); - } - } - - private NoiseColorScale activeColorScale() { - return activeColorScale(FULL_DETAIL_SAMPLE_STEP); - } - - // A coarse frame's sample stands for a whole square of pixels, so texture pixels would show magnified there. - private NoiseColorScale activeColorScale(int sampleStep) { - PaletteLayerPreview preview = palettePreview; - if (preview == null) { - BlockRange blockRange = samplerBlockRange; - return blockRange == null ? palette : new BlockHeightColorScale(palette, blockRange.lowest(), blockRange.highest()); - } - boolean showTexturePixels = viewport.blocksPerPixel() * sampleStep <= TEXTURE_PIXELS_MAX_BLOCKS_PER_PIXEL; - return new PaletteLayerScale(paletteInspector.selectedView(), preview, palette, showTexturePixels); - } - - private void applySeed() { - String rawSeed = seedField.getText().trim(); - try { - long nextSeed = Long.parseLong(rawSeed); - seedField.putClientProperty(FlatClientProperties.OUTLINE, null); - if (nextSeed == seed) { - return; - } - seed = nextSeed; - if (selectedSource != null && selectedSource.usesSeed()) { - loadSelectedSource(); - } - } catch (NumberFormatException error) { - seedField.putClientProperty(FlatClientProperties.OUTLINE, FlatClientProperties.OUTLINE_ERROR); - statusBar.showError("Seed must be a whole number"); - } - } - - private void requestPreview() { - if (display.showsTerrain()) { - requestTerrain(); - return; - } - if (disposed || sampler == null || getWidth() < 1 || renderHeight() < 1) { - repaint(); - return; - } - refinementTimer.stop(); - viewRevision++; - int sampleStep = NoiseRenderCoordinator.sampleStepForBudget( - getWidth(), - renderHeight(), - interactiveSampleBudget() - ); - interactiveFrame = requestRender(sampleStep); - } - - private void showAs(NoiseDisplay nextDisplay) { - if (nextDisplay == display) { - return; - } - display = nextDisplay; - displayButtons.get(nextDisplay).setSelected(true); - terrainPane.setVisible(nextDisplay.showsTerrain()); - refreshTerrainControls(); - revalidate(); - if (!nextDisplay.showsTerrain()) { - terrainView.hide(); - requestFocusInWindow(); - requestPreview(); - refreshStatus(); - return; - } - // Turns around the middle of the flat view, so switching to 3D shows the same stretch of noise. - terrainView.centerOn(viewport.centerX(), viewport.centerZ()); - requestTerrain(); - terrainViewport.requestFocusInWindow(); - refreshStatus(); - } - - private void requestTerrain() { - NoiseProvider terrainNoise = sampler; - if (disposed || !display.showsTerrain() || terrainNoise == null) { - return; - } - double waterLevel = samplerBlockRange == null ? Double.NaN : 0D; - TerrainSampling sampling = TerrainSampling.ofNoise(terrainNoise, terrainHeights(), activeColorScale(), waterLevel); - if (!terrainViewport.isShowingScene()) { - terrainViewport.showLoading("Sampling " + (selectedSource == null ? "noise" : selectedSource.text())); - } - terrainView.show(sampling); - } - - // Noise measured in blocks is its own height; any other noise is stretched from its colour range up to the chosen height. - private DoubleUnaryOperator terrainHeights() { - if (samplerBlockRange != null) { - return value -> value; - } - NoiseColorScale colorScale = activeColorScale(); - double lowest = colorScale.minimum(); - double span = colorScale.maximum() - lowest; - double heightBlocks = heightSlider.blocks(); - return value -> (value - lowest) / span * heightBlocks; - } - - /** - * Keeps the 3D views clear of a panel floating over the explorer's left side. - */ - void setCoveredLeftWidth(int width) { - terrainViewport.setCoveredLeftWidth(width); - } - - // Draws one frame at a time while the view moves, so each frame finishes and the next one starts from where the view is by then. - private void requestInteractiveFrame() { - repaint(); - if (isInteractiveFrameInFlight()) { - interactiveFramePending = true; - return; - } - requestPreview(); - } - - private boolean isInteractiveFrameInFlight() { - return interactiveFrame != null && interactiveFrame.revision() == viewRevision; - } - - // The last frame's speed predicts this one, so cheap views draw sharp straight away instead of starting blocky. It - // outlives a switch to another source, which samples about as fast. - private long interactiveSampleBudget() { - NoiseRenderCoordinator.Result lastResult = lastTimedFrame; - if (lastResult == null) { - return COARSE_SAMPLE_BUDGET; - } - return timedSampleBudget(lastResult, INTERACTIVE_FRAME_TARGET_MILLIS); - } - - private void requestRefinement() { - if (disposed || sampler == null || getWidth() < 1 || renderHeight() < 1) { - return; - } - NoiseRenderCoordinator.Result currentResult = renderResult; - if (currentResult == null || currentResult.request().revision() != viewRevision) { - return; - } - long sampleBudget = refinedSampleBudget(currentResult); - int sampleStep = NoiseRenderCoordinator.nextRefinementStep( - getWidth(), - renderHeight(), - currentResult.request().sampleStep(), - sampleBudget - ); - if (sampleStep >= currentResult.request().sampleStep()) { - return; - } - requestRender(sampleStep); - } - - // Blocks and their textures are slower to sample, so palettes get longer refinement passes than plain noise. - private long refinedSampleBudget(NoiseRenderCoordinator.Result currentResult) { - double targetMilliseconds = mode == ExplorerMode.PALETTES ? PALETTE_REFINEMENT_TARGET_MILLIS : REFINEMENT_TARGET_MILLIS; - return timedSampleBudget(currentResult, targetMilliseconds); - } - - private long timedSampleBudget(NoiseRenderCoordinator.Result lastResult, double targetMilliseconds) { - BufferedImage lastImage = lastResult.image(); - long renderedPixels = (long) lastImage.getWidth() * lastImage.getHeight(); - if (lastResult.milliseconds() <= 0D) { - return maximumSampleBudget(); - } - return NoiseRenderCoordinator.timeBoundSampleBudget( - renderedPixels, - lastResult.milliseconds(), - targetMilliseconds, - COARSE_SAMPLE_BUDGET, - maximumSampleBudget() - ); - } - - private long maximumSampleBudget() { - return Math.max(COARSE_SAMPLE_BUDGET, (long) getWidth() * renderHeight()); - } - - private NoiseRenderCoordinator.Request requestRender(int sampleStep) { - NoiseRenderCoordinator.Request request = new NoiseRenderCoordinator.Request( - viewRevision, - sampler, - viewport, - activeColorScale(sampleStep), - getWidth(), - renderHeight(), - sampleStep - ); - renderCoordinator.request(request); - return request; - } - - private void installInputHandlers() { - MouseAdapter mouseHandler = new MouseAdapter() { - @Override - public void mousePressed(MouseEvent event) { - requestFocusInWindow(); - dragPoint = event.getPoint(); - pointer = event.getPoint(); - } - - @Override - public void mouseReleased(MouseEvent event) { - boolean wasDragging = dragPoint != null; - dragPoint = null; - if (wasDragging) { - requestInteractiveFrame(); - } - } - - @Override - public void mouseDragged(MouseEvent event) { - Point nextPoint = event.getPoint(); - pointer = nextPoint; - if (dragPoint != null) { - double deltaX = nextPoint.getX() - dragPoint.getX(); - double deltaZ = nextPoint.getY() - dragPoint.getY(); - viewport = viewport.panPixels(deltaX, deltaZ); - dragPoint = nextPoint; - requestInteractiveFrame(); - } - } - - @Override - public void mouseMoved(MouseEvent event) { - pointer = event.getPoint(); - refreshPointerStatus(); - } - - @Override - public void mouseExited(MouseEvent event) { - pointer = null; - refreshPointerStatus(); - } - - @Override - public void mouseWheelMoved(MouseWheelEvent event) { - pointer = event.getPoint(); - double factor = Math.pow(2D, event.getPreciseWheelRotation() * WHEEL_ZOOM_EXPONENT); - viewport = viewport.zoomAt( - event.getX(), - Math.min(event.getY(), renderHeight()), - getWidth(), - renderHeight(), - factor - ); - requestInteractiveFrame(); - event.consume(); - } - }; - addMouseListener(mouseHandler); - addMouseMotionListener(mouseHandler); - addMouseWheelListener(mouseHandler); - addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent event) { - resizeTimer.restart(); - } - }); - } - - // A hotload replaces the engine; the explorer stays on the world it was opened for. - private Engine engineAfterHotload() { - return MapHost.findEngine(paletteStart == null ? null : paletteStart.worldId()); - } - - void resetViewport() { - if (display.showsTerrain()) { - terrainViewport.resetCamera(); - return; - } - viewport = initialViewport; - requestPreview(); - } - - private void handleHotload() { - Engine refreshedEngine = engineAfterHotload(); - EventQueue.invokeLater(() -> { - if (disposed) { - return; - } - if (refreshedEngine != null && !refreshedEngine.isClosed()) { - activeEngine = refreshedEngine; - } - loadCatalog(); - if (selectedSource != null && selectedSource.category() == NoiseCategory.CUSTOM) { - loadSelectedSource(); - } - }); - } - - void close() { - if (disposed) { - return; - } - disposed = true; - if (locationTracker != null) { - locationTracker.stop(); - } - refinementTimer.stop(); - resizeTimer.stop(); - crossfade.clear(); - MapHost.unregisterHotloadHook(hotloadHook); - sourceLoadRevision.incrementAndGet(); - catalogLoadRevision.incrementAndGet(); - sourceExecutor.shutdownNow(); - catalogExecutor.shutdownNow(); - renderCoordinator.close(); - terrainView.close(); - terrainWorkers.shutdownNow(); - terrainSamplers.shutdownNow(); - terrainViewport.close(); - } - - @Override - protected void paintComponent(Graphics graphics) { - super.paintComponent(graphics); - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - canvas.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); - int renderHeight = renderHeight(); - drawEmptyState(canvas, getWidth(), renderHeight); - if (renderResult != null) { - drawLatestFrame(canvas, renderResult, getWidth(), renderHeight); - } - drawOutgoingFrame(canvas, getWidth(), renderHeight); - drawCrosshair(canvas, getWidth(), renderHeight); - drawLegend(canvas, getWidth()); - } finally { - canvas.dispose(); - } - } - - // Returns true when the view moved while the frame rendered, after starting the frame for where it is now. - private boolean finishInteractiveFrame(NoiseRenderCoordinator.Request finishedRequest) { - if (finishedRequest != interactiveFrame) { - return false; - } - interactiveFrame = null; - if (!interactiveFramePending) { - return false; - } - interactiveFramePending = false; - requestPreview(); - return true; - } - - private void drawOutgoingFrame(Graphics2D canvas, int width, int renderHeight) { - NoiseRenderCoordinator.Result outgoing = crossfade.outgoing(); - if (outgoing == null) { - return; - } - Composite opaque = canvas.getComposite(); - canvas.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, crossfade.outgoingOpacity())); - drawLatestFrame(canvas, outgoing, width, renderHeight); - canvas.setComposite(opaque); - } - - // Moves and scales the last finished frame to the current view, so the map follows the mouse before the next frame lands. - private void drawLatestFrame(Graphics2D canvas, NoiseRenderCoordinator.Result frame, int width, int renderHeight) { - NoiseRenderCoordinator.Request request = frame.request(); - BufferedImage image = frame.image(); - NoiseViewport frameViewport = request.viewport(); - double frameScreenWidth = image.getWidth() * (double) request.sampleStep(); - double frameScreenHeight = image.getHeight() * (double) request.sampleStep(); - int left = (int) Math.round(viewport.screenX(frameViewport.worldX(0D, request.width()), width)); - int top = (int) Math.round(viewport.screenZ(frameViewport.worldZ(0D, request.height()), renderHeight)); - int right = (int) Math.round(viewport.screenX(frameViewport.worldX(frameScreenWidth, request.width()), width)); - int bottom = (int) Math.round(viewport.screenZ(frameViewport.worldZ(frameScreenHeight, request.height()), renderHeight)); - Object interpolation = request.sampleStep() == 1 || mode == ExplorerMode.PALETTES - ? RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR - : RenderingHints.VALUE_INTERPOLATION_BILINEAR; - canvas.setRenderingHint(RenderingHints.KEY_INTERPOLATION, interpolation); - canvas.drawImage(image, left, top, right - left, bottom - top, null); - } - - private static void drawEmptyState(Graphics2D canvas, int width, int height) { - canvas.setColor(StudioTheme.EDITOR_BACKGROUND); - canvas.fillRect(0, 0, width, height); - canvas.setColor(GRID); - for (int x = 0; x < width; x += 48) { - canvas.drawLine(x, 0, x, height); - } - for (int y = 0; y < height; y += 48) { - canvas.drawLine(0, y, width, y); - } - } - - private static void drawCrosshair(Graphics2D canvas, int width, int height) { - int centerX = width / 2; - int centerZ = height / 2; - canvas.setColor(CROSSHAIR); - canvas.setStroke(new BasicStroke(1F)); - int armLength = StudioTheme.scale(8); - canvas.drawLine(centerX - armLength, centerZ, centerX + armLength, centerZ); - canvas.drawLine(centerX, centerZ - armLength, centerX, centerZ + armLength); - } - - private void drawLegend(Graphics2D canvas, int width) { - NoiseColorScale colorScale = activeColorScale(); - canvas.setFont(StudioTheme.smallFont()); - String minimum = formatNumber(colorScale.minimum()); - String maximum = formatNumber(colorScale.maximum()); - String label = colorScale.label(); - int padding = StudioTheme.scale(9); - int labelGap = StudioTheme.scale(12); - int gradientHeight = StudioTheme.scale(8); - int textWidth = canvas.getFontMetrics().stringWidth(minimum) + canvas.getFontMetrics().stringWidth(label) - + canvas.getFontMetrics().stringWidth(maximum) + labelGap * 2; - int legendWidth = Math.max(StudioTheme.scale(LEGEND_WIDTH), textWidth + padding * 2); - int legendHeight = padding * 2 + gradientHeight + StudioTheme.scale(4) + canvas.getFontMetrics().getHeight(); - int legendX = Math.max(StudioTheme.scale(10), width - legendWidth - StudioTheme.scale(12)); - int legendY = StudioTheme.scale(12); - canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - StudioOverlay.drawCard(canvas, legendX, legendY, legendWidth, legendHeight); - int gradientX = legendX + padding; - int gradientY = legendY + padding; - int gradientWidth = legendWidth - padding * 2; - for (int x = 0; x < gradientWidth; x++) { - double normalized = x / (double) Math.max(1, gradientWidth - 1); - canvas.setColor(colorScale.displayColorNormalized(normalized)); - canvas.drawLine(gradientX + x, gradientY, gradientX + x, gradientY + gradientHeight); - } - int baseline = gradientY + gradientHeight + StudioTheme.scale(4) + canvas.getFontMetrics().getAscent(); - canvas.setColor(StudioTheme.TEXT); - canvas.drawString(minimum, gradientX, baseline); - canvas.drawString(maximum, gradientX + gradientWidth - canvas.getFontMetrics().stringWidth(maximum), baseline); - int labelWidth = canvas.getFontMetrics().stringWidth(label); - canvas.drawString(label, legendX + (legendWidth - labelWidth) / 2, baseline); - } - - private void refreshStatus() { - if (errorMessage != null) { - statusBar.showError("Error: " + errorMessage); - } else { - statusBar.showSummary(primaryStatus()); - } - refreshPointerStatus(); - } - - // Only the status bar changes when the pointer moves, so moving the mouse never redraws the map. - private void refreshPointerStatus() { - if (display.showsTerrain()) { - statusBar.showPosition(TERRAIN_CAMERA_HINT); - statusBar.showActivity(describeTerrain()); - return; - } - int renderHeight = renderHeight(); - Point currentPointer = pointer; - double screenX = currentPointer == null ? getWidth() / 2D : currentPointer.getX(); - double screenZ = currentPointer == null ? renderHeight / 2D : Math.min(currentPointer.getY(), renderHeight); - double worldX = viewport.worldX(screenX, getWidth()); - double worldZ = viewport.worldZ(screenZ, renderHeight); - statusBar.showPosition(String.format(Locale.ROOT, "X %.1f Z %.1f %s blocks/px", worldX, worldZ, - formatScale(viewport.blocksPerPixel()))); - statusBar.showActivity(pointerDetail(worldX, worldZ)); - } - - private String pointerDetail(double worldX, double worldZ) { - if (catalogLoading && renderResult == null) { - return "Loading catalog..."; - } - NoiseRenderCoordinator.Result result = renderResult; - if (result == null) { - return ""; - } - PaletteLayerPreview preview = palettePreview; - if (preview != null) { - return describePaletteAt(preview, worldX, worldZ); - } - long clipped = result.underflow() + result.overflow(); - return "range " + formatNumber(result.minimum()) + " to " + formatNumber(result.maximum()) - + " clipped " + clipped + " invalid " + result.invalid(); - } - - private String describeTerrain() { - int pending = terrainView.pendingTiles(); - return pending == 0 ? "" : "Sampling " + pending + (pending == 1 ? " tile" : " tiles"); - } - - private String primaryStatus() { - String sourceName = selectedSource == null ? "No source" : sourceTitle(selectedSource); - if (sourceLoading) { - return sourceName + " · loading"; - } - if (display.showsTerrain()) { - return terrainStatus(sourceName); - } - if (rendering && renderResult == null) { - return sourceName + " · rendering"; - } - if (renderResult == null) { - return sourceName; - } - NoiseRenderCoordinator.Result result = renderResult; - String quality = result.request().sampleStep() == 1 - ? "full detail" - : "1 sample per " + result.request().sampleStep() + " px"; - String seedText = selectedSource != null && selectedSource.usesSeed() ? " · seed " + seed : ""; - return sourceName + seedText + " · " + quality + " · " + String.format(Locale.ROOT, "%.0f ms", result.milliseconds()); - } - - private String terrainStatus(String sourceName) { - int detailStep = terrainView.detailStep(); - if (detailStep == 0) { - return sourceName + " · sampling"; - } - String seedText = selectedSource != null && selectedSource.usesSeed() ? " · seed " + seed : ""; - String detail = detailStep == 1 ? "full detail" : "1 column per " + detailStep + " blocks"; - return sourceName + seedText + " · " + detail; - } - - private static String sourceTitle(SourceItem source) { - return source.category() == NoiseCategory.PACK_PALETTES - ? source.rawName() + " · " + paletteOf(source).lowercaseLabel() - : source.text(); - } - - private static String describePaletteAt(PaletteLayerPreview preview, double worldX, double worldZ) { - double noise = preview.sample(worldX, worldZ); - if (Double.isNaN(noise)) { - return preview.palette().kind() == BiomePalette.Kind.DECORATOR - ? "The decorator places nothing here" - : "The layer doesn't reach this depth here"; - } - return preview.entryForNoise(noise).block() + " noise " + formatNumber(noise); - } - - private int renderHeight() { - return Math.max(1, getHeight()); - } - - private static String formatScale(double blocksPerPixel) { - if (blocksPerPixel >= 1D) { - return String.format(Locale.ROOT, "%.2f", blocksPerPixel); - } - return "1/" + String.format(Locale.ROOT, "%.0f", 1D / blocksPerPixel); - } - - private static String formatNumber(double value) { - if (!Double.isFinite(value)) { - return "n/a"; - } - return String.format(Locale.ROOT, "%.4f", value); - } - - private static String readableError(Throwable error) { - String message = error.getMessage(); - if (message == null || message.isBlank()) { - return error.getClass().getSimpleName(); - } - return message; - } - - private static SourceItem findSourceById(String id, List sources) { - for (SourceItem source : sources) { - if (source.id().equals(id)) { - return source; - } - } - return null; - } - - private static void submitLatest(ThreadPoolExecutor executor, Runnable task) { - if (executor.isShutdown()) { - return; - } - executor.getQueue().clear(); - executor.execute(task); - } - - private static NoiseCategory categorize(NoiseStyle style) { - String name = style.name(); - if (name.startsWith("STATIC")) { - return NoiseCategory.STATIC; - } - if (name.startsWith("IRIS")) { - return NoiseCategory.IRIS; - } - if (name.startsWith("CLOVER")) { - return NoiseCategory.CLOVER; - } - if (name.startsWith("VASCULAR")) { - return NoiseCategory.VASCULAR; - } - if (name.equals("FLAT")) { - return NoiseCategory.UTILITY; - } - if (name.startsWith("CELLULAR")) { - return NoiseCategory.CELLULAR; - } - if (name.startsWith("HEX") || name.equals("HEXAGON")) { - return NoiseCategory.HEXAGON; - } - if (name.startsWith("SIERPINSKI")) { - return NoiseCategory.SIERPINSKI; - } - if (name.startsWith("NOWHERE")) { - return NoiseCategory.NOWHERE; - } - if (name.startsWith("GLOB")) { - return NoiseCategory.GLOBE; - } - if (name.startsWith("PERLIN")) { - return NoiseCategory.PERLIN; - } - if (name.startsWith("CUBIC") || (name.startsWith("FRACTAL") && name.contains("CUBIC"))) { - return NoiseCategory.CUBIC; - } - if (name.contains("SIMPLEX") && !name.startsWith("FRACTAL")) { - return NoiseCategory.SIMPLEX; - } - if (name.startsWith("FRACTAL")) { - return NoiseCategory.FRACTAL; - } - return NoiseCategory.OTHER; - } - - private static String categoryLabel(NoiseCategory category) { - return switch (category) { - case CUSTOM -> "Custom"; - case PACK_GENERATORS -> "Pack Generators"; - case PACK_PALETTES -> "Pack Palettes"; - case SIMPLEX -> "Simplex"; - case PERLIN -> "Perlin"; - case CELLULAR -> "Cellular"; - case IRIS -> "Iris"; - case CLOVER -> "Clover"; - case HEXAGON -> "Hexagon"; - case VASCULAR -> "Vascular"; - case GLOBE -> "Globe"; - case CUBIC -> "Cubic"; - case FRACTAL -> "Fractal"; - case STATIC -> "Static"; - case NOWHERE -> "Nowhere"; - case SIERPINSKI -> "Sierpinski"; - case UTILITY -> "Utility"; - case OTHER -> "Other"; - }; - } - - private static String formatName(String rawName) { - if (rawName == null || rawName.isEmpty()) { - return "Unnamed"; - } - String lower = rawName.toLowerCase(Locale.ROOT).replace('_', ' '); - return Character.toUpperCase(lower.charAt(0)) + lower.substring(1); - } - - @FunctionalInterface - private interface SourceFactory { - LoadedSource create(long seed, int paletteDepth); - } - - /** - * @param blockRange the heights in blocks the noise spans, or null when its values aren't heights - */ - private record LoadedSource(NoiseProvider sampler, PaletteLayerPreview palettePreview, BlockRange blockRange) { - private static LoadedSource of(NoiseProvider sampler) { - return new LoadedSource(sampler, null, null); - } - } - - private record BlockRange(double lowest, double highest) { - } - - private record SourceItem(String id, String text, String rawName, NoiseCategory category, boolean usesSeed, - SourceFactory factory) { - } - - private record ListItem(String text, SourceItem source) { - } - - private final class PaletteInspectorListener implements PaletteInspectorPanel.Listener { - @Override - public void onViewChanged(PaletteLayerScale.View view) { - requestPreview(); - } - - @Override - public void onDepthChanged(int depth) { - if (depth == paletteDepth) { - return; - } - paletteDepth = depth; - loadSelectedSource(); - } - } - - private final class RenderListener implements NoiseRenderCoordinator.Listener { - @Override - public void onRenderStarted(NoiseRenderCoordinator.Request request) { - EventQueue.invokeLater(() -> { - if (!disposed && request.revision() == viewRevision) { - rendering = true; - refreshStatus(); - } - }); - } - - @Override - public void onRenderCompleted(NoiseRenderCoordinator.Result result) { - EventQueue.invokeLater(() -> { - if (disposed || result.request().revision() != viewRevision) { - return; - } - rendering = false; - errorMessage = null; - renderResult = result; - lastTimedFrame = result; - crossfade.reveal(); - repaint(); - refreshStatus(); - if (finishInteractiveFrame(result.request())) { - return; - } - if (result.request().sampleStep() <= 1) { - return; - } - long nextBudget = refinedSampleBudget(result); - int nextStep = NoiseRenderCoordinator.nextRefinementStep( - result.request().width(), - result.request().height(), - result.request().sampleStep(), - nextBudget - ); - if (nextStep < result.request().sampleStep()) { - refinementTimer.restart(); - } - }); - } - - @Override - public void onRenderFailed(NoiseRenderCoordinator.Request request, Throwable error) { - IrisLogging.reportError(error); - EventQueue.invokeLater(() -> { - if (disposed || request.revision() != viewRevision) { - return; - } - if (request == interactiveFrame) { - interactiveFrame = null; - interactiveFramePending = false; - } - rendering = false; - errorMessage = readableError(error); - repaint(); - refreshStatus(); - }); - } - } - - private static final class SourceCellRenderer extends DefaultListCellRenderer { - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, - boolean selected, boolean focus) { - ListItem item = (ListItem) value; - boolean header = item.source() == null; - super.getListCellRendererComponent(list, header ? item.text().toUpperCase(Locale.ROOT) : item.text(), index, - selected && !header, false); - if (header) { - setFont(StudioTheme.sectionFont()); - setForeground(StudioTheme.MUTED_TEXT); - setBorder(StudioTheme.emptyBorder(12, 12, 4, 12)); - } else { - setFont(StudioTheme.font()); - setBorder(StudioTheme.emptyBorder(3, 20, 3, 12)); - } - setHorizontalAlignment(SwingConstants.LEFT); - return this; - } - } - - private enum ExplorerMode { - NOISE, - PALETTES - } - - private enum NoiseDisplay { - FLAT("2D", "The noise from above, coloured by value"), - TERRAIN("3D", "The noise as terrain built from blocks, the way Minecraft would place it"); - - private final String label; - private final String description; - - NoiseDisplay(String label, String description) { - this.label = label; - this.description = description; - } - - private String label() { - return label; - } - - private String description() { - return description; - } - - private boolean showsTerrain() { - return this == TERRAIN; - } - } - - private enum NoiseCategory { - CUSTOM, - PACK_GENERATORS, - PACK_PALETTES, - SIMPLEX, - PERLIN, - CELLULAR, - IRIS, - CLOVER, - HEXAGON, - VASCULAR, - GLOBE, - CUBIC, - FRACTAL, - STATIC, - NOWHERE, - SIERPINSKI, - UTILITY, - OTHER; - - private boolean isFromPack() { - return this == PACK_GENERATORS || this == PACK_PALETTES; - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/NoisePalette.java b/core/src/main/java/art/arcane/iris/studio/map/NoisePalette.java deleted file mode 100644 index 5acf684f9..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/NoisePalette.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.awt.Color; - -enum NoisePalette implements NoiseColorScale { - TERRAIN("Terrain", 0D, 1D, new int[]{0x071A2F, 0x155E75, 0x2A9D8F, 0xE9C46A, 0xF4F1DE}), - SIGNED("Signed", -1D, 1D, new int[]{0x173B66, 0x4F86C6, 0xE7EDF3, 0xE89555, 0x9D3B35}), - GRAYSCALE("Grayscale", 0D, 1D, new int[]{0x050505, 0xFFFFFF}); - - static final int INVALID_COLOR = 0xFF2DAA; - - private final String label; - private final double minimum; - private final double maximum; - private final int[] lookup; - private final Color[] displayColors; - - NoisePalette(String label, double minimum, double maximum, int[] stops) { - this.label = label; - this.minimum = minimum; - this.maximum = maximum; - this.lookup = buildLookup(stops); - this.displayColors = buildDisplayColors(lookup); - } - - int color(double value) { - if (!Double.isFinite(value)) { - return INVALID_COLOR; - } - return colorFinite(value); - } - - @Override - public int colorFinite(double value) { - double normalized = (value - minimum) / (maximum - minimum); - return colorNormalized(normalized); - } - - int colorNormalized(double normalized) { - double clipped = Math.max(0D, Math.min(1D, normalized)); - return lookup[(int) Math.round(clipped * (lookup.length - 1))]; - } - - @Override - public int colorInvalid() { - return INVALID_COLOR; - } - - @Override - public Color displayColorNormalized(double normalized) { - double clipped = Math.max(0D, Math.min(1D, normalized)); - return displayColors[(int) Math.round(clipped * (displayColors.length - 1))]; - } - - @Override - public String label() { - return label; - } - - @Override - public double minimum() { - return minimum; - } - - @Override - public double maximum() { - return maximum; - } - - @Override - public String toString() { - return label; - } - - private static int[] buildLookup(int[] stops) { - int[] values = new int[256]; - for (int index = 0; index < values.length; index++) { - double position = (index / 255D) * (stops.length - 1); - int lowerIndex = Math.min(stops.length - 2, (int) position); - double fraction = position - lowerIndex; - values[index] = interpolate(stops[lowerIndex], stops[lowerIndex + 1], fraction); - } - return values; - } - - private static Color[] buildDisplayColors(int[] lookup) { - Color[] colors = new Color[lookup.length]; - for (int index = 0; index < lookup.length; index++) { - colors[index] = new Color(lookup[index]); - } - return colors; - } - - private static int interpolate(int from, int to, double fraction) { - int red = channel(from, 16, to, fraction); - int green = channel(from, 8, to, fraction); - int blue = channel(from, 0, to, fraction); - return (red << 16) | (green << 8) | blue; - } - - private static int channel(int from, int shift, int to, double fraction) { - int fromChannel = (from >>> shift) & 0xFF; - int toChannel = (to >>> shift) & 0xFF; - return (int) Math.round(fromChannel + ((toChannel - fromChannel) * fraction)); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/NoisePickChart.java b/core/src/main/java/art/arcane/iris/studio/map/NoisePickChart.java deleted file mode 100644 index e16174412..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/NoisePickChart.java +++ /dev/null @@ -1,340 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import javax.swing.JComponent; -import java.awt.Color; -import java.awt.Cursor; -import java.awt.Dimension; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.Comparator; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import java.util.function.Consumer; -import java.util.stream.Collectors; - -/** - * One noise that picks regions or biomes: the spread of its values in view above the bands that pick each option, - * and a table of how much of the noise each option is given and how much it gets in view. A long table shows only - * the options with the most ground in view until asked for all; a noise with one option to pick is a single line. - */ -final class NoisePickChart extends JComponent { - private static final long serialVersionUID = 1873365510472853316L; - private static final int PREFERRED_WIDTH = 300; - private static final int MARGIN = 16; - private static final int HISTOGRAM_HEIGHT = 64; - private static final int BAND_HEIGHT = 12; - private static final int TITLE_GAP = 6; - private static final int SECTION_GAP = 12; - private static final int BOTTOM_GAP = 14; - private static final Color HISTOGRAM_BAR = new Color(0x9D, 0xA0, 0xA8, 150); - private static final Color BAND_DIVIDER = new Color(255, 255, 255, 70); - private static final String WIDEST_SHARE = "▲ 100.0%"; - private static final int SHORT_TABLE_ROWS = 6; - - private final NoisePickSpread spread; - private final List rows; - private final String optionNoun; - private final Consumer onShowAllRowsChanged; - private boolean showsAllRows; - private Rectangle showAllToggleBounds; - - /** - * @param optionNoun what the noise picks, as a table heading: "Regions" or "Biomes" - * @param showsAllRows whether a long table starts with all its rows - * @param onShowAllRowsChanged receives whether the table shows all its rows after the user asked for more or fewer - */ - NoisePickChart(NoisePickSpread spread, String optionNoun, boolean showsAllRows, Consumer onShowAllRowsChanged) { - this.spread = spread; - this.rows = spread.rows(); - this.optionNoun = optionNoun; - this.showsAllRows = showsAllRows; - this.onShowAllRowsChanged = onShowAllRowsChanged; - setAlignmentX(LEFT_ALIGNMENT); - listenForShowAllToggle(); - } - - @Override - public Dimension getPreferredSize() { - if (hasSingleOption()) { - return new Dimension(StudioTheme.scale(PREFERRED_WIDTH), StudioTheme.scale(SECTION_GAP) + tableHeight() - + StudioTheme.scale(BOTTOM_GAP)); - } - int height = StudioTheme.scale(SECTION_GAP) + spreadHeight() + StudioTheme.scale(SECTION_GAP) + tableHeight() - + StudioTheme.scale(BOTTOM_GAP); - return new Dimension(StudioTheme.scale(PREFERRED_WIDTH), height); - } - - @Override - public Dimension getMaximumSize() { - return new Dimension(Integer.MAX_VALUE, getPreferredSize().height); - } - - @Override - protected void paintComponent(Graphics graphics) { - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - int margin = StudioTheme.scale(MARGIN); - int width = getWidth() - margin * 2; - int top = StudioTheme.scale(SECTION_GAP); - if (hasSingleOption()) { - drawSingleOption(canvas, margin, top, width); - return; - } - drawSpread(canvas, margin, top, width); - drawTable(canvas, margin, top + spreadHeight() + StudioTheme.scale(SECTION_GAP), width); - } finally { - canvas.dispose(); - } - } - - private int spreadHeight() { - return sectionMetrics().getHeight() + StudioTheme.scale(TITLE_GAP) + StudioTheme.scale(HISTOGRAM_HEIGHT) - + StudioTheme.scale(2) + StudioTheme.scale(BAND_HEIGHT) + StudioTheme.scale(3) + smallMetrics().getHeight(); - } - - private boolean hasSingleOption() { - return rows.size() == 1; - } - - private boolean isLongTable() { - return rows.size() > SHORT_TABLE_ROWS; - } - - private int tableHeight() { - int toggleRows = isLongTable() ? 1 : 0; - return sectionMetrics().getHeight() + StudioTheme.scale(TITLE_GAP) + rowHeight() * (shownRows().size() + toggleRows); - } - - // A short table keeps the options with the most ground in view, still in the order the noise meets them. - private List shownRows() { - if (showsAllRows || !isLongTable()) { - return rows; - } - Set largest = rows.stream() - .sorted(Comparator.comparingDouble(NoisePickSpread.Row::actualShare).reversed()) - .limit(SHORT_TABLE_ROWS) - .collect(Collectors.toSet()); - return rows.stream().filter(largest::contains).toList(); - } - - private void listenForShowAllToggle() { - MouseAdapter toggle = new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent event) { - if (showAllToggleBounds == null || !showAllToggleBounds.contains(event.getPoint())) { - return; - } - showsAllRows = !showsAllRows; - onShowAllRowsChanged.accept(showsAllRows); - revalidate(); - repaint(); - } - - @Override - public void mouseMoved(MouseEvent event) { - boolean overToggle = showAllToggleBounds != null && showAllToggleBounds.contains(event.getPoint()); - setCursor(overToggle ? Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) : null); - } - }; - addMouseListener(toggle); - addMouseMotionListener(toggle); - } - - private void drawSingleOption(Graphics2D canvas, int x, int top, int width) { - drawSectionTitle(canvas, spread.title(), x, top + sectionMetrics().getAscent()); - int rowTop = top + sectionMetrics().getHeight() + StudioTheme.scale(TITLE_GAP); - NoisePickSpread.Row row = rows.getFirst(); - String only = "picked everywhere"; - int nameRight = x + width - textMetrics().stringWidth(only) - StudioTheme.scale(10); - int baseline = drawOptionName(canvas, row, x, rowTop, nameRight); - canvas.setColor(StudioTheme.MUTED_TEXT); - drawRightAligned(canvas, only, x + width, baseline); - } - - private void drawSpread(Graphics2D canvas, int x, int top, int width) { - drawSectionTitle(canvas, spread.title(), x, top + sectionMetrics().getAscent()); - int histogramTop = top + sectionMetrics().getHeight() + StudioTheme.scale(TITLE_GAP); - int histogramHeight = StudioTheme.scale(HISTOGRAM_HEIGHT); - drawHistogram(canvas, x, histogramTop, width, histogramHeight); - int bandTop = histogramTop + histogramHeight + StudioTheme.scale(2); - drawBands(canvas, x, width, histogramTop, bandTop); - - canvas.setFont(StudioTheme.smallFont()); - canvas.setColor(StudioTheme.SECONDARY_TEXT); - FontMetrics metrics = canvas.getFontMetrics(); - int labelY = bandTop + StudioTheme.scale(BAND_HEIGHT) + StudioTheme.scale(3) + metrics.getAscent(); - canvas.drawString("0", x, labelY); - canvas.drawString("0.5", x + (width - metrics.stringWidth("0.5")) / 2, labelY); - canvas.drawString("1", x + width - metrics.stringWidth("1"), labelY); - } - - private void drawHistogram(Graphics2D canvas, int x, int top, int width, int height) { - long[] histogram = spread.histogram(); - long peak = 1L; - for (long count : histogram) { - peak = Math.max(peak, count); - } - canvas.setColor(HISTOGRAM_BAR); - for (int bin = 0; bin < histogram.length; bin++) { - int barLeft = x + (bin * width) / histogram.length; - int barRight = x + ((bin + 1) * width) / histogram.length; - int barHeight = (int) Math.round(height * (histogram[bin] / (double) peak)); - canvas.fillRect(barLeft, top + height - barHeight, Math.max(1, barRight - barLeft - 1), barHeight); - } - } - - private void drawBands(Graphics2D canvas, int x, int width, int histogramTop, int bandTop) { - int bandHeight = StudioTheme.scale(BAND_HEIGHT); - for (NoisePickSpread.Band band : spread.bands()) { - int bandLeft = x + (int) Math.round(band.fromNoise() * width); - int bandRight = x + (int) Math.round(band.toNoise() * width); - canvas.setColor(new Color(band.option().color())); - canvas.fillRect(bandLeft, bandTop, Math.max(1, bandRight - bandLeft), bandHeight); - if (band.toNoise() < 1D) { - canvas.setColor(BAND_DIVIDER); - canvas.drawLine(bandRight, histogramTop, bandRight, bandTop + bandHeight - 1); - } - } - } - - private void drawTable(Graphics2D canvas, int x, int top, int width) { - int columnGap = StudioTheme.scale(10); - int actualRight = x + width; - int weightRight = actualRight - textMetrics().stringWidth(WIDEST_SHARE) - columnGap; - int nameRight = weightRight - textMetrics().stringWidth(WIDEST_SHARE) - columnGap; - int titleBaseline = top + sectionMetrics().getAscent(); - drawSectionTitle(canvas, optionNoun, x, titleBaseline); - canvas.setFont(StudioTheme.sectionFont()); - drawRightAligned(canvas, "WEIGHT", weightRight, titleBaseline); - drawRightAligned(canvas, "IN VIEW", actualRight, titleBaseline); - - int rowHeight = rowHeight(); - int rowTop = top + sectionMetrics().getHeight() + StudioTheme.scale(TITLE_GAP); - for (NoisePickSpread.Row row : shownRows()) { - int baseline = drawOptionName(canvas, row, x, rowTop, nameRight); - canvas.setColor(StudioTheme.SECONDARY_TEXT); - drawRightAligned(canvas, percent(row.weightShare()), weightRight, baseline); - boolean farFromWeight = row.isFarBelowWeight() || row.isFarAboveWeight(); - canvas.setColor(farFromWeight ? StudioTheme.WARNING : StudioTheme.TEXT); - drawRightAligned(canvas, actualText(row), actualRight, baseline); - rowTop += rowHeight; - } - showAllToggleBounds = isLongTable() ? drawShowAllToggle(canvas, x, rowTop) : null; - } - - // Returns the row's text baseline. - private int drawOptionName(Graphics2D canvas, NoisePickSpread.Row row, int x, int rowTop, int nameRight) { - FontMetrics text = textMetrics(); - int rowHeight = rowHeight(); - int swatchSize = text.getAscent() - text.getDescent(); - int baseline = rowTop + (rowHeight + text.getAscent() - text.getDescent()) / 2; - int arc = StudioTheme.scale(3); - canvas.setColor(new Color(row.option().color())); - canvas.fillRoundRect(x, rowTop + (rowHeight - swatchSize) / 2, swatchSize, swatchSize, arc, arc); - canvas.setFont(StudioTheme.font()); - canvas.setColor(StudioTheme.TEXT); - int nameLeft = x + swatchSize + StudioTheme.scale(7); - canvas.drawString(fit(canvas, distinctName(row, rows), nameRight - nameLeft), nameLeft, baseline); - return baseline; - } - - private Rectangle drawShowAllToggle(Graphics2D canvas, int x, int rowTop) { - String text = showsAllRows - ? "Show fewer" - : "Show all " + rows.size() + " " + optionNoun.toLowerCase(Locale.ROOT); - FontMetrics metrics = textMetrics(); - int baseline = rowTop + (rowHeight() + metrics.getAscent() - metrics.getDescent()) / 2; - canvas.setFont(StudioTheme.font()); - canvas.setColor(StudioTheme.LINK); - canvas.drawString(text, x, baseline); - return new Rectangle(x, rowTop, metrics.stringWidth(text), rowHeight()); - } - - private int rowHeight() { - return textMetrics().getHeight() + StudioTheme.scale(4); - } - - private FontMetrics textMetrics() { - return getFontMetrics(StudioTheme.font()); - } - - private FontMetrics smallMetrics() { - return getFontMetrics(StudioTheme.smallFont()); - } - - private FontMetrics sectionMetrics() { - return getFontMetrics(StudioTheme.sectionFont()); - } - - private static void drawSectionTitle(Graphics2D canvas, String title, int x, int y) { - canvas.setFont(StudioTheme.sectionFont()); - canvas.setColor(StudioTheme.MUTED_TEXT); - canvas.drawString(title.toUpperCase(Locale.ROOT), x, y); - } - - private static void drawRightAligned(Graphics2D canvas, String text, int right, int y) { - canvas.drawString(text, right - canvas.getFontMetrics().stringWidth(text), y); - } - - // Two biomes in different folders can share a name, so their keys tell them apart. - private static String distinctName(NoisePickSpread.Row row, List rows) { - String name = row.option().name(); - boolean shared = rows.stream().anyMatch(other -> other != row && other.option().name().equals(name)); - return shared ? name + " (" + row.option().key() + ")" : name; - } - - private static String actualText(NoisePickSpread.Row row) { - if (row.isFarBelowWeight()) { - return "▼ " + percent(row.actualShare()); - } - if (row.isFarAboveWeight()) { - return "▲ " + percent(row.actualShare()); - } - return percent(row.actualShare()); - } - - static String percent(double share) { - if (share > 0D && share < 0.001D) { - return "<0.1%"; - } - return String.format(Locale.ROOT, "%.1f%%", share * 100D); - } - - private static String fit(Graphics2D canvas, String text, int maxWidth) { - FontMetrics metrics = canvas.getFontMetrics(); - if (metrics.stringWidth(text) <= maxWidth) { - return text; - } - String shortened = text; - while (shortened.length() > 1 && metrics.stringWidth(shortened + "…") > maxWidth) { - shortened = shortened.substring(0, shortened.length() - 1); - } - return shortened + "…"; - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/NoiseRenderCoordinator.java b/core/src/main/java/art/arcane/iris/studio/map/NoiseRenderCoordinator.java deleted file mode 100644 index c29abff36..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/NoiseRenderCoordinator.java +++ /dev/null @@ -1,397 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.volmlib.util.function.NoiseProvider; - -import java.awt.image.BufferedImage; -import java.util.Objects; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.concurrent.atomic.AtomicReference; - -final class NoiseRenderCoordinator implements AutoCloseable { - private static final int BANDS_PER_WORKER = 4; - - private final int workerCount; - private final Listener listener; - private final ThreadFactory workerThreadFactory; - private final AtomicReference latestRequested = new AtomicReference<>(); - private final AtomicLong latestRevision = new AtomicLong(); - private final AtomicBoolean closed = new AtomicBoolean(); - - NoiseRenderCoordinator(Listener listener) { - this(Math.min(4, Math.max(1, Runtime.getRuntime().availableProcessors() / 2)), listener); - } - - NoiseRenderCoordinator(int workerCount, Listener listener) { - this.workerCount = Math.max(1, workerCount); - this.listener = Objects.requireNonNull(listener, "listener"); - AtomicInteger threadIds = new AtomicInteger(); - workerThreadFactory = runnable -> { - Thread thread = new Thread(runnable, "Iris Noise Renderer " + threadIds.incrementAndGet()); - thread.setDaemon(true); - thread.setPriority(Thread.MIN_PRIORITY); - return thread; - }; - } - - synchronized void request(Request request) { - Objects.requireNonNull(request, "request"); - if (closed.get() || request.revision() < latestRevision.get()) { - return; - } - latestRevision.accumulateAndGet(request.revision(), Math::max); - cancelActiveRender(); - ThreadPoolExecutor workers = new ThreadPoolExecutor(workerCount, workerCount, 0L, TimeUnit.MILLISECONDS, - new LinkedBlockingQueue<>(), workerThreadFactory); - MapHost.interruptOnPluginShutdown(workers); - RenderGeneration generation = new RenderGeneration(request, workers); - latestRequested.set(generation); - listener.onRenderStarted(request); - for (int band = 0; band < generation.bandCount(); band++) { - int bandIndex = band; - try { - workers.execute(() -> renderBand(generation, bandIndex)); - } catch (RejectedExecutionException rejected) { - generation.fail(rejected); - finishBand(generation); - } - } - } - - synchronized void cancel(long revision) { - latestRevision.accumulateAndGet(revision, Math::max); - cancelActiveRender(); - } - - boolean isClosed() { - return closed.get(); - } - - static int sampleStepForBudget(int width, int height, long sampleBudget) { - if (width < 1 || height < 1 || sampleBudget < 1L) { - throw new IllegalArgumentException("Invalid noise sample budget"); - } - long totalSamples = (long) width * height; - int sampleStep = Math.max(1, (int) Math.ceil(Math.sqrt(totalSamples / (double) sampleBudget))); - while (sampleCount(width, height, sampleStep) > sampleBudget) { - sampleStep++; - } - return sampleStep; - } - - static long sampleCount(int width, int height, int sampleStep) { - if (width < 1 || height < 1 || sampleStep < 1) { - throw new IllegalArgumentException("Invalid noise sample dimensions"); - } - long outputWidth = ((long) width + sampleStep - 1L) / sampleStep; - long outputHeight = ((long) height + sampleStep - 1L) / sampleStep; - return outputWidth * outputHeight; - } - - static int nextRefinementStep(int width, int height, int currentStep, long sampleBudget) { - if (currentStep <= 1) { - throw new IllegalArgumentException("Noise refinement requires a coarse input"); - } - return Math.min(currentStep, sampleStepForBudget(width, height, sampleBudget)); - } - - static long timeBoundSampleBudget(long completedSamples, double milliseconds, double targetMilliseconds, - long minimumBudget, long maximumBudget) { - if (completedSamples < 1L - || !Double.isFinite(milliseconds) - || milliseconds <= 0D - || !Double.isFinite(targetMilliseconds) - || targetMilliseconds <= 0D - || minimumBudget < 1L - || maximumBudget < minimumBudget) { - throw new IllegalArgumentException("Invalid timed noise sample budget"); - } - double projectedSamples = Math.ceil((completedSamples / milliseconds) * targetMilliseconds); - long timeBoundBudget = (long) Math.min(maximumBudget, projectedSamples); - return Math.max(minimumBudget, timeBoundBudget); - } - - @Override - public synchronized void close() { - if (!closed.compareAndSet(false, true)) { - return; - } - latestRevision.incrementAndGet(); - cancelActiveRender(); - } - - private void renderBand(RenderGeneration generation, int bandIndex) { - try { - if (isCurrent(generation)) { - renderRows(generation, bandIndex); - } - } catch (Throwable error) { - generation.fail(error); - } finally { - finishBand(generation); - } - } - - private synchronized void finishBand(RenderGeneration generation) { - if (!generation.completeBand()) { - return; - } - generation.executor().shutdown(); - if (!isCurrent(generation)) { - return; - } - try { - Throwable failure = generation.failure(); - if (failure != null) { - listener.onRenderFailed(generation.request(), failure); - return; - } - listener.onRenderCompleted(generation.result()); - } finally { - latestRequested.compareAndSet(generation, null); - } - } - - private void renderRows(RenderGeneration generation, int bandIndex) { - Request request = generation.request(); - int outputWidth = generation.outputWidth(); - int outputHeight = generation.outputHeight(); - int[] pixels = generation.pixels(); - BandStats stats = generation.bandStats(bandIndex); - int fromY = (outputHeight * bandIndex) / generation.bandCount(); - int toY = (outputHeight * (bandIndex + 1)) / generation.bandCount(); - double sampleOffset = request.sampleStep() * 0.5D; - double startWorldX = request.viewport().worldX(sampleOffset, request.width()); - double worldStep = request.viewport().blocksPerPixel() * request.sampleStep(); - NoiseColorScale colorScale = request.colorScale(); - double paletteMinimum = colorScale.minimum(); - double paletteMaximum = colorScale.maximum(); - for (int y = fromY; y < toY; y++) { - double screenY = (y * (double) request.sampleStep()) + sampleOffset; - double worldZ = request.viewport().worldZ(screenY, request.height()); - double worldX = startWorldX; - int pixelIndex = y * outputWidth; - boolean centerRow = y == outputHeight / 2; - for (int x = 0; x < outputWidth; x++) { - if ((x & 31) == 0 && (!isCurrent(generation) || Thread.currentThread().isInterrupted())) { - return; - } - double value = request.sampler().noise(worldX, worldZ); - boolean center = centerRow && x == outputWidth / 2; - if (Double.isFinite(value)) { - pixels[pixelIndex++] = colorScale.colorAt(value, worldX, worldZ); - stats.acceptFinite(value, center, paletteMinimum, paletteMaximum); - } else { - pixels[pixelIndex++] = colorScale.colorInvalidAt(worldX, worldZ); - stats.acceptInvalid(value, center); - } - worldX += worldStep; - } - } - } - - private boolean isCurrent(RenderGeneration generation) { - return !closed.get() - && latestRequested.get() == generation - && generation.request().revision() >= latestRevision.get(); - } - - private void cancelActiveRender() { - RenderGeneration generation = latestRequested.getAndSet(null); - if (generation != null) { - generation.executor().shutdownNow(); - } - } - - private static int outputWidth(Request request) { - return Math.max(1, (request.width() + request.sampleStep() - 1) / request.sampleStep()); - } - - private static int outputHeight(Request request) { - return Math.max(1, (request.height() + request.sampleStep() - 1) / request.sampleStep()); - } - - private static RenderStats combine(BandStats[] bands) { - long samples = 0L; - long underflow = 0L; - long overflow = 0L; - long invalid = 0L; - double minimum = Double.POSITIVE_INFINITY; - double maximum = Double.NEGATIVE_INFINITY; - double centerValue = Double.NaN; - for (BandStats band : bands) { - samples += band.samples; - underflow += band.underflow; - overflow += band.overflow; - invalid += band.invalid; - minimum = Math.min(minimum, band.minimum); - maximum = Math.max(maximum, band.maximum); - if (!Double.isNaN(band.centerValue)) { - centerValue = band.centerValue; - } - } - if (minimum == Double.POSITIVE_INFINITY) { - minimum = Double.NaN; - maximum = Double.NaN; - } - return new RenderStats(samples, minimum, maximum, centerValue, underflow, overflow, invalid); - } - - interface Listener { - void onRenderStarted(Request request); - - void onRenderCompleted(Result result); - - void onRenderFailed(Request request, Throwable error); - } - - record Request(long revision, NoiseProvider sampler, NoiseViewport viewport, NoiseColorScale colorScale, - int width, int height, int sampleStep) { - Request { - Objects.requireNonNull(sampler, "sampler"); - Objects.requireNonNull(viewport, "viewport"); - Objects.requireNonNull(colorScale, "colorScale"); - if (revision < 0L || width < 1 || height < 1 || sampleStep < 1) { - throw new IllegalArgumentException("Invalid noise render request"); - } - } - } - - record Result(Request request, BufferedImage image, double milliseconds, long samples, double minimum, - double maximum, double centerValue, long underflow, long overflow, long invalid) { - } - - private static final class RenderGeneration { - private final Request request; - private final ThreadPoolExecutor executor; - private final long startedNanos = System.nanoTime(); - private final int outputWidth; - private final int outputHeight; - private final int[] pixels; - private final BandStats[] bandStats; - private final AtomicInteger remainingBands; - private final AtomicReference failure = new AtomicReference<>(); - - private RenderGeneration(Request request, ThreadPoolExecutor executor) { - this.request = request; - this.executor = executor; - this.outputWidth = NoiseRenderCoordinator.outputWidth(request); - this.outputHeight = NoiseRenderCoordinator.outputHeight(request); - this.pixels = new int[outputWidth * outputHeight]; - this.bandStats = new BandStats[Math.min(executor.getCorePoolSize() * BANDS_PER_WORKER, outputHeight)]; - for (int band = 0; band < bandStats.length; band++) { - bandStats[band] = new BandStats(); - } - this.remainingBands = new AtomicInteger(bandStats.length); - } - - private Request request() { - return request; - } - - private ThreadPoolExecutor executor() { - return executor; - } - - private int bandCount() { - return bandStats.length; - } - - private int outputWidth() { - return outputWidth; - } - - private int outputHeight() { - return outputHeight; - } - - private int[] pixels() { - return pixels; - } - - private BandStats bandStats(int band) { - return bandStats[band]; - } - - private void fail(Throwable error) { - failure.compareAndSet(null, error); - } - - private Throwable failure() { - return failure.get(); - } - - // True for the band that finishes last, which is the one that publishes the frame. - private boolean completeBand() { - return remainingBands.decrementAndGet() == 0; - } - - private Result result() { - BufferedImage image = MapHost.uncachedImage(pixels, outputWidth, outputHeight); - RenderStats combined = combine(bandStats); - double milliseconds = (System.nanoTime() - startedNanos) / 1_000_000D; - return new Result(request, image, milliseconds, combined.samples, combined.minimum, combined.maximum, - combined.centerValue, combined.underflow, combined.overflow, combined.invalid); - } - } - - private static final class BandStats { - private long samples; - private long underflow; - private long overflow; - private long invalid; - private double minimum = Double.POSITIVE_INFINITY; - private double maximum = Double.NEGATIVE_INFINITY; - private double centerValue = Double.NaN; - - private void acceptFinite(double value, boolean center, double paletteMinimum, double paletteMaximum) { - samples++; - if (center) { - centerValue = value; - } - minimum = Math.min(minimum, value); - maximum = Math.max(maximum, value); - if (value < paletteMinimum) { - underflow++; - } else if (value > paletteMaximum) { - overflow++; - } - } - - private void acceptInvalid(double value, boolean center) { - samples++; - invalid++; - if (center) { - centerValue = value; - } - } - } - - private record RenderStats(long samples, double minimum, double maximum, double centerValue, - long underflow, long overflow, long invalid) { - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/NoiseTerrain.java b/core/src/main/java/art/arcane/iris/studio/map/NoiseTerrain.java deleted file mode 100644 index 3da957d58..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/NoiseTerrain.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.util.Arrays; - -/** - * A stretch of noise or world as terrain at Minecraft scale: one height in blocks and one colour per column, each column - * {@code step} blocks wide and deep. Columns without a valid value are left out. - */ -record NoiseTerrain(int originX, int originZ, int columns, int rows, int step, float[] heights, int[] colors, - double lowest, double highest) { - /** - * Samples every column of the grid. - */ - static NoiseTerrain sample(TerrainSampling sampling, TerrainGrid grid) { - float[] heights = new float[grid.columns() * grid.rows()]; - int[] colors = new int[heights.length]; - for (int row = 0; row < grid.rows(); row++) { - sampling.columns().sampleRow(grid, row, heights, colors); - } - return of(grid, heights, colors); - } - - static NoiseTerrain empty(TerrainGrid grid) { - float[] heights = new float[grid.columns() * grid.rows()]; - Arrays.fill(heights, Float.NaN); - return of(grid, heights, new int[heights.length]); - } - - private static NoiseTerrain of(TerrainGrid grid, float[] heights, int[] colors) { - double lowest = Double.NaN; - double highest = Double.NaN; - for (float height : heights) { - if (Float.isNaN(height)) { - continue; - } - lowest = Double.isNaN(lowest) ? height : Math.min(lowest, height); - highest = Double.isNaN(highest) ? height : Math.max(highest, height); - } - return new NoiseTerrain(grid.originX(), grid.originZ(), grid.columns(), grid.rows(), grid.step(), heights, colors, - lowest, highest); - } - - boolean hasHeight(int column, int row) { - return column >= 0 && row >= 0 && column < columns && row < rows && !Float.isNaN(heights[row * columns + column]); - } - - float height(int column, int row) { - return heights[row * columns + column]; - } - - int color(int column, int row) { - return colors[row * columns + column]; - } - - // The world position of a column's or row's first block. - double worldX(double column) { - return originX + column * step; - } - - double worldZ(double row) { - return originZ + row * step; - } - - int sizeX() { - return columns * step; - } - - int sizeZ() { - return rows * step; - } - - boolean isEmpty() { - return Double.isNaN(lowest); - } - - // A block below the lowest point, where sides on the terrain's edge end. - int baseY() { - return (int) Math.floor(lowest) - 1; - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/NoiseTerrainRenderer.java b/core/src/main/java/art/arcane/iris/studio/map/NoiseTerrainRenderer.java deleted file mode 100644 index c22ffb646..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/NoiseTerrainRenderer.java +++ /dev/null @@ -1,440 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.awt.image.BufferedImage; -import java.awt.image.DataBufferInt; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.concurrent.Callable; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.Future; - -/** - * Draws noise terrain without a graphics card. Block columns get Minecraft's face shading and an outline around every - * block, until blocks get too small on screen to outline. Noise measured in blocks gets see-through water up to its - * level. - *

- * Each frame is split into horizontal bands drawn side by side, every band drawing only the pixels in its rows. Block - * faces are found once per terrain; each frame only works out which rows they cover, so bands skip the rest cheaply. - */ -final class NoiseTerrainRenderer { - private static final double TOP_SHADE = 1D; - private static final double NORTH_SOUTH_SHADE = 0.8D; - private static final double EAST_WEST_SHADE = 0.6D; - private static final double LEAST_SIDE_CONTRAST = 0.35D; - // The graphics card draws with these too, so both look alike. - static final int WATER_COLOR = 0x3F76E4; - static final double WATER_OPACITY = 0.55D; - static final double OUTLINE_SHADE = 0.72D; - static final double OUTLINE_LIGHTENING = 0.25D; - static final double DARK_LUMINANCE = 70D; - static final double LEAST_OUTLINE_SPACING_PIXELS = 4D; - static final double FULL_OUTLINE_SPACING_PIXELS = 12D; - static final double OUTLINE_HALF_WIDTH_PIXELS = 0.5D; - // A few slices per worker even out slices that take longer, like bands crossing the busiest part of the terrain. - private static final int SLICES_PER_WORKER = 2; - // Shared edges land exactly on pixel centres now and then; a little overlap keeps them from leaving cracks. - private static final double EDGE_TOLERANCE = 1e-6D; - private static final double EDGE_ON_DETERMINANT = 1e-9D; - - private final TerrainLayer layer; - private final NoiseTerrain terrain; - private final OrbitProjection projection; - private final int width; - private final int[] pixels; - private final double[] depths; - private final FaceRows faceRows; - private final int bandTop; - private final int bandBottom; - private final int[] runColors; - - private NoiseTerrainRenderer(Frame frame, TerrainLayer layer, FaceRows faceRows, int bandTop, int bandBottom) { - this.layer = layer; - this.terrain = layer.terrain(); - this.projection = frame.projection(); - this.width = frame.width(); - this.pixels = frame.pixels(); - this.depths = frame.depths(); - this.faceRows = faceRows; - this.bandTop = bandTop; - this.bandBottom = bandBottom; - this.runColors = new int[Math.max(terrain.columns(), terrain.rows())]; - } - - static OrbitPicture render(NoiseTerrainScene scene, OrbitCamera camera, int width, int height, int coveredLeftWidth) { - BufferedImage image = new BufferedImage(Math.max(1, width), Math.max(1, height), BufferedImage.TYPE_INT_RGB); - Frame frame = Frame.of(image, scene, camera, coveredLeftWidth); - List faceRows = new ArrayList<>(scene.layers().size()); - for (HoledLayer layer : scene.layers()) { - faceRows.add(FaceRows.of(frame, layer.layer(), layer.holeOfAllFillers(), scene)); - } - inSlices(image.getHeight(), scene, (top, bottom) -> drawBand(frame, scene, faceRows, top, bottom - 1)); - return OrbitPicture.of(image, frame.depths(), frame.projection()); - } - - // Every layer draws what it has in the band's rows; the water goes over all of them last. - private static void drawBand(Frame frame, NoiseTerrainScene scene, List faceRows, int bandTop, int bandBottom) { - frame.clearRows(bandTop, bandBottom); - for (int layer = 0; layer < scene.layers().size(); layer++) { - new NoiseTerrainRenderer(frame, scene.layers().get(layer).layer(), faceRows.get(layer), bandTop, bandBottom).drawBlocks(); - } - if (scene.hasWater() && !scene.layers().isEmpty()) { - NoiseTerrainScene.Extent extent = scene.extent(); - new NoiseTerrainRenderer(frame, scene.layers().get(0).layer(), FaceRows.NONE, bandTop, bandBottom) - .drawWater(extent.minX(), extent.minZ(), extent.sizeX(), extent.sizeZ(), BlockFaces.blockTop(scene.waterLevel())); - } - } - - // Splits {@code total} items into a few slices per worker and works on them side by side. - private static void inSlices(int total, NoiseTerrainScene scene, SliceWork work) { - int sliceCount = Math.min(total, scene.workerCount() * SLICES_PER_WORKER); - List> slices = new ArrayList<>(sliceCount); - for (int slice = 0; slice < sliceCount; slice++) { - int from = total * slice / sliceCount; - int to = total * (slice + 1) / sliceCount; - slices.add(() -> { - work.doSlice(from, to); - return null; - }); - } - try { - for (Future slice : scene.workers().invokeAll(slices)) { - slice.get(); - } - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - } catch (ExecutionException error) { - throw new IllegalStateException("Drawing the terrain failed", error.getCause()); - } - } - - private void drawBlocks() { - BlockFaces faces = layer.faces(); - for (int face = 0; face < faces.count(); face++) { - if (faceRows.crosses(face, bandTop, bandBottom)) { - drawFace(faces, face); - } - } - } - - // A face stretching over several columns is still coloured and outlined column by column. - private void drawFace(BlockFaces faces, int face) { - BlockFaces.Facing facing = faces.facing(face); - double shade = faceShadeAt(facing, projection.pixelsPerBlock()); - int columns = faces.columns(face); - for (int along = 0; along < columns; along++) { - int column = faces.firstColumn(face) + (facing.runsAlongX() ? along : 0); - int row = faces.firstRow(face) + (facing.runsAlongX() ? 0 : along); - runColors[along] = shade(terrain.color(column, row), shade); - } - fillQuad(faces.originX(face), faces.originY(face), faces.originZ(face), faces.runX(face), 0D, faces.runZ(face), - 0D, faces.reachY(face), faces.reachZ(face), facing.normalX, facing.normalY, facing.normalZ, - runColors, columns, faces.height(face)); - } - - // How much a face's colour is darkened, with blocks drawn {@code pixelsPerBlock} wide. - static double faceShadeAt(BlockFaces.Facing facing, double pixelsPerBlock) { - return withContrast(faceShade(facing), blockSideContrast(pixelsPerBlock)); - } - - private static double faceShade(BlockFaces.Facing facing) { - return switch (facing) { - case TOP -> TOP_SHADE; - case NORTH, SOUTH -> NORTH_SOUTH_SHADE; - case WEST, EAST -> EAST_WEST_SHADE; - }; - } - - // Blocks a few pixels wide show their sides as one-pixel slivers on every slope; at full contrast those read as noise. - private static double blockSideContrast(double pixelsPerBlock) { - return LEAST_SIDE_CONTRAST + (1D - LEAST_SIDE_CONTRAST) * outlineStrength(pixelsPerBlock); - } - - private static double withContrast(double faceShade, double contrast) { - return 1D - (1D - faceShade) * contrast; - } - - // Water is drawn last, blended over whatever lies below its surface, without hiding what is behind it. - private void drawWater(double x, double z, double sizeX, double sizeZ, double level) { - Footprint water = new Footprint(x, level, z, sizeX, 0, 0, 0, 0, sizeZ); - if (water.isEmpty()) { - return; - } - for (int y = water.top; y <= water.bottom; y++) { - water.spanRow(y); - for (int pixelX = water.rowStart; pixelX <= water.rowEnd; pixelX++) { - double alongU = water.alongU(pixelX, y); - double alongV = water.alongV(pixelX, y); - int index = y * width + pixelX; - if (isInside(alongU, alongV) && water.depthAt(alongU, alongV) > depths[index]) { - pixels[index] = blend(WATER_COLOR, pixels[index], WATER_OPACITY); - } - } - } - } - - /** - * Fills the parallelogram from {@code origin} along both edges, with lines {@code 1 / units} of the way along - * each edge; no lines when {@code units} is 0. Each of the {@code unitsU} blocks along the first edge takes its - * colour from {@code colorsAlongU}; with no units, the whole face takes the first. - */ - private void fillQuad(double originX, double originY, double originZ, double uX, double uY, double uZ, - double vX, double vY, double vZ, int normalX, int normalY, int normalZ, - int[] colorsAlongU, int unitsU, int unitsV) { - if (!projection.facesCamera(normalX, normalY, normalZ)) { - return; - } - Footprint quad = new Footprint(originX, originY, originZ, uX, uY, uZ, vX, vY, vZ); - if (quad.isEmpty()) { - return; - } - double pixelsPerUnitU = unitsU == 0 ? 0D : quad.lengthU() / unitsU; - double pixelsPerUnitV = unitsV == 0 ? 0D : quad.lengthV() / unitsV; - double outlineStrengthU = outlineStrength(pixelsPerUnitU); - double outlineStrengthV = outlineStrength(pixelsPerUnitV); - int lastUnitU = Math.max(0, unitsU - 1); - for (int y = quad.top; y <= quad.bottom; y++) { - quad.spanRow(y); - for (int x = quad.rowStart; x <= quad.rowEnd; x++) { - double alongU = quad.alongU(x, y); - double alongV = quad.alongV(x, y); - if (!isInside(alongU, alongV)) { - continue; - } - int index = y * width + x; - double depth = quad.depthAt(alongU, alongV); - if (depth < depths[index]) { - continue; - } - depths[index] = depth; - int color = colorsAlongU[Math.max(0, Math.min(lastUnitU, (int) (alongU * unitsU)))]; - if (isOnLine(alongU, unitsU, pixelsPerUnitU)) { - pixels[index] = blend(outlineOf(color), color, outlineStrengthU); - } else if (isOnLine(alongV, unitsV, pixelsPerUnitV)) { - pixels[index] = blend(outlineOf(color), color, outlineStrengthV); - } else { - pixels[index] = color; - } - } - } - } - - private static boolean isInside(double alongU, double alongV) { - return alongU >= -EDGE_TOLERANCE && alongU <= 1D + EDGE_TOLERANCE && alongV >= -EDGE_TOLERANCE && alongV <= 1D + EDGE_TOLERANCE; - } - - // Lines fade in as blocks grow on screen; dense lines at full strength would only speckle the face. - private static double outlineStrength(double pixelsPerUnit) { - double fadeIn = (pixelsPerUnit - LEAST_OUTLINE_SPACING_PIXELS) / (FULL_OUTLINE_SPACING_PIXELS - LEAST_OUTLINE_SPACING_PIXELS); - return Math.max(0D, Math.min(1D, fadeIn)); - } - - // Lines closer together than a few pixels would only grey the face out, so they are left out. - private static boolean isOnLine(double along, int units, double pixelsPerUnit) { - if (pixelsPerUnit < LEAST_OUTLINE_SPACING_PIXELS) { - return false; - } - double unitsAlong = along * units; - return Math.abs(unitsAlong - Math.rint(unitsAlong)) * pixelsPerUnit < OUTLINE_HALF_WIDTH_PIXELS; - } - - // Dark faces get lighter outlines, so the blocks of a black low still show. - private static int outlineOf(int color) { - double luminance = 0.3D * ((color >>> 16) & 0xFF) + 0.59D * ((color >>> 8) & 0xFF) + 0.11D * (color & 0xFF); - return luminance < DARK_LUMINANCE ? blend(0xFFFFFF, color, OUTLINE_LIGHTENING) : shade(color, OUTLINE_SHADE); - } - - private static int shade(int color, double shade) { - return BlockPreviewColors.shade(color, shade); - } - - private static int blend(int over, int under, double coverage) { - return blendChannel(over, under, coverage, 16) << 16 | blendChannel(over, under, coverage, 8) << 8 | blendChannel(over, under, coverage, 0); - } - - private static int blendChannel(int over, int under, double coverage, int shift) { - return (int) Math.round(((over >>> shift) & 0xFF) * coverage + ((under >>> shift) & 0xFF) * (1D - coverage)); - } - - /** - * What every band of one frame shares: the image's pixels and depths, and where the terrain lands on it. - */ - private record Frame(OrbitProjection projection, int width, int[] pixels, double[] depths) { - static Frame of(BufferedImage image, NoiseTerrainScene scene, OrbitCamera camera, int coveredLeftWidth) { - OrbitProjection projection = scene.projection(camera, image.getWidth(), image.getHeight(), coveredLeftWidth); - int[] pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); - return new Frame(projection, image.getWidth(), pixels, new double[pixels.length]); - } - - void clearRows(int top, int bottom) { - int from = top * width; - int to = (bottom + 1) * width; - Arrays.fill(pixels, from, to, StudioTheme.EDITOR_BACKGROUND.getRGB() & 0xFFFFFF); - Arrays.fill(depths, from, to, Double.NEGATIVE_INFINITY); - } - } - - /** - * The screen rows each block face of a layer spans this frame, worked out once so every band skips the faces it - * doesn't cross without projecting them again. - */ - private record FaceRows(int[] tops, int[] bottoms) { - static final FaceRows NONE = new FaceRows(new int[0], new int[0]); - - static FaceRows of(Frame frame, TerrainLayer layer, TerrainHole hole, NoiseTerrainScene scene) { - BlockFaces faces = layer.faces(); - FaceRows rows = new FaceRows(new int[faces.count()], new int[faces.count()]); - inSlices(faces.count(), scene, (from, to) -> rows.measure(faces, hole, frame.projection(), from, to)); - return rows; - } - - // Faces looking away from the camera, or not showing with the hole, are never drawn, so they span no rows. - private void measure(BlockFaces faces, TerrainHole hole, OrbitProjection projection, int fromFace, int toFace) { - for (int face = fromFace; face < toFace; face++) { - BlockFaces.Facing facing = faces.facing(face); - if (!projection.facesCamera(facing.normalX, facing.normalY, facing.normalZ) || !hole.shows(faces, face)) { - tops[face] = Integer.MAX_VALUE; - bottoms[face] = Integer.MIN_VALUE; - continue; - } - double originY = projection.screenY(faces.originX(face), faces.originY(face), faces.originZ(face)); - double runY = projection.screenStepY(faces.runX(face), 0D, faces.runZ(face)); - double reachY = projection.screenStepY(0D, faces.reachY(face), faces.reachZ(face)); - tops[face] = (int) Math.floor(originY + Math.min(0D, runY) + Math.min(0D, reachY)); - bottoms[face] = (int) Math.ceil(originY + Math.max(0D, runY) + Math.max(0D, reachY)); - } - } - - boolean crosses(int face, int top, int bottom) { - return tops[face] <= bottom && bottoms[face] >= top; - } - } - - @FunctionalInterface - private interface SliceWork { - void doSlice(int from, int to); - } - - /** - * Where a parallelogram, from an origin along two edges, lands in this band: the pixels around it, and how far - * along each edge, and how near, any pixel inside it is. - */ - private final class Footprint { - private final double originX; - private final double originY; - private final double originDepth; - private final double edgeUX; - private final double edgeUY; - private final double edgeUDepth; - private final double edgeVX; - private final double edgeVY; - private final double edgeVDepth; - private final double determinant; - private final int left; - private final int right; - private final int top; - private final int bottom; - private int rowStart; - private int rowEnd; - - private Footprint(double x, double y, double z, double uX, double uY, double uZ, double vX, double vY, double vZ) { - originX = projection.screenX(x, y, z); - originY = projection.screenY(x, y, z); - originDepth = projection.depth(x, y, z); - edgeUX = projection.screenStepX(uX, uZ); - edgeUY = projection.screenStepY(uX, uY, uZ); - edgeUDepth = projection.depthStep(uX, uY, uZ); - edgeVX = projection.screenStepX(vX, vZ); - edgeVY = projection.screenStepY(vX, vY, vZ); - edgeVDepth = projection.depthStep(vX, vY, vZ); - determinant = edgeUX * edgeVY - edgeUY * edgeVX; - left = Math.max(0, (int) Math.floor(min(originX, originX + edgeUX, originX + edgeVX, originX + edgeUX + edgeVX))); - right = Math.min(width - 1, (int) Math.ceil(max(originX, originX + edgeUX, originX + edgeVX, originX + edgeUX + edgeVX))); - top = Math.max(bandTop, (int) Math.floor(min(originY, originY + edgeUY, originY + edgeVY, originY + edgeUY + edgeVY))); - bottom = Math.min(bandBottom, (int) Math.ceil(max(originY, originY + edgeUY, originY + edgeVY, originY + edgeUY + edgeVY))); - } - - // Edge-on faces cover no pixels, and faces outside the band are another band's work. - private boolean isEmpty() { - return Math.abs(determinant) < EDGE_ON_DETERMINANT || top > bottom || left > right; - } - - /** - * Narrows {@link #rowStart} to {@link #rowEnd} to the pixels of row {@code y} the footprint can cover, so long - * thin faces lying across the screen don't cost their whole bounding box. A pixel or so either side is kept; - * the caller still tests every pixel. - */ - private void spanRow(int y) { - double fromOriginY = y + 0.5D - originY; - double slopeU = edgeVY / determinant; - double startU = -fromOriginY * edgeVX / determinant; - double slopeV = -edgeUY / determinant; - double startV = fromOriginY * edgeUX / determinant; - double[] range = {Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY}; - keepWhere(range, slopeU, startU, 0D, 1D); - keepWhere(range, slopeV, startV, 0D, 1D); - rowStart = Math.max(left, (int) Math.floor(range[0] + originX - 0.5D)); - rowEnd = Math.min(right, (int) Math.ceil(range[1] + originX - 0.5D)); - } - - // Narrows the range of offsets from the origin to where {@code start + slope * offset} stays within the limits. - private static void keepWhere(double[] range, double slope, double start, double lowest, double highest) { - if (Math.abs(slope) < EDGE_ON_DETERMINANT) { - if (start < lowest - EDGE_TOLERANCE || start > highest + EDGE_TOLERANCE) { - range[0] = Double.POSITIVE_INFINITY; - } - return; - } - double atLowest = (lowest - EDGE_TOLERANCE - start) / slope; - double atHighest = (highest + EDGE_TOLERANCE - start) / slope; - range[0] = Math.max(range[0], Math.min(atLowest, atHighest)); - range[1] = Math.min(range[1], Math.max(atLowest, atHighest)); - } - - private double alongU(int x, int y) { - return ((x + 0.5D - originX) * edgeVY - (y + 0.5D - originY) * edgeVX) / determinant; - } - - private double alongV(int x, int y) { - return ((y + 0.5D - originY) * edgeUX - (x + 0.5D - originX) * edgeUY) / determinant; - } - - private double depthAt(double alongU, double alongV) { - return originDepth + alongU * edgeUDepth + alongV * edgeVDepth; - } - - private double lengthU() { - return Math.hypot(edgeUX, edgeUY); - } - - private double lengthV() { - return Math.hypot(edgeVX, edgeVY); - } - - private static double min(double a, double b, double c, double d) { - return Math.min(Math.min(a, b), Math.min(c, d)); - } - - private static double max(double a, double b, double c, double d) { - return Math.max(Math.max(a, b), Math.max(c, d)); - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/NoiseTerrainScene.java b/core/src/main/java/art/arcane/iris/studio/map/NoiseTerrainScene.java deleted file mode 100644 index 828933ed4..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/NoiseTerrainScene.java +++ /dev/null @@ -1,139 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.util.List; -import java.util.Optional; -import java.util.concurrent.ExecutorService; - -/** - * Endless noise terrain as the orbit viewport shows it: the tiles in sight as block columns, drawn by - * {@code workerCount} of {@code workers} at once on machines without a graphics card. The camera's pivot is given - * from {@code anchor}, and zoom sets pixels per block directly, so tiles coming and going never move the view. - * - * @param floorY where sides on the edge of the sampled ground end - * @param waterLevel the height water fills up to, or NaN when the noise has no water - */ -record NoiseTerrainScene(List layers, Vec3 anchor, int floorY, int topY, double waterLevel, - ExecutorService workers, int workerCount) implements OrbitScene { - // Looks further down than the object viewer, so a landscape's shape reads before its sides. - static final OrbitCamera START = new OrbitCamera(0.76D, 0.62D, 1D, Vec3.ZERO); - private static final double VIEW_HEIGHT_BLOCKS_AT_ZOOM_ONE = 384D; - // Looking level would see endless ground, and looking up only its underside. - private static final double LOWEST_PITCH = 0.1D; - private static final double HIGHEST_PITCH = 1.3D; - private static final double TALLEST_VIEW_BLOCKS = 100_000D; - private static final double SHORTEST_VIEW_BLOCKS = 24D; - private static final OrbitLimits LIMITS = new OrbitLimits(LOWEST_PITCH, HIGHEST_PITCH, - VIEW_HEIGHT_BLOCKS_AT_ZOOM_ONE / TALLEST_VIEW_BLOCKS, VIEW_HEIGHT_BLOCKS_AT_ZOOM_ONE / SHORTEST_VIEW_BLOCKS); - - static OrbitProjection projectionFrom(Vec3 anchor, OrbitCamera camera, int width, int height, int coveredLeftWidth) { - int covered = Math.max(0, Math.min(width - 1, coveredLeftWidth)); - return OrbitProjection.atScale(anchor, camera, height / VIEW_HEIGHT_BLOCKS_AT_ZOOM_ONE, width, height, covered); - } - - @Override - public boolean isEmpty() { - return layers.stream().allMatch(layer -> layer.terrain().isEmpty()); - } - - @Override - public OrbitCamera startingCamera() { - return START; - } - - @Override - public OrbitLimits limits() { - return LIMITS; - } - - @Override - public OrbitPicture render(OrbitCamera camera, int width, int height, int coveredLeftWidth) { - return renderOnCard(camera, width, height, coveredLeftWidth) - .orElseGet(() -> NoiseTerrainRenderer.render(this, camera, width, height, coveredLeftWidth)); - } - - private Optional renderOnCard(OrbitCamera camera, int width, int height, int coveredLeftWidth) { - if (!GpuLibrary.isLoaded()) { - return Optional.empty(); - } - return GpuTerrainRenderer.render(this, camera, width, height, coveredLeftWidth); - } - - @Override - public boolean canRenderOnScreen() { - return GpuLibrary.isLoaded() && GpuFrames.canDrawOnScreen(); - } - - @Override - public Optional renderOnScreen(ScreenTarget screen, OrbitCamera camera, int width, int height, int coveredLeftWidth) { - return GpuTerrainRenderer.renderOnScreen(this, screen, camera, width, height, coveredLeftWidth); - } - - @Override - public OrbitProjection projection(OrbitCamera camera, int width, int height, int coveredLeftWidth) { - return projectionFrom(anchor, camera, width, height, coveredLeftWidth); - } - - boolean hasWater() { - return Double.isFinite(waterLevel) && waterLevel > floorY; - } - - /** - * Where the layers lie, from the floor to the highest ground, so water can spread under all of them. - */ - Extent extent() { - double minX = Double.POSITIVE_INFINITY; - double minZ = Double.POSITIVE_INFINITY; - double maxX = Double.NEGATIVE_INFINITY; - double maxZ = Double.NEGATIVE_INFINITY; - double lowest = floorY; - double highest = topY; - for (HoledLayer layer : layers) { - NoiseTerrain terrain = layer.terrain(); - minX = Math.min(minX, terrain.originX()); - minZ = Math.min(minZ, terrain.originZ()); - maxX = Math.max(maxX, terrain.originX() + (double) terrain.sizeX()); - maxZ = Math.max(maxZ, terrain.originZ() + (double) terrain.sizeZ()); - if (!terrain.isEmpty()) { - lowest = Math.min(lowest, terrain.baseY()); - highest = Math.max(highest, BlockFaces.blockTop(terrain.highest())); - } - } - return new Extent(minX, lowest, minZ, maxX, highest, maxZ); - } - - record Extent(double minX, double minY, double minZ, double maxX, double maxY, double maxZ) { - double sizeX() { - return maxX - minX; - } - - double sizeZ() { - return maxZ - minZ; - } - - // The farthest any of it lies from a point, which the depth buffer has to reach. - double farthestFrom(Vec3 point) { - double x = Math.max(Math.abs(minX - point.x()), Math.abs(maxX - point.x())); - double y = Math.max(Math.abs(minY - point.y()), Math.abs(maxY - point.y())); - double z = Math.max(Math.abs(minZ - point.z()), Math.abs(maxZ - point.z())); - return Math.sqrt(x * x + y * y + z * z); - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/NoiseTerrainView.java b/core/src/main/java/art/arcane/iris/studio/map/NoiseTerrainView.java deleted file mode 100644 index 749daef66..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/NoiseTerrainView.java +++ /dev/null @@ -1,256 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.spi.IrisLogging; - -import javax.swing.Timer; -import java.awt.EventQueue; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * What the 3D noise view shows: endless terrain, sampled tile by tile wherever the camera looks. Whenever the camera - * moves or another tile is sampled, what to draw is worked out again off the Swing thread. - */ -final class NoiseTerrainView { - private final OrbitViewport viewport; - private final ExecutorService renderWorkers; - private final ExecutorService samplers; - private final int workerCount; - private final ExecutorService coverer = Executors.newSingleThreadExecutor(task -> { - Thread thread = new Thread(task, "Iris Noise Terrain Cover"); - thread.setDaemon(true); - return thread; - }); - private final AtomicBoolean coverQueued = new AtomicBoolean(); - private final AtomicBoolean closed = new AtomicBoolean(); - private final Timer retryTimer = new Timer(1, event -> requestCover()); - private volatile TerrainTiles tiles; - private volatile Vec3 anchor; - private volatile ViewState view; - private volatile boolean hidden = true; - private double centerX; - private double centerZ; - private boolean recentered = true; - private TerrainCover.Result shown; - private Runnable onProgress = () -> { - }; - - NoiseTerrainView(OrbitViewport viewport, ExecutorService renderWorkers, ExecutorService samplers, int workerCount) { - this.viewport = viewport; - this.renderWorkers = renderWorkers; - this.samplers = samplers; - this.workerCount = workerCount; - retryTimer.setRepeats(false); - MapHost.interruptOnPluginShutdown(coverer); - viewport.onViewChange(this::viewChanged); - } - - /** - * Shows the ground around this point next, turning around it. - */ - void centerOn(double worldX, double worldZ) { - centerX = worldX; - centerZ = worldZ; - recentered = true; - if (viewport.isShowingScene()) { - viewport.centerPivot(); - } - } - - /** - * Samples the terrain anew, as the camera looks at it, keeping the camera if the view already shows some. The ground - * shown so far stays until its tiles are sampled anew. - */ - void show(TerrainSampling sampling) { - if (closed.get()) { - return; - } - retryTimer.stop(); - if (recentered || anchor == null) { - anchor = new Vec3(centerX, (sampling.floorY() + sampling.topY()) / 2D, centerZ); - recentered = false; - } - TerrainTiles previous = tiles; - Map shownBefore = previous == null ? Map.of() : previous.layersInUse(); - if (previous != null) { - previous.close(); - } - tiles = new TerrainTiles(sampling, samplers, workerCount, this::requestCover, shownBefore); - hidden = false; - viewChanged(); - } - - /** - * Goes on sampling what the camera looks at after {@link #hide}, with the tiles sampled before. - */ - void resume() { - if (closed.get() || tiles == null) { - return; - } - hidden = false; - viewChanged(); - } - - // Nothing is sampled for a view no one sees. - void hide() { - hidden = true; - retryTimer.stop(); - TerrainTiles current = tiles; - if (current != null) { - current.sampleOnly(List.of(), Set.of()); - } - } - - void invalidate() { - retryTimer.stop(); - TerrainTiles current = tiles; - tiles = null; - shown = null; - if (current != null) { - current.close(); - } - } - - /** - * @param listener runs on the Swing thread whenever the detail wanted or the tiles still to sample change - */ - void onProgress(Runnable listener) { - onProgress = listener; - } - - // How many blocks wide the columns are that the view wants, or 0 before anything was worked out. - int detailStep() { - return shown == null ? 0 : shown.detailStep(); - } - - int pendingTiles() { - return shown == null ? 0 : shown.pendingTiles(); - } - - /** - * How the view looks at the ground for its newest camera, or null before it has any ground to look at. - */ - GroundSight groundSight() { - TerrainTiles current = tiles; - ViewState state = view; - Vec3 at = anchor; - if (current == null || state == null || at == null || state.width() < 1 || state.height() < 1) { - return null; - } - OrbitProjection projection = NoiseTerrainScene.projectionFrom(at, state.camera(), state.width(), state.height(), state.coveredLeftWidth()); - TerrainSampling sampling = current.sampling(); - int left = Math.max(0, Math.min(state.width() - 1, state.coveredLeftWidth())); - return new GroundSight(projection, left, state.width(), state.height(), sampling.floorY(), sampling.topY()); - } - - void close() { - if (!closed.compareAndSet(false, true)) { - return; - } - hidden = true; - invalidate(); - coverer.shutdownNow(); - } - - // Before the first scene, the viewport still holds whatever camera it had; the scene will start it afresh. - private void viewChanged() { - if (closed.get()) { - return; - } - OrbitCamera camera = viewport.isShowingScene() ? viewport.camera() : NoiseTerrainScene.START; - view = new ViewState(camera, viewport.getWidth(), viewport.getHeight(), viewport.coveredLeftWidth()); - requestCover(); - } - - // Requests while one waits to start are one and the same: it will see the newest view and tiles anyway. - private void requestCover() { - if (closed.get() || hidden || coverQueued.getAndSet(true)) { - return; - } - try { - coverer.execute(() -> { - coverQueued.set(false); - coverSafely(); - }); - } catch (RejectedExecutionException rejected) { - coverQueued.set(false); - if (!closed.get() && !coverer.isShutdown()) { - throw rejected; - } - } - } - - private void coverSafely() { - try { - cover(); - } catch (RuntimeException error) { - IrisLogging.reportError(error); - } - } - - private void cover() { - TerrainTiles current = tiles; - ViewState state = view; - Vec3 at = anchor; - if (closed.get() || hidden || current == null || state == null || at == null || state.width() < 1 || state.height() < 1) { - return; - } - OrbitProjection projection = NoiseTerrainScene.projectionFrom(at, state.camera(), state.width(), state.height(), state.coveredLeftWidth()); - TerrainCover.Result result = TerrainCover.of(current, projection, state.width(), state.height(), state.coveredLeftWidth()); - TerrainSampling sampling = current.sampling(); - NoiseTerrainScene scene = new NoiseTerrainScene(result.layers(), at, sampling.floorY(), sampling.topY(), - sampling.waterLevel(), renderWorkers, workerCount); - EventQueue.invokeLater(() -> showCovered(current, scene, result)); - } - - // Until any ground is sampled, the view keeps what it showed before, or its loading animation. - private void showCovered(TerrainTiles coveredTiles, NoiseTerrainScene scene, TerrainCover.Result result) { - if (closed.get() || hidden || coveredTiles != tiles) { - return; - } - long retryDelay = coveredTiles.retryDelayNanos(); - if (retryDelay >= 0L) { - retryTimer.setInitialDelay((int) Math.max(1L, TimeUnit.NANOSECONDS.toMillis(retryDelay) + 1L)); - retryTimer.restart(); - } else { - retryTimer.stop(); - } - shown = result; - onProgress.run(); - if (scene.isEmpty() && result.pendingTiles() > 0) { - return; - } - if (viewport.isShowingScene()) { - viewport.replaceScene(scene); - } else { - viewport.show(scene); - } - } - - private record ViewState(OrbitCamera camera, int width, int height, int coveredLeftWidth) { - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/NoiseViewport.java b/core/src/main/java/art/arcane/iris/studio/map/NoiseViewport.java deleted file mode 100644 index 329088844..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/NoiseViewport.java +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -record NoiseViewport(double centerX, double centerZ, double blocksPerPixel) { - static final double MIN_BLOCKS_PER_PIXEL = 0.0001D; - static final double MAX_BLOCKS_PER_PIXEL = 1_000_000D; - - NoiseViewport { - if (!Double.isFinite(centerX) || !Double.isFinite(centerZ)) { - throw new IllegalArgumentException("Viewport center must be finite"); - } - if (!Double.isFinite(blocksPerPixel) || blocksPerPixel <= 0D) { - throw new IllegalArgumentException("Viewport scale must be finite and positive"); - } - } - - double worldX(double screenX, int width) { - return centerX + ((screenX - (width / 2D)) * blocksPerPixel); - } - - double worldZ(double screenZ, int height) { - return centerZ + ((screenZ - (height / 2D)) * blocksPerPixel); - } - - double screenX(double worldX, int width) { - return ((worldX - centerX) / blocksPerPixel) + (width / 2D); - } - - double screenZ(double worldZ, int height) { - return ((worldZ - centerZ) / blocksPerPixel) + (height / 2D); - } - - NoiseViewport panPixels(double deltaX, double deltaZ) { - return new NoiseViewport( - centerX - (deltaX * blocksPerPixel), - centerZ - (deltaZ * blocksPerPixel), - blocksPerPixel - ); - } - - NoiseViewport zoomAt(double screenX, double screenZ, int width, int height, double factor) { - if (!Double.isFinite(factor) || factor <= 0D) { - throw new IllegalArgumentException("Zoom factor must be finite and positive"); - } - double anchorX = worldX(screenX, width); - double anchorZ = worldZ(screenZ, height); - double nextScale = Math.max(MIN_BLOCKS_PER_PIXEL, - Math.min(MAX_BLOCKS_PER_PIXEL, blocksPerPixel * factor)); - double nextCenterX = anchorX - ((screenX - (width / 2D)) * nextScale); - double nextCenterZ = anchorZ - ((screenZ - (height / 2D)) * nextScale); - return new NoiseViewport(nextCenterX, nextCenterZ, nextScale); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/ObjectBrowser.java b/core/src/main/java/art/arcane/iris/studio/map/ObjectBrowser.java deleted file mode 100644 index ffd280829..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/ObjectBrowser.java +++ /dev/null @@ -1,276 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.JTree; -import javax.swing.ToolTipManager; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeCellRenderer; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; -import java.awt.BorderLayout; -import java.awt.Component; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.function.Consumer; - -/** - * Every object in the pack as a folder tree, with a search that matches every word typed anywhere in an object's path. - */ -final class ObjectBrowser extends JPanel { - private static final long serialVersionUID = 6795434561028735214L; - private static final int ROW_HEIGHT = 24; - - private final Consumer onObjectChosen; - private final JTextField searchField = new JTextField(); - private final DefaultTreeModel treeModel = new DefaultTreeModel(new DefaultMutableTreeNode()); - private final JTree tree = new JTree(treeModel); - private final JLabel countLabel = new JLabel(); - private final String noun; - private List objectKeys = List.of(); - private String chosenKey; - private boolean updatingSelection; - - /** - * @param noun what one entry is called in the browser's texts, such as "object" - */ - ObjectBrowser(String noun, Consumer onObjectChosen) { - super(new BorderLayout()); - this.noun = noun; - this.onObjectChosen = onObjectChosen; - countLabel.setText("Loading " + noun + "s..."); - StudioToolbar.makeSearchField(searchField, "Search " + noun + "s..."); - searchField.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void insertUpdate(DocumentEvent event) { - rebuildTree(); - } - - @Override - public void removeUpdate(DocumentEvent event) { - rebuildTree(); - } - - @Override - public void changedUpdate(DocumentEvent event) { - rebuildTree(); - } - }); - tree.setRootVisible(false); - tree.setShowsRootHandles(true); - tree.setRowHeight(StudioTheme.scale(ROW_HEIGHT)); - tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); - tree.setCellRenderer(new EntryRenderer()); - ToolTipManager.sharedInstance().registerComponent(tree); - tree.addTreeSelectionListener(event -> { - if (!updatingSelection && nodeAt(event.getPath()) instanceof Entry entry && entry.isObject()) { - chosenKey = entry.key(); - onObjectChosen.accept(entry.key()); - } - }); - countLabel.setFont(StudioTheme.smallFont()); - countLabel.setForeground(StudioTheme.SECONDARY_TEXT); - add(StudioToolbar.padded(searchField, 8, 8, 8, 8), BorderLayout.NORTH); - add(StickyFolderHeaders.around(tree, StudioToolbar.scroll(tree)), BorderLayout.CENTER); - add(StudioToolbar.padded(countLabel, 6, 12, 8, 12), BorderLayout.SOUTH); - } - - void showObjects(List keys) { - objectKeys = keys.stream().sorted(Comparator.comparing(key -> key.toLowerCase(Locale.ROOT))).toList(); - countLabel.setText(objectKeys.size() == 1 ? "1 " + noun : objectKeys.size() + " " + noun + "s"); - rebuildTree(); - } - - void showError(String text) { - countLabel.setText(text); - } - - String firstObject() { - return objectKeys.isEmpty() ? null : objectKeys.get(0); - } - - private void rebuildTree() { - String[] words = searchField.getText().trim().toLowerCase(Locale.ROOT).split("\\s+"); - boolean searching = !searchField.getText().isBlank(); - DefaultMutableTreeNode root = searching ? searchResults(words) : folderTree(); - treeModel.setRoot(root); - if (searching) { - expandAll(); - } - selectChosen(); - } - - private DefaultMutableTreeNode searchResults(String[] words) { - DefaultMutableTreeNode root = new DefaultMutableTreeNode(); - for (String key : objectKeys) { - if (matchesEveryWord(key, words)) { - root.add(new DefaultMutableTreeNode(Entry.object(key, key))); - } - } - if (root.getChildCount() == 0) { - root.add(new DefaultMutableTreeNode(Entry.note("No matching " + noun + "s"))); - } - return root; - } - - private static boolean matchesEveryWord(String key, String[] words) { - String lowerKey = key.toLowerCase(Locale.ROOT); - for (String word : words) { - if (!lowerKey.contains(word)) { - return false; - } - } - return true; - } - - // Folders come before the objects beside them, like a file browser. - private DefaultMutableTreeNode folderTree() { - Folder top = new Folder(); - for (String key : objectKeys) { - Folder folder = top; - String[] parts = key.split("/"); - for (int index = 0; index < parts.length - 1; index++) { - folder = folder.subfolders.computeIfAbsent(parts[index], name -> new Folder()); - } - folder.objects.add(key); - } - DefaultMutableTreeNode root = new DefaultMutableTreeNode(); - addFolderContents(root, top, ""); - return root; - } - - private static void addFolderContents(DefaultMutableTreeNode node, Folder folder, String path) { - for (Map.Entry subfolder : folder.subfolders.entrySet()) { - String subfolderPath = path + subfolder.getKey() + "/"; - DefaultMutableTreeNode child = new DefaultMutableTreeNode(Entry.folder(subfolder.getKey(), subfolderPath)); - addFolderContents(child, subfolder.getValue(), subfolderPath); - node.add(child); - } - for (String key : folder.objects) { - node.add(new DefaultMutableTreeNode(Entry.object(key.substring(key.lastIndexOf('/') + 1), key))); - } - } - - void select(String key) { - chosenKey = key; - selectChosen(); - } - - private void selectChosen() { - DefaultMutableTreeNode node = chosenKey == null ? null : findObjectNode((DefaultMutableTreeNode) treeModel.getRoot()); - updatingSelection = true; - try { - if (node == null) { - tree.clearSelection(); - return; - } - TreePath path = new TreePath(node.getPath()); - tree.setSelectionPath(path); - tree.scrollPathToVisible(path); - } finally { - updatingSelection = false; - } - } - - private DefaultMutableTreeNode findObjectNode(DefaultMutableTreeNode node) { - if (node.getUserObject() instanceof Entry entry && entry.isObject() && entry.key().equals(chosenKey)) { - return node; - } - for (int index = 0; index < node.getChildCount(); index++) { - DefaultMutableTreeNode found = findObjectNode((DefaultMutableTreeNode) node.getChildAt(index)); - if (found != null) { - return found; - } - } - return null; - } - - private void expandAll() { - for (int row = 0; row < tree.getRowCount(); row++) { - tree.expandRow(row); - } - } - - private static Object nodeAt(TreePath path) { - return path == null ? null : ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); - } - - private static final class Folder { - private final Map subfolders = new LinkedHashMap<>(); - private final List objects = new ArrayList<>(); - } - - /** - * A row of the tree: an object with its key, a folder with its path, or a note without either. - */ - private record Entry(String label, String key, String folderPath) { - static Entry object(String label, String key) { - return new Entry(label, key, null); - } - - static Entry folder(String label, String path) { - return new Entry(label, null, path); - } - - static Entry note(String text) { - return new Entry(text, null, null); - } - - boolean isObject() { - return key != null; - } - - @Override - public String toString() { - return label; - } - } - - private static final class EntryRenderer extends DefaultTreeCellRenderer { - private static final long serialVersionUID = -4316652201793418740L; - - private EntryRenderer() { - setLeafIcon(null); - setOpenIcon(null); - setClosedIcon(null); - } - - @Override - public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, - boolean leaf, int row, boolean focus) { - Object userObject = ((DefaultMutableTreeNode) value).getUserObject(); - super.getTreeCellRendererComponent(tree, userObject == null ? "" : userObject.toString(), selected, expanded, leaf, row, false); - boolean isNote = userObject instanceof Entry entry && !entry.isObject() && entry.folderPath() == null; - setFont(StudioTheme.font()); - setForeground(isNote ? StudioTheme.MUTED_TEXT : StudioTheme.TEXT); - setToolTipText(userObject instanceof Entry entry ? entry.isObject() ? entry.key() : entry.folderPath() : null); - return this; - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/ObjectExplorer.java b/core/src/main/java/art/arcane/iris/studio/map/ObjectExplorer.java deleted file mode 100644 index d7e350ed2..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/ObjectExplorer.java +++ /dev/null @@ -1,649 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.studio.map.BlockTextures.BlockTexture; -import art.arcane.iris.pack.loading.IrisData; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.structure.object.IrisObject; -import art.arcane.iris.generation.geometry.IrisBlockVector; -import art.arcane.volmlib.nativelib.terrain.NativeBlockState; - -import javax.swing.JComponent; -import javax.swing.JPanel; -import java.awt.CardLayout; -import java.awt.EventQueue; -import java.awt.event.KeyEvent; -import java.awt.image.BufferedImage; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.OptionalLong; -import java.util.Set; -import java.util.UUID; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicLong; - -/** - * The map window's Objects and Procedural views: everything its source offers in a folder tree, the chosen one in 3D, - * and what it is made of. A procedural object's variants can also be compared side by side, baked from any seed. - * Inspired by the Procedural Objects workbench. - */ -final class ObjectExplorer { - private static final String TINT_BIOME = "minecraft:plains"; - private static final int UNKNOWN_BLOCK_COLOR = 0x8A8A8A; - private static final String CAMERA_HINT = "Drag to orbit · Right-drag to pan · Scroll to zoom · Page Up/Down cuts layers · R resets"; - private static final String ONE_VARIANT_CARD = "one variant"; - private static final String ALL_VARIANTS_CARD = "all variants"; - - private final Engine startEngine; - private final UUID worldId; - private final ObjectSource source; - private final ObjectBrowser browser; - private final OrbitViewport viewport = new OrbitViewport("Iris Object Viewer", "Choose an object"); - private final ObjectLayerCut layerCut = new ObjectLayerCut(shownLayers -> showLayerCut()); - private final ObjectVariantPicker variantPicker = new ObjectVariantPicker(this::showVariant, this::showSeed, this::toggleComparing); - private final ObjectVariantGallery gallery = new ObjectVariantGallery(this::openVariant, this::redrawThumbnails); - private final CardLayout viewCards = new CardLayout(); - private final JPanel views = new JPanel(viewCards); - private final JComponent viewWithOverlays; - private final ObjectOverviewPanel overview; - private final StudioStatusBar statusBar = new StudioStatusBar(); - private final LatestMeasurement bakeTimer = new LatestMeasurement<>("Iris Bake Timer"); - private final ExecutorService loader = Executors.newSingleThreadExecutor(runnable -> { - Thread thread = new Thread(runnable, "Iris Object Loader"); - thread.setDaemon(true); - thread.setPriority(Thread.MIN_PRIORITY); - return thread; - }); - private final ExecutorService thumbnailPainter = Executors.newSingleThreadExecutor(runnable -> { - Thread thread = new Thread(runnable, "Iris Variant Thumbnails"); - thread.setDaemon(true); - thread.setPriority(Thread.MIN_PRIORITY); - return thread; - }); - private final AtomicLong objectRevision = new AtomicLong(); - private final AtomicLong variantListRevision = new AtomicLong(); - private final AtomicLong meshRevision = new AtomicLong(); - private final Map models = new ConcurrentHashMap<>(); - private final Runnable hotloadHook = this::reloadPack; - private volatile boolean closed; - private volatile BlockTextures textures; - private volatile BiomeTintColors tintColors; - private String shownKey; - private List shownVariants = List.of(); - private int shownVariantIndex; - private OptionalLong packSeed = OptionalLong.empty(); - private OptionalLong shownSeed = OptionalLong.empty(); - private boolean comparingVariants; - private long thumbnailsDrawnForRevision = -1; - private LoadedObject shown; - private ObjectMesh wholeMesh; - private Set seeThroughTypes = Set.of(); - - ObjectExplorer(Engine engine, UUID worldId, ObjectSource source) { - this.startEngine = engine; - this.worldId = worldId; - this.source = source; - this.browser = new ObjectBrowser(source.noun(), this::showObject); - this.overview = new ObjectOverviewPanel(this::showSeeThrough, source.isBaked()); - views.add(layerCut.floatingOver(viewport), ONE_VARIANT_CARD); - views.add(gallery, ALL_VARIANTS_CARD); - this.viewWithOverlays = variantPicker.floatingOver(views); - MapHost.interruptOnPluginShutdown(loader); - MapHost.interruptOnPluginShutdown(thumbnailPainter); - MapHost.registerHotloadHook(hotloadHook); - statusBar.showPosition(CAMERA_HINT); - viewport.bindKey(KeyEvent.VK_PAGE_UP, "show-layer-above", () -> layerCut.stepBy(1)); - viewport.bindKey(KeyEvent.VK_PAGE_DOWN, "hide-top-layer", () -> layerCut.stepBy(-1)); - viewport.bindKey(KeyEvent.VK_OPEN_BRACKET, "previous-variant", () -> variantPicker.stepBy(-1)); - viewport.bindKey(KeyEvent.VK_CLOSE_BRACKET, "next-variant", () -> variantPicker.stepBy(1)); - viewport.bindKey(KeyEvent.VK_G, "compare-variants", this::toggleComparing); - gallery.bindKey(KeyEvent.VK_OPEN_BRACKET, "previous-variant", () -> variantPicker.stepBy(-1)); - gallery.bindKey(KeyEvent.VK_CLOSE_BRACKET, "next-variant", () -> variantPicker.stepBy(1)); - gallery.bindKey(KeyEvent.VK_G, "show-one-variant", this::toggleComparing); - gallery.bindKey(KeyEvent.VK_ESCAPE, "close-comparison", this::toggleComparing); - } - - JComponent browser() { - return browser; - } - - /** - * The 3D view with the slider that cuts away its top layers, or every variant side by side, under the bar that - * steps through variants and seeds. - */ - JComponent view() { - return viewWithOverlays; - } - - void setCoveredLeftWidth(int width) { - viewport.setCoveredLeftWidth(width); - gallery.setCoveredLeftWidth(width); - variantPicker.setCoveredLeftWidth(width); - } - - JComponent overview() { - return overview; - } - - StudioStatusBar statusBar() { - return statusBar; - } - - void resetCamera() { - viewport.resetCamera(); - } - - // Textures load first, since the first object would otherwise be drawn in flat colours. - synchronized void open() { - if (closed) { - return; - } - viewport.showLoading("Loading Minecraft textures"); - loader.execute(() -> { - if (!loadTextures() || closed) { - return; - } - List keys = objectKeys(); - publish(() -> showCatalog(keys)); - }); - } - - synchronized void close() { - if (closed) { - return; - } - closed = true; - MapHost.unregisterHotloadHook(hotloadHook); - objectRevision.incrementAndGet(); - variantListRevision.incrementAndGet(); - meshRevision.incrementAndGet(); - loader.shutdownNow(); - thumbnailPainter.shutdownNow(); - bakeTimer.discardPending(); - bakeTimer.close(); - viewport.close(); - gallery.close(); - } - - private boolean loadTextures() { - try { - BlockTextures loaded = BlockTextures.shared().get(); - BiomeTintColors colors = loaded.biomeColors().vanilla(TINT_BIOME); - synchronized (this) { - if (closed) { - return false; - } - tintColors = colors; - textures = loaded; - } - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return false; - } catch (ExecutionException | RuntimeException unavailable) { - publish(() -> statusBar.showError("Minecraft textures are unavailable, objects use plain colours")); - } - return !closed; - } - - private void publish(Runnable update) { - if (closed) { - return; - } - EventQueue.invokeLater(() -> { - synchronized (ObjectExplorer.this) { - if (!closed) { - update.run(); - } - } - }); - } - - private List objectKeys() { - return source.keys(engine().getData()); - } - - private synchronized void showCatalog(List keys) { - if (closed) { - return; - } - statusBar.showActivity(""); - browser.showObjects(keys); - String key = shownKey != null && keys.contains(shownKey) ? shownKey : browser.firstObject(); - if (key == null) { - viewport.showEmptyState(source.emptyState()); - bakeTimer.discardPending(); - overview.clear(); - layerCut.showHeight(1); - if (comparingVariants) { - toggleComparing(); - } - showVariantList(List.of(), OptionalLong.empty(), OptionalLong.empty(), 0); - return; - } - browser.select(key); - showObject(key); - } - - /** - * Shows the first variant of the entry, baked from the pack's seed. The pack reloading the shown entry keeps the - * variant and the seed being looked at, unless the pack itself now sets another seed. - */ - private synchronized void showObject(String key) { - if (closed) { - return; - } - boolean reloadingShownObject = key.equals(shownKey); - OptionalLong previousPackSeed = packSeed; - OptionalLong exploredSeed = shownSeed; - int variantIndex = reloadingShownObject ? shownVariantIndex : 0; - shownKey = key; - if (!reloadingShownObject) { - variantPicker.forgetTriedSeeds(); - showVariantList(List.of(), OptionalLong.empty(), OptionalLong.empty(), 0); - } - long revision = startBaking(key); - loader.execute(() -> { - if (closed || revision != objectRevision.get()) { - return; - } - OptionalLong pack = source.seed(key); - OptionalLong seed = reloadingShownObject && pack.equals(previousPackSeed) ? exploredSeed : pack; - loadVariants(revision, key, pack, seed, variantIndex); - }); - } - - // The seed shows at once, so stepping again continues from it even while this one bakes or fails. - private synchronized void showSeed(long seed) { - if (closed) { - return; - } - String key = shownKey; - OptionalLong pack = packSeed; - int variantIndex = shownVariantIndex; - shownSeed = OptionalLong.of(seed); - variantPicker.showSeed(shownSeed, pack); - long revision = startBaking(key + " with seed " + seed); - loader.execute(() -> { - if (!closed && revision == objectRevision.get()) { - loadVariants(revision, key, pack, OptionalLong.of(seed), variantIndex); - } - }); - } - - // On the loader thread. - private void loadVariants(long revision, String key, OptionalLong pack, OptionalLong seed, int preferredIndex) { - if (closed || revision != objectRevision.get()) { - return; - } - try { - IrisData data = engine().getData(); - List variants = seed.isPresent() ? source.variants(data, key, seed.getAsLong()) : source.variants(data, key); - if (variants.isEmpty()) { - throw new IllegalStateException("Nothing could be loaded for " + key); - } - if (closed || revision != objectRevision.get()) { - return; - } - int index = preferredIndex < variants.size() ? preferredIndex : 0; - LoadedObject loaded = load(variants.get(index)); - publish(() -> { - if (closed || revision != objectRevision.get()) { - return; - } - showVariantList(variants, pack, seed, index); - showLoaded(revision, loaded); - timeBake(data, key, seed); - }); - } catch (RuntimeException error) { - publish(() -> showFailure(revision, key, error)); - } - } - - // Off the loader thread, so stepping through variants and seeds never waits on the timing. - private void timeBake(IrisData data, String key, OptionalLong seed) { - if (!source.isBaked() || seed.isEmpty()) { - return; - } - long bakedSeed = seed.getAsLong(); - overview.showTimingBake(); - bakeTimer.measureUntilSuperseded(stillWanted -> BakeTiming.measure(() -> source.timeBake(data, key, bakedSeed), stillWanted), - timing -> publish(() -> overview.showBakeTiming(timing))); - } - - private void showVariantList(List variants, OptionalLong pack, OptionalLong seed, int index) { - shownVariants = variants; - shownVariantIndex = index; - packSeed = pack; - shownSeed = seed; - variantListRevision.incrementAndGet(); - variantPicker.showVariants(variants.size(), index); - variantPicker.showSeed(seed, pack); - if (!comparingVariants) { - return; - } - if (variants.isEmpty()) { - gallery.showLoading(); - } else if (variants.size() == 1) { - toggleComparing(); - } else { - drawThumbnails(); - } - } - - private synchronized void showVariant(int index) { - if (closed) { - return; - } - if (index >= shownVariants.size()) { - return; - } - shownVariantIndex = index; - gallery.select(index); - IrisObject variant = shownVariants.get(index); - long revision = startLoading(variant.getLoadKey()); - loader.execute(() -> { - if (closed || revision != objectRevision.get()) { - return; - } - LoadedObject loaded = load(variant); - publish(() -> showLoaded(revision, loaded)); - }); - } - - private synchronized void openVariant(int index) { - if (closed) { - return; - } - variantPicker.showVariants(shownVariants.size(), index); - showVariant(index); - toggleComparing(); - } - - private synchronized void toggleComparing() { - if (closed) { - return; - } - if (!comparingVariants && shownVariants.size() < 2) { - return; - } - comparingVariants = !comparingVariants; - variantPicker.showComparing(comparingVariants); - viewCards.show(views, comparingVariants ? ALL_VARIANTS_CARD : ONE_VARIANT_CARD); - if (comparingVariants) { - drawThumbnails(); - gallery.requestFocusInWindow(); - } else { - viewport.requestFocusInWindow(); - } - } - - private synchronized void redrawThumbnails() { - if (closed) { - return; - } - thumbnailsDrawnForRevision = -1; - if (comparingVariants) { - drawThumbnails(); - } - } - - /** - * Fills the side-by-side view with every shown variant, all drawn at the scale that fits the largest, so their - * sizes compare. Thumbnails arrive one at a time on their own thread, leaving the loader free for the 3D view. - */ - private synchronized void drawThumbnails() { - if (closed) { - return; - } - long revision = variantListRevision.get(); - if (revision == thumbnailsDrawnForRevision) { - return; - } - thumbnailsDrawnForRevision = revision; - List variants = shownVariants; - gallery.showVariants(galleryHeading(), variants.size(), shownVariantIndex); - int size = gallery.thumbnailSize(); - thumbnailPainter.execute(() -> { - List meshes = new ArrayList<>(); - for (IrisObject variant : variants) { - if (closed || revision != variantListRevision.get()) { - return; - } - meshes.add(ObjectMesh.build(visibleBlocks(variant), this::modelOf)); - } - ObjectMesh.Bounds sizeToFit = largestSize(meshes); - for (int index = 0; index < meshes.size() && !closed && revision == variantListRevision.get(); index++) { - BufferedImage thumbnail = ObjectRenderer.renderThumbnail(meshes.get(index), sizeToFit, size, size); - int shownIndex = index; - publish(() -> { - if (revision == variantListRevision.get()) { - gallery.showThumbnail(shownIndex, thumbnail); - } - }); - } - }); - } - - private String galleryHeading() { - return String.format(Locale.ROOT, "%s · %d variants%s", shownKey, shownVariants.size(), seedNote()); - } - - private static ObjectMesh.Bounds largestSize(List meshes) { - int sizeX = 1; - int sizeY = 1; - int sizeZ = 1; - for (ObjectMesh mesh : meshes) { - sizeX = Math.max(sizeX, mesh.bounds().sizeX()); - sizeY = Math.max(sizeY, mesh.bounds().sizeY()); - sizeZ = Math.max(sizeZ, mesh.bounds().sizeZ()); - } - return new ObjectMesh.Bounds(0, 0, 0, sizeX, sizeY, sizeZ); - } - - // A new list of variants is on its way, so every thumbnail is outdated, unlike when stepping to another variant. - private long startBaking(String key) { - if (comparingVariants) { - gallery.showLoading(); - } - return startLoading(key); - } - - private long startLoading(String key) { - shown = null; - wholeMesh = null; - meshRevision.incrementAndGet(); - viewport.showLoading("Loading " + key); - return objectRevision.incrementAndGet(); - } - - private LoadedObject load(IrisObject object) { - Map blocks = visibleBlocks(object); - ObjectMesh.Bounds extent = ObjectMesh.Bounds.of(blocks.keySet()); - ObjectMesh.Bounds bounds = source.groundY(object).stream().mapToObj(extent::standingOn).findFirst().orElse(extent); - ObjectMesh mesh = ObjectMesh.build(blocks, this::modelOf, bounds, block -> false); - ObjectSummary summary = ObjectSummary.of(object.getLoadKey(), mesh.bounds(), blocks.values(), this::iconOf); - return new LoadedObject(blocks, mesh, summary); - } - - private static Map visibleBlocks(IrisObject object) { - Map blocks = new HashMap<>(); - object.getBlocks().forEach((position, block) -> { - if (!block.isAir()) { - blocks.put(position, block); - } - }); - return blocks; - } - - - private void showLoaded(long revision, LoadedObject loaded) { - if (closed || revision != objectRevision.get()) { - return; - } - shown = loaded; - wholeMesh = loaded.mesh(); - seeThroughTypes = Set.of(); - statusBar.showActivity(""); - viewport.show(loaded.mesh()); - overview.show(loaded.summary()); - layerCut.showHeight(loaded.mesh().bounds().sizeY()); - showMeshSummary(loaded.mesh()); - } - - private void showMeshSummary(ObjectMesh mesh) { - ObjectSummary summary = shown.summary(); - String cut = layerCut.isCutting() - ? String.format(Locale.ROOT, " · showing layers 1-%d of %d", layerCut.shownLayerCount(), layerCut.layerCount()) - : ""; - statusBar.showSummary(String.format(Locale.ROOT, "%s%s · %,d blocks · %,d faces drawn%s", - summary.key(), seedNote(), summary.blockCount(), mesh.faceCount(), cut)); - } - - // A seed being tried is not in the pack until its "seed" field says so. - private String seedNote() { - if (shownSeed.isEmpty()) { - return ""; - } - String note = " · seed " + shownSeed.getAsLong(); - return shownSeed.equals(packSeed) ? note : note + " (the pack has " + packSeed.getAsLong() + ")"; - } - - private synchronized void showSeeThrough(Set blockTypes) { - if (closed) { - return; - } - seeThroughTypes = blockTypes; - rebuildWholeMesh(); - } - - // Blocks behind see-through ones get their hidden faces back, so the mesh is built again. - private synchronized void rebuildWholeMesh() { - if (closed) { - return; - } - LoadedObject object = shown; - if (object == null) { - return; - } - long revision = meshRevision.incrementAndGet(); - Set seeThrough = seeThroughTypes; - loader.execute(() -> { - if (closed || revision != meshRevision.get()) { - return; - } - ObjectMesh mesh = seeThrough.isEmpty() - ? object.mesh() - : ObjectMesh.build(object.blocks(), this::modelOf, object.mesh().bounds(), - block -> seeThrough.contains(BlockNames.typeOf(block))); - publish(() -> { - if (revision == meshRevision.get() && shown == object) { - wholeMesh = mesh; - showLayerCut(); - } - }); - }); - } - - private synchronized void showLayerCut() { - if (closed) { - return; - } - if (wholeMesh == null) { - return; - } - int highestShownY = wholeMesh.bounds().minY() + layerCut.shownLayerCount() - 1; - ObjectMesh mesh = layerCut.isCutting() ? wholeMesh.cutAbove(highestShownY) : wholeMesh; - viewport.replaceScene(mesh); - showMeshSummary(mesh); - } - - private void showFailure(long revision, String key, Throwable error) { - if (closed || revision != objectRevision.get()) { - return; - } - statusBar.showActivity(""); - viewport.showMessage("Could not load " + key); - gallery.showMessage("Could not load " + key); - thumbnailsDrawnForRevision = -1; - bakeTimer.discardPending(); - overview.clear(); - layerCut.showHeight(1); - statusBar.showError(error.getMessage() == null ? error.getClass().getSimpleName() : error.getMessage()); - } - - // The pack's files may have changed, so the list and the shown object are read again. - private synchronized void reloadPack() { - if (closed) { - return; - } - loader.execute(() -> { - if (closed) { - return; - } - List keys = objectKeys(); - publish(() -> showCatalog(keys)); - }); - } - - private Engine engine() { - Engine current = MapHost.findEngine(worldId); - return current != null && !current.isClosed() ? current : startEngine; - } - - private BlockModel modelOf(NativeBlockState block) { - return models.computeIfAbsent(block.key(), state -> { - BlockTextures available = textures; - if (available == null) { - return BlockModel.solidColor(UNKNOWN_BLOCK_COLOR); - } - return available.model(block).map(this::withBiomeTint).orElseGet(() -> BlockModel.solidColor(UNKNOWN_BLOCK_COLOR)); - }); - } - - private BufferedImage iconOf(NativeBlockState block) { - BlockTextures available = textures; - if (available == null) { - return null; - } - return available.iconTexture(block).map(this::withBiomeTint).map(BlockTexture::toImage).orElse(null); - } - - // Objects have no biome of their own, so grass and leaves get plains' colours. - private BlockModel withBiomeTint(BlockModel model) { - return model.withTextures(this::withBiomeTint); - } - - private BlockTexture withBiomeTint(BlockTexture texture) { - BiomeTintColors colors = tintColors; - if (texture.biomeTint() == null || colors == null) { - return texture; - } - return texture.tinted(colors.colorAt(texture.biomeTint(), 0, 0)); - } - - private record LoadedObject(Map blocks, ObjectMesh mesh, ObjectSummary summary) { - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/ObjectLayerCut.java b/core/src/main/java/art/arcane/iris/studio/map/ObjectLayerCut.java deleted file mode 100644 index bd5e490a8..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/ObjectLayerCut.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import javax.swing.JComponent; -import java.util.function.IntConsumer; - -/** - * A slider floating on the right of the 3D view that hides an object's top layers, to look inside buildings floor by - * floor. Most objects never need it, so it stays faint until the mouse comes near or a cut is active. - */ -final class ObjectLayerCut { - private static final String TOOLTIP = "Hide the top layers to look inside · Page Up / Page Down"; - - private final FloatingSlider slider = new FloatingSlider(TOOLTIP, this::showCut); - private final IntConsumer onLayersChanged; - - /** - * @param onLayersChanged told how many layers from the bottom stay visible whenever the user moves the slider - */ - ObjectLayerCut(IntConsumer onLayersChanged) { - this.onLayersChanged = onLayersChanged; - showHeight(1); - } - - /** - * The view with this slider floating over its right edge, halfway down. - */ - JComponent floatingOver(JComponent view) { - return slider.floatingOver(view); - } - - /** - * Shows every layer of a newly chosen object without telling anyone, since nothing is hidden yet. - */ - void showHeight(int layers) { - int layerCount = Math.max(1, layers); - slider.showQuietly(1, layerCount, layerCount); - showCutState(); - slider.setVisible(layers > 1); - } - - void stepBy(int layers) { - if (slider.isVisible()) { - slider.moveBy(layers); - } - } - - boolean isCutting() { - return slider.value() < slider.maximum(); - } - - int shownLayerCount() { - return slider.value(); - } - - int layerCount() { - return slider.maximum(); - } - - private void showCut(int shownLayers) { - showCutState(); - onLayersChanged.accept(shownLayers); - } - - private void showCutState() { - slider.showLabel(isCutting() ? Integer.toString(slider.value()) : ""); - slider.setStandingOut(isCutting()); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/ObjectMesh.java b/core/src/main/java/art/arcane/iris/studio/map/ObjectMesh.java deleted file mode 100644 index c79f8f5cc..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/ObjectMesh.java +++ /dev/null @@ -1,289 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -package art.arcane.iris.studio.map; - -import art.arcane.iris.generation.decoration.IrisProceduralBlocks; -import art.arcane.iris.generation.geometry.IrisBlockVector; -import art.arcane.iris.studio.map.BlockModel.Face; -import art.arcane.volmlib.nativelib.terrain.NativeBlockState; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.function.Function; -import java.util.function.Predicate; - -/** - * The faces of an object's blocks that can be seen from outside. A face is left out when the neighbour on its side - * covers that side, which is most of them in a large object. See-through faces, like water and stained glass, are - * kept apart because they are drawn last, blended over everything behind them. Top faces covered only by the block - * above are kept aside too, so the top layers can be cut away without building the mesh again; what is cut away stays - * as a faint ghost of the object's shape. - */ -record ObjectMesh(List solidQuads, List translucentQuads, List cutAwayQuads, List topsUnderBlockAbove, - Bounds bounds) implements OrbitScene { - private static final double SEE_THROUGH_OPACITY = 0.22D; - private static final double FULL_OPACITY = 1D; - private static final double CUT_AWAY_OPACITY = 0.1D; - - static ObjectMesh build(Map blocks, Function modelOf) { - return build(blocks, modelOf, Bounds.of(blocks.keySet()), block -> false); - } - - /** - * @param bounds the whole object's extent, kept when only part of it is drawn so the view does not jump - * @param isSeeThrough blocks drawn faintly, which hide nothing behind them, to look past them into the object - */ - static ObjectMesh build(Map blocks, Function modelOf, Bounds bounds, - Predicate isSeeThrough) { - List solid = new ArrayList<>(); - List translucent = new ArrayList<>(); - List topsUnderBlockAbove = new ArrayList<>(); - BlockGrid grid = new BlockGrid(blocks, modelOf, bounds, isSeeThrough); - for (IrisBlockVector position : blocks.keySet()) { - int x = position.getBlockX(); - int y = position.getBlockY(); - int z = position.getBlockZ(); - int cell = grid.cellAt(x, y, z); - for (Face face : grid.modelIn(cell).faces()) { - Quad quad = new Quad(face, x, y, z, grid.isSeeThroughIn(cell) ? SEE_THROUGH_OPACITY : FULL_OPACITY); - if (!grid.isHiddenByNeighbour(x, y, z, face)) { - (quad.isBlended() ? translucent : solid).add(quad); - } else if (face.cullFace() == CubeFace.UP) { - topsUnderBlockAbove.add(quad); - } - } - } - return new ObjectMesh(List.copyOf(solid), List.copyOf(translucent), List.of(), List.copyOf(topsUnderBlockAbove), bounds); - } - - /** - * This mesh with the blocks above the given layer faded to a ghost of the object's shape, and the tops of that - * layer's blocks showing again. Quick enough to follow a slider as it moves. - */ - ObjectMesh cutAbove(int highestShownY) { - List solid = new ArrayList<>(); - List translucent = new ArrayList<>(); - List cutAway = new ArrayList<>(); - for (Quad quad : solidQuads) { - keepOrCutAway(quad, highestShownY, solid, cutAway); - } - for (Quad quad : translucentQuads) { - keepOrCutAway(quad, highestShownY, translucent, cutAway); - } - for (Quad quad : topsUnderBlockAbove) { - if (quad.y() == highestShownY) { - (quad.isBlended() ? translucent : solid).add(quad); - } - } - return new ObjectMesh(solid, translucent, cutAway, List.of(), bounds); - } - - private static void keepOrCutAway(Quad quad, int highestShownY, List kept, List cutAway) { - if (quad.y() <= highestShownY) { - kept.add(quad); - } else { - cutAway.add(quad.faded(CUT_AWAY_OPACITY)); - } - } - - @Override - public boolean isEmpty() { - return solidQuads.isEmpty() && translucentQuads.isEmpty() && cutAwayQuads.isEmpty(); - } - - @Override - public OrbitPicture render(OrbitCamera camera, int width, int height, int coveredLeftWidth) { - return renderOnCard(camera, width, height, coveredLeftWidth) - .orElseGet(() -> ObjectRenderer.render(this, camera, width, height, coveredLeftWidth)); - } - - private Optional renderOnCard(OrbitCamera camera, int width, int height, int coveredLeftWidth) { - if (!GpuLibrary.isLoaded()) { - return Optional.empty(); - } - return GpuObjectRenderer.render(this, camera, width, height, coveredLeftWidth); - } - - @Override - public boolean canRenderOnScreen() { - return GpuLibrary.isLoaded() && GpuFrames.canDrawOnScreen(); - } - - @Override - public Optional renderOnScreen(ScreenTarget screen, OrbitCamera camera, int width, int height, int coveredLeftWidth) { - return GpuObjectRenderer.renderOnScreen(this, screen, camera, width, height, coveredLeftWidth); - } - - @Override - public OrbitProjection projection(OrbitCamera camera, int width, int height, int coveredLeftWidth) { - return ObjectRenderer.projection(this, camera, width, height, coveredLeftWidth); - } - - int faceCount() { - return solidQuads.size() + translucentQuads.size(); - } - - /** - * The object's blocks laid out in an array over its bounds, so finding a block's neighbours is quick. Looking them - * up by {@link BlockVector} in a map is slow, since its hash codes collide a lot. - */ - private static final class BlockGrid { - private final Bounds bounds; - private final NativeBlockState[] blocks; - private final BlockModel[] models; - private final boolean[] seeThrough; - - BlockGrid(Map placed, Function modelOf, Bounds bounds, - Predicate isSeeThrough) { - this.bounds = bounds; - int cells = bounds.sizeX() * bounds.sizeY() * bounds.sizeZ(); - this.blocks = new NativeBlockState[cells]; - this.models = new BlockModel[cells]; - this.seeThrough = new boolean[cells]; - placed.forEach((position, block) -> { - int cell = cellAt(position.getBlockX(), position.getBlockY(), position.getBlockZ()); - blocks[cell] = block; - models[cell] = modelOf.apply(block); - seeThrough[cell] = isSeeThrough.test(block); - }); - } - - int cellAt(int x, int y, int z) { - return ((y - bounds.minY()) * bounds.sizeZ() + (z - bounds.minZ())) * bounds.sizeX() + (x - bounds.minX()); - } - - BlockModel modelIn(int cell) { - return models[cell]; - } - - boolean isSeeThroughIn(int cell) { - return seeThrough[cell]; - } - - // Glass next to glass and water next to water hide the side between them too, as they do in the game. A - // see-through block only hides sides of other see-through blocks, so whatever it covers shows through it. - boolean isHiddenByNeighbour(int x, int y, int z, Face face) { - CubeFace side = face.cullFace(); - if (side == null || !contains(x + side.stepX(), y + side.stepY(), z + side.stepZ())) { - return false; - } - int cell = cellAt(x, y, z); - int neighbourCell = cellAt(x + side.stepX(), y + side.stepY(), z + side.stepZ()); - NativeBlockState neighbour = blocks[neighbourCell]; - if (neighbour == null || (seeThrough[neighbourCell] && !seeThrough[cell])) { - return false; - } - BlockModel neighbourModel = models[neighbourCell]; - if (neighbourModel.coveredSides().contains(side.opposite())) { - return true; - } - return isSameBlockType(neighbour, blocks[cell]) && models[cell].hidesSameBlockSides() - && neighbourModel.hidesSameBlockSides(); - } - - private static boolean isSameBlockType(NativeBlockState first, NativeBlockState second) { - return IrisProceduralBlocks.materialKey(first).equals(IrisProceduralBlocks.materialKey(second)); - } - - private boolean contains(int x, int y, int z) { - return x >= bounds.minX() && x < bounds.maxX() && y >= bounds.minY() && y < bounds.maxY() - && z >= bounds.minZ() && z < bounds.maxZ(); - } - } - - /** - * A model face placed at a block in the object, drawn at the given opacity on top of its texture's own. - */ - record Quad(Face face, int x, int y, int z, double opacity) { - boolean isBlended() { - return opacity < FULL_OPACITY || face.texture().isTranslucent(); - } - - Quad faded(double factor) { - return new Quad(face, x, y, z, opacity * factor); - } - - double originX() { - return x + face.origin().x(); - } - - double originY() { - return y + face.origin().y(); - } - - double originZ() { - return z + face.origin().z(); - } - } - - /** - * The blocks' extent, with the maximum one past the last block so a single block spans one unit, and the height the - * terrain surface meets the object at. - */ - record Bounds(int minX, int minY, int minZ, int maxX, int maxY, int maxZ, int groundY) { - private static final Bounds EMPTY = new Bounds(0, 0, 0, 1, 1, 1); - - /** An extent standing on its lowest block. */ - Bounds(int minX, int minY, int minZ, int maxX, int maxY, int maxZ) { - this(minX, minY, minZ, maxX, maxY, maxZ, minY); - } - - /** This extent with the terrain surface at {@code groundY}, so anything below it shows as buried. */ - Bounds standingOn(int groundY) { - return new Bounds(minX, minY, minZ, maxX, maxY, maxZ, groundY); - } - - static Bounds of(Iterable positions) { - int minX = Integer.MAX_VALUE; - int minY = Integer.MAX_VALUE; - int minZ = Integer.MAX_VALUE; - int maxX = Integer.MIN_VALUE; - int maxY = Integer.MIN_VALUE; - int maxZ = Integer.MIN_VALUE; - for (IrisBlockVector position : positions) { - minX = Math.min(minX, position.getBlockX()); - minY = Math.min(minY, position.getBlockY()); - minZ = Math.min(minZ, position.getBlockZ()); - maxX = Math.max(maxX, position.getBlockX() + 1); - maxY = Math.max(maxY, position.getBlockY() + 1); - maxZ = Math.max(maxZ, position.getBlockZ() + 1); - } - return minX == Integer.MAX_VALUE ? EMPTY : new Bounds(minX, minY, minZ, maxX, maxY, maxZ); - } - - int sizeX() { - return maxX - minX; - } - - int sizeY() { - return maxY - minY; - } - - int sizeZ() { - return maxZ - minZ; - } - - int largestSize() { - return Math.max(sizeX(), Math.max(sizeY(), sizeZ())); - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/ObjectOverviewPanel.java b/core/src/main/java/art/arcane/iris/studio/map/ObjectOverviewPanel.java deleted file mode 100644 index 97b27e8d6..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/ObjectOverviewPanel.java +++ /dev/null @@ -1,368 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import javax.swing.BorderFactory; -import javax.swing.BoxLayout; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.SwingUtilities; -import javax.swing.DefaultListCellRenderer; -import javax.swing.DefaultListModel; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import java.awt.AlphaComposite; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Composite; -import java.awt.Cursor; -import java.awt.Insets; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GridLayout; -import java.awt.RenderingHints; -import java.awt.image.BufferedImage; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; -import java.util.function.Consumer; - -/** - * The chosen object's size and the blocks it is made of, most used first, like the overview in Procedural Objects. - * Clicking a block makes it see-through in the 3D view, to look past walls into the object. - */ -final class ObjectOverviewPanel extends JPanel { - private static final long serialVersionUID = -8811407613645718290L; - private static final int PANEL_WIDTH = 280; - private static final int ROW_HEIGHT = 26; - private static final int ICON_SIZE = 16; - private static final int ICON_GAP = 8; - private static final int ROW_PADDING = 10; - private static final int SHARE_WIDTH = 92; - private static final int SHARE_BAR_HEIGHT = 4; - private static final float SEE_THROUGH_ICON_OPACITY = 0.3F; - private static final String SEE_THROUGH_HINT = "Click a block to see through it"; - - private final JLabel title = new JLabel(" "); - private final JLabel path = new JLabel(" "); - private final JLabel size = statValue(); - private final JLabel blockCount = statValue(); - private final JLabel blockTypes = statValue(); - private final JLabel filled = statValue(); - private final BakeMeter bakeMeter = new BakeMeter(); - private final JTextField filterField = new JTextField(); - private final DefaultListModel rows = new DefaultListModel<>(); - private final JList list = new JList<>(rows) { - @Override - public boolean getScrollableTracksViewportWidth() { - return true; - } - }; - private final JLabel seeThroughHint = new JLabel(SEE_THROUGH_HINT); - private final JButton showAllSolid = new JButton("Show all solid"); - private final Set seeThroughTypes = new LinkedHashSet<>(); - private final Consumer> onSeeThroughChanged; - private ObjectSummary summary; - - /** - * @param onSeeThroughChanged told which block types to draw see-through whenever the user changes them - * @param showsBakeTime whether the objects are baked, so the time their bake takes is shown - */ - ObjectOverviewPanel(Consumer> onSeeThroughChanged, boolean showsBakeTime) { - super(new BorderLayout()); - this.onSeeThroughChanged = onSeeThroughChanged; - setPreferredSize(StudioTheme.scaledSize(PANEL_WIDTH, 0)); - setBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, StudioTheme.SEPARATOR)); - setBackground(StudioTheme.PANEL_BACKGROUND); - add(buildHeader(showsBakeTime), BorderLayout.NORTH); - add(buildBlockList(), BorderLayout.CENTER); - } - - void show(ObjectSummary nextSummary) { - summary = nextSummary; - title.setText(nextSummary.name()); - path.setText(nextSummary.key()); - path.setToolTipText(nextSummary.key()); - size.setText(nextSummary.sizeX() + " × " + nextSummary.sizeY() + " × " + nextSummary.sizeZ()); - blockCount.setText(formatCount(nextSummary.blockCount())); - blockTypes.setText(formatCount(nextSummary.blockUses().size())); - filled.setText(String.format(Locale.ROOT, "%.1f%%", nextSummary.filledFraction() * 100D)); - seeThroughTypes.clear(); - showSeeThroughState(); - refilter(); - } - - void showTimingBake() { - bakeMeter.showTiming(); - } - - void showBakeTiming(BakeTiming timing) { - bakeMeter.show(timing); - } - - void clear() { - summary = null; - title.setText(" "); - path.setText(" "); - for (JLabel value : List.of(size, blockCount, blockTypes, filled)) { - value.setText("—"); - } - bakeMeter.clear(); - rows.clear(); - seeThroughTypes.clear(); - showSeeThroughState(); - } - - private JPanel buildHeader(boolean showsBakeTime) { - JPanel header = new JPanel(); - header.setLayout(new BoxLayout(header, BoxLayout.Y_AXIS)); - header.setOpaque(false); - header.setBorder(StudioTheme.emptyBorder(12, 16, 8, 16)); - title.setFont(StudioTheme.titleFont()); - path.setFont(StudioTheme.smallFont()); - path.setForeground(StudioTheme.SECONDARY_TEXT); - header.add(leftAligned(title)); - header.add(leftAligned(path)); - - JPanel stats = new JPanel(new GridLayout(2, 2, StudioTheme.scale(12), StudioTheme.scale(8))); - stats.setOpaque(false); - stats.setBorder(StudioTheme.emptyBorder(12, 0, 4, 0)); - stats.add(stat("Size · X × Y × Z", size)); - stats.add(stat("Blocks", blockCount)); - stats.add(stat("Block types", blockTypes)); - stats.add(stat("Filled volume", filled)); - filled.setToolTipText("How much of the object's bounding box its blocks fill"); - header.add(leftAligned(stats)); - if (showsBakeTime) { - JPanel bakeTime = stat("Bake time", bakeMeter); - bakeTime.setBorder(StudioTheme.emptyBorder(4, 0, 4, 0)); - header.add(leftAligned(bakeTime)); - } - clear(); - return header; - } - - private JPanel buildBlockList() { - JPanel blocks = new JPanel(new BorderLayout()); - blocks.setOpaque(false); - StudioToolbar.makeSearchField(filterField, "Find a block..."); - filterField.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void insertUpdate(DocumentEvent event) { - refilter(); - } - - @Override - public void removeUpdate(DocumentEvent event) { - refilter(); - } - - @Override - public void changedUpdate(DocumentEvent event) { - refilter(); - } - }); - list.setFocusable(false); - list.setFixedCellHeight(StudioTheme.scale(ROW_HEIGHT)); - list.setCellRenderer(new BlockUseRenderer()); - list.setBackground(StudioTheme.PANEL_BACKGROUND); - list.setBorder(StudioTheme.emptyBorder(0, 6, 4, 6)); - list.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - list.addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent event) { - int row = list.locationToIndex(event.getPoint()); - if (SwingUtilities.isLeftMouseButton(event) && row >= 0 && list.getCellBounds(row, row).contains(event.getPoint())) { - toggleSeeThrough(rows.get(row).blockType()); - } - } - }); - JPanel top = new JPanel(); - top.setLayout(new BoxLayout(top, BoxLayout.Y_AXIS)); - top.setOpaque(false); - top.add(leftAligned(StudioToolbar.padded(filterField, 4, 12, 4, 12))); - top.add(leftAligned(StudioToolbar.padded(seeThroughRow(), 0, 14, 6, 12))); - blocks.add(top, BorderLayout.NORTH); - blocks.add(StudioToolbar.scroll(list), BorderLayout.CENTER); - return blocks; - } - - private JPanel seeThroughRow() { - seeThroughHint.setFont(StudioTheme.smallFont()); - seeThroughHint.setForeground(StudioTheme.MUTED_TEXT); - showAllSolid.setFont(StudioTheme.smallFont()); - showAllSolid.setForeground(StudioTheme.LINK); - showAllSolid.setBorderPainted(false); - showAllSolid.setContentAreaFilled(false); - showAllSolid.setFocusable(false); - showAllSolid.setMargin(new Insets(0, 0, 0, 0)); - showAllSolid.setBorder(BorderFactory.createEmptyBorder()); - showAllSolid.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - showAllSolid.addActionListener(event -> { - seeThroughTypes.clear(); - seeThroughChanged(); - }); - JPanel row = new JPanel(new BorderLayout()); - row.setOpaque(false); - row.add(seeThroughHint, BorderLayout.CENTER); - row.add(showAllSolid, BorderLayout.EAST); - showSeeThroughState(); - return row; - } - - private void toggleSeeThrough(String blockType) { - if (!seeThroughTypes.remove(blockType)) { - seeThroughTypes.add(blockType); - } - seeThroughChanged(); - } - - private void seeThroughChanged() { - showSeeThroughState(); - list.repaint(); - onSeeThroughChanged.accept(Set.copyOf(seeThroughTypes)); - } - - private void showSeeThroughState() { - int count = seeThroughTypes.size(); - seeThroughHint.setText(count == 0 ? SEE_THROUGH_HINT : count == 1 ? "1 block see-through" : count + " blocks see-through"); - showAllSolid.setVisible(count > 0); - } - - private void refilter() { - rows.clear(); - if (summary == null) { - return; - } - String filter = filterField.getText().trim().toLowerCase(Locale.ROOT).replace(' ', '_'); - for (ObjectSummary.BlockUse use : summary.blockUses()) { - if (use.blockType().contains(filter)) { - rows.addElement(use); - } - } - } - - private static JPanel stat(String label, JComponent value) { - JPanel stat = new JPanel(new BorderLayout()); - stat.setOpaque(false); - JLabel name = new JLabel(label); - name.setFont(StudioTheme.smallFont()); - name.setForeground(StudioTheme.MUTED_TEXT); - stat.add(name, BorderLayout.NORTH); - stat.add(value, BorderLayout.CENTER); - return stat; - } - - private static JLabel statValue() { - JLabel value = new JLabel("—"); - value.setFont(StudioTheme.boldFont()); - return value; - } - - private static Component leftAligned(JPanel panel) { - panel.setAlignmentX(LEFT_ALIGNMENT); - return panel; - } - - private static Component leftAligned(JLabel label) { - label.setAlignmentX(LEFT_ALIGNMENT); - return label; - } - - private static String formatCount(int count) { - return String.format(Locale.ROOT, "%,d", count); - } - - private final class BlockUseRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 2785337045812613941L; - private transient BufferedImage icon; - private boolean seeThrough; - private double share; - private String percent = ""; - - @Override - public Component getListCellRendererComponent(JList owner, Object value, int index, boolean selected, boolean focused) { - ObjectSummary.BlockUse use = (ObjectSummary.BlockUse) value; - super.getListCellRendererComponent(owner, use.blockType(), index, false, false); - seeThrough = seeThroughTypes.contains(use.blockType()); - setFont(StudioTheme.font()); - setForeground(seeThrough ? StudioTheme.MUTED_TEXT : StudioTheme.TEXT); - setBorder(StudioTheme.emptyBorder(0, ROW_PADDING + ICON_SIZE + ICON_GAP, 0, ROW_PADDING + SHARE_WIDTH)); - setToolTipText(use.blockType() + " · " + formatCount(use.count()) + " blocks · click to " - + (seeThrough ? "make solid again" : "see through it")); - icon = use.icon(); - share = summary == null || summary.blockCount() == 0 ? 0D : use.count() / (double) summary.blockCount(); - percent = share > 0D && share < 0.001D ? "<0.1%" : String.format(Locale.ROOT, "%.1f%%", share * 100D); - return this; - } - - @Override - protected void paintComponent(Graphics graphics) { - super.paintComponent(graphics); - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - int iconSize = StudioTheme.scale(ICON_SIZE); - int iconX = StudioTheme.scale(ROW_PADDING); - int iconY = (getHeight() - iconSize) / 2; - if (icon != null) { - canvas.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); - Composite solid = canvas.getComposite(); - if (seeThrough) { - canvas.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, SEE_THROUGH_ICON_OPACITY)); - } - canvas.drawImage(icon, iconX, iconY, iconSize, iconSize, null); - canvas.setComposite(solid); - } else { - canvas.setColor(StudioTheme.CONTROL_BORDER); - canvas.drawRect(iconX, iconY, iconSize - 1, iconSize - 1); - } - drawShare(canvas); - } finally { - canvas.dispose(); - } - } - - private void drawShare(Graphics2D canvas) { - canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - canvas.setFont(StudioTheme.smallFont()); - int padding = StudioTheme.scale(ROW_PADDING); - int percentWidth = canvas.getFontMetrics().stringWidth("100.0%"); - int barWidth = StudioTheme.scale(SHARE_WIDTH) - percentWidth - StudioTheme.scale(6); - int barX = getWidth() - padding - StudioTheme.scale(SHARE_WIDTH); - int barHeight = StudioTheme.scale(SHARE_BAR_HEIGHT); - int barY = (getHeight() - barHeight) / 2; - canvas.setColor(StudioTheme.HOVER_BACKGROUND); - canvas.fillRoundRect(barX, barY, barWidth, barHeight, barHeight, barHeight); - canvas.setColor(seeThrough ? StudioTheme.CONTROL_BORDER : StudioTheme.ACCENT); - canvas.fillRoundRect(barX, barY, Math.max(barHeight, (int) Math.round(barWidth * share)), barHeight, barHeight, barHeight); - canvas.setColor(StudioTheme.SECONDARY_TEXT); - int textWidth = canvas.getFontMetrics().stringWidth(percent); - int baseline = (getHeight() + canvas.getFontMetrics().getAscent() - canvas.getFontMetrics().getDescent()) / 2; - canvas.drawString(percent, getWidth() - padding - textWidth, baseline); - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/ObjectRenderer.java b/core/src/main/java/art/arcane/iris/studio/map/ObjectRenderer.java deleted file mode 100644 index 28cc9ace4..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/ObjectRenderer.java +++ /dev/null @@ -1,305 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.studio.map.BlockModel.Face; -import art.arcane.iris.studio.map.BlockModel.TextureMapping; -import art.arcane.iris.studio.map.BlockTextures.BlockTexture; - -import java.awt.Color; -import java.awt.image.BufferedImage; -import java.awt.image.DataBufferInt; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Comparator; -import java.util.List; - -/** - * Draws an object mesh with an orthographic camera into a picture, without a graphics card: each quad is filled pixel - * by pixel, and a depth buffer keeps the nearest one. A cut-away part's faint ghost only fills pixels the object - * leaves empty, so it never hazes over what is shown. See-through quads come last, farthest first, each blended over - * what is already drawn. - */ -final class ObjectRenderer { - private static final Color GRID = new ThemeColor(0xE3E4E8, 0x34373C); - private static final int GRID_LINES_PER_SIDE = 25; - private static final double GRID_REACH = 0.7D; - private static final double GRID_BELOW_OBJECT = 0.035D; - // Shared quad edges land exactly on pixel centres now and then; a little overlap keeps them from leaving cracks. - private static final double EDGE_TOLERANCE = 1e-6D; - private static final double EDGE_ON_DETERMINANT = 1e-9D; - // A face's own texels end a hair inside its UV rectangle, so rounding never picks the texel next to it. - private static final double TEXEL_EDGE_MARGIN = 1e-6D; - private static final double FULL_ALPHA = 255D; - // Zoom 2 fills the picture with the object's bounding box; thumbnails keep a hair of margin around it. - private static final OrbitCamera THUMBNAIL_CAMERA = new OrbitCamera(OrbitCamera.START.yaw(), OrbitCamera.START.pitch(), 1.9D, Vec3.ZERO); - - private final int width; - private final int height; - private final int[] pixels; - private final double[] depths; - private final boolean[] showsObject; - private final OrbitProjection projection; - private final int gridColor = GRID.getRGB() & 0xFFFFFF; - - private ObjectRenderer(BufferedImage image, OrbitProjection projection) { - this.width = image.getWidth(); - this.height = image.getHeight(); - this.pixels = ((DataBufferInt) image.getRaster().getDataBuffer()).getData(); - this.depths = new double[pixels.length]; - this.showsObject = new boolean[pixels.length]; - this.projection = projection; - Arrays.fill(pixels, StudioTheme.EDITOR_BACKGROUND.getRGB() & 0xFFFFFF); - Arrays.fill(depths, Double.NEGATIVE_INFINITY); - } - - static OrbitPicture render(ObjectMesh mesh, OrbitCamera camera, int width, int height, int coveredLeftWidth) { - BufferedImage image = blankImage(width, height); - ObjectRenderer renderer = new ObjectRenderer(image, projection(mesh, camera, image.getWidth(), image.getHeight(), coveredLeftWidth)); - renderer.drawGrid(mesh.bounds()); - renderer.drawMesh(mesh); - return OrbitPicture.of(image, renderer.depths, renderer.projection); - } - - static OrbitProjection projection(ObjectMesh mesh, OrbitCamera camera, int width, int height, int coveredLeftWidth) { - int covered = Math.max(0, Math.min(Math.max(1, width) - 1, coveredLeftWidth)); - return projection(mesh.bounds(), mesh.bounds(), camera, Math.max(1, width), Math.max(1, height), covered); - } - - /** - * Draws {@code mesh} from the starting angle, without the floor grid, at the scale that fits an object of - * {@code sizeToFit}. Objects drawn with the same size compare at their true sizes, standing on the same ground. - */ - static BufferedImage renderThumbnail(ObjectMesh mesh, ObjectMesh.Bounds sizeToFit, int width, int height) { - BufferedImage image = blankImage(width, height); - new ObjectRenderer(image, projection(mesh.bounds(), sizeToFit, THUMBNAIL_CAMERA, image.getWidth(), image.getHeight(), 0)).drawMesh(mesh); - return image; - } - - /** - * @param shown the object drawn, centred across and standing where an object of {@code scaledAs} would - * @param scaledAs the size that is fitted to the view - */ - private static OrbitProjection projection(ObjectMesh.Bounds shown, ObjectMesh.Bounds scaledAs, OrbitCamera camera, - int width, int height, int coveredLeftWidth) { - Vec3 center = new Vec3((shown.minX() + shown.maxX()) / 2D, shown.minY() + scaledAs.sizeY() / 2D, (shown.minZ() + shown.maxZ()) / 2D); - Vec3 fittedSize = new Vec3(scaledAs.sizeX(), scaledAs.sizeY(), scaledAs.sizeZ()); - return new OrbitProjection(center, fittedSize, camera, OrbitCamera.START, width, height, coveredLeftWidth); - } - - private static BufferedImage blankImage(int width, int height) { - return new BufferedImage(Math.max(1, width), Math.max(1, height), BufferedImage.TYPE_INT_RGB); - } - - private void drawMesh(ObjectMesh mesh) { - for (ObjectMesh.Quad quad : mesh.solidQuads()) { - drawQuad(quad, Pass.SOLID); - } - for (ObjectMesh.Quad quad : mesh.cutAwayQuads()) { - drawQuad(quad, Pass.CUT_AWAY_GHOST); - } - for (ObjectMesh.Quad quad : farthestFirst(mesh.translucentQuads())) { - drawQuad(quad, Pass.BLENDED); - } - } - - private List farthestFirst(List quads) { - List sorted = new ArrayList<>(quads); - sorted.sort(Comparator.comparingDouble(this::centerDepth)); - return sorted; - } - - private double centerDepth(ObjectMesh.Quad quad) { - Face face = quad.face(); - return projection.depth( - quad.originX() + (face.edgeU().x() + face.edgeV().x()) / 2D, - quad.originY() + (face.edgeU().y() + face.edgeV().y()) / 2D, - quad.originZ() + (face.edgeU().z() + face.edgeV().z()) / 2D); - } - - private void drawGrid(ObjectMesh.Bounds bounds) { - FloorGrid grid = FloorGrid.under(bounds); - int reach = grid.reach(); - for (int offset = -reach; offset <= reach; offset += grid.step()) { - drawLine(grid.centerX() + offset, grid.floorY(), grid.centerZ() - reach, grid.centerX() + offset, grid.floorY(), grid.centerZ() + reach); - drawLine(grid.centerX() - reach, grid.floorY(), grid.centerZ() + offset, grid.centerX() + reach, grid.floorY(), grid.centerZ() + offset); - } - } - - private void drawLine(double fromX, double fromY, double fromZ, double toX, double toY, double toZ) { - double startX = projection.screenX(fromX, fromY, fromZ); - double startY = projection.screenY(fromX, fromY, fromZ); - double startDepth = projection.depth(fromX, fromY, fromZ); - double endX = projection.screenX(toX, toY, toZ); - double endY = projection.screenY(toX, toY, toZ); - double endDepth = projection.depth(toX, toY, toZ); - int steps = (int) Math.ceil(Math.max(Math.abs(endX - startX), Math.abs(endY - startY))); - for (int step = 0; step <= steps; step++) { - double progress = steps == 0 ? 0D : step / (double) steps; - int x = (int) (startX + (endX - startX) * progress); - int y = (int) (startY + (endY - startY) * progress); - if (x < 0 || y < 0 || x >= width || y >= height) { - continue; - } - int index = y * width + x; - double depth = startDepth + (endDepth - startDepth) * progress; - if (depth > depths[index]) { - depths[index] = depth; - pixels[index] = gridColor; - } - } - } - - // Later faces win ties, so an overlay drawn on the same box, like grass on a grass block's side, shows on top. - private void drawQuad(ObjectMesh.Quad quad, Pass pass) { - Face face = quad.face(); - if (!projection.facesCamera(face.normal().x(), face.normal().y(), face.normal().z())) { - return; - } - Vec3 u = face.edgeU(); - Vec3 v = face.edgeV(); - double originX = projection.screenX(quad.originX(), quad.originY(), quad.originZ()); - double originY = projection.screenY(quad.originX(), quad.originY(), quad.originZ()); - double originDepth = projection.depth(quad.originX(), quad.originY(), quad.originZ()); - double edgeUX = projection.screenStepX(u.x(), u.z()); - double edgeUY = projection.screenStepY(u.x(), u.y(), u.z()); - double edgeUDepth = projection.depthStep(u.x(), u.y(), u.z()); - double edgeVX = projection.screenStepX(v.x(), v.z()); - double edgeVY = projection.screenStepY(v.x(), v.y(), v.z()); - double edgeVDepth = projection.depthStep(v.x(), v.y(), v.z()); - double determinant = edgeUX * edgeVY - edgeUY * edgeVX; - if (Math.abs(determinant) < EDGE_ON_DETERMINANT) { - return; - } - - int left = Math.max(0, (int) Math.floor(min4(originX, originX + edgeUX, originX + edgeVX, originX + edgeUX + edgeVX))); - int right = Math.min(width - 1, (int) Math.ceil(max4(originX, originX + edgeUX, originX + edgeVX, originX + edgeUX + edgeVX))); - int top = Math.max(0, (int) Math.floor(min4(originY, originY + edgeUY, originY + edgeVY, originY + edgeUY + edgeVY))); - int bottom = Math.min(height - 1, (int) Math.ceil(max4(originY, originY + edgeUY, originY + edgeVY, originY + edgeUY + edgeVY))); - if (left > right || top > bottom) { - return; - } - - BlockTexture texture = face.texture(); - TextureMapping mapping = face.mapping(); - TexelRange columns = TexelRange.of(mapping.u(), mapping.uAlongU(), mapping.uAlongV(), texture.width()); - TexelRange rows = TexelRange.of(mapping.v(), mapping.vAlongU(), mapping.vAlongV(), texture.height()); - int[] texels = texture.pixels(); - boolean[] opaque = texture.opaque(); - int[] alphas = texture.alphas(); - double shade = face.shade(); - double alongUPerPixelX = edgeVY / determinant; - double alongVPerPixelX = -edgeUY / determinant; - for (int y = top; y <= bottom; y++) { - double offsetX = left + 0.5D - originX; - double offsetY = y + 0.5D - originY; - double alongU = (offsetX * edgeVY - offsetY * edgeVX) / determinant; - double alongV = (offsetY * edgeUX - offsetX * edgeUY) / determinant; - int rowStart = y * width; - for (int x = left; x <= right; x++, alongU += alongUPerPixelX, alongV += alongVPerPixelX) { - if (alongU < -EDGE_TOLERANCE || alongU > 1D + EDGE_TOLERANCE || alongV < -EDGE_TOLERANCE || alongV > 1D + EDGE_TOLERANCE) { - continue; - } - int index = rowStart + x; - double depth = originDepth + alongU * edgeUDepth + alongV * edgeVDepth; - if (depth < depths[index] || (pass == Pass.CUT_AWAY_GHOST && showsObject[index])) { - continue; - } - int texelX = columns.texelAt(mapping.u() + alongU * mapping.uAlongU() + alongV * mapping.uAlongV()); - int texelY = rows.texelAt(mapping.v() + alongU * mapping.vAlongU() + alongV * mapping.vAlongV()); - int texel = texelY * texture.width() + texelX; - if (!opaque[texel]) { - continue; - } - int color = BlockPreviewColors.shade(texels[texel], shade); - if (pass != Pass.SOLID) { - pixels[index] = blend(color, pixels[index], (alphas == null ? 1D : alphas[texel] / FULL_ALPHA) * quad.opacity()); - continue; - } - depths[index] = depth; - pixels[index] = color; - showsObject[index] = true; - } - } - } - - private static int blend(int over, int under, double coverage) { - return blendChannel(over, under, coverage, 16) << 16 | blendChannel(over, under, coverage, 8) << 8 | blendChannel(over, under, coverage, 0); - } - - private static int blendChannel(int over, int under, double coverage, int shift) { - return (int) Math.round(((over >>> shift) & 0xFF) * coverage + ((under >>> shift) & 0xFF) * (1D - coverage)); - } - - private static double min4(double a, double b, double c, double d) { - return Math.min(Math.min(a, b), Math.min(c, d)); - } - - private static double max4(double a, double b, double c, double d) { - return Math.max(Math.max(a, b), Math.max(c, d)); - } - - /** - * The texels a face covers along one texture axis, so a pixel on the face's edge never takes its neighbour's. - */ - record TexelRange(int first, int last, int size) { - static TexelRange of(double start, double alongU, double alongV, int size) { - double low = start + Math.min(0D, alongU) + Math.min(0D, alongV); - double high = start + Math.max(0D, alongU) + Math.max(0D, alongV); - int first = clamp((int) Math.floor(low * size + TEXEL_EDGE_MARGIN), size); - int last = Math.max(first, clamp((int) Math.ceil(high * size - TEXEL_EDGE_MARGIN) - 1, size)); - return new TexelRange(first, last, size); - } - - int texelAt(double fraction) { - int texel = (int) Math.floor(fraction * size); - return texel < first ? first : Math.min(texel, last); - } - - private static int clamp(int texel, int size) { - return Math.max(0, Math.min(size - 1, texel)); - } - } - - /** - * The grid on the ground under an object, a square of lines reaching past it on every side. - */ - record FloorGrid(int centerX, double floorY, int centerZ, int reach, int step) { - static FloorGrid under(ObjectMesh.Bounds bounds) { - int reach = (int) Math.ceil(bounds.largestSize() * GRID_REACH); - int step = Math.max(1, (int) Math.ceil(reach / (double) GRID_LINES_PER_SIDE)); - return new FloorGrid(Math.floorDiv(bounds.minX() + bounds.maxX(), 2), bounds.groundY() - GRID_BELOW_OBJECT, - Math.floorDiv(bounds.minZ() + bounds.maxZ(), 2), reach, step); - } - - int linesPerDirection() { - return 2 * reach / step + 1; - } - - int color() { - return GRID.getRGB(); - } - } - - private enum Pass { - SOLID, - CUT_AWAY_GHOST, - BLENDED - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/ObjectSeedChooser.java b/core/src/main/java/art/arcane/iris/studio/map/ObjectSeedChooser.java deleted file mode 100644 index aa0dea240..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/ObjectSeedChooser.java +++ /dev/null @@ -1,160 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package art.arcane.iris.studio.map; - -import javax.swing.DefaultComboBoxModel; -import javax.swing.DefaultListCellRenderer; -import javax.swing.JComboBox; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.UIManager; -import java.awt.BorderLayout; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.EventQueue; -import java.util.ArrayList; -import java.util.List; -import java.util.OptionalLong; -import java.util.concurrent.ThreadLocalRandom; -import java.util.function.LongConsumer; - -/** - * Where the seed of a procedural object's variants is chosen: typed in, picked again from the seeds tried on this - * object with the pack's own first, or rerolled at random. It keeps its size whatever it shows, so the bar it sits in - * never shifts under the mouse. - */ -final class ObjectSeedChooser extends JPanel { - private static final long serialVersionUID = 3127745038254406118L; - private static final int FIELD_WIDTH = 120; - private static final int TRIED_SEEDS_KEPT = 12; - // Small enough to read back and type, and far more seeds than anyone tries. - private static final int RANDOM_SEED_BOUND = 1_000_000; - - private final JComboBox seeds = new JComboBox<>(); - private final LongConsumer onSeedChosen; - private final List triedSeedsNewestFirst = new ArrayList<>(); - private OptionalLong packSeed = OptionalLong.empty(); - private long shownSeed; - private boolean showingSeeds; - - /** - * @param onSeedChosen told the seed to bake the variants from whenever the user chooses another one - */ - ObjectSeedChooser(LongConsumer onSeedChosen) { - super(new BorderLayout(StudioTheme.scale(4), 0)); - this.onSeedChosen = onSeedChosen; - setOpaque(false); - JLabel label = new JLabel("Seed"); - label.setFont(StudioTheme.smallFont()); - label.setForeground(StudioTheme.SECONDARY_TEXT); - seeds.setEditable(true); - seeds.setFont(StudioTheme.smallFont()); - seeds.setToolTipText("Type a seed and press Enter, or pick one tried before"); - seeds.setRenderer(new PackSeedMarker()); - seeds.setPreferredSize(new Dimension(StudioTheme.scale(FIELD_WIDTH), seeds.getPreferredSize().height)); - seeds.addActionListener(event -> { - if (!showingSeeds) { - EventQueue.invokeLater(this::chooseEnteredSeed); - } - }); - add(label, BorderLayout.WEST); - add(seeds, BorderLayout.CENTER); - add(StudioToolbar.button("Reroll", "Bake the variants from a random seed", this::reroll), BorderLayout.EAST); - } - - /** Starts a new object's list of tried seeds. */ - void forgetTriedSeeds() { - triedSeedsNewestFirst.clear(); - } - - void showSeed(long shown, OptionalLong pack) { - shownSeed = shown; - packSeed = pack; - if (!isPackSeed(shown)) { - rememberTried(shown); - } - DefaultComboBoxModel choices = new DefaultComboBoxModel<>(); - pack.ifPresent(choices::addElement); - triedSeedsNewestFirst.forEach(choices::addElement); - showingSeeds = true; - try { - seeds.setModel(choices); - seeds.setSelectedItem(shown); - } finally { - showingSeeds = false; - } - } - - private void rememberTried(long seed) { - triedSeedsNewestFirst.remove(seed); - triedSeedsNewestFirst.add(0, seed); - while (triedSeedsNewestFirst.size() > TRIED_SEEDS_KEPT) { - triedSeedsNewestFirst.remove(triedSeedsNewestFirst.size() - 1); - } - } - - // A pick from the list arrives as a seed, anything typed as text. - private void chooseEnteredSeed() { - OptionalLong entered = parse(seeds.getSelectedItem()); - if (entered.isEmpty()) { - UIManager.getLookAndFeel().provideErrorFeedback(seeds); - showSeed(shownSeed, packSeed); - return; - } - if (entered.getAsLong() != shownSeed) { - onSeedChosen.accept(entered.getAsLong()); - } - } - - private static OptionalLong parse(Object entered) { - if (entered instanceof Long seed) { - return OptionalLong.of(seed); - } - try { - return OptionalLong.of(Long.parseLong(String.valueOf(entered).trim())); - } catch (NumberFormatException notASeed) { - return OptionalLong.empty(); - } - } - - private void reroll() { - long seed; - do { - seed = ThreadLocalRandom.current().nextInt(RANDOM_SEED_BOUND); - } while (seed == shownSeed); - onSeedChosen.accept(seed); - } - - private boolean isPackSeed(Object seed) { - return packSeed.isPresent() && seed instanceof Long value && value == packSeed.getAsLong(); - } - - private final class PackSeedMarker extends DefaultListCellRenderer { - private static final long serialVersionUID = -6061513307766393251L; - - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, boolean selected, boolean focused) { - super.getListCellRendererComponent(list, value, index, selected, focused); - if (index >= 0 && isPackSeed(value)) { - setText(value + " (pack)"); - } - return this; - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/ObjectSummary.java b/core/src/main/java/art/arcane/iris/studio/map/ObjectSummary.java deleted file mode 100644 index 877c4b222..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/ObjectSummary.java +++ /dev/null @@ -1,66 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.volmlib.nativelib.terrain.NativeBlockState; - -import java.awt.image.BufferedImage; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Function; - -/** - * What an object is made of: its size and how many of each block type it uses, most used first. - */ -record ObjectSummary(String key, int sizeX, int sizeY, int sizeZ, int blockCount, List blockUses) { - static ObjectSummary of(String key, ObjectMesh.Bounds bounds, Iterable blocks, - Function iconOf) { - Map counts = new HashMap<>(); - Map examples = new HashMap<>(); - int blockCount = 0; - for (NativeBlockState block : blocks) { - String blockType = BlockNames.typeOf(block); - counts.merge(blockType, 1, Integer::sum); - examples.putIfAbsent(blockType, block); - blockCount++; - } - List uses = counts.entrySet().stream() - .map(count -> new BlockUse(count.getKey(), count.getValue(), iconOf.apply(examples.get(count.getKey())))) - .sorted(Comparator.comparingInt(BlockUse::count).reversed().thenComparing(BlockUse::blockType)) - .toList(); - return new ObjectSummary(key, bounds.sizeX(), bounds.sizeY(), bounds.sizeZ(), blockCount, uses); - } - - String name() { - return key.substring(key.lastIndexOf('/') + 1); - } - - double filledFraction() { - long volume = (long) sizeX * sizeY * sizeZ; - return volume == 0 ? 0D : blockCount / (double) volume; - } - - /** - * @param icon the block's texture, or null when Minecraft's textures are not available - */ - record BlockUse(String blockType, int count, BufferedImage icon) { - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/ObjectVariantGallery.java b/core/src/main/java/art/arcane/iris/studio/map/ObjectVariantGallery.java deleted file mode 100644 index 2d996a120..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/ObjectVariantGallery.java +++ /dev/null @@ -1,376 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package art.arcane.iris.studio.map; - -import javax.swing.AbstractAction; -import javax.swing.BorderFactory; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.KeyStroke; -import javax.swing.Scrollable; -import javax.swing.Timer; -import java.awt.AlphaComposite; -import java.awt.BorderLayout; -import java.awt.Cursor; -import java.awt.Dimension; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.event.ActionEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.geom.RoundRectangle2D; -import java.awt.image.BufferedImage; -import java.util.ArrayList; -import java.util.List; -import java.util.function.IntConsumer; - -/** - * Every variant of a procedural object side by side, drawn at one scale so their sizes compare. Clicking one opens it - * in the 3D view. While new thumbnails are drawn, each card keeps its old one faded until its own arrives; cards - * still waiting after a moment play the loading animation, one after another like a wave. - */ -final class ObjectVariantGallery extends JPanel { - private static final long serialVersionUID = 6153024487310558262L; - private static final int THUMBNAIL_SIZE = 220; - private static final int CARD_PADDING = 6; - private static final int CARD_GAP = 12; - private static final int EDGE_MARGIN = 16; - // The variant bar floats over the bottom edge, so the last row scrolls clear of it. - private static final int VARIANT_BAR_CLEARANCE = 64; - private static final float OUTDATED_THUMBNAIL_OPACITY = 0.35F; - private static final int THUMBNAIL_SIZE_PER_LOADING_BLOCK = 14; - private static final int LOADING_WAVE_STEP_MILLIS = 90; - - private final JLabel title = new JLabel(" "); - private final CardGrid grid = new CardGrid(); - private final IntConsumer onVariantOpened; - private final Runnable onThemeChanged; - private final List cards = new ArrayList<>(); - private final Timer loadingTicker = new Timer(LoadingAnimation.FRAME_MILLIS, event -> repaintWaitingCards()); - private boolean closed; - private int coveredLeftWidth; - private int selectedIndex; - private long waitingSinceMillis; - - /** - * @param onVariantOpened told the index of a variant the user clicks - * @param onThemeChanged told when the theme changes, since thumbnails are drawn on the theme's background - */ - ObjectVariantGallery(IntConsumer onVariantOpened, Runnable onThemeChanged) { - super(new BorderLayout(0, StudioTheme.scale(EDGE_MARGIN))); - this.onVariantOpened = onVariantOpened; - this.onThemeChanged = onThemeChanged; - setOpaque(true); - setBackground(StudioTheme.EDITOR_BACKGROUND); - setFocusable(true); - title.setFont(StudioTheme.sectionFont()); - title.setForeground(StudioTheme.TEXT); - JScrollPane scroll = StudioToolbar.scroll(grid); - scroll.setOpaque(false); - scroll.getViewport().setOpaque(false); - add(title, BorderLayout.NORTH); - add(scroll, BorderLayout.CENTER); - keepClearOfOverlays(); - } - - @Override - public void updateUI() { - super.updateUI(); - if (onThemeChanged != null) { - onThemeChanged.run(); - } - } - - void close() { - closed = true; - loadingTicker.stop(); - } - - void bindKey(int keyCode, String name, Runnable action) { - getInputMap(WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(KeyStroke.getKeyStroke(keyCode, 0), name); - getActionMap().put(name, new AbstractAction() { - @Override - public void actionPerformed(ActionEvent event) { - action.run(); - } - }); - } - - void setCoveredLeftWidth(int width) { - coveredLeftWidth = width; - keepClearOfOverlays(); - revalidate(); - } - - int thumbnailSize() { - return StudioTheme.scale(THUMBNAIL_SIZE); - } - - /** - * Cards for {@code count} variants, waiting for their thumbnails. The cards already shown stay, with their old - * thumbnails faded, so a reroll never blanks the view. - */ - void showVariants(String heading, int count, int selected) { - if (closed) { - return; - } - title.setText(heading); - if (count != cards.size()) { - replaceCards(count); - } - startWaiting(); - select(selected); - } - - /** Fades every thumbnail while something new loads. */ - void showLoading() { - startWaiting(); - } - - void showThumbnail(int index, BufferedImage thumbnail) { - if (closed) { - return; - } - if (index < cards.size()) { - cards.get(index).showThumbnail(thumbnail); - } - if (cards.stream().noneMatch(VariantCard::isWaiting)) { - loadingTicker.stop(); - } - } - - private void replaceCards(int count) { - cards.clear(); - grid.removeAll(); - for (int index = 0; index < count; index++) { - VariantCard card = new VariantCard(index); - cards.add(card); - grid.add(card); - } - grid.revalidate(); - grid.repaint(); - } - - private void startWaiting() { - if (closed) { - return; - } - if (!loadingTicker.isRunning()) { - waitingSinceMillis = System.currentTimeMillis(); - loadingTicker.start(); - } - cards.forEach(VariantCard::markOutdated); - } - - private void repaintWaitingCards() { - if (closed) { - return; - } - if (LoadingAnimation.isDue(waitingSinceMillis)) { - cards.stream().filter(VariantCard::isWaiting).forEach(VariantCard::repaint); - } - } - - void select(int index) { - selectedIndex = index; - cards.forEach(VariantCard::repaint); - if (index < cards.size()) { - VariantCard card = cards.get(index); - grid.scrollRectToVisible(card.getBounds()); - } - } - - void showMessage(String text) { - title.setText(text); - loadingTicker.stop(); - cards.clear(); - grid.removeAll(); - grid.revalidate(); - grid.repaint(); - } - - private void keepClearOfOverlays() { - int margin = StudioTheme.scale(EDGE_MARGIN); - setBorder(BorderFactory.createEmptyBorder(margin, coveredLeftWidth + margin, StudioTheme.scale(VARIANT_BAR_CLEARANCE), margin)); - } - - /** - * Cards in as many columns as fit the width, wrapping onto more rows. - */ - private final class CardGrid extends JPanel implements Scrollable { - private static final long serialVersionUID = -3618705187215931408L; - - CardGrid() { - super(null); - setOpaque(false); - } - - @Override - public void doLayout() { - Dimension card = cardSize(); - int gap = StudioTheme.scale(CARD_GAP); - int columns = columns(); - for (int index = 0; index < getComponentCount(); index++) { - int column = index % columns; - int row = index / columns; - getComponent(index).setBounds(column * (card.width + gap), row * (card.height + gap), card.width, card.height); - } - } - - @Override - public Dimension getPreferredSize() { - Dimension card = cardSize(); - int gap = StudioTheme.scale(CARD_GAP); - int rows = (getComponentCount() + columns() - 1) / columns(); - return new Dimension(card.width, Math.max(0, rows * (card.height + gap) - gap)); - } - - private int columns() { - int gap = StudioTheme.scale(CARD_GAP); - return Math.max(1, (getWidth() + gap) / (cardSize().width + gap)); - } - - @Override - public Dimension getPreferredScrollableViewportSize() { - return getPreferredSize(); - } - - @Override - public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { - return cardSize().height / 4; - } - - @Override - public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { - return visibleRect.height; - } - - @Override - public boolean getScrollableTracksViewportWidth() { - return true; - } - - @Override - public boolean getScrollableTracksViewportHeight() { - return false; - } - } - - private Dimension cardSize() { - int padding = StudioTheme.scale(CARD_PADDING); - int labelHeight = getFontMetrics(StudioTheme.smallFont()).getHeight(); - return new Dimension(thumbnailSize() + 2 * padding, thumbnailSize() + labelHeight + 3 * padding); - } - - private final class VariantCard extends JComponent { - private static final long serialVersionUID = 2296135546207834180L; - - private final int index; - private BufferedImage thumbnail; - private boolean thumbnailOutdated; - private boolean hovered; - - VariantCard(int index) { - this.index = index; - setToolTipText("Open variant " + (index + 1) + " in 3D"); - setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent event) { - onVariantOpened.accept(VariantCard.this.index); - } - - @Override - public void mouseEntered(MouseEvent event) { - setHovered(true); - } - - @Override - public void mouseExited(MouseEvent event) { - setHovered(false); - } - }); - } - - void showThumbnail(BufferedImage image) { - thumbnail = image; - thumbnailOutdated = false; - repaint(); - } - - void markOutdated() { - thumbnailOutdated = true; - repaint(); - } - - boolean isWaiting() { - return thumbnail == null || thumbnailOutdated; - } - - private void setHovered(boolean nowHovered) { - hovered = nowHovered; - repaint(); - } - - @Override - protected void paintComponent(Graphics graphics) { - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - double arc = StudioTheme.scale(StudioTheme.OVERLAY_ARC); - canvas.setColor(index == selectedIndex ? StudioTheme.SELECTION : hovered ? StudioTheme.HOVER_BACKGROUND : StudioTheme.PANEL_BACKGROUND); - canvas.fill(new RoundRectangle2D.Double(0, 0, getWidth(), getHeight(), arc, arc)); - int padding = StudioTheme.scale(CARD_PADDING); - int size = thumbnailSize(); - canvas.setFont(StudioTheme.smallFont()); - FontMetrics metrics = canvas.getFontMetrics(); - drawThumbnail(canvas, padding, size); - canvas.setColor(StudioTheme.TEXT); - drawCentered(canvas, "Variant " + (index + 1), padding * 2 + size + metrics.getAscent()); - } finally { - canvas.dispose(); - } - } - - private void drawThumbnail(Graphics2D canvas, int padding, int size) { - if (thumbnail != null) { - Graphics2D faded = (Graphics2D) canvas.create(); - if (thumbnailOutdated) { - faded.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, OUTDATED_THUMBNAIL_OPACITY)); - } - faded.drawImage(thumbnail, padding, padding, size, size, null); - faded.dispose(); - } - if (isWaiting() && LoadingAnimation.isDue(waitingSinceMillis)) { - long shownMillis = System.currentTimeMillis() - waitingSinceMillis - LoadingAnimation.SHOW_AFTER_MILLIS; - LoadingAnimation.paint(canvas, padding + size / 2D, padding + size / 2D, size / (double) THUMBNAIL_SIZE_PER_LOADING_BLOCK, - shownMillis - (long) index * LOADING_WAVE_STEP_MILLIS); - } - } - - private void drawCentered(Graphics2D canvas, String text, int baseline) { - canvas.drawString(text, (getWidth() - canvas.getFontMetrics().stringWidth(text)) / 2, baseline); - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/ObjectVariantPicker.java b/core/src/main/java/art/arcane/iris/studio/map/ObjectVariantPicker.java deleted file mode 100644 index 73a4b182b..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/ObjectVariantPicker.java +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ -package art.arcane.iris.studio.map; - -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.SwingConstants; -import java.awt.BorderLayout; -import java.awt.Dimension; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.geom.RoundRectangle2D; -import java.util.OptionalLong; -import java.util.function.IntConsumer; -import java.util.function.LongConsumer; - -/** - * A small bar floating at the bottom of the object view that steps through the variants of a procedural object and - * the seeds they are baked from, and switches between one variant in 3D and all of them side by side. It hides itself - * for anything with a single variant and no seed. - */ -final class ObjectVariantPicker extends JPanel { - private static final long serialVersionUID = -2716301839488217455L; - private static final int BOTTOM_MARGIN = 14; - private static final int VARIANT_LABEL_WIDTH = 110; - private static final int SECTION_GAP = 10; - private static final String VARIANT_SHORTCUT_HINT = " · [ and ]"; - private static final String COMPARE_SHORTCUT_HINT = " · G"; - - private final JLabel shownVariant = label(VARIANT_LABEL_WIDTH); - private final JComponent variantStepper; - private final ObjectSeedChooser seedChooser; - private final JButton compareButton; - private final IntConsumer onVariantChosen; - private int variantCount; - private int shownIndex; - private boolean seeded; - private int coveredLeftWidth; - - /** - * @param onVariantChosen told the index of the variant to show whenever the user steps to another one - * @param onSeedChosen told the seed to bake the variants from whenever the user chooses another one - * @param onCompareToggled told when the user switches between one variant and all of them - */ - ObjectVariantPicker(IntConsumer onVariantChosen, LongConsumer onSeedChosen, Runnable onCompareToggled) { - this.onVariantChosen = onVariantChosen; - setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); - setOpaque(false); - setBorder(StudioTheme.emptyBorder(3, 4, 3, 4)); - variantStepper = stepper(shownVariant, - StudioToolbar.button("‹", "Previous variant" + VARIANT_SHORTCUT_HINT, () -> stepBy(-1)), - StudioToolbar.button("›", "Next variant" + VARIANT_SHORTCUT_HINT, () -> stepBy(1))); - seedChooser = new ObjectSeedChooser(onSeedChosen); - compareButton = StudioToolbar.button("", "", onCompareToggled); - add(variantStepper); - add(Box.createHorizontalStrut(StudioTheme.scale(SECTION_GAP))); - add(seedChooser); - add(Box.createHorizontalStrut(StudioTheme.scale(SECTION_GAP))); - add(compareButton); - showComparing(false); - showVariants(0, 0); - } - - private static JLabel label(int width) { - JLabel label = new JLabel(" ", SwingConstants.CENTER); - label.setFont(StudioTheme.smallFont()); - label.setForeground(StudioTheme.TEXT); - label.setPreferredSize(new Dimension(StudioTheme.scale(width), label.getPreferredSize().height)); - return label; - } - - private static JComponent stepper(JLabel shown, JButton previous, JButton next) { - JPanel stepper = new JPanel(new BorderLayout()); - stepper.setOpaque(false); - stepper.add(previous, BorderLayout.WEST); - stepper.add(shown, BorderLayout.CENTER); - stepper.add(next, BorderLayout.EAST); - return stepper; - } - - /** - * The view with this bar floating over its bottom edge, centred on the part the left island leaves uncovered. - */ - JComponent floatingOver(JComponent view) { - ObjectVariantPicker picker = this; - JPanel stack = new JPanel(null) { - private static final long serialVersionUID = 1609842937565014832L; - - // The bar overlaps the view, so the view may not repaint without the bar on top of it. - @Override - public boolean isOptimizedDrawingEnabled() { - return false; - } - - @Override - public void doLayout() { - view.setBounds(0, 0, getWidth(), getHeight()); - Dimension size = picker.getPreferredSize(); - int centerX = coveredLeftWidth + (getWidth() - coveredLeftWidth) / 2; - picker.setBounds(centerX - size.width / 2, getHeight() - size.height - StudioTheme.scale(BOTTOM_MARGIN), size.width, size.height); - } - }; - stack.add(picker); - stack.add(view); - return stack; - } - - void setCoveredLeftWidth(int width) { - coveredLeftWidth = width; - relayout(); - } - - /** - * Shows variant {@code index} of {@code count} without telling anyone, since the caller already shows it. - */ - void showVariants(int count, int index) { - variantCount = count; - shownIndex = index; - shownVariant.setText("Variant " + (index + 1) + " of " + count); - variantStepper.setVisible(count > 1); - compareButton.setVisible(count > 1); - showWhenUseful(); - } - - /** - * Shows the seed the variants are baked from; empty for objects not generated from a seed. - */ - void showSeed(OptionalLong shown, OptionalLong pack) { - seeded = shown.isPresent(); - seedChooser.setVisible(seeded); - shown.ifPresent(seed -> seedChooser.showSeed(seed, pack)); - showWhenUseful(); - } - - void forgetTriedSeeds() { - seedChooser.forgetTriedSeeds(); - } - - void showComparing(boolean comparing) { - compareButton.setText(comparing ? "3D view" : "All variants"); - compareButton.setToolTipText((comparing ? "Show the chosen variant in 3D" : "Show every variant side by side") + COMPARE_SHORTCUT_HINT); - relayout(); - } - - void stepBy(int step) { - if (variantCount < 2) { - return; - } - shownIndex = Math.floorMod(shownIndex + step, variantCount); - showVariants(variantCount, shownIndex); - onVariantChosen.accept(shownIndex); - } - - private void showWhenUseful() { - setVisible(variantCount > 1 || seeded); - relayout(); - } - - private void relayout() { - if (getParent() != null) { - getParent().revalidate(); - getParent().repaint(); - } - } - - @Override - protected void paintComponent(Graphics graphics) { - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - double arc = StudioTheme.scale(StudioTheme.OVERLAY_ARC); - RoundRectangle2D shape = new RoundRectangle2D.Double(0.5, 0.5, getWidth() - 1D, getHeight() - 1D, arc, arc); - canvas.setColor(StudioTheme.OVERLAY_BACKGROUND); - canvas.fill(shape); - canvas.setColor(StudioTheme.OVERLAY_BORDER); - canvas.draw(shape); - } finally { - canvas.dispose(); - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/OrbitCamera.java b/core/src/main/java/art/arcane/iris/studio/map/OrbitCamera.java deleted file mode 100644 index 1a2f2d9b8..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/OrbitCamera.java +++ /dev/null @@ -1,48 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -/** - * Where the 3D viewers look from: turned by yaw around the vertical axis, tilted down by pitch, both in radians, around - * a pivot drawn in the middle of the view. The pivot is given in blocks from the middle of the scene. Zoom 1 fits the - * scene in the view at the starting angle. - */ -record OrbitCamera(double yaw, double pitch, double zoom, Vec3 pivot) { - static final OrbitCamera START = new OrbitCamera(0.76D, 0.38D, 1.72D, Vec3.ZERO); - private static final double RADIANS_PER_DRAGGED_PIXEL = 0.008D; - - OrbitCamera orbitedBy(double draggedX, double draggedY, OrbitLimits limits) { - double nextPitch = limits.pitchWithin(pitch + draggedY * RADIANS_PER_DRAGGED_PIXEL); - return new OrbitCamera(yaw + draggedX * RADIANS_PER_DRAGGED_PIXEL, nextPitch, zoom, pivot); - } - - /** - * @param towardFixedPoint how far from the pivot, across the view, the point that stays in place lies, like the one - * under the cursor - */ - OrbitCamera zoomedBy(double factor, OrbitLimits limits, Vec3 towardFixedPoint) { - double nextZoom = limits.zoomWithin(zoom * factor); - double appliedFactor = nextZoom / zoom; - return new OrbitCamera(yaw, pitch, nextZoom, pivot.plus(towardFixedPoint.times(1D - 1D / appliedFactor))); - } - - OrbitCamera pannedBy(Vec3 blocks) { - return new OrbitCamera(yaw, pitch, zoom, pivot.plus(blocks)); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/OrbitLimits.java b/core/src/main/java/art/arcane/iris/studio/map/OrbitLimits.java deleted file mode 100644 index 1bf0fa4e2..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/OrbitLimits.java +++ /dev/null @@ -1,34 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -/** - * How far a scene lets the orbit camera tilt and zoom. Pitch is in radians, positive looking down. - */ -record OrbitLimits(double lowestPitch, double highestPitch, double leastZoom, double mostZoom) { - static final OrbitLimits DEFAULT = new OrbitLimits(-1.3D, 1.3D, 0.4D, 12D); - - double pitchWithin(double pitch) { - return Math.max(lowestPitch, Math.min(highestPitch, pitch)); - } - - double zoomWithin(double zoom) { - return Math.max(leastZoom, Math.min(mostZoom, zoom)); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/OrbitPicture.java b/core/src/main/java/art/arcane/iris/studio/map/OrbitPicture.java deleted file mode 100644 index d0464ada4..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/OrbitPicture.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.awt.image.BufferedImage; -import java.util.List; -import java.util.OptionalDouble; - -/** - * A drawn view of a scene, with how far toward the camera from the pivot the surface drawn in the middle of the view - * lies; orbiting turns around that surface. Swing paints the patches. A whole picture is one patch covering the view; - * a frame drawn straight into the view's window is already on screen, and only keeps the patches Swing paints where - * panels float over that window. - * - * @param depthInMiddle empty when nothing was drawn in the middle - * @param catchingUp when the scene wasn't all drawn yet, so drawing the same camera again shows more - */ -record OrbitPicture(int width, int height, boolean onScreen, List patches, OptionalDouble depthInMiddle, - boolean catchingUp) { - static OrbitPicture whole(BufferedImage image, OptionalDouble depthInMiddle) { - return new OrbitPicture(image.getWidth(), image.getHeight(), false, List.of(new PicturePatch(0, 0, image)), depthInMiddle, false); - } - - static OrbitPicture onScreen(int width, int height, List patches, OptionalDouble depthInMiddle) { - return new OrbitPicture(width, height, true, patches, depthInMiddle, false); - } - - OrbitPicture stillCatchingUp() { - return new OrbitPicture(width, height, onScreen, patches, depthInMiddle, true); - } - - /** - * @param depths one per pixel, row by row; negative infinity where nothing was drawn - */ - static OrbitPicture of(BufferedImage image, double[] depths, OrbitProjection projection) { - int middleX = (int) projection.screenCenterX(); - int middleY = (int) projection.screenCenterY(); - if (middleX < 0 || middleY < 0 || middleX >= image.getWidth() || middleY >= image.getHeight()) { - return whole(image, OptionalDouble.empty()); - } - return whole(image, finite(depths[middleY * image.getWidth() + middleX])); - } - - static OptionalDouble finite(double depth) { - return Double.isFinite(depth) ? OptionalDouble.of(depth) : OptionalDouble.empty(); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/OrbitProjection.java b/core/src/main/java/art/arcane/iris/studio/map/OrbitProjection.java deleted file mode 100644 index de054555e..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/OrbitProjection.java +++ /dev/null @@ -1,171 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -/** - * Turns block positions into pixels with an orthographic orbit camera. Larger depth is nearer the camera. - */ -final class OrbitProjection { - private final double centerX; - private final double centerY; - private final double centerZ; - private final double cosYaw; - private final double sinYaw; - private final double cosPitch; - private final double sinPitch; - private final double pixelsPerBlock; - private final double screenCenterX; - private final double screenCenterY; - - /** - * @param center the middle of the scene, which the camera's pivot is given from; the pivot is drawn in the middle - * of the uncovered view - * @param fittedSize the extent that fits the view at zoom 1, seen from {@code fittedFrom}'s angle - */ - OrbitProjection(Vec3 center, Vec3 fittedSize, OrbitCamera camera, OrbitCamera fittedFrom, int width, int height, int coveredLeftWidth) { - this(center, camera, fittedPixelsPerBlock(fittedSize, camera, fittedFrom, width - coveredLeftWidth, height), width, height, coveredLeftWidth); - } - - private OrbitProjection(Vec3 center, OrbitCamera camera, double pixelsPerBlock, int width, int height, int coveredLeftWidth) { - this.centerX = center.x() + camera.pivot().x(); - this.centerY = center.y() + camera.pivot().y(); - this.centerZ = center.z() + camera.pivot().z(); - this.cosYaw = Math.cos(camera.yaw()); - this.sinYaw = Math.sin(camera.yaw()); - this.cosPitch = Math.cos(camera.pitch()); - this.sinPitch = Math.sin(camera.pitch()); - this.pixelsPerBlock = pixelsPerBlock; - this.screenCenterX = coveredLeftWidth + (width - coveredLeftWidth) / 2D; - this.screenCenterY = height / 2D; - } - - /** - * For scenes without a size to fit, like endless terrain: zoom 1 draws {@code pixelsPerBlockAtZoomOne}. - */ - static OrbitProjection atScale(Vec3 center, OrbitCamera camera, double pixelsPerBlockAtZoomOne, int width, int height, int coveredLeftWidth) { - return new OrbitProjection(center, camera, camera.zoom() * pixelsPerBlockAtZoomOne, width, height, coveredLeftWidth); - } - - private static double fittedPixelsPerBlock(Vec3 fittedSize, OrbitCamera camera, OrbitCamera fittedFrom, int visibleWidth, int height) { - double largestSize = Math.max(fittedSize.x(), Math.max(fittedSize.y(), fittedSize.z())); - double fit = fitAtAngle(fittedSize, largestSize, fittedFrom, visibleWidth / (double) height); - return camera.zoom() * fit * height / 2D / largestSize; - } - - // How far to scale the extent down so it fits the view at the given angle; orbiting keeps the scale. - private static double fitAtAngle(Vec3 size, double largestSize, OrbitCamera angle, double aspect) { - double width = size.x() / largestSize; - double height = size.y() / largestSize; - double depth = size.z() / largestSize; - double projectedWidth = Math.abs(Math.cos(angle.yaw())) * width + Math.abs(Math.sin(angle.yaw())) * depth; - double projectedDepth = Math.abs(Math.sin(angle.yaw())) * width + Math.abs(Math.cos(angle.yaw())) * depth; - double projectedHeight = Math.abs(Math.cos(angle.pitch())) * height + Math.abs(Math.sin(angle.pitch())) * projectedDepth; - return Math.min(1D, Math.min(aspect / projectedWidth, 1D / projectedHeight)); - } - - double pixelsPerBlock() { - return pixelsPerBlock; - } - - double screenCenterX() { - return screenCenterX; - } - - double screenCenterY() { - return screenCenterY; - } - - /** - * The blocks a move across the picture covers, in the plane of the picture: moving by it keeps every point's depth. - */ - Vec3 acrossPicture(double screenDeltaX, double screenDeltaY) { - double across = screenDeltaX / pixelsPerBlock; - double up = -screenDeltaY / pixelsPerBlock; - return new Vec3(cosYaw * across - sinPitch * sinYaw * up, cosPitch * up, -sinYaw * across - sinPitch * cosYaw * up); - } - - // A block's length along every pixel's line of sight, toward the camera; it moves nothing on the picture. - Vec3 towardCamera() { - return new Vec3(cosPitch * sinYaw, sinPitch, cosPitch * cosYaw); - } - - double screenX(double x, double y, double z) { - return screenCenterX + screenStepX(x - centerX, z - centerZ); - } - - double screenY(double x, double y, double z) { - return screenCenterY + screenStepY(x - centerX, y - centerY, z - centerZ); - } - - double depth(double x, double y, double z) { - return depthStep(x - centerX, y - centerY, z - centerZ); - } - - double screenStepX(double x, double z) { - return (cosYaw * x - sinYaw * z) * pixelsPerBlock; - } - - double screenStepY(double x, double y, double z) { - double towardCamera = sinYaw * x + cosYaw * z; - return -(cosPitch * y - sinPitch * towardCamera) * pixelsPerBlock; - } - - double depthStep(double x, double y, double z) { - double towardCamera = sinYaw * x + cosYaw * z; - return sinPitch * y + cosPitch * towardCamera; - } - - /** - * The point at height {@code y} drawn at a pixel. Looking level along the ground, every pixel's line of sight runs - * parallel to it, so the point lies infinitely far off. - */ - Vec3 pointAt(double screenX, double screenY, double y) { - double across = (screenX - screenCenterX) / pixelsPerBlock; - double up = (screenCenterY - screenY) / pixelsPerBlock; - double towardCamera = (cosPitch * (y - centerY) - up) / sinPitch; - double x = cosYaw * across + sinYaw * towardCamera; - double z = cosYaw * towardCamera - sinYaw * across; - return new Vec3(centerX + x, y, centerZ + z); - } - - boolean facesCamera(double normalX, double normalY, double normalZ) { - return depthStep(normalX, normalY, normalZ) > 0D; - } - - // The point the pivot puts in the middle of the view; positions relative to it are what the clip matrix takes. - Vec3 center() { - return new Vec3(centerX, centerY, centerZ); - } - - /** - * This projection for a graphics card: a column-major matrix from a position relative to {@link #center()} to clip - * space, where nearer is smaller and anything within {@code depthRange} blocks of the centre lies between the near - * and far planes. Clip space runs bottom-up, so pictures read back from it are upside down. - */ - float[] clipMatrix(int width, int height, double depthRange) { - double perBlockX = 2D * pixelsPerBlock / width; - double perBlockY = 2D * pixelsPerBlock / height; - return new float[]{ - (float) (perBlockX * cosYaw), (float) (-perBlockY * sinPitch * sinYaw), (float) (-cosPitch * sinYaw / depthRange), 0F, - 0F, (float) (perBlockY * cosPitch), (float) (-sinPitch / depthRange), 0F, - (float) (-perBlockX * sinYaw), (float) (-perBlockY * sinPitch * cosYaw), (float) (-cosPitch * cosYaw / depthRange), 0F, - (float) (2D * screenCenterX / width - 1D), (float) (1D - 2D * screenCenterY / height), 0F, 1F - }; - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/OrbitScene.java b/core/src/main/java/art/arcane/iris/studio/map/OrbitScene.java deleted file mode 100644 index c0870de96..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/OrbitScene.java +++ /dev/null @@ -1,63 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.util.Optional; - -/** - * Something the orbit viewport shows, drawn into a picture for any camera. - */ -interface OrbitScene { - boolean isEmpty(); - - default OrbitCamera startingCamera() { - return OrbitCamera.START; - } - - default OrbitLimits limits() { - return OrbitLimits.DEFAULT; - } - - /** - * @param coveredLeftWidth how much of the picture's left side something floats over, so the scene is centred and - * fitted in the rest - */ - OrbitPicture render(OrbitCamera camera, int width, int height, int coveredLeftWidth); - - /** - * Whether {@link #renderOnScreen} may draw this scene, as far as is known before trying. - */ - default boolean canRenderOnScreen() { - return false; - } - - /** - * Draws a frame straight into the view's window, like {@link #render} would draw a picture. - * - * @return the frame, or nothing when the caller should render a picture instead - */ - default Optional renderOnScreen(ScreenTarget screen, OrbitCamera camera, int width, int height, int coveredLeftWidth) { - return Optional.empty(); - } - - /** - * Where {@link #render} puts the scene for this camera and picture size. - */ - OrbitProjection projection(OrbitCamera camera, int width, int height, int coveredLeftWidth); -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/OrbitViewport.java b/core/src/main/java/art/arcane/iris/studio/map/OrbitViewport.java deleted file mode 100644 index 2044e5e3a..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/OrbitViewport.java +++ /dev/null @@ -1,683 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import javax.swing.AbstractAction; -import javax.swing.JComponent; -import javax.swing.KeyStroke; -import javax.swing.SwingUtilities; -import javax.swing.Timer; -import java.awt.AlphaComposite; -import java.awt.Dimension; -import java.awt.EventQueue; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GraphicsConfiguration; -import java.awt.Point; -import java.awt.RenderingHints; -import java.awt.Toolkit; -import java.awt.event.ActionEvent; -import java.awt.event.ActionListener; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.KeyEvent; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseWheelEvent; -import java.util.Optional; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.function.UnaryOperator; - -/** - * A 3D view of one scene, like an object or a stretch of noise. Drag to orbit around what is in the middle; right-drag, - * middle-drag or shift-drag to pan; scroll to zoom toward the cursor. Arrow keys orbit and plus and minus zoom too. Frames are drawn on a background thread, one at a time, always - * for the latest camera. While the next scene loads, the last picture stays up; only a slow load dims it under the - * loading animation. - */ -final class OrbitViewport extends JComponent { - private static final long serialVersionUID = -3175226517409913524L; - private static final double WHEEL_ZOOM_EXPONENT = 0.12D; - private static final double KEY_ZOOM_FACTOR = 1.1D; - private static final int KEY_ORBIT_PIXELS = 12; - private static final float LOADING_DIM_OPACITY = 0.88F; - private static final double LOADING_BLOCK_SIZE = 16D; - private static final int LOADING_TEXT_GAP = 46; - private static final double FRAME_TIME_SMOOTHING = 0.2D; - private static final double NANOS_PER_SECOND = 1_000_000_000D; - private static final int FRAME_RATE_MARGIN = 10; - - private final ExecutorService renderThread; - private final GpuCanvas canvas; - private final FrameRateLabel frameRateLabel = new FrameRateLabel(); - private OrbitScene scene; - private OrbitCamera camera = OrbitCamera.START; - private OrbitPicture picture; - private OrbitCamera pictureCamera; - private String message; - private EmptyState emptyState; - private volatile boolean closed; - private boolean rendering; - private boolean renderAgain; - private Point dragPoint; - private Drag drag = Drag.ORBIT; - private int coveredLeftWidth; - private final Timer loadingTicker = new Timer(LoadingAnimation.FRAME_MILLIS, event -> showLoadingProgress()); - private final Timer loadingCloser = singleShot(event -> finishLoading()); - private String loadingText; - private long loadingSinceMillis; - private double smoothedFrameNanos; - private Runnable viewChanged = () -> { - }; - - /** - * @param initialMessage what the view says until it is given something to show - */ - OrbitViewport(String renderThreadName, String initialMessage) { - message = initialMessage; - renderThread = Executors.newSingleThreadExecutor(runnable -> { - Thread thread = new Thread(runnable, renderThreadName); - thread.setDaemon(true); - return thread; - }); - MapHost.interruptOnPluginShutdown(renderThread); - setOpaque(true); - setBackground(StudioTheme.EDITOR_BACKGROUND); - setFocusable(true); - frameRateLabel.setVisible(false); - add(frameRateLabel); - canvas = GpuLibrary.isLoaded() && GlxDisplay.isSwingOnX() ? new GpuCanvas(this, this::requestFrame) : null; - if (canvas != null) { - canvas.setVisible(false); - add(canvas); - } - installMouseControls(); - installKeyControls(); - addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent event) { - if (closed) { - return; - } - requestFrame(); - viewChanged.run(); - } - }); - } - - // The theme changed, and the last frame was drawn on the old theme's background. - @Override - public void updateUI() { - super.updateUI(); - requestFrame(); - } - - @Override - public void doLayout() { - if (canvas != null) { - canvas.setBounds(0, 0, getWidth(), getHeight()); - } - Dimension label = frameRateLabel.getPreferredSize(); - int margin = StudioTheme.scale(FRAME_RATE_MARGIN); - frameRateLabel.setBounds(getWidth() - margin - label.width, margin, label.width, label.height); - } - - // The frame rate floats over the window frames are drawn into. - @Override - public boolean isOptimizedDrawingEnabled() { - return false; - } - - // The last picture stays up until the first one of this scene is drawn. - synchronized void show(OrbitScene nextScene) { - if (closed) { - return; - } - scene = nextScene; - camera = nextScene.startingCamera(); - message = nextScene.isEmpty() ? "No visible blocks" : null; - emptyState = null; - if (nextScene.isEmpty()) { - forgetPicture(); - finishLoading(); - } - requestFrame(); - repaint(); - viewChanged.run(); - } - - /** - * @param listener runs on the Swing thread whenever what the view shows of its scene moves: the camera, or the - * view's size or covered part - */ - void onViewChange(Runnable listener) { - viewChanged = listener; - } - - OrbitCamera camera() { - return camera; - } - - int coveredLeftWidth() { - return coveredLeftWidth; - } - - /** - * Marks the view as loading something new. A load already under way keeps its start, so stepping quickly through - * objects still shows the animation once the wait adds up. - */ - synchronized void showLoading(String text) { - if (closed) { - return; - } - if (loadingText == null) { - loadingSinceMillis = System.currentTimeMillis(); - } - loadingText = text; - message = null; - emptyState = null; - loadingCloser.stop(); - loadingTicker.start(); - } - - // A load that finishes just after the animation appeared would otherwise only flash it. - private synchronized void finishLoadingOnceShownLongEnough() { - if (closed) { - return; - } - long remainingMillis = LoadingAnimation.remainingShowMillis(loadingSinceMillis); - if (loadingText == null || remainingMillis == 0L) { - finishLoading(); - return; - } - loadingCloser.setInitialDelay((int) remainingMillis); - loadingCloser.restart(); - } - - // Swing paints the animation over the whole view, so it is shown over a picture rather than over the window. - private synchronized void showLoadingProgress() { - if (closed) { - return; - } - if (canvas != null && canvas.isVisible() && !drawsOnScreen()) { - requestFrame(); - } - updateFrameRateLabel(); - repaint(); - } - - private boolean isLoadingShown() { - return loadingText != null && LoadingAnimation.isDue(loadingSinceMillis); - } - - // Every picture finishes loading, so only a load still under way asks for a frame, or each frame would ask for the next. - private synchronized void finishLoading() { - if (closed) { - return; - } - if (loadingText == null) { - return; - } - loadingText = null; - loadingTicker.stop(); - loadingCloser.stop(); - updateFrameRateLabel(); - requestFrame(); - repaint(); - } - - private static Timer singleShot(ActionListener action) { - Timer timer = new Timer(0, action); - timer.setRepeats(false); - return timer; - } - - /** - * Swaps in another version of the same scene, like an object with its top layers cut away, keeping the camera. - */ - synchronized void replaceScene(OrbitScene nextScene) { - if (closed) { - return; - } - scene = nextScene; - message = nextScene.isEmpty() ? "No visible blocks" : null; - emptyState = null; - requestFrame(); - repaint(); - } - - void bindKey(int keyCode, String name, Runnable action) { - getInputMap(WHEN_FOCUSED).put(KeyStroke.getKeyStroke(keyCode, 0), name); - getActionMap().put(name, new AbstractAction() { - @Override - public void actionPerformed(ActionEvent event) { - if (!closed) { - action.run(); - } - } - }); - } - - boolean isShowingScene() { - return scene != null; - } - - synchronized void showMessage(String text) { - if (closed) { - return; - } - scene = null; - message = text; - emptyState = null; - forgetPicture(); - finishLoading(); - repaint(); - } - - synchronized void showEmptyState(EmptyState state) { - if (closed) { - return; - } - scene = null; - message = null; - emptyState = state; - forgetPicture(); - finishLoading(); - repaint(); - } - - private void forgetPicture() { - picture = null; - hideCanvas(); - updateFrameRateLabel(); - } - - private void hideCanvas() { - if (canvas != null && canvas.isVisible()) { - canvas.setVisible(false); - } - } - - private void updateFrameRateLabel() { - frameRateLabel.setVisible(picture != null && smoothedFrameNanos != 0D && !isLoadingShown()); - } - - /** - * Keeps the scene clear of a panel floating over the viewport's left side. - */ - synchronized void setCoveredLeftWidth(int width) { - if (closed) { - return; - } - if (width == coveredLeftWidth) { - return; - } - coveredLeftWidth = width; - requestFrame(); - viewChanged.run(); - } - - // Turns around the scene's middle again, keeping the angle and zoom. - void centerPivot() { - moveCamera(current -> new OrbitCamera(current.yaw(), current.pitch(), current.zoom(), Vec3.ZERO)); - } - - void resetCamera() { - moveCamera(current -> scene == null ? OrbitCamera.START : scene.startingCamera()); - } - - synchronized void close() { - if (closed) { - return; - } - closed = true; - scene = null; - picture = null; - pictureCamera = null; - loadingText = null; - renderAgain = false; - loadingTicker.stop(); - loadingCloser.stop(); - renderThread.shutdownNow(); - } - - private synchronized void moveCamera(UnaryOperator move) { - if (closed) { - return; - } - camera = move.apply(camera); - requestFrame(); - viewChanged.run(); - } - - private synchronized void requestFrame() { - if (closed || scene == null || scene.isEmpty() || getWidth() < 1 || getHeight() < 1) { - return; - } - if (rendering) { - renderAgain = true; - return; - } - rendering = true; - OrbitScene frameScene = scene; - OrbitCamera frameCamera = camera; - int width = getWidth(); - int height = getHeight(); - int covered = coveredLeftWidth; - ScreenTarget screen = screenTarget(); - long requestedAtNanos = System.nanoTime(); - renderThread.execute(() -> { - if (closed || Thread.currentThread().isInterrupted()) { - return; - } - OrbitPicture drawn = draw(frameScene, screen, frameCamera, width, height, covered); - if (closed || Thread.currentThread().isInterrupted()) { - return; - } - boolean missedScreen = screen != null && !drawn.onScreen(); - EventQueue.invokeLater(() -> finishFrame(frameScene, frameCamera, screen, drawn, missedScreen, requestedAtNanos)); - }); - } - - private static OrbitPicture draw(OrbitScene scene, ScreenTarget screen, OrbitCamera camera, int width, int height, int covered) { - if (screen != null) { - Optional onScreen = scene.renderOnScreen(screen, camera, width, height, covered); - if (onScreen.isPresent()) { - return onScreen.get(); - } - } - return scene.render(camera, width, height, covered); - } - - /** - * Frames go straight into the window when the view is on screen, the scene can be drawn that way, Swing has nothing - * to paint over the whole view, and the screen's pixels are the view's own. The window is shown before the frame is - * drawn into it. Showing it maps it even while its card is hidden, where it would cover the card that is open. - * - * @return the window, or nothing to draw a picture for Swing instead - */ - private ScreenTarget screenTarget() { - if (!drawsOnScreen()) { - return null; - } - if (!canvas.isVisible()) { - canvas.setVisible(true); - } - return new ScreenTarget(canvas, FloatingPanels.seeThroughOver(canvas)); - } - - private boolean drawsOnScreen() { - return canvas != null && isShowing() && canvas.window() != 0L && scene != null && !scene.isEmpty() - && scene.canRenderOnScreen() && !isLoadingShown() && hasUnscaledPixels(); - } - - private boolean hasUnscaledPixels() { - GraphicsConfiguration configuration = getGraphicsConfiguration(); - return configuration != null && configuration.getDefaultTransform().isIdentity(); - } - - /** - * Until the card is opened, nothing knows whether frames can go into the window; the first picture opens it. A - * frame that should have gone into the window but couldn't isn't tried again right away. A frame for a scene - * replaced meanwhile is never shown. The frame counts as rendering until it is on its way to the screen, so a - * frame asked for while it is taken, like when it ends a load, can't be drawn over it first. - */ - private synchronized void finishFrame(OrbitScene frameScene, OrbitCamera frameCamera, ScreenTarget screen, OrbitPicture drawn, - boolean missedScreen, long requestedAtNanos) { - if (closed) { - return; - } - measureFrameTime(System.nanoTime() - requestedAtNanos); - if (frameScene == scene) { - takePicture(drawn, frameCamera); - paintPicture(drawn); - showInWindow(screen, drawn); - } - rendering = false; - boolean canGoOnScreen = !missedScreen && canvas != null && !canvas.isVisible() && drawsOnScreen(); - if (renderAgain || drawn.catchingUp() || canGoOnScreen) { - renderAgain = false; - requestFrame(); - } - } - - /** - * A frame in the window only goes on screen once Swing has painted its patches, or the panels floating over the - * window would show the frame before. Swing and the card reach the screen through separate connections, so - * Swing's is flushed first. The render thread shows the frame before it draws the next one into the window. - */ - private synchronized void showInWindow(ScreenTarget screen, OrbitPicture drawn) { - if (closed) { - return; - } - if (!drawn.onScreen()) { - return; - } - Toolkit.getDefaultToolkit().sync(); - renderThread.execute(() -> { - if (closed || Thread.currentThread().isInterrupted()) { - return; - } - if (!GpuFrames.showOnScreen(screen)) { - EventQueue.invokeLater(this::requestFrame); - } - }); - } - - // A whole picture replaces the window until frames go into it again. - private void takePicture(OrbitPicture drawn, OrbitCamera frameCamera) { - picture = drawn; - pictureCamera = frameCamera; - if (!drawn.onScreen()) { - hideCanvas(); - } - frameRateLabel.showRate(NANOS_PER_SECOND / smoothedFrameNanos); - updateFrameRateLabel(); - finishLoadingOnceShownLongEnough(); - } - - private void paintPicture(OrbitPicture drawn) { - if (!drawn.onScreen()) { - repaint(); - return; - } - // Repainting would merge the patches into one box spanning most of the view, and paint everything in it. - for (PicturePatch patch : drawn.patches()) { - paintImmediately(patch.bounds()); - } - } - - private void measureFrameTime(long frameNanos) { - smoothedFrameNanos = smoothedFrameNanos == 0D - ? frameNanos - : smoothedFrameNanos + (frameNanos - smoothedFrameNanos) * FRAME_TIME_SMOOTHING; - } - - @Override - protected void paintComponent(Graphics graphics) { - graphics.setColor(getBackground()); - graphics.fillRect(0, 0, getWidth(), getHeight()); - if (picture != null) { - for (PicturePatch patch : picture.patches()) { - graphics.drawImage(patch.image(), patch.x(), patch.y(), null); - } - } - if (isLoadingShown()) { - drawLoading((Graphics2D) graphics); - } - if (message != null) { - drawMessage((Graphics2D) graphics); - } - if (emptyState != null) { - emptyState.paint((Graphics2D) graphics, this, coveredLeftWidth + (getWidth() - coveredLeftWidth) / 2, getHeight() / 2); - } - } - - private void drawLoading(Graphics2D graphics) { - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - if (picture != null) { - canvas.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, LOADING_DIM_OPACITY)); - canvas.setColor(getBackground()); - canvas.fillRect(0, 0, getWidth(), getHeight()); - canvas.setComposite(AlphaComposite.SrcOver); - } - int centerX = coveredLeftWidth + (getWidth() - coveredLeftWidth) / 2; - int centerY = getHeight() / 2; - long shownMillis = System.currentTimeMillis() - loadingSinceMillis - LoadingAnimation.SHOW_AFTER_MILLIS; - LoadingAnimation.paint(canvas, centerX, centerY, StudioTheme.scale(LOADING_BLOCK_SIZE), shownMillis); - canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - canvas.setFont(StudioTheme.font()); - canvas.setColor(StudioTheme.MUTED_TEXT); - String text = loadingText + "..."; - int textWidth = canvas.getFontMetrics().stringWidth(text); - canvas.drawString(text, centerX - textWidth / 2, centerY + StudioTheme.scale(LOADING_TEXT_GAP)); - } finally { - canvas.dispose(); - } - } - - private void drawMessage(Graphics2D canvas) { - canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - canvas.setFont(StudioTheme.font()); - canvas.setColor(StudioTheme.MUTED_TEXT); - int textWidth = canvas.getFontMetrics().stringWidth(message); - canvas.drawString(message, (getWidth() - textWidth) / 2, getHeight() / 2); - } - - private void installMouseControls() { - MouseAdapter mouse = new MouseAdapter() { - @Override - public void mousePressed(MouseEvent event) { - dragPoint = event.getPoint(); - drag = Drag.startedBy(event); - if (drag == Drag.ORBIT) { - pivotOnSurfaceInMiddle(); - } - requestFocusInWindow(); - } - - @Override - public void mouseReleased(MouseEvent event) { - dragPoint = null; - } - - @Override - public void mouseDragged(MouseEvent event) { - if (dragPoint == null) { - return; - } - int draggedX = event.getX() - dragPoint.x; - int draggedY = event.getY() - dragPoint.y; - dragPoint = event.getPoint(); - if (drag == Drag.PAN) { - panBy(draggedX, draggedY); - } else { - moveCamera(current -> current.orbitedBy(draggedX, draggedY, limits())); - } - } - - @Override - public void mouseWheelMoved(MouseWheelEvent event) { - zoomBy(Math.exp(-event.getPreciseWheelRotation() * WHEEL_ZOOM_EXPONENT), event.getX(), event.getY()); - } - }; - addMouseListener(mouse); - addMouseMotionListener(mouse); - addMouseWheelListener(mouse); - } - - private void installKeyControls() { - bindKey(KeyEvent.VK_LEFT, "orbit-left", current -> current.orbitedBy(-KEY_ORBIT_PIXELS, 0, limits())); - bindKey(KeyEvent.VK_RIGHT, "orbit-right", current -> current.orbitedBy(KEY_ORBIT_PIXELS, 0, limits())); - bindKey(KeyEvent.VK_UP, "orbit-up", current -> current.orbitedBy(0, KEY_ORBIT_PIXELS, limits())); - bindKey(KeyEvent.VK_DOWN, "orbit-down", current -> current.orbitedBy(0, -KEY_ORBIT_PIXELS, limits())); - bindKey(KeyEvent.VK_EQUALS, "zoom-in", () -> zoomTowardMiddle(KEY_ZOOM_FACTOR)); - bindKey(KeyEvent.VK_ADD, "zoom-in-keypad", () -> zoomTowardMiddle(KEY_ZOOM_FACTOR)); - bindKey(KeyEvent.VK_MINUS, "zoom-out", () -> zoomTowardMiddle(1D / KEY_ZOOM_FACTOR)); - bindKey(KeyEvent.VK_SUBTRACT, "zoom-out-keypad", () -> zoomTowardMiddle(1D / KEY_ZOOM_FACTOR)); - } - - private void bindKey(int keyCode, String name, UnaryOperator move) { - bindKey(keyCode, name, () -> moveCamera(move)); - } - - private OrbitLimits limits() { - return scene == null ? OrbitLimits.DEFAULT : scene.limits(); - } - - private OrbitProjection currentProjection() { - return scene.projection(camera, getWidth(), getHeight(), coveredLeftWidth); - } - - // The ground follows the cursor, like dragging a map. - private void panBy(int draggedX, int draggedY) { - if (scene == null) { - return; - } - Vec3 dragged = currentProjection().acrossPicture(-draggedX, -draggedY); - moveCamera(current -> current.pannedBy(dragged)); - } - - private void zoomTowardMiddle(double factor) { - if (scene == null) { - return; - } - OrbitProjection projection = currentProjection(); - zoomBy(factor, projection.screenCenterX(), projection.screenCenterY()); - } - - // What is under the cursor stays under it. - private void zoomBy(double factor, double cursorX, double cursorY) { - if (scene == null) { - return; - } - OrbitProjection projection = currentProjection(); - Vec3 towardCursor = projection.acrossPicture(cursorX - projection.screenCenterX(), cursorY - projection.screenCenterY()); - OrbitLimits limits = scene.limits(); - moveCamera(current -> current.zoomedBy(factor, limits, towardCursor)); - } - - /** - * Slides the pivot along the line of sight onto whatever is drawn in the middle of the view, so orbiting turns - * around it instead of a point in the air. The picture doesn't move, since the slide is along the line of sight. - */ - private void pivotOnSurfaceInMiddle() { - if (scene == null || picture == null || !camera.equals(pictureCamera) - || picture.width() != getWidth() || picture.height() != getHeight()) { - return; - } - OrbitProjection projection = currentProjection(); - picture.depthInMiddle().ifPresent(depth -> { - camera = camera.pannedBy(projection.towardCamera().times(depth)); - pictureCamera = camera; - }); - } - - private enum Drag { - ORBIT, - PAN; - - // Like most 3D editors: the left button orbits, the right or middle button, or shift, pans. - static Drag startedBy(MouseEvent event) { - boolean pans = event.isShiftDown() || SwingUtilities.isMiddleMouseButton(event) || SwingUtilities.isRightMouseButton(event); - return pans ? PAN : ORBIT; - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/PackFileOpener.java b/core/src/main/java/art/arcane/iris/studio/map/PackFileOpener.java deleted file mode 100644 index b02562d76..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/PackFileOpener.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.generation.runtime.IrisComplex; -import art.arcane.iris.generation.terrain.IrisRegion; -import art.arcane.iris.studio.map.components.MapLayer; - -import java.awt.Desktop; -import java.io.File; -import java.util.Optional; - -/** - * Opens the pack file behind what a map layer shows at a spot in the editor. - */ -final class PackFileOpener { - private PackFileOpener() { - } - - /** The opened file's name, or empty when nothing could be opened. */ - static Optional openAt(Engine engine, double worldX, double worldZ, MapLayer layer) { - if (!Desktop.isDesktopSupported()) { - return Optional.empty(); - } - IrisComplex complex = engine.getComplex(); - File file = switch (layer.type()) { - case BIOME, HEIGHT, RIVER, OBJECT_LOAD, DECORATOR_LOAD, LAYER_LOAD -> complex.getTrueBiomeStream().get(worldX, worldZ).openInVSCode(); - case BIOME_LAND -> complex.getLandBiomeStream().get(worldX, worldZ).openInVSCode(); - case BIOME_SEA -> complex.getSeaBiomeStream().get(worldX, worldZ).openInVSCode(); - case REGION -> complex.getRegionStream().get(worldX, worldZ).openInVSCode(); - case REGION_PREVIEW -> openPreviewedBiome(engine, layer.previewRegionKey(), worldX, worldZ); - case CAVE_LAND -> complex.getCaveBiomeStream().get(worldX, worldZ).openInVSCode(); - }; - return Optional.ofNullable(file).map(File::getName); - } - - private static File openPreviewedBiome(Engine engine, String regionKey, double worldX, double worldZ) { - IrisRegion region = engine.getData().getRegionLoader().load(regionKey); - return region == null ? null : engine.getComplex().surfaceBiomeAsIfIn(region, worldX, worldZ).openInVSCode(); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/PaletteExplorerStart.java b/core/src/main/java/art/arcane/iris/studio/map/PaletteExplorerStart.java deleted file mode 100644 index 745afb32f..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/PaletteExplorerStart.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.generation.runtime.Engine; - -import java.util.UUID; - -public record PaletteExplorerStart(Engine engine, UUID worldId, UUID playerId, String biomeKey, double centerX, double centerZ) { -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/PaletteInspectorPanel.java b/core/src/main/java/art/arcane/iris/studio/map/PaletteInspectorPanel.java deleted file mode 100644 index 93b220b36..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/PaletteInspectorPanel.java +++ /dev/null @@ -1,401 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import javax.swing.BorderFactory; -import javax.swing.ButtonGroup; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JToggleButton; -import javax.swing.SwingConstants; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GridLayout; -import java.awt.RenderingHints; -import java.util.Locale; - - -final class PaletteInspectorPanel extends JPanel { - private static final long serialVersionUID = 4473102938518712001L; - private static final int PANEL_WIDTH = 310; - private static final Color HISTOGRAM_BAR = new Color(0x9D, 0xA0, 0xA8, 150); - private static final Color BAND_DIVIDER = new Color(255, 255, 255, 70); - - private final Listener listener; - private final JLabel titleLabel = new JLabel(); - private final JLabel detailLabel = new JLabel(); - private final JLabel depthLabel = new JLabel("", SwingConstants.CENTER); - private final JButton shallowerButton = new JButton("‹"); - private final JButton deeperButton = new JButton("›"); - private final JPanel depthRow = new JPanel(new BorderLayout(StudioTheme.scale(6), 0)); - private final StatisticsView statisticsView = new StatisticsView(); - private PaletteLayerScale.View selectedView = PaletteLayerScale.View.BLOCKS; - private int depth; - private int deepestDepth; - - PaletteInspectorPanel(Listener listener) { - super(new BorderLayout()); - this.listener = listener; - setPreferredSize(StudioTheme.scaledSize(PANEL_WIDTH, 0)); - setBorder(BorderFactory.createMatteBorder(0, 1, 0, 0, StudioTheme.SEPARATOR)); - add(buildControls(), BorderLayout.NORTH); - add(StudioToolbar.scroll(statisticsView), BorderLayout.CENTER); - setVisible(false); - } - - void showPreview(PaletteLayerPreview preview) { - titleLabel.setText(preview.biomeKey() + " · " + preview.palette().lowercaseLabel()); - detailLabel.setText(placementText(preview)); - depth = preview.depth(); - deepestDepth = Math.max(0, preview.maxThickness() - 1); - refreshDepthControls(); - statisticsView.show(preview); - setVisible(true); - } - - void hideInspector() { - setVisible(false); - } - - PaletteLayerScale.View selectedView() { - return selectedView; - } - - private JPanel buildControls() { - JPanel controls = new JPanel(new GridLayout(0, 1, 0, StudioTheme.scale(6))); - controls.setBorder(BorderFactory.createCompoundBorder( - BorderFactory.createMatteBorder(0, 0, 1, 0, StudioTheme.SEPARATOR), - StudioTheme.emptyBorder(12, 14, 12, 14) - )); - titleLabel.setFont(StudioTheme.titleFont()); - detailLabel.setForeground(StudioTheme.SECONDARY_TEXT); - detailLabel.setFont(StudioTheme.smallFont()); - controls.add(titleLabel); - controls.add(detailLabel); - - controls.add(sectionLabel("Show")); - controls.add(buildViewButtons()); - controls.add(sectionLabel("Depth")); - controls.add(buildDepthRow()); - return controls; - } - - private JPanel buildViewButtons() { - JPanel row = new JPanel(new GridLayout(1, 0, StudioTheme.scale(4), 0)); - row.setOpaque(false); - ButtonGroup group = new ButtonGroup(); - for (PaletteLayerScale.View view : PaletteLayerScale.View.values()) { - JToggleButton button = new JToggleButton(view.toString()); - button.setFocusable(false); - button.setSelected(view == selectedView); - button.addActionListener(event -> { - selectedView = view; - listener.onViewChanged(view); - }); - group.add(button); - row.add(button); - } - return row; - } - - private JPanel buildDepthRow() { - depthRow.setOpaque(false); - shallowerButton.setToolTipText("Show the block one higher up"); - deeperButton.setToolTipText("Show the block one further down"); - shallowerButton.addActionListener(event -> changeDepth(-1)); - deeperButton.addActionListener(event -> changeDepth(1)); - depthRow.add(shallowerButton, BorderLayout.WEST); - depthRow.add(depthLabel, BorderLayout.CENTER); - depthRow.add(deeperButton, BorderLayout.EAST); - return depthRow; - } - - private void changeDepth(int step) { - int nextDepth = Math.clamp(depth + step, 0, deepestDepth); - if (nextDepth == depth) { - return; - } - depth = nextDepth; - refreshDepthControls(); - listener.onDepthChanged(depth); - } - - private void refreshDepthControls() { - depthLabel.setText(depthText(depth, deepestDepth)); - shallowerButton.setEnabled(depth > 0); - deeperButton.setEnabled(depth < deepestDepth); - } - - private static JLabel sectionLabel(String text) { - JLabel label = new JLabel(text.toUpperCase(Locale.ROOT)); - label.setForeground(StudioTheme.MUTED_TEXT); - label.setFont(StudioTheme.sectionFont()); - return label; - } - - // Stacked layers divide their coordinates by the zoom twice before sampling; wall and slab blocks only once. - private static String placementText(PaletteLayerPreview preview) { - if (!preview.palette().kind().isStacked()) { - return "Single blocks · zoom " + formatZoom(preview.zoom()); - } - return thicknessText(preview) + " · zoom " + formatZoom(preview.zoom()) - + " (×" + formatZoom(preview.zoom() * preview.zoom()) + " effective)"; - } - - private static String thicknessText(PaletteLayerPreview preview) { - if (preview.minThickness() == preview.maxThickness()) { - return preview.maxThickness() + (preview.maxThickness() == 1 ? " block thick" : " blocks thick"); - } - return preview.minThickness() + "–" + preview.maxThickness() + " blocks thick"; - } - - private static String depthText(int depth, int deepestDepth) { - if (deepestDepth == 0) { - return "Top block only"; - } - return depth == 0 ? "Top block" : depth + (depth == 1 ? " block down" : " blocks down"); - } - - private static String formatZoom(double zoom) { - return zoom == Math.rint(zoom) ? Long.toString((long) zoom) : String.format(Locale.ROOT, "%.2f", zoom); - } - - private static String percent(double share) { - if (share > 0D && share < 0.001D) { - return "<0.1%"; - } - return String.format(Locale.ROOT, "%.1f%%", share * 100D); - } - - interface Listener { - void onViewChanged(PaletteLayerScale.View view); - - void onDepthChanged(int depth); - } - - private static final class StatisticsView extends JComponent { - private static final long serialVersionUID = -2318840125766150871L; - private static final int MARGIN = 14; - private static final int HISTOGRAM_HEIGHT = 84; - private static final int BAND_HEIGHT = 12; - private static final int SECTION_GAP = 18; - private static final int TITLE_GAP = 6; - private static final String WIDEST_WEIGHT = "100.0%"; - private static final String WIDEST_ACTUAL = "▲ 100.0%"; - - private PaletteLayerPreview preview; - - private StatisticsView() { - setOpaque(true); - setBackground(StudioTheme.PANEL_BACKGROUND); - } - - private void show(PaletteLayerPreview nextPreview) { - preview = nextPreview; - revalidate(); - repaint(); - } - - @Override - public Dimension getPreferredSize() { - int preferredWidth = StudioTheme.scale(PANEL_WIDTH - 20); - if (preview == null) { - return new Dimension(preferredWidth, 0); - } - int margin = StudioTheme.scale(MARGIN); - int height = margin + valueSpreadHeight() + StudioTheme.scale(SECTION_GAP) + blockTableHeight() + margin; - return new Dimension(preferredWidth, height); - } - - @Override - protected void paintComponent(Graphics graphics) { - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - canvas.setColor(StudioTheme.PANEL_BACKGROUND); - canvas.fillRect(0, 0, getWidth(), getHeight()); - if (preview == null) { - return; - } - int margin = StudioTheme.scale(MARGIN); - int width = getWidth() - margin * 2; - int top = margin; - drawValueSpread(canvas, margin, top, width); - top += valueSpreadHeight() + StudioTheme.scale(SECTION_GAP); - drawBlockTable(canvas, margin, top, width); - } finally { - canvas.dispose(); - } - } - - private int valueSpreadHeight() { - return sectionMetrics().getHeight() + StudioTheme.scale(TITLE_GAP) + StudioTheme.scale(HISTOGRAM_HEIGHT) - + StudioTheme.scale(2) + StudioTheme.scale(BAND_HEIGHT) + StudioTheme.scale(3) + smallMetrics().getHeight(); - } - - private int blockTableHeight() { - return sectionMetrics().getHeight() + StudioTheme.scale(TITLE_GAP) + rowHeight() * preview.entries().size(); - } - - private int rowHeight() { - return textMetrics().getHeight() + StudioTheme.scale(4); - } - - private FontMetrics textMetrics() { - return getFontMetrics(StudioTheme.font()); - } - - private FontMetrics smallMetrics() { - return getFontMetrics(StudioTheme.smallFont()); - } - - private FontMetrics sectionMetrics() { - return getFontMetrics(StudioTheme.sectionFont()); - } - - private void drawValueSpread(Graphics2D canvas, int x, int top, int width) { - drawSectionTitle(canvas, "Noise values this layer produces", x, top + sectionMetrics().getAscent()); - int histogramTop = top + sectionMetrics().getHeight() + StudioTheme.scale(TITLE_GAP); - int histogramHeight = StudioTheme.scale(HISTOGRAM_HEIGHT); - int bandHeight = StudioTheme.scale(BAND_HEIGHT); - long[] histogram = preview.histogram(); - long peak = 1L; - for (long count : histogram) { - peak = Math.max(peak, count); - } - canvas.setColor(HISTOGRAM_BAR); - for (int bin = 0; bin < histogram.length; bin++) { - int barLeft = x + (bin * width) / histogram.length; - int barRight = x + ((bin + 1) * width) / histogram.length; - int barHeight = (int) Math.round(histogramHeight * (histogram[bin] / (double) peak)); - canvas.fillRect(barLeft, histogramTop + histogramHeight - barHeight, Math.max(1, barRight - barLeft - 1), barHeight); - } - - int bandTop = histogramTop + histogramHeight + StudioTheme.scale(2); - for (PaletteLayerPreview.Entry entry : preview.entries()) { - if (Double.isNaN(entry.lowestNoise())) { - continue; - } - int bandLeft = x + (int) Math.round(entry.lowestNoise() * width); - int bandRight = x + (int) Math.round(entry.highestNoise() * width); - canvas.setColor(new Color(entry.color())); - canvas.fillRect(bandLeft, bandTop, Math.max(1, bandRight - bandLeft), bandHeight); - if (entry.highestNoise() < 1D) { - canvas.setColor(BAND_DIVIDER); - canvas.drawLine(bandRight, histogramTop, bandRight, bandTop + bandHeight - 1); - } - } - - canvas.setFont(StudioTheme.smallFont()); - canvas.setColor(StudioTheme.SECONDARY_TEXT); - FontMetrics metrics = canvas.getFontMetrics(); - int labelY = bandTop + bandHeight + StudioTheme.scale(3) + metrics.getAscent(); - canvas.drawString("0", x, labelY); - canvas.drawString("0.5", x + (width - metrics.stringWidth("0.5")) / 2, labelY); - canvas.drawString("1", x + width - metrics.stringWidth("1"), labelY); - } - - private void drawBlockTable(Graphics2D canvas, int x, int top, int width) { - int columnGap = StudioTheme.scale(10); - int actualRight = x + width; - int weightRight = actualRight - textMetrics().stringWidth(WIDEST_ACTUAL) - columnGap; - int nameRight = weightRight - textMetrics().stringWidth(WIDEST_WEIGHT) - columnGap; - int titleBaseline = top + sectionMetrics().getAscent(); - drawSectionTitle(canvas, "Blocks", x, titleBaseline); - drawRightAligned(canvas, "weight", weightRight, titleBaseline); - drawRightAligned(canvas, "actual", actualRight, titleBaseline); - - int rowHeight = rowHeight(); - FontMetrics text = textMetrics(); - int swatchSize = text.getAscent() - text.getDescent(); - int rowTop = top + sectionMetrics().getHeight() + StudioTheme.scale(TITLE_GAP); - for (PaletteLayerPreview.Entry entry : preview.entries()) { - int baseline = rowTop + (rowHeight + text.getAscent() - text.getDescent()) / 2; - drawSwatch(canvas, entry, x, rowTop + (rowHeight - swatchSize) / 2, swatchSize); - canvas.setFont(StudioTheme.font()); - canvas.setColor(entry.found() ? StudioTheme.TEXT : StudioTheme.ERROR); - String name = entry.found() ? shortBlockName(entry.block()) : shortBlockName(entry.block()) + " (not found)"; - int nameLeft = x + swatchSize + StudioTheme.scale(7); - canvas.drawString(fit(canvas, name, nameRight - nameLeft), nameLeft, baseline); - canvas.setColor(StudioTheme.SECONDARY_TEXT); - drawRightAligned(canvas, percent(entry.weightShare()), weightRight, baseline); - canvas.setColor(actualColor(entry)); - drawRightAligned(canvas, actualText(entry), actualRight, baseline); - rowTop += rowHeight; - } - } - - private static void drawSwatch(Graphics2D canvas, PaletteLayerPreview.Entry entry, int x, int y, int size) { - if (entry.texture() != null) { - canvas.drawImage(entry.texture().toImage(), x, y, size, size, null); - return; - } - canvas.setColor(new Color(entry.color())); - int arc = StudioTheme.scale(3); - canvas.fillRoundRect(x, y, size, size, arc, arc); - } - - private static String actualText(PaletteLayerPreview.Entry entry) { - if (entry.isFarBelowWeight()) { - return "▼ " + percent(entry.actualShare()); - } - if (entry.isFarAboveWeight()) { - return "▲ " + percent(entry.actualShare()); - } - return percent(entry.actualShare()); - } - - private static Color actualColor(PaletteLayerPreview.Entry entry) { - return entry.isFarBelowWeight() || entry.isFarAboveWeight() ? StudioTheme.WARNING : StudioTheme.TEXT; - } - - private static void drawSectionTitle(Graphics2D canvas, String title, int x, int y) { - canvas.setFont(StudioTheme.sectionFont()); - canvas.setColor(StudioTheme.MUTED_TEXT); - canvas.drawString(title.toUpperCase(Locale.ROOT), x, y); - } - - private static void drawRightAligned(Graphics2D canvas, String text, int right, int y) { - canvas.drawString(text, right - canvas.getFontMetrics().stringWidth(text), y); - } - - private static String shortBlockName(String block) { - return block.startsWith("minecraft:") ? block.substring("minecraft:".length()) : block; - } - - private static String fit(Graphics2D canvas, String text, int maxWidth) { - FontMetrics metrics = canvas.getFontMetrics(); - if (metrics.stringWidth(text) <= maxWidth) { - return text; - } - String shortened = text; - while (shortened.length() > 1 && metrics.stringWidth(shortened + "…") > maxWidth) { - shortened = shortened.substring(0, shortened.length() - 1); - } - return shortened + "…"; - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/PaletteLayerPreview.java b/core/src/main/java/art/arcane/iris/studio/map/PaletteLayerPreview.java deleted file mode 100644 index a3aecf10c..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/PaletteLayerPreview.java +++ /dev/null @@ -1,425 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.studio.map.BlockTextures.BlockTexture; -import art.arcane.iris.pack.loading.IrisData; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.generation.biome.IrisBiome; -import art.arcane.iris.generation.block.IrisBlockData; -import art.arcane.volmlib.nativelib.terrain.NativeBlockState; -import art.arcane.volmlib.util.collection.KList; -import art.arcane.volmlib.util.math.RNG; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -final class PaletteLayerPreview { - static final int HISTOGRAM_BINS = 50; - private static final int STATISTICS_GRID_SIZE = 64; - private static final double STATISTICS_SPACING_BLOCKS = 37D; - private static final int MISSING_BLOCK_COLOR = 0x5A5F6B; - private static final double FAR_FROM_WEIGHT_FACTOR = 2D; - private static final int BLOCK_CACHE_SIZE = 1 << 16; - private static final int NO_OVERHANG = -1; - - private final BiomePalette palette; - private final KList blocks; - private final BiomePalettePlacement placement; - private final PaletteLayerPreview ground; - private final boolean[] showsGroundByEntry; - private final int depth; - private final IrisData data; - private final int[] entryBySlot; - private final BiomeTintField biomeTints; - private final BlockTexture[] textureByEntry; - private final BlockTexture[] upperHalfByEntry; - private final boolean hasTallPlants; - private final BlockTexture[] legendTextureByEntry; - private final int[] legendColorByEntry; - private final List entries; - private final SampledBlock[] blockCache = new SampledBlock[BLOCK_CACHE_SIZE]; - private final long[] histogram; - - private PaletteLayerPreview(BiomePalette palette, BiomePalettePlacement placement, PaletteLayerPreview ground, int depth, - IrisData data, BlockTextures textures, BiomeTintField biomeTints) { - this.palette = palette; - this.blocks = placement.blocks(); - this.placement = placement; - this.ground = ground; - this.depth = depth; - this.data = data; - this.entryBySlot = PaletteSlots.entryPerSlot(blocks, data); - if (entryBySlot.length == 0) { - throw new IllegalStateException("No block of " + palette.biomeKey() + " " + palette.lowercaseLabel() + " could be found"); - } - this.biomeTints = biomeTints; - this.showsGroundByEntry = resolveGroundShowingEntries(); - this.textureByEntry = resolveEntryTextures(textures); - this.upperHalfByEntry = resolveUpperHalves(textures); - this.hasTallPlants = Arrays.stream(upperHalfByEntry).anyMatch(Objects::nonNull); - this.legendTextureByEntry = tintForLegend(legendTextures()); - this.legendColorByEntry = resolveLegendColors(); - - Statistics statistics = measure(); - this.histogram = statistics.histogram(); - this.entries = describeEntries(statistics.sharesByEntry()); - } - - static PaletteLayerPreview load(Engine engine, BiomePalette palette, int depth, BlockTextures textures) { - if (engine == null || engine.isClosed()) { - throw new IllegalStateException("Open a studio world to preview pack palettes"); - } - IrisData data = engine.getData(); - IrisBiome biome = data.getBiomeLoader().load(palette.biomeKey()); - if (biome == null || palette.blocksIn(biome) == null) { - throw new IllegalStateException("Palette removed during hotload: " + palette.biomeKey() + " " + palette.lowercaseLabel()); - } - BiomePalettePlacement placement = BiomePalettePlacement.of(engine, biome, palette); - BiomeTintField biomeTints = textures == null - ? null - : new BiomeTintField(biome, new RNG(engine.getSeedManager().getBiome()), textures.biomeColors()); - PaletteLayerPreview ground = palette.kind() == BiomePalette.Kind.DECORATOR - ? groundUnder(engine, palette.biomeKey(), biome, data, textures, biomeTints) - : null; - return new PaletteLayerPreview(palette, placement, ground, depth, data, textures, biomeTints); - } - - // Decorations stand on the biome's top surface layer, so that is what shows around and between them. - private static PaletteLayerPreview groundUnder(Engine engine, String biomeKey, IrisBiome biome, IrisData data, - BlockTextures textures, BiomeTintField biomeTints) { - BiomePalette topLayer = new BiomePalette(biomeKey, BiomePalette.Kind.LAYER, 0); - KList blocks = topLayer.blocksIn(biome); - if (blocks == null || blocks.isEmpty()) { - return null; - } - return new PaletteLayerPreview(topLayer, BiomePalettePlacement.of(engine, biome, topLayer), null, 0, data, textures, - biomeTints); - } - - // The world picks one block per whole coordinate, and zoomed in, many pixels fall on the same block. - double sample(double x, double z) { - int blockX = (int) Math.floor(x); - int blockZ = (int) Math.floor(z); - int cacheSlot = blockCacheSlot(blockX, blockZ); - SampledBlock cached = blockCache[cacheSlot]; - if (cached != null && cached.x() == blockX && cached.z() == blockZ) { - return cached.noise(); - } - double noise = sampleBlock(blockX, blockZ); - blockCache[cacheSlot] = new SampledBlock(blockX, blockZ, noise); - return noise; - } - - private double sampleBlock(int blockX, int blockZ) { - if (placement.thickness(blockX, blockZ) <= depth) { - return Double.NaN; - } - return placement.noise(blockX, blockZ, depth); - } - - private static int blockCacheSlot(int blockX, int blockZ) { - long hash = blockX * 0x9E3779B97F4A7C15L ^ blockZ * 0xC2B2AE3D27D4EB4FL; - return (int) ((hash ^ (hash >>> 29)) & (BLOCK_CACHE_SIZE - 1)); - } - - int colorForNoise(double noise) { - return legendColorByEntry[entryIndexForNoise(noise)]; - } - - int blockColorAt(double noise, double worldX, double worldZ, boolean showTexturePixels) { - int overhang = showTexturePixels ? overhangColorAt(worldX, worldZ) : NO_OVERHANG; - if (overhang != NO_OVERHANG) { - return overhang; - } - int entry = entryIndexForNoise(noise); - if (showsGroundByEntry[entry]) { - return bareColorAt(worldX, worldZ, showTexturePixels); - } - BlockTexture texture = textureByEntry[entry]; - if (texture == null) { - return legendColorByEntry[entry]; - } - if (ground != null && showTexturePixels && !texture.isOpaqueAt(worldX, worldZ)) { - return groundColorAt(worldX, worldZ, true); - } - int untintedColor = showTexturePixels ? texture.texelAt(worldX, worldZ) : texture.averageColor(); - return tinted(texture, untintedColor, worldX, worldZ); - } - - /** - * The colour where the palette places nothing: the ground under a decorator, or plain dark otherwise. - */ - int bareColorAt(double worldX, double worldZ, boolean showTexturePixels) { - if (ground == null) { - return PaletteLayerScale.ABSENT_COLOR; - } - int overhang = showTexturePixels ? overhangColorAt(worldX, worldZ) : NO_OVERHANG; - return overhang != NO_OVERHANG ? overhang : groundColorAt(worldX, worldZ, showTexturePixels); - } - - // A two block tall plant stands up on the map: its top half covers the block above it, which is one block north. - private int overhangColorAt(double worldX, double worldZ) { - if (!hasTallPlants) { - return NO_OVERHANG; - } - double plantZ = worldZ + 1D; - double noise = sample(worldX, plantZ); - if (Double.isNaN(noise)) { - return NO_OVERHANG; - } - BlockTexture upperHalf = upperHalfByEntry[entryIndexForNoise(noise)]; - if (upperHalf == null || !upperHalf.isOpaqueAt(worldX, worldZ)) { - return NO_OVERHANG; - } - return tinted(upperHalf, upperHalf.texelAt(worldX, worldZ), worldX, plantZ); - } - - private int tinted(BlockTexture texture, int untintedColor, double worldX, double worldZ) { - if (texture.biomeTint() == null) { - return untintedColor; - } - int tint = biomeTints.colorAt(texture.biomeTint(), (int) Math.floor(worldX), (int) Math.floor(worldZ)); - return BlockTexture.multiply(untintedColor, tint); - } - - private int groundColorAt(double worldX, double worldZ, boolean showTexturePixels) { - double noise = ground.sample(worldX, worldZ); - return Double.isNaN(noise) ? PaletteLayerScale.ABSENT_COLOR : ground.blockColorAt(noise, worldX, worldZ, showTexturePixels); - } - - // A decorator places air to leave gaps, which looks the same as placing nothing. - private boolean[] resolveGroundShowingEntries() { - boolean[] showsGround = new boolean[blocks.size()]; - for (int entry = 0; entry < blocks.size(); entry++) { - NativeBlockState block = blocks.get(entry).getBlockData(data); - showsGround[entry] = ground != null && block != null && block.isAir(); - } - return showsGround; - } - - Entry entryForNoise(double noise) { - return entries.get(entryIndexForNoise(noise)); - } - - String biomeKey() { - return palette.biomeKey(); - } - - BiomePalette palette() { - return palette; - } - - int depth() { - return depth; - } - - int minThickness() { - return placement.minThickness(); - } - - int maxThickness() { - return placement.maxThickness(); - } - - double zoom() { - return placement.zoom(); - } - - List entries() { - return entries; - } - - long[] histogram() { - return histogram.clone(); - } - - private int entryIndexForNoise(double noise) { - return entryBySlot[PaletteSlots.slotForNoise(noise, entryBySlot.length)]; - } - - private BlockTexture[] resolveEntryTextures(BlockTextures textures) { - BlockTexture[] resolved = new BlockTexture[blocks.size()]; - if (textures == null) { - return resolved; - } - for (int entry = 0; entry < blocks.size(); entry++) { - NativeBlockState block = blocks.get(entry).getBlockData(data); - resolved[entry] = block == null ? null : textureOf(block, textures).orElse(null); - } - return resolved; - } - - private BlockTexture[] resolveUpperHalves(BlockTextures textures) { - BlockTexture[] resolved = new BlockTexture[blocks.size()]; - if (textures == null || palette.kind() != BiomePalette.Kind.DECORATOR) { - return resolved; - } - for (int entry = 0; entry < blocks.size(); entry++) { - NativeBlockState block = blocks.get(entry).getBlockData(data); - resolved[entry] = block == null ? null : textures.upperHalfIcon(block).orElse(null); - } - return resolved; - } - - // Tall plants are known by their top half, the way Minecraft draws them in the inventory. - private BlockTexture[] legendTextures() { - BlockTexture[] legend = textureByEntry.clone(); - for (int entry = 0; entry < legend.length; entry++) { - if (upperHalfByEntry[entry] != null) { - legend[entry] = upperHalfByEntry[entry]; - } - } - return legend; - } - - private Optional textureOf(NativeBlockState block, BlockTextures textures) { - return palette.kind() == BiomePalette.Kind.DECORATOR ? textures.iconTexture(block) : textures.topTexture(block); - } - - // The legend shows tinted blocks as they look at the world origin, where the statistics are sampled too. - private BlockTexture[] tintForLegend(BlockTexture[] textures) { - BlockTexture[] tinted = new BlockTexture[textures.length]; - for (int entry = 0; entry < textures.length; entry++) { - BlockTexture texture = textures[entry]; - tinted[entry] = texture == null || texture.biomeTint() == null - ? texture - : texture.tinted(biomeTints.colorAt(texture.biomeTint(), 0, 0)); - } - return tinted; - } - - // Blocks without a texture, like custom blocks or everything before the textures load, fall back to plain colours. - private int[] resolveLegendColors() { - List untexturedBlocks = new ArrayList<>(); - for (int entry = 0; entry < blocks.size(); entry++) { - NativeBlockState block = blocks.get(entry).getBlockData(data); - if (block != null && textureByEntry[entry] == null) { - untexturedBlocks.add(block); - } - } - Map mapColorsByBlock = BlockPreviewColors.colorsByBlock(untexturedBlocks); - int[] colors = new int[blocks.size()]; - for (int entry = 0; entry < blocks.size(); entry++) { - NativeBlockState block = blocks.get(entry).getBlockData(data); - if (block == null) { - colors[entry] = MISSING_BLOCK_COLOR; - } else if (legendTextureByEntry[entry] != null) { - colors[entry] = legendTextureByEntry[entry].averageColor(); - } else { - colors[entry] = mapColorsByBlock.get(block.key()); - } - } - return colors; - } - - private Statistics measure() { - long[] values = new long[HISTOGRAM_BINS]; - long[] samplesByEntry = new long[blocks.size()]; - long present = 0; - double origin = -STATISTICS_GRID_SIZE * STATISTICS_SPACING_BLOCKS / 2D; - for (int gridX = 0; gridX < STATISTICS_GRID_SIZE; gridX++) { - for (int gridZ = 0; gridZ < STATISTICS_GRID_SIZE; gridZ++) { - double noise = sample(origin + gridX * STATISTICS_SPACING_BLOCKS, origin + gridZ * STATISTICS_SPACING_BLOCKS); - if (Double.isNaN(noise)) { - continue; - } - present++; - values[Math.clamp((int) (noise * HISTOGRAM_BINS), 0, HISTOGRAM_BINS - 1)]++; - samplesByEntry[entryIndexForNoise(noise)]++; - } - } - double[] sharesByEntry = new double[samplesByEntry.length]; - for (int entry = 0; entry < samplesByEntry.length; entry++) { - sharesByEntry[entry] = present == 0 ? 0D : samplesByEntry[entry] / (double) present; - } - return new Statistics(values, sharesByEntry); - } - - private List describeEntries(double[] sharesByEntry) { - int slotCount = entryBySlot.length; - List described = new ArrayList<>(blocks.size()); - for (int entry = 0; entry < blocks.size(); entry++) { - IrisBlockData block = blocks.get(entry); - int firstSlot = firstSlotOf(entry); - int lastSlot = lastSlotOf(entry); - boolean placed = firstSlot >= 0; - described.add(new Entry( - block.getBlock(), - block.getWeight(), - block.getBlockData(data) != null, - legendColorByEntry[entry], - legendTextureByEntry[entry], - placed ? (lastSlot - firstSlot + 1) / (double) slotCount : 0D, - sharesByEntry[entry], - placed ? slotLowerBound(firstSlot, slotCount) : Double.NaN, - placed ? slotUpperBound(lastSlot, slotCount) : Double.NaN - )); - } - return List.copyOf(described); - } - - private int firstSlotOf(int entry) { - for (int slot = 0; slot < entryBySlot.length; slot++) { - if (entryBySlot[slot] == entry) { - return slot; - } - } - return -1; - } - - private int lastSlotOf(int entry) { - for (int slot = entryBySlot.length - 1; slot >= 0; slot--) { - if (entryBySlot[slot] == entry) { - return slot; - } - } - return -1; - } - - // Slots are picked by rounding, so the first and last slot only own half a step of the value range. - private static double slotLowerBound(int slot, int slotCount) { - return slot == 0 ? 0D : (slot - 0.5D) / (slotCount - 1); - } - - private static double slotUpperBound(int slot, int slotCount) { - return slot == slotCount - 1 ? 1D : (slot + 0.5D) / (slotCount - 1); - } - - record Entry(String block, int weight, boolean found, int color, BlockTexture texture, double weightShare, - double actualShare, double lowestNoise, double highestNoise) { - boolean isFarBelowWeight() { - return found && actualShare < weightShare / FAR_FROM_WEIGHT_FACTOR; - } - - boolean isFarAboveWeight() { - return found && actualShare > weightShare * FAR_FROM_WEIGHT_FACTOR; - } - } - - private record SampledBlock(int x, int z, double noise) { - } - - private record Statistics(long[] histogram, double[] sharesByEntry) { - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/PaletteLayerScale.java b/core/src/main/java/art/arcane/iris/studio/map/PaletteLayerScale.java deleted file mode 100644 index 76e94462e..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/PaletteLayerScale.java +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.awt.Color; - -final class PaletteLayerScale implements NoiseColorScale { - static final int ABSENT_COLOR = 0x161A24; - private static final double OVERLAY_DARKEST_SHADE = 0.3D; - - private final View view; - private final PaletteLayerPreview preview; - private final NoisePalette noisePalette; - private final boolean showTexturePixels; - - PaletteLayerScale(View view, PaletteLayerPreview preview, NoisePalette noisePalette, boolean showTexturePixels) { - this.view = view; - this.preview = preview; - this.noisePalette = noisePalette; - this.showTexturePixels = showTexturePixels; - } - - @Override - public int colorAt(double value, double worldX, double worldZ) { - if (view == View.NOISE) { - return noisePalette.colorFinite(value); - } - int blockColor = preview.blockColorAt(value, worldX, worldZ, showTexturePixels); - return view == View.BLOCKS ? blockColor : BlockPreviewColors.shade(blockColor, overlayShade(value)); - } - - @Override - public int colorFinite(double value) { - return switch (view) { - case BLOCKS -> preview.colorForNoise(value); - case NOISE -> noisePalette.colorFinite(value); - case BLOCKS_SHADED_BY_NOISE -> BlockPreviewColors.shade(preview.colorForNoise(value), overlayShade(value)); - }; - } - - @Override - public int colorInvalid() { - return ABSENT_COLOR; - } - - @Override - public int colorInvalidAt(double worldX, double worldZ) { - return view == View.NOISE ? ABSENT_COLOR : preview.bareColorAt(worldX, worldZ, showTexturePixels); - } - - @Override - public Color displayColorNormalized(double normalized) { - return new Color(colorFinite(minimum() + normalized * (maximum() - minimum()))); - } - - @Override - public String label() { - return view == View.NOISE ? noisePalette.label() : view.toString(); - } - - @Override - public double minimum() { - return view == View.NOISE ? noisePalette.minimum() : 0D; - } - - @Override - public double maximum() { - return view == View.NOISE ? noisePalette.maximum() : 1D; - } - - private static double overlayShade(double value) { - return OVERLAY_DARKEST_SHADE + (1D - OVERLAY_DARKEST_SHADE) * Math.clamp(value, 0D, 1D); - } - - enum View { - BLOCKS("Blocks"), - NOISE("Noise"), - BLOCKS_SHADED_BY_NOISE("Both"); - - private final String label; - - View(String label) { - this.label = label; - } - - @Override - public String toString() { - return label; - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/PaletteNavigator.java b/core/src/main/java/art/arcane/iris/studio/map/PaletteNavigator.java deleted file mode 100644 index 65aa42228..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/PaletteNavigator.java +++ /dev/null @@ -1,527 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.studio.map.PaletteCatalog.BiomeEntry; -import art.arcane.iris.studio.map.PaletteCatalog.BiomeGroup; -import art.arcane.iris.studio.map.PaletteCatalog.RegionEntry; -import art.arcane.iris.studio.map.PlayerLocationTracker.PlayerLocation; - -import javax.swing.BorderFactory; -import javax.swing.ButtonGroup; -import javax.swing.DefaultListCellRenderer; -import javax.swing.DefaultListModel; -import javax.swing.JLabel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.JToggleButton; -import javax.swing.JTree; -import javax.swing.ListSelectionModel; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import javax.swing.tree.DefaultMutableTreeNode; -import javax.swing.tree.DefaultTreeCellRenderer; -import javax.swing.tree.DefaultTreeModel; -import javax.swing.tree.TreePath; -import javax.swing.tree.TreeSelectionModel; -import java.awt.BorderLayout; -import java.awt.CardLayout; -import java.awt.Component; -import java.awt.GridLayout; -import java.awt.Rectangle; -import java.util.Enumeration; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Set; - - -final class PaletteNavigator extends JPanel { - private static final long serialVersionUID = -6402313718430917284L; - private static final String HERE_CARD = "here"; - private static final String OVERVIEW_CARD = "overview"; - private static final int MESSAGE_WRAP_WIDTH_PIXELS = 190; - - private final Listener listener; - private final CardLayout cards = new CardLayout(); - private final JPanel cardPanel = new JPanel(cards); - private final JLabel regionLabel = new JLabel(); - private final DefaultListModel hereRows = new DefaultListModel<>(); - private final JList hereList = new JList<>(hereRows); - private final JTextField searchField = new JTextField(); - private final DefaultTreeModel treeModel = new DefaultTreeModel(new DefaultMutableTreeNode()); - private final JTree overviewTree = new JTree(treeModel); - - private PaletteCatalog catalog; - private PlayerLocation location; - private BiomePalette selectedPalette; - private boolean updatingSelection; - private boolean untracked; - - PaletteNavigator(Listener listener) { - super(new BorderLayout()); - this.listener = listener; - cardPanel.add(buildHereCard(), HERE_CARD); - cardPanel.add(buildOverviewCard(), OVERVIEW_CARD); - add(buildTabBar(), BorderLayout.NORTH); - add(cardPanel, BorderLayout.CENTER); - refreshHere(); - } - - void showCatalog(PaletteCatalog nextCatalog) { - catalog = nextCatalog; - rebuildOverview(); - refreshHere(); - } - - void showLocation(PlayerLocation nextLocation) { - location = nextLocation; - refreshHere(); - } - - // Without a player there is nowhere to call "here", so the Here tab explains how to get one instead. - void showUntracked() { - untracked = true; - refreshHere(); - } - - void markSelected(BiomePalette palette) { - selectedPalette = palette; - updatingSelection = true; - try { - selectInHereList(); - selectInTree(); - } finally { - updatingSelection = false; - } - } - - private JPanel buildTabBar() { - JPanel bar = new JPanel(new GridLayout(1, 2, 0, 0)); - bar.setBorder(BorderFactory.createMatteBorder(0, 0, 1, 0, StudioTheme.SEPARATOR)); - ButtonGroup group = new ButtonGroup(); - JToggleButton here = createTab("Here", HERE_CARD, group); - JToggleButton overview = createTab("Overview", OVERVIEW_CARD, group); - bar.add(here); - bar.add(overview); - here.doClick(); - return bar; - } - - private JToggleButton createTab(String text, String card, ButtonGroup group) { - JToggleButton tab = StudioToolbar.tab(text); - tab.addActionListener(event -> cards.show(cardPanel, card)); - group.add(tab); - return tab; - } - - private JPanel buildHereCard() { - JPanel card = new JPanel(new BorderLayout()); - JPanel location = new JPanel(new GridLayout(0, 1, 0, StudioTheme.scale(3))); - location.setBorder(StudioTheme.emptyBorder(9, 12, 5, 12)); - location.add(regionLabel); - - hereList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - hereList.setCellRenderer(new HereRowRenderer()); - hereList.addListSelectionListener(event -> { - HereRow row = hereList.getSelectedValue(); - if (!event.getValueIsAdjusting() && !updatingSelection && row != null && row.biomeKey() != null) { - choose(row.biomeKey(), row.palette()); - } - }); - card.add(location, BorderLayout.NORTH); - card.add(StudioToolbar.scroll(hereList), BorderLayout.CENTER); - return card; - } - - private JPanel buildOverviewCard() { - JPanel card = new JPanel(new BorderLayout()); - StudioToolbar.makeSearchField(searchField, "Search biomes, snippets or blocks..."); - searchField.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void insertUpdate(DocumentEvent event) { - rebuildOverview(); - } - - @Override - public void removeUpdate(DocumentEvent event) { - rebuildOverview(); - } - - @Override - public void changedUpdate(DocumentEvent event) { - rebuildOverview(); - } - }); - - overviewTree.setRootVisible(false); - overviewTree.setShowsRootHandles(true); - overviewTree.setRowHeight(StudioTheme.scale(24)); - overviewTree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION); - overviewTree.setCellRenderer(new OverviewRenderer()); - overviewTree.addTreeSelectionListener(event -> { - if (!updatingSelection && nodeAt(event.getPath()) instanceof OverviewNode node && node.biomeKey() != null) { - choose(node.biomeKey(), node.palette()); - } - }); - card.add(StudioToolbar.padded(searchField, 8, 8, 8, 8), BorderLayout.NORTH); - card.add(StudioToolbar.scroll(overviewTree), BorderLayout.CENTER); - return card; - } - - // Choosing a biome rather than one of its palettes opens its first palette. - private void choose(String biomeKey, BiomePalette palette) { - BiomeEntry biome = catalog == null ? null : catalog.biome(biomeKey); - BiomePalette chosen = palette != null ? palette : biome == null ? null : biome.firstPalette(); - if (chosen != null) { - listener.onPaletteChosen(chosen); - } - } - - private void refreshHere() { - updatingSelection = true; - try { - hereRows.clear(); - if (untracked) { - showHereMessage("Run /iris std pal in-game to see the palettes where you stand."); - return; - } - if (location == null || catalog == null) { - showHereMessage("Finding where you are..."); - return; - } - switch (location.status()) { - case OFFLINE -> showHereMessage("You are offline."); - case IN_OTHER_WORLD -> showHereMessage("You left the world this window shows."); - case IN_REGION -> showHereRows(location); - } - selectInHereList(); - } finally { - updatingSelection = false; - } - } - - private void showHereMessage(String message) { - regionLabel.setText("" + message + ""); - } - - private void showHereRows(PlayerLocation here) { - RegionEntry region = catalog.region(here.regionKey()); - regionLabel.setText(labeled("Region", region == null ? here.regionKey() : region.name(), here.regionKey())); - addBiomePalettes("Surface biome here", here.surfaceBiomeKey()); - if (here.isBelowSurfaceBiome()) { - addBiomePalettes("Underground biome at your height", here.biomeAtPositionKey()); - } - if (region == null) { - return; - } - hereRows.addElement(HereRow.header("Biomes in this region")); - for (String biomeKey : region.allBiomeKeys()) { - addRegionBiome(biomeKey, 0, new HashSet<>(), here); - } - } - - private void addBiomePalettes(String title, String biomeKey) { - BiomeEntry biome = catalog.biome(biomeKey); - if (biome == null) { - return; - } - hereRows.addElement(HereRow.header(title)); - hereRows.addElement(HereRow.biome(biomeText(biome, childOfText(biome)), biomeKey, 0)); - addPaletteRows(biome, 0); - } - - private void addPaletteRows(BiomeEntry biome, int nesting) { - for (PaletteCatalog.PaletteSummary summary : biome.palettes()) { - hereRows.addElement(HereRow.palette(summary.text(), summary.palette(), nesting)); - } - } - - // Children sit under the biome they grow inside of, so a child biome is found where it actually appears. - private void addRegionBiome(String biomeKey, int nesting, Set ancestors, PlayerLocation here) { - BiomeEntry biome = catalog.biome(biomeKey); - if (biome == null || !ancestors.add(biomeKey)) { - return; - } - boolean standingHere = biomeKey.equals(here.surfaceBiomeKey()) || biomeKey.equals(here.biomeAtPositionKey()); - hereRows.addElement(HereRow.biome(biomeText(biome, standingHere ? "you are here" : null), biomeKey, nesting)); - addPaletteRows(biome, nesting); - for (String childKey : biome.childKeys()) { - addRegionBiome(childKey, nesting + 1, new HashSet<>(ancestors), here); - } - } - - private String childOfText(BiomeEntry biome) { - if (biome.parentKeys().isEmpty()) { - return null; - } - List parentNames = biome.parentKeys().stream() - .map(key -> catalog.biome(key) == null ? key : catalog.biome(key).name()) - .toList(); - return "child of " + String.join(", ", parentNames); - } - - private void rebuildOverview() { - if (catalog == null) { - return; - } - String filter = searchField.getText().trim().toLowerCase(Locale.ROOT); - DefaultMutableTreeNode root = new DefaultMutableTreeNode(); - for (RegionEntry region : catalog.regions()) { - boolean regionMatches = !filter.isEmpty() && region.name().toLowerCase(Locale.ROOT).contains(filter); - DefaultMutableTreeNode regionNode = new DefaultMutableTreeNode(new OverviewNode(region.name(), region.key(), null, null)); - for (BiomeGroup group : region.groups()) { - DefaultMutableTreeNode groupNode = new DefaultMutableTreeNode(); - for (String biomeKey : group.biomeKeys()) { - addBiomeNode(groupNode, biomeKey, regionMatches ? "" : filter, new HashSet<>()); - } - if (groupNode.getChildCount() > 0) { - groupNode.setUserObject(new OverviewNode(group.label(), groupNode.getChildCount() + " biomes", null, null)); - regionNode.add(groupNode); - } - } - if (regionNode.getChildCount() > 0) { - root.add(regionNode); - } - } - DefaultMutableTreeNode outside = new DefaultMutableTreeNode(); - for (String biomeKey : catalog.biomesOutsideRegions()) { - addBiomeNode(outside, biomeKey, filter, new HashSet<>()); - } - if (outside.getChildCount() > 0) { - outside.setUserObject(new OverviewNode("Not in any region", outside.getChildCount() + " biomes", null, null)); - root.add(outside); - } - addSnippetNodes(root, filter); - updatingSelection = true; - try { - treeModel.setRoot(root); - if (!filter.isEmpty()) { - expandDownToBiomes(root); - } - selectInTree(); - } finally { - updatingSelection = false; - } - } - - private void addBiomeNode(DefaultMutableTreeNode parent, String biomeKey, String filter, Set ancestors) { - BiomeEntry biome = catalog.biome(biomeKey); - if (biome == null || !ancestors.add(biomeKey)) { - return; - } - DefaultMutableTreeNode biomeNode = new DefaultMutableTreeNode(new OverviewNode(biome.name(), biomeKey, biomeKey, null)); - for (PaletteCatalog.PaletteSummary summary : biome.palettes()) { - biomeNode.add(new DefaultMutableTreeNode(new OverviewNode(summary.text(), null, biomeKey, summary.palette()))); - } - for (String childKey : biome.childKeys()) { - addBiomeNode(biomeNode, childKey, filter, new HashSet<>(ancestors)); - } - boolean hasMatchingChild = biomeNode.getChildCount() > biome.palettes().size(); - if (filter.isEmpty() || biome.matches(filter) || hasMatchingChild) { - parent.add(biomeNode); - } - } - - // Snippets sit below the regions, so a palette picked elsewhere is still found in its biome first. - private void addSnippetNodes(DefaultMutableTreeNode root, String filter) { - for (BiomePalette.SnippetFolder folder : BiomePalette.SnippetFolder.values()) { - DefaultMutableTreeNode folderNode = new DefaultMutableTreeNode(); - catalog.snippets().stream() - .filter(snippet -> snippet.folder() == folder && (filter.isEmpty() || snippet.matches(filter))) - .forEach(snippet -> folderNode.add(snippetNode(snippet))); - if (folderNode.getChildCount() > 0) { - folderNode.setUserObject(new OverviewNode(folder.label() + " snippets", folderNode.getChildCount() + " files", null, null)); - root.add(folderNode); - } - } - } - - // Picking a snippet opens it where the first biome using it places it; its children open the other uses. - private DefaultMutableTreeNode snippetNode(PaletteCatalog.SnippetEntry snippet) { - if (snippet.uses().isEmpty()) { - return new DefaultMutableTreeNode(new OverviewNode(snippet.path(), "not used by any biome", null, null)); - } - BiomePalette firstUse = snippet.uses().get(0); - String usedBy = snippet.uses().size() == 1 ? "used once" : "used " + snippet.uses().size() + " times"; - DefaultMutableTreeNode node = new DefaultMutableTreeNode(new OverviewNode(snippet.path() + " · " + snippet.blocks(), - usedBy, firstUse.biomeKey(), firstUse)); - for (BiomePalette use : snippet.uses()) { - BiomeEntry biome = catalog.biome(use.biomeKey()); - String biomeName = biome == null ? use.biomeKey() : biome.name(); - node.add(new DefaultMutableTreeNode(new OverviewNode(biomeName + " · " + use.lowercaseLabel(), use.biomeKey(), - use.biomeKey(), use))); - } - return node; - } - - private void expandDownToBiomes(DefaultMutableTreeNode root) { - Enumeration nodes = root.breadthFirstEnumeration(); - while (nodes.hasMoreElements()) { - DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodes.nextElement(); - if (node.getUserObject() instanceof OverviewNode overview && overview.biomeKey() != null) { - overviewTree.expandPath(new TreePath(((DefaultMutableTreeNode) node.getParent()).getPath())); - } - } - } - - private void selectInTree() { - if (selectedNodeShowsSelectedPalette()) { - return; - } - DefaultMutableTreeNode match = findLayerNode((DefaultMutableTreeNode) treeModel.getRoot()); - if (match == null) { - overviewTree.clearSelection(); - return; - } - TreePath path = new TreePath(match.getPath()); - overviewTree.setSelectionPath(path); - overviewTree.makeVisible(path); - Rectangle row = overviewTree.getPathBounds(path); - if (row != null) { - overviewTree.scrollRectToVisible(new Rectangle(0, row.y, 1, row.height)); - } - } - - // The same palette can be listed under its biome and under its snippet; the row the user picked stays picked. - private boolean selectedNodeShowsSelectedPalette() { - return nodeAt(overviewTree.getSelectionPath()) instanceof OverviewNode node - && node.palette() != null - && node.palette().equals(selectedPalette); - } - - private DefaultMutableTreeNode findLayerNode(DefaultMutableTreeNode root) { - Enumeration nodes = root.depthFirstEnumeration(); - while (nodes.hasMoreElements()) { - DefaultMutableTreeNode node = (DefaultMutableTreeNode) nodes.nextElement(); - if (node.getUserObject() instanceof OverviewNode overview - && overview.palette() != null - && overview.palette().equals(selectedPalette)) { - return node; - } - } - return null; - } - - private void selectInHereList() { - for (int index = 0; index < hereRows.size(); index++) { - HereRow row = hereRows.get(index); - if (row.palette() != null && row.palette().equals(selectedPalette)) { - hereList.setSelectedIndex(index); - return; - } - } - hereList.clearSelection(); - } - - private static Object nodeAt(TreePath path) { - return path == null ? null : ((DefaultMutableTreeNode) path.getLastPathComponent()).getUserObject(); - } - - private static String biomeText(BiomeEntry biome, String note) { - String noteText = note == null ? "" : " · " + escape(note); - return "" + escape(biome.name()) + noteText + " " + escape(biome.key()) - + ""; - } - - private static String labeled(String title, String name, String key) { - return "" + title + "  " + escape(name) - + " " + escape(key) + ""; - } - - private static String escape(String text) { - return text.replace("&", "&").replace("<", "<").replace(">", ">"); - } - - interface Listener { - void onPaletteChosen(BiomePalette palette); - } - - /** - * @param nesting how many parent biomes deep the row's biome sits - */ - private record HereRow(String text, String biomeKey, BiomePalette palette, int nesting, boolean header) { - private static HereRow header(String text) { - return new HereRow(text, null, null, 0, true); - } - - private static HereRow biome(String text, String biomeKey, int nesting) { - return new HereRow(text, biomeKey, null, nesting, false); - } - - private static HereRow palette(String text, BiomePalette palette, int nesting) { - return new HereRow(text, palette.biomeKey(), palette, nesting, false); - } - } - - private record OverviewNode(String label, String detail, String biomeKey, BiomePalette palette) { - private String html() { - if (detail == null) { - return escape(label); - } - return "" + escape(label) + " " + escape(detail) + ""; - } - } - - private static final class HereRowRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = 2785341117408251320L; - private static final int HEADER_INDENT = 11; - private static final int BIOME_INDENT = 20; - private static final int PALETTE_INDENT = 34; - private static final int CHILD_INDENT = 16; - - @Override - public Component getListCellRendererComponent(JList list, Object value, int index, boolean selected, boolean focus) { - HereRow row = (HereRow) value; - boolean selectable = row.biomeKey() != null; - super.getListCellRendererComponent(list, row.header() ? row.text().toUpperCase(Locale.ROOT) : row.text(), index, - selected && selectable, false); - setFont(row.header() ? StudioTheme.sectionFont() : StudioTheme.font()); - if (row.header()) { - setForeground(StudioTheme.MUTED_TEXT); - } - int indent = row.header() ? HEADER_INDENT - : (row.palette() != null ? PALETTE_INDENT : BIOME_INDENT) + row.nesting() * CHILD_INDENT; - setBorder(StudioTheme.emptyBorder(row.header() ? 11 : 4, indent, 4, 10)); - return this; - } - } - - private static final class OverviewRenderer extends DefaultTreeCellRenderer { - private static final long serialVersionUID = -1950176034017718227L; - - private OverviewRenderer() { - setLeafIcon(null); - setOpenIcon(null); - setClosedIcon(null); - } - - @Override - public Component getTreeCellRendererComponent(JTree tree, Object value, boolean selected, boolean expanded, - boolean leaf, int row, boolean focus) { - Object userObject = ((DefaultMutableTreeNode) value).getUserObject(); - String text = userObject instanceof OverviewNode node ? node.html() : ""; - super.getTreeCellRendererComponent(tree, text, selected, expanded, leaf, row, false); - boolean groupsOthers = userObject instanceof OverviewNode node && node.biomeKey() == null && !leaf; - setFont(groupsOthers ? StudioTheme.boldFont() : StudioTheme.font()); - return this; - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/PickInspectorPanel.java b/core/src/main/java/art/arcane/iris/studio/map/PickInspectorPanel.java deleted file mode 100644 index 1102b167e..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/PickInspectorPanel.java +++ /dev/null @@ -1,388 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.studio.map.components.PickDisplay; - -import javax.swing.BorderFactory; -import javax.swing.BoxLayout; -import javax.swing.ButtonGroup; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.Icon; -import javax.swing.JPanel; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.JToggleButton; -import javax.swing.SwingUtilities; -import javax.swing.UIManager; -import javax.swing.text.DefaultCaret; -import java.awt.BorderLayout; -import java.awt.CardLayout; -import java.awt.Color; -import java.awt.Cursor; -import java.awt.Dimension; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.GridLayout; -import java.awt.RenderingHints; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.EnumMap; -import java.util.HashSet; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.function.BooleanSupplier; -import java.util.function.Consumer; - -/** - * The inspector of the region and biome views: how noise picks the regions or biomes in view, measured against what - * is in view and put in words, with a switch for how the map draws the picks. What the user opens or closes stays so - * while the view is measured again. - */ -final class PickInspectorPanel extends JPanel { - private static final long serialVersionUID = -2874105263188240317L; - private static final String MESSAGE_CARD = "message"; - private static final String DETAILS_CARD = "details"; - private static final int PANEL_WIDTH = 330; - - private final JLabel title = new JLabel(); - private final JLabel detail = new JLabel(); - private final Map displayButtons = new EnumMap<>(PickDisplay.class); - private final CardLayout cards = new CardLayout(); - private final JPanel cardPanel = new JPanel(cards); - private final JTextArea message = wrappingText(); - private final JPanel details = new ViewportWidthPanel(); - private final JScrollPane detailsScroll = StudioToolbar.scroll(details); - private final Set expandedSectionKeys = new HashSet<>(); - private final Set fullTableKeys = new HashSet<>(); - private final String picksName; - private boolean sectionsChosenByUser; - private String shownDetailsTitle; - - /** - * @param picksName what the map shows when it draws the picks: "Regions" or "Biomes" - * @param onDisplayChosen receives how the map should draw the picks - */ - PickInspectorPanel(String picksName, Consumer onDisplayChosen) { - super(new BorderLayout()); - this.picksName = picksName; - setPreferredSize(StudioTheme.scaledSize(PANEL_WIDTH, 0)); - setBackground(StudioTheme.PANEL_BACKGROUND); - add(buildHeader(onDisplayChosen), BorderLayout.NORTH); - cardPanel.setOpaque(false); - cardPanel.add(buildMessageCard(), MESSAGE_CARD); - details.setLayout(new BoxLayout(details, BoxLayout.Y_AXIS)); - details.setBackground(StudioTheme.PANEL_BACKGROUND); - cardPanel.add(detailsScroll, DETAILS_CARD); - add(cardPanel, BorderLayout.CENTER); - showMeasuring(picksName); - } - - void selectDisplay(PickDisplay display) { - displayButtons.get(display).setSelected(true); - } - - void showMeasuring(String name) { - showHeader(name, "Measuring what is in view…"); - showMessage(""); - } - - void showRegionPicks(NoisePickSpread spread) { - showHeader("Regions", "Region noise, split by rarity"); - nameFirstDisplay("Regions"); - showDetails(List.of(noiseChart(spread, "Regions", "regions"))); - } - - void showBiomePicks(String regionName, List spreads) { - showHeader(regionName, "Biome noise, split by rarity"); - nameFirstDisplay("Biomes"); - showDetails(spreads.stream().map(spread -> (JComponent) noiseChart(spread, "Biomes", spread.title())).toList()); - } - - /** - * One collapsible section per region in view, each with how it picks its biomes. Until the user opens or closes - * one, only the first is open. - */ - void showRegionSections(String detailText, List

sections) { - showHeader(picksName, detailText); - nameFirstDisplay(picksName); - if (!sectionsChosenByUser) { - expandedSectionKeys.clear(); - sections.stream().findFirst().ifPresent(first -> expandedSectionKeys.add(first.key())); - } - List components = new ArrayList<>(); - for (Section section : sections) { - components.add(new SectionPanel(section, expandedSectionKeys.contains(section.key()))); - } - showDetails(components); - } - - /** - * A chart whose long table remembers, by this key, whether the user asked for all its rows. - */ - NoisePickChart noiseChart(NoisePickSpread spread, String optionNoun, String key) { - return new NoisePickChart(spread, optionNoun, fullTableKeys.contains(key), showsAll -> { - if (showsAll) { - fullTableKeys.add(key); - } else { - fullTableKeys.remove(key); - } - }); - } - - private JPanel buildHeader(Consumer onDisplayChosen) { - JPanel header = new JPanel(new GridLayout(0, 1, 0, StudioTheme.scale(6))); - header.setOpaque(false); - header.setBorder(BorderFactory.createCompoundBorder( - BorderFactory.createMatteBorder(0, 0, 1, 0, StudioTheme.SEPARATOR), - StudioTheme.emptyBorder(10, 16, 12, 16))); - title.setFont(StudioTheme.titleFont()); - detail.setFont(StudioTheme.smallFont()); - detail.setForeground(StudioTheme.MUTED_TEXT); - header.add(title); - header.add(detail); - header.add(sectionLabel("Show")); - header.add(buildDisplayButtons(onDisplayChosen)); - return header; - } - - private JPanel buildDisplayButtons(Consumer onDisplayChosen) { - JPanel row = new JPanel(new GridLayout(1, 0, StudioTheme.scale(4), 0)); - row.setOpaque(false); - ButtonGroup group = new ButtonGroup(); - for (PickDisplay display : PickDisplay.values()) { - JToggleButton button = new JToggleButton(displayName(display)); - button.setFocusable(false); - button.setSelected(display == PickDisplay.PICKS); - button.addActionListener(event -> onDisplayChosen.accept(display)); - group.add(button); - row.add(button); - displayButtons.put(display, button); - } - return row; - } - - private String displayName(PickDisplay display) { - return switch (display) { - case PICKS -> picksName; - case NOISE -> "Noise"; - case BOTH -> "Both"; - }; - } - - private void nameFirstDisplay(String name) { - displayButtons.get(PickDisplay.PICKS).setText(name); - } - - private JPanel buildMessageCard() { - JPanel card = new JPanel(new BorderLayout()); - card.setOpaque(false); - message.setBorder(StudioTheme.emptyBorder(12, 16, 12, 16)); - card.add(message, BorderLayout.NORTH); - return card; - } - - private void showHeader(String name, String detailText) { - title.setText(name); - detail.setText(detailText); - } - - private void rememberSectionExpanded(String key, boolean expanded) { - sectionsChosenByUser = true; - if (expanded) { - expandedSectionKeys.add(key); - } else { - expandedSectionKeys.remove(key); - } - } - - private void showMessage(String text) { - message.setText(text); - cards.show(cardPanel, MESSAGE_CARD); - } - - // Measuring the same subject again keeps the scroll position, so panning the map doesn't jump the list. - private void showDetails(List charts) { - boolean sameSubject = Objects.equals(title.getText(), shownDetailsTitle); - int scrollPosition = sameSubject ? detailsScroll.getVerticalScrollBar().getValue() : 0; - shownDetailsTitle = title.getText(); - details.removeAll(); - charts.forEach(details::add); - details.revalidate(); - details.repaint(); - cards.show(cardPanel, DETAILS_CARD); - SwingUtilities.invokeLater(() -> detailsScroll.getVerticalScrollBar().setValue(scrollPosition)); - } - - private static JLabel sectionLabel(String text) { - JLabel label = new JLabel(text.toUpperCase(Locale.ROOT)); - label.setForeground(StudioTheme.MUTED_TEXT); - label.setFont(StudioTheme.sectionFont()); - return label; - } - - private static JTextArea wrappingText() { - JTextArea text = new JTextArea(); - text.setEditable(false); - text.setFocusable(false); - text.setOpaque(false); - ((DefaultCaret) text.getCaret()).setUpdatePolicy(DefaultCaret.NEVER_UPDATE); - text.setLineWrap(true); - text.setWrapStyleWord(true); - text.setFont(StudioTheme.font()); - text.setForeground(StudioTheme.SECONDARY_TEXT); - return text; - } - - /** - * One region of the biome view's inspector. - * - * @param share how much of the view the region covers - * @param summary what the closed section says about its content, like "7 biomes" - */ - record Section(String key, String name, int color, double share, String summary, List charts) { - } - - /** - * A region's header, which opens and closes the charts below it. - */ - private final class SectionPanel extends JPanel { - private static final long serialVersionUID = 2318546098861530717L; - - private final JPanel body = new JPanel(); - - private SectionPanel(Section section, boolean expanded) { - setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); - setOpaque(false); - setAlignmentX(LEFT_ALIGNMENT); - body.setLayout(new BoxLayout(body, BoxLayout.Y_AXIS)); - body.setOpaque(false); - body.setAlignmentX(LEFT_ALIGNMENT); - section.charts().forEach(body::add); - body.setVisible(expanded); - add(new SectionHeader(section, body::isVisible, () -> toggle(section))); - add(body); - } - - private void toggle(Section section) { - body.setVisible(!body.isVisible()); - rememberSectionExpanded(section.key(), body.isVisible()); - revalidate(); - repaint(); - } - } - - /** - * A region's name in its colour behind an open or closed chevron, with what it holds and how much of the view it - * covers; clicking it opens or closes the region. - */ - private static final class SectionHeader extends JComponent { - private static final long serialVersionUID = -4730226930154581123L; - private static final int HEIGHT = 32; - private static final int MARGIN = 16; - private static final int CHEVRON_WIDTH = 16; - // The chevron icon's glyph sits in its middle, with this much empty space either side. - private static final int CHEVRON_GLYPH_INSET = 4; - private static final int SWATCH_SIZE = 12; - private static final int SWATCH_GAP = 8; - private static final int SUMMARY_GAP = 8; - - private final Section section; - private final BooleanSupplier expanded; - - private SectionHeader(Section section, BooleanSupplier expanded, Runnable onToggle) { - this.section = section; - this.expanded = expanded; - setAlignmentX(LEFT_ALIGNMENT); - setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR)); - addMouseListener(new MouseAdapter() { - @Override - public void mouseClicked(MouseEvent event) { - onToggle.run(); - repaint(); - } - }); - } - - @Override - public Dimension getPreferredSize() { - return StudioTheme.scaledSize(PANEL_WIDTH, HEIGHT); - } - - @Override - public Dimension getMaximumSize() { - return new Dimension(Integer.MAX_VALUE, getPreferredSize().height); - } - - @Override - protected void paintComponent(Graphics graphics) { - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - canvas.setColor(StudioTheme.SEPARATOR); - canvas.fillRect(0, 0, getWidth(), 1); - int left = StudioTheme.scale(MARGIN - CHEVRON_GLYPH_INSET); - paintChevron(canvas, left); - left += StudioTheme.scale(CHEVRON_WIDTH - CHEVRON_GLYPH_INSET + SWATCH_GAP); - int swatch = StudioTheme.scale(SWATCH_SIZE); - canvas.setColor(new Color(section.color())); - int arc = StudioTheme.scale(4); - canvas.fillRoundRect(left, (getHeight() - swatch) / 2, swatch, swatch, arc, arc); - left += swatch + StudioTheme.scale(SWATCH_GAP); - - canvas.setFont(StudioTheme.smallFont()); - FontMetrics small = canvas.getFontMetrics(); - String share = NoisePickChart.percent(section.share()); - int shareLeft = getWidth() - StudioTheme.scale(MARGIN) - small.stringWidth(share); - canvas.setFont(StudioTheme.boldFont()); - FontMetrics bold = canvas.getFontMetrics(); - int baseline = (getHeight() + bold.getAscent() - bold.getDescent()) / 2; - canvas.setColor(StudioTheme.TEXT); - canvas.drawString(section.name(), left, baseline); - left += bold.stringWidth(section.name()) + StudioTheme.scale(SUMMARY_GAP); - - canvas.setFont(StudioTheme.smallFont()); - canvas.setColor(StudioTheme.MUTED_TEXT); - if (section.summary() != null && left + small.stringWidth(section.summary()) < shareLeft - StudioTheme.scale(SUMMARY_GAP)) { - canvas.drawString(section.summary(), left, baseline); - } - canvas.setColor(StudioTheme.SECONDARY_TEXT); - canvas.drawString(share, shareLeft, baseline); - } finally { - canvas.dispose(); - } - } - - private void paintChevron(Graphics2D canvas, int left) { - Icon chevron = UIManager.getIcon(expanded.getAsBoolean() ? "Tree.expandedIcon" : "Tree.collapsedIcon"); - if (chevron == null) { - return; - } - chevron.paintIcon(this, canvas, left + (StudioTheme.scale(CHEVRON_WIDTH) - chevron.getIconWidth()) / 2, - (getHeight() - chevron.getIconHeight()) / 2); - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/PicturePatch.java b/core/src/main/java/art/arcane/iris/studio/map/PicturePatch.java deleted file mode 100644 index 600c03d55..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/PicturePatch.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.awt.Rectangle; -import java.awt.image.BufferedImage; - -/** - * Part of a drawn view that Swing paints, at its place in the view. - */ -record PicturePatch(int x, int y, BufferedImage image) { - Rectangle bounds() { - return new Rectangle(x, y, image.getWidth(), image.getHeight()); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/PlayerLocationTracker.java b/core/src/main/java/art/arcane/iris/studio/map/PlayerLocationTracker.java deleted file mode 100644 index 2e3bdbfa2..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/PlayerLocationTracker.java +++ /dev/null @@ -1,141 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.generation.biome.IrisBiome; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.generation.terrain.IrisRegion; -import art.arcane.iris.studio.view.GuiOverlay; -import art.arcane.iris.studio.view.OpenerPosition; - -import javax.swing.Timer; -import java.awt.EventQueue; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Supplier; - -/** - * Follows the region and biomes where the player who opened the map stands. - */ -final class PlayerLocationTracker { - private static final int CHECK_INTERVAL_MILLIS = 500; - - private final Supplier engine; - private final GuiOverlay overlay; - private final Listener listener; - private final Timer timer; - private final ExecutorService lookups = Executors.newSingleThreadExecutor(runnable -> { - Thread thread = new Thread(runnable, "Iris Map Player Location"); - thread.setDaemon(true); - return thread; - }); - private final AtomicBoolean checkQueued = new AtomicBoolean(); - private volatile PlayerLocation lastLocation; - - private PlayerLocationTracker(Supplier engine, GuiOverlay overlay, Listener listener) { - this.engine = engine; - this.overlay = overlay; - this.listener = listener; - this.timer = new Timer(CHECK_INTERVAL_MILLIS, event -> queueCheck()); - MapHost.interruptOnPluginShutdown(lookups); - } - - static PlayerLocationTracker follow(Supplier engine, GuiOverlay overlay, Listener listener) { - PlayerLocationTracker tracker = new PlayerLocationTracker(engine, overlay, listener); - if (overlay == null) { - EventQueue.invokeLater(() -> listener.onLocationChanged(PlayerLocation.OFFLINE)); - return tracker; - } - tracker.timer.setInitialDelay(0); - tracker.timer.start(); - return tracker; - } - - void stop() { - timer.stop(); - lookups.shutdownNow(); - } - - private void queueCheck() { - if (!checkQueued.compareAndSet(false, true)) { - return; - } - overlay.requestOpenerPosition(position -> { - try { - lookups.execute(() -> publish(locate(position))); - } catch (RuntimeException rejected) { - checkQueued.set(false); - } - }); - } - - private void publish(PlayerLocation location) { - checkQueued.set(false); - if (location.equals(lastLocation)) { - return; - } - lastLocation = location; - EventQueue.invokeLater(() -> listener.onLocationChanged(location)); - } - - private PlayerLocation locate(OpenerPosition position) { - if (position.status() == OpenerPosition.Status.OFFLINE) { - return PlayerLocation.OFFLINE; - } - Engine current = engine.get(); - if (position.status() == OpenerPosition.Status.IN_OTHER_WORLD || current == null || current.isClosed()) { - return PlayerLocation.IN_OTHER_WORLD; - } - int blockX = (int) Math.floor(position.x()); - int blockY = (int) Math.floor(position.y()); - int blockZ = (int) Math.floor(position.z()); - IrisRegion region = current.getRegion(blockX, blockZ); - String surfaceBiome = keyOf(current.getSurfaceBiome(blockX, blockZ)); - String biomeAtPosition = keyOf(current.getBiomeOrMantle(blockX, blockY - current.getMinHeight(), blockZ)); - if (region == null || region.getLoadKey() == null || surfaceBiome == null) { - return PlayerLocation.IN_OTHER_WORLD; - } - return new PlayerLocation(Status.IN_REGION, region.getLoadKey(), surfaceBiome, biomeAtPosition); - } - - private static String keyOf(IrisBiome biome) { - return biome == null ? null : biome.getLoadKey(); - } - - enum Status { - OFFLINE, - IN_OTHER_WORLD, - IN_REGION - } - - // Biomes are 3D: underground, the biome at the player's position can differ from the surface biome above it. - record PlayerLocation(Status status, String regionKey, String surfaceBiomeKey, String biomeAtPositionKey) { - static final PlayerLocation OFFLINE = new PlayerLocation(Status.OFFLINE, null, null, null); - static final PlayerLocation IN_OTHER_WORLD = new PlayerLocation(Status.IN_OTHER_WORLD, null, null, null); - - boolean isBelowSurfaceBiome() { - return biomeAtPositionKey != null && !biomeAtPositionKey.equals(surfaceBiomeKey); - } - } - - interface Listener { - void onLocationChanged(PlayerLocation location); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/PlayerMarker.java b/core/src/main/java/art/arcane/iris/studio/map/PlayerMarker.java deleted file mode 100644 index d8e6d31ff..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/PlayerMarker.java +++ /dev/null @@ -1,123 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.studio.view.GuiMarker; - -import java.awt.BasicStroke; -import java.awt.Color; -import java.awt.FontMetrics; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.geom.AffineTransform; -import java.awt.geom.Path2D; -import java.awt.geom.RoundRectangle2D; - -/** - * A player on the map: an arrow pointing the way they look, like a minimap's, with their name in a pill above it. - * Blue with a white edge and a soft shadow, so it stands out on grass, sand and water alike. - */ -final class PlayerMarker { - private static final Color ARROW_FILL = StudioTheme.ACCENT; - private static final Color ARROW_EDGE = Color.WHITE; - private static final Color ARROW_OUTLINE = new Color(0, 0, 0, 150); - private static final Color SHADOW = new Color(0, 0, 0, 90); - private static final double ARROW_HALF_LENGTH = 9.5D; - private static final double ARROW_HALF_WIDTH = 7.5D; - private static final double ARROW_NOTCH = 3.5D; - private static final double ARROW_EDGE_WIDTH = 1.75D; - private static final double ARROW_OUTLINE_WIDTH = 1D; - private static final double SHADOW_OFFSET = 1.5D; - private static final int LABEL_GAP = 5; - private static final int LABEL_PADDING_X = 6; - private static final int LABEL_PADDING_Y = 1; - private static final double MINECRAFT_YAW_TO_SCREEN_DEGREES = 180D; - - private PlayerMarker() { - } - - static void paint(Graphics2D graphics, int screenX, int screenY, GuiMarker player) { - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - canvas.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); - canvas.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); - paintArrow(canvas, screenX, screenY, player.yaw()); - paintLabel(canvas, screenX, screenY, player.label()); - } finally { - canvas.dispose(); - } - } - - private static void paintArrow(Graphics2D canvas, int screenX, int screenY, float yaw) { - Path2D arrow = arrowFacing(yaw); - canvas.setColor(SHADOW); - canvas.fill(AffineTransform.getTranslateInstance(screenX, screenY + StudioTheme.scale(SHADOW_OFFSET)).createTransformedShape(arrow)); - Path2D placed = (Path2D) arrow.clone(); - placed.transform(AffineTransform.getTranslateInstance(screenX, screenY)); - // Strokes are centred on the outline, so each ring is drawn twice its width and the next one covers its inner half. - drawRing(canvas, placed, ARROW_OUTLINE, ARROW_EDGE_WIDTH + ARROW_OUTLINE_WIDTH); - drawRing(canvas, placed, ARROW_EDGE, ARROW_EDGE_WIDTH); - canvas.setColor(ARROW_FILL); - canvas.fill(placed); - } - - private static void drawRing(Graphics2D canvas, Path2D arrow, Color color, double width) { - canvas.setStroke(new BasicStroke((float) StudioTheme.scale(width * 2D), BasicStroke.CAP_ROUND, BasicStroke.JOIN_ROUND)); - canvas.setColor(color); - canvas.draw(arrow); - } - - /** - * The arrow around the origin. Minecraft's yaw 0 faces south, which is down on the map, while the arrow is drawn - * pointing up, so it turns half a circle further than the yaw. - */ - private static Path2D arrowFacing(float yaw) { - double length = StudioTheme.scale(ARROW_HALF_LENGTH); - double width = StudioTheme.scale(ARROW_HALF_WIDTH); - double notch = StudioTheme.scale(ARROW_NOTCH); - Path2D arrow = new Path2D.Double(); - arrow.moveTo(0D, -length); - arrow.lineTo(width, length); - arrow.lineTo(0D, length - notch); - arrow.lineTo(-width, length); - arrow.closePath(); - arrow.transform(AffineTransform.getRotateInstance(Math.toRadians(yaw + MINECRAFT_YAW_TO_SCREEN_DEGREES))); - return arrow; - } - - private static void paintLabel(Graphics2D canvas, int screenX, int screenY, String name) { - canvas.setFont(StudioTheme.smallFont()); - FontMetrics metrics = canvas.getFontMetrics(); - int width = metrics.stringWidth(name) + StudioTheme.scale(LABEL_PADDING_X) * 2; - int height = metrics.getHeight() + StudioTheme.scale(LABEL_PADDING_Y) * 2; - int left = screenX - width / 2; - double arrowReach = ARROW_HALF_LENGTH + ARROW_EDGE_WIDTH + ARROW_OUTLINE_WIDTH; - int bottom = screenY - (int) Math.ceil(StudioTheme.scale(arrowReach)) - StudioTheme.scale(LABEL_GAP); - int top = bottom - height; - RoundRectangle2D pill = new RoundRectangle2D.Double(left + 0.5D, top + 0.5D, width - 1D, height - 1D, height, height); - canvas.setColor(StudioTheme.OVERLAY_BACKGROUND); - canvas.fill(pill); - canvas.setStroke(new BasicStroke(1F)); - canvas.setColor(StudioTheme.OVERLAY_BORDER); - canvas.draw(pill); - canvas.setColor(StudioTheme.TEXT); - canvas.drawString(name, left + StudioTheme.scale(LABEL_PADDING_X), top + StudioTheme.scale(LABEL_PADDING_Y) + metrics.getAscent()); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/RegionExplorer.java b/core/src/main/java/art/arcane/iris/studio/map/RegionExplorer.java deleted file mode 100644 index b72707c3d..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/RegionExplorer.java +++ /dev/null @@ -1,185 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.studio.map.PickMeasuring.TypedSpread; -import art.arcane.iris.studio.map.RegionNavigator.RegionRow; -import art.arcane.iris.studio.map.components.PickDisplay; -import art.arcane.iris.generation.runtime.IrisComplex; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.generation.terrain.InferredType; -import art.arcane.iris.generation.terrain.IrisRegion; - -import java.util.ArrayList; -import java.util.List; -import java.util.Objects; -import java.util.function.Consumer; -import java.util.function.Supplier; - -/** - * The region view's explorer: shows how the region noise picks the regions, and for a chosen region fills the map with - * its biomes and shows how they are picked, measured against what is in view. - */ -final class RegionExplorer { - private final Supplier engineSource; - private final Consumer onPreviewChanged; - private final RegionNavigator navigator = new RegionNavigator(this::choose); - private final PickInspectorPanel inspector; - private final LatestMeasurement measurer = new LatestMeasurement<>("Iris Region Explorer"); - private String chosenRegionKey; - private MapCensus.ViewArea latestArea; - private MapCensus.ViewArea measuredArea; - - /** - * @param onPreviewChanged receives the region to fill the map with, or null to show every region again - * @param onDisplayChosen receives how the map should draw the picks - */ - RegionExplorer(Supplier engineSource, Consumer onPreviewChanged, Consumer onDisplayChosen) { - this.engineSource = engineSource; - this.onPreviewChanged = onPreviewChanged; - this.inspector = new PickInspectorPanel("Regions", onDisplayChosen); - } - - RegionNavigator navigator() { - return navigator; - } - - PickInspectorPanel inspector() { - return inspector; - } - - void loadRegions() { - Engine engine = engineSource.get(); - if (engine == null || engine.getComplex() == null) { - return; - } - List rows = new ArrayList<>(); - for (IrisRegion region : engine.getComplex().noisePickedRegions()) { - rows.add(new RegionRow(region.getLoadKey(), region.getName(), PickMeasuring.regionColor(engine, region))); - } - navigator.showRegions(rows); - } - - /** - * Measures the regions, or the chosen region's biomes, against this area, unless that was already done. - */ - void measure(MapCensus.ViewArea area) { - latestArea = area; - if (area == null || area.equals(measuredArea)) { - return; - } - measuredArea = area; - String regionKey = chosenRegionKey; - measurer.measure(() -> measurePicks(regionKey, area), this::show); - } - - /** - * The pack changed, so the regions and their biomes are read again. - */ - void refresh() { - loadRegions(); - measuredArea = null; - measure(latestArea); - } - - void close() { - measurer.close(); - } - - private void choose(String regionKey) { - chosenRegionKey = regionKey; - measuredArea = null; - measurer.discardPending(); - onPreviewChanged.accept(regionKey); - inspector.showMeasuring(regionKey == null ? "Regions" : regionName(regionKey)); - measure(latestArea); - } - - private String regionName(String regionKey) { - Engine engine = engineSource.get(); - IrisRegion region = engine == null ? null : engine.getData().getRegionLoader().load(regionKey); - return region == null ? regionKey : region.getName(); - } - - private void show(Measurement measurement) { - if (!Objects.equals(measurement.regionKey(), chosenRegionKey)) { - return; - } - switch (measurement) { - case RegionPicks picks -> inspector.showRegionPicks(picks.spread()); - case BiomePicks picks -> inspector.showBiomePicks(picks.regionName(), picks.spreads()); - } - } - - private Measurement measurePicks(String regionKey, MapCensus.ViewArea area) { - Engine engine = engineSource.get(); - IrisComplex complex = engine == null ? null : engine.getComplex(); - if (complex == null) { - return null; - } - if (regionKey == null) { - return measureRegionPicks(engine, complex, area); - } - IrisRegion region = engine.getData().getRegionLoader().load(regionKey); - if (region == null) { - return null; - } - return measureBiomePicks(engine, complex, region, area); - } - - private static RegionPicks measureRegionPicks(Engine engine, IrisComplex complex, MapCensus.ViewArea area) { - List options = complex.noisePickedRegions().stream() - .map(region -> PickMeasuring.regionOption(engine, region)) - .toList(); - NoisePickSpread spread = NoisePickSpread.of("Region noise in view", options); - PickMeasuring.forEachSample(area, (x, z) -> spread.add(complex.getRegionStyleStream().get(x, z))); - return new RegionPicks(spread); - } - - // The preview treats every spot as part of the region, so each spot's biome list is the one its surface needs. - private static BiomePicks measureBiomePicks(Engine engine, IrisComplex complex, IrisRegion region, MapCensus.ViewArea area) { - List spreads = PickMeasuring.biomeSpreads(engine, complex, region); - PickMeasuring.forEachSample(area, (x, z) -> { - InferredType type = complex.surfacePickAsIfIn(region, x, z).type(); - spreads.stream() - .filter(typed -> typed.type() == type) - .findFirst() - .ifPresent(typed -> typed.spread().add(complex.biomePickNoise(region, type, x, z))); - }); - List plainSpreads = spreads.stream().map(TypedSpread::spread).toList(); - return new BiomePicks(region.getLoadKey(), region.getName(), plainSpreads); - } - - /** - * What was measured for the region view; the region key is null when every region was measured. - */ - private sealed interface Measurement permits RegionPicks, BiomePicks { - String regionKey(); - } - - private record RegionPicks(NoisePickSpread spread) implements Measurement { - @Override - public String regionKey() { - return null; - } - } - - private record BiomePicks(String regionKey, String regionName, List spreads) implements Measurement { - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/RegionNavigator.java b/core/src/main/java/art/arcane/iris/studio/map/RegionNavigator.java deleted file mode 100644 index 3780dc95a..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/RegionNavigator.java +++ /dev/null @@ -1,173 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import javax.swing.DefaultListCellRenderer; -import javax.swing.DefaultListModel; -import javax.swing.JList; -import javax.swing.JPanel; -import javax.swing.JTextField; -import javax.swing.ListSelectionModel; -import javax.swing.event.DocumentEvent; -import javax.swing.event.DocumentListener; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Component; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.util.List; -import java.util.Locale; -import java.util.Objects; -import java.util.function.Consumer; - -/** - * The region view's sidebar: every region of the pack, or all of them at once, to fill the map with. - */ -final class RegionNavigator extends JPanel { - private static final long serialVersionUID = 3150735486722101466L; - private static final RegionRow ALL_REGIONS = new RegionRow(null, "All regions", -1); - private static final int ROW_HEIGHT = 24; - private static final int SWATCH_SIZE = 12; - private static final int SWATCH_GAP = 8; - private static final int ROW_PADDING = 10; - - private final Consumer onRegionChosen; - private final JTextField searchField = new JTextField(); - private final DefaultListModel rows = new DefaultListModel<>(); - private final JList list = new JList<>(rows); - private List regions = List.of(); - private String chosenKey; - private boolean updatingRows; - - /** - * @param onRegionChosen receives the chosen region's key, or null for all regions - */ - RegionNavigator(Consumer onRegionChosen) { - super(new BorderLayout()); - this.onRegionChosen = onRegionChosen; - StudioToolbar.makeSearchField(searchField, "Search regions..."); - searchField.getDocument().addDocumentListener(new DocumentListener() { - @Override - public void insertUpdate(DocumentEvent event) { - showMatchingRows(); - } - - @Override - public void removeUpdate(DocumentEvent event) { - showMatchingRows(); - } - - @Override - public void changedUpdate(DocumentEvent event) { - showMatchingRows(); - } - }); - list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - list.setFixedCellHeight(StudioTheme.scale(ROW_HEIGHT)); - list.setCellRenderer(new RegionRowRenderer()); - list.addListSelectionListener(event -> { - RegionRow row = list.getSelectedValue(); - if (!event.getValueIsAdjusting() && !updatingRows && row != null && !Objects.equals(row.key(), chosenKey)) { - chosenKey = row.key(); - onRegionChosen.accept(chosenKey); - } - }); - add(StudioToolbar.padded(searchField, 8, 8, 8, 8), BorderLayout.NORTH); - add(StudioToolbar.scroll(list), BorderLayout.CENTER); - showMatchingRows(); - } - - void showRegions(List nextRegions) { - regions = List.copyOf(nextRegions); - showMatchingRows(); - } - - private void showMatchingRows() { - String filter = searchField.getText().trim().toLowerCase(Locale.ROOT); - updatingRows = true; - try { - rows.clear(); - rows.addElement(ALL_REGIONS); - for (RegionRow region : regions) { - if (filter.isEmpty() || region.name().toLowerCase(Locale.ROOT).contains(filter) - || region.key().toLowerCase(Locale.ROOT).contains(filter)) { - rows.addElement(region); - } - } - selectChosenRow(); - } finally { - updatingRows = false; - } - } - - private void selectChosenRow() { - for (int index = 0; index < rows.size(); index++) { - if (Objects.equals(rows.get(index).key(), chosenKey)) { - list.setSelectedIndex(index); - return; - } - } - list.clearSelection(); - } - - /** - * @param color the region's map colour, or -1 for the all regions row - */ - record RegionRow(String key, String name, int color) { - } - - private static final class RegionRowRenderer extends DefaultListCellRenderer { - private static final long serialVersionUID = -6114522950207432516L; - private Color swatch; - - @Override - public Component getListCellRendererComponent(JList owner, Object value, int index, boolean selected, boolean focused) { - RegionRow row = (RegionRow) value; - super.getListCellRendererComponent(owner, row.name(), index, selected, false); - setFont(row.key() == null ? StudioTheme.boldFont() : StudioTheme.font()); - setBorder(StudioTheme.emptyBorder(0, ROW_PADDING + SWATCH_SIZE + SWATCH_GAP, 0, ROW_PADDING)); - setToolTipText(row.key()); - swatch = row.color() < 0 ? null : new Color(row.color()); - return this; - } - - @Override - protected void paintComponent(Graphics graphics) { - super.paintComponent(graphics); - if (swatch == null) { - return; - } - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - int size = StudioTheme.scale(SWATCH_SIZE); - int x = StudioTheme.scale(ROW_PADDING); - int y = (getHeight() - size) / 2; - int arc = StudioTheme.scale(4); - canvas.setColor(swatch); - canvas.fillRoundRect(x, y, size, size, arc, arc); - canvas.setColor(StudioTheme.CONTROL_BORDER); - canvas.drawRoundRect(x, y, size - 1, size - 1, arc, arc); - } finally { - canvas.dispose(); - } - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/ResourceUsage.java b/core/src/main/java/art/arcane/iris/studio/map/ResourceUsage.java deleted file mode 100644 index 7fe7f9124..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/ResourceUsage.java +++ /dev/null @@ -1,134 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import com.formdev.flatlaf.extras.FlatSVGIcon; - -import javax.swing.BoxLayout; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.Timer; -import java.awt.Color; -import java.awt.Dimension; -import java.lang.management.ManagementFactory; -import java.lang.management.OperatingSystemMXBean; -import java.util.Locale; - -/** - * The server's CPU and Java memory use, refreshed every second. The map runs inside the server, so heavy views show - * up here. CPU counts like {@code top}: 100% is one thread kept busy. - */ -final class ResourceUsage extends JPanel { - private static final long serialVersionUID = -6203817540921165472L; - private static final int REFRESH_MILLIS = 1000; - private static final double HIGH_USAGE = 0.8D; - private static final double BYTES_PER_GIGABYTE = 1024D * 1024D * 1024D; - private static final int THREADS = Runtime.getRuntime().availableProcessors(); - - private final Timer refresher = new Timer(REFRESH_MILLIS, event -> refresh()); - private final OperatingSystemMXBean system = ManagementFactory.getOperatingSystemMXBean(); - private final Reading cpu = new Reading("iris/icons/lightning.svg", THREADS * 100 + "%", - "Server CPU, 100% per busy thread, " + THREADS + " threads in all"); - private final Reading memory = new Reading("iris/icons/memory.svg", "99.9 / 99.9 GB", "Java memory the server uses, of its maximum"); - - ResourceUsage() { - setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); - setOpaque(false); - setBorder(StudioTheme.emptyBorder(0, 6, 0, 10)); - add(cpu); - add(memory); - refresh(); - } - - void start() { - refresher.start(); - } - - void stop() { - refresher.stop(); - } - - @Override - public Dimension getMaximumSize() { - return getPreferredSize(); - } - - private void refresh() { - double cpuLoad = processCpuLoad(); - cpu.show(cpuLoad < 0D ? "–" : String.format(Locale.ROOT, "%d%%", Math.round(cpuLoad * THREADS * 100D)), cpuLoad >= HIGH_USAGE); - Runtime runtime = Runtime.getRuntime(); - long usedBytes = runtime.totalMemory() - runtime.freeMemory(); - long maximumBytes = runtime.maxMemory(); - memory.show(String.format(Locale.ROOT, "%.1f / %.1f GB", usedBytes / BYTES_PER_GIGABYTE, maximumBytes / BYTES_PER_GIGABYTE), - usedBytes >= maximumBytes * HIGH_USAGE); - } - - // The share of every core the server uses; below zero when the JVM cannot tell, which only HotSpot's own bean can. - private double processCpuLoad() { - return system instanceof com.sun.management.OperatingSystemMXBean hotspot ? hotspot.getProcessCpuLoad() : -1D; - } - - /** - * One reading with its icon, as wide as its widest value so the toolbar holds still. - */ - private static final class Reading extends JLabel { - private static final long serialVersionUID = 7712069348214552014L; - private static final int ICON_SIZE = 16; - private static final int ICON_GAP = 4; - private static final int READING_GAP = 12; - - private final String widestValue; - private boolean high; - - private Reading(String iconPath, String widestValue, String tooltip) { - this.widestValue = widestValue; - FlatSVGIcon icon = new FlatSVGIcon(iconPath, ICON_SIZE, ICON_SIZE, ResourceUsage.class.getClassLoader()); - icon.setColorFilter(new FlatSVGIcon.ColorFilter(drawn -> color())); - setIcon(icon); - setIconTextGap(StudioTheme.scale(ICON_GAP)); - setFont(StudioTheme.smallFont()); - setBorder(StudioTheme.emptyBorder(0, READING_GAP, 0, 0)); - setToolTipText(tooltip); - } - - private void show(String value, boolean highUsage) { - high = highUsage; - setText(value); - setForeground(color()); - repaint(); - } - - private Color color() { - return high ? StudioTheme.WARNING : StudioTheme.SECONDARY_TEXT; - } - - @Override - public Dimension getPreferredSize() { - Dimension size = super.getPreferredSize(); - size.width = getInsets().left + getIcon().getIconWidth() + getIconTextGap() - + getFontMetrics(getFont()).stringWidth(widestValue) + getInsets().right; - return size; - } - - @Override - public Dimension getMaximumSize() { - return getPreferredSize(); - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/ScreenTarget.java b/core/src/main/java/art/arcane/iris/studio/map/ScreenTarget.java deleted file mode 100644 index 9d7714c93..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/ScreenTarget.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.awt.Rectangle; -import java.util.List; - -/** - * A view's own window, to draw a frame straight into. - * - * @param seeThrough the parts of the view panels float over, which Swing paints instead of the window - */ -record ScreenTarget(GpuCanvas canvas, List seeThrough) { -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/StickyFolderHeaders.java b/core/src/main/java/art/arcane/iris/studio/map/StickyFolderHeaders.java deleted file mode 100644 index df9ebaa03..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/StickyFolderHeaders.java +++ /dev/null @@ -1,268 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - - -package art.arcane.iris.studio.map; - -import javax.swing.CellRendererPane; -import javax.swing.Icon; -import javax.swing.JComponent; -import javax.swing.JLayer; -import javax.swing.JScrollPane; -import javax.swing.JTree; -import javax.swing.JViewport; -import javax.swing.SwingUtilities; -import javax.swing.UIManager; -import javax.swing.plaf.LayerUI; -import javax.swing.plaf.basic.BasicTreeUI; -import javax.swing.tree.TreePath; -import java.awt.AWTEvent; -import java.awt.Color; -import java.awt.Component; -import java.awt.Cursor; -import java.awt.GradientPaint; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.List; - -/** - * Keeps the folders around the top row of a scrolled tree pinned at the top, so a long folder never hides where it - * is. The next folder pushes the last header up as it arrives, and clicking a header jumps to its folder. - */ -final class StickyFolderHeaders extends LayerUI { - private static final long serialVersionUID = -2205474187531254372L; - private static final int SHADOW_HEIGHT = 4; - private static final Color SHADOW = new ThemeColor(new Color(0, 0, 0, 28), new Color(0, 0, 0, 90)); - private static final Color NO_SHADOW = new Color(0, 0, 0, 0); - // The folder handle sits one indent to the left of the folder's name, as the tree draws it. - private static final int HANDLE_NUDGE = 1; - - private final JTree tree; - private final CellRendererPane rendererPane = new CellRendererPane(); - private transient JLayer layer; - private int hoveredHeader = -1; - - private StickyFolderHeaders(JTree tree) { - this.tree = tree; - } - - static JLayer around(JTree tree, JScrollPane scrollPane) { - // Copying the scrolled pixels would drag the pinned headers along, so every scroll repaints instead. - scrollPane.getViewport().setScrollMode(JViewport.SIMPLE_SCROLL_MODE); - StickyFolderHeaders headers = new StickyFolderHeaders(tree); - JLayer layer = new JLayer<>(scrollPane, headers); - scrollPane.getViewport().addChangeListener(event -> layer.repaint()); - return layer; - } - - @Override - @SuppressWarnings("unchecked") - public void installUI(JComponent component) { - super.installUI(component); - layer = (JLayer) component; - layer.setLayerEventMask(AWTEvent.MOUSE_EVENT_MASK | AWTEvent.MOUSE_MOTION_EVENT_MASK); - tree.add(rendererPane); - } - - @Override - public void uninstallUI(JComponent component) { - layer.setLayerEventMask(0); - tree.remove(rendererPane); - layer = null; - super.uninstallUI(component); - } - - @Override - public void paint(Graphics graphics, JComponent component) { - super.paint(graphics, component); - List
headers = pinnedHeaders(); - if (headers.isEmpty()) { - return; - } - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - Rectangle viewport = viewportBounds(); - canvas.clipRect(viewport.x, viewport.y, viewport.width, viewport.height); - for (int index = 0; index < headers.size(); index++) { - paintHeader(canvas, headers.get(index), index == hoveredHeader, viewport); - } - Header last = headers.get(headers.size() - 1); - int shadowTop = viewport.y + last.top() + tree.getRowHeight(); - canvas.setPaint(new GradientPaint(0, shadowTop, SHADOW, 0, shadowTop + StudioTheme.scale(SHADOW_HEIGHT), NO_SHADOW)); - canvas.fillRect(viewport.x, shadowTop, viewport.width, StudioTheme.scale(SHADOW_HEIGHT)); - } finally { - canvas.dispose(); - } - } - - private void paintHeader(Graphics2D canvas, Header header, boolean hovered, Rectangle viewport) { - int rowHeight = tree.getRowHeight(); - int top = viewport.y + header.top(); - Rectangle row = tree.getRowBounds(header.row()); - int left = viewport.x + row.x - scrolledView().x; - canvas.setColor(hovered ? StudioTheme.HOVER_BACKGROUND : tree.getBackground()); - canvas.fillRect(viewport.x, top, viewport.width, rowHeight); - paintFolderHandle(canvas, left, top + rowHeight / 2); - Component renderer = tree.getCellRenderer().getTreeCellRendererComponent( - tree, header.path().getLastPathComponent(), false, true, false, header.row(), false); - rendererPane.paintComponent(canvas, renderer, tree, left, top, viewport.x + viewport.width - left, rowHeight, true); - } - - private void paintFolderHandle(Graphics2D canvas, int folderLeft, int middleY) { - Icon handle = UIManager.getIcon("Tree.expandedIcon"); - if (handle == null || !(tree.getUI() instanceof BasicTreeUI treeUI)) { - return; - } - int middleX = folderLeft - treeUI.getRightChildIndent() + HANDLE_NUDGE; - handle.paintIcon(tree, canvas, middleX - handle.getIconWidth() / 2, middleY - handle.getIconHeight() / 2); - } - - @Override - protected void processMouseEvent(MouseEvent event, JLayer source) { - if (event.getID() == MouseEvent.MOUSE_EXITED) { - hover(-1); - return; - } - int index = headerAt(event); - if (index < 0) { - return; - } - event.consume(); - if (event.getID() == MouseEvent.MOUSE_CLICKED && SwingUtilities.isLeftMouseButton(event)) { - jumpTo(pinnedHeaders().get(index), index); - } - } - - @Override - protected void processMouseMotionEvent(MouseEvent event, JLayer source) { - hover(headerAt(event)); - } - - private void hover(int index) { - if (index == hoveredHeader) { - return; - } - hoveredHeader = index; - tree.setCursor(index >= 0 ? Cursor.getPredefinedCursor(Cursor.HAND_CURSOR) : null); - layer.repaint(); - } - - // The folder lands just below the headers of the folders around it. - private void jumpTo(Header header, int level) { - Rectangle row = tree.getRowBounds(header.row()); - JViewport viewport = layer.getView().getViewport(); - int top = Math.max(0, row.y - level * tree.getRowHeight()); - int bottomLimit = Math.max(0, tree.getHeight() - viewport.getExtentSize().height); - viewport.setViewPosition(new Point(viewport.getViewPosition().x, Math.min(top, bottomLimit))); - } - - private int headerAt(MouseEvent event) { - if (layer == null || event.getComponent() == null) { - return -1; - } - Point point = SwingUtilities.convertPoint(event.getComponent(), event.getPoint(), layer); - Rectangle viewport = viewportBounds(); - if (!viewport.contains(point)) { - return -1; - } - List
headers = pinnedHeaders(); - for (int index = headers.size() - 1; index >= 0; index--) { - int top = viewport.y + headers.get(index).top(); - if (point.y >= top && point.y < top + tree.getRowHeight()) { - return index; - } - } - return -1; - } - - /** - * For each depth, the folder holding the row just under the headers above it, as long as that folder's own row - * has scrolled out of sight. - */ - private List
pinnedHeaders() { - List
headers = new ArrayList<>(); - int rowHeight = tree.getRowHeight(); - if (layer == null || rowHeight <= 0 || tree.getRowCount() == 0) { - return headers; - } - Rectangle view = scrolledView(); - for (int level = 0; ; level++) { - int slotTop = level * rowHeight; - int row = tree.getClosestRowForLocation(view.x, view.y + slotTop); - TreePath path = row < 0 ? null : tree.getPathForRow(row); - if (path == null || !isInsideFolderAt(path, level)) { - return headers; - } - TreePath folder = ancestorAt(path, level); - Rectangle lastRow = tree.getRowBounds(lastRowInside(folder, row)); - int top = Math.min(slotTop, lastRow.y + lastRow.height - view.y - rowHeight); - headers.add(new Header(folder, tree.getRowForPath(folder), top)); - if (top < slotTop) { - return headers; - } - } - } - - // The hidden root is the path's first element, so the folder at depth 0 is its second. - private static boolean isInsideFolderAt(TreePath path, int level) { - return path.getPathCount() > level + 2; - } - - private static TreePath ancestorAt(TreePath path, int level) { - TreePath ancestor = path; - while (ancestor.getPathCount() > level + 2) { - ancestor = ancestor.getParentPath(); - } - return ancestor; - } - - // A folder's rows sit together, so the last one is found by halving the rows after a row known to be inside. - private int lastRowInside(TreePath folder, int rowInside) { - int low = rowInside; - int high = tree.getRowCount() - 1; - while (low < high) { - int middle = (low + high + 1) >>> 1; - if (folder.isDescendant(tree.getPathForRow(middle))) { - low = middle; - } else { - high = middle - 1; - } - } - return low; - } - - private Rectangle scrolledView() { - return layer.getView().getViewport().getViewRect(); - } - - private Rectangle viewportBounds() { - JViewport viewport = layer.getView().getViewport(); - Point origin = SwingUtilities.convertPoint(viewport, 0, 0, layer); - return new Rectangle(origin.x, origin.y, viewport.getWidth(), viewport.getHeight()); - } - - /** - * A pinned folder, its row in the tree and how far below the top of the visible rows it is drawn. - */ - private record Header(TreePath path, int row, int top) { - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/StudioOverlay.java b/core/src/main/java/art/arcane/iris/studio/map/StudioOverlay.java deleted file mode 100644 index 85b9b732f..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/StudioOverlay.java +++ /dev/null @@ -1,64 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.RenderingHints; -import java.awt.Shape; -import java.awt.geom.RoundRectangle2D; - -/** - * Draws the floating cards (legends, hover details, hints) on top of a map, styled like IntelliJ's popups. - */ -final class StudioOverlay { - private static final Color FOOTER_BACKGROUND = new ThemeColor(0xF7F8FA, 0x27292C); - - private StudioOverlay() { - } - - static void drawCard(Graphics2D canvas, int x, int y, int width, int height) { - drawCard(canvas, x, y, width, height, 0); - } - - /** - * Draws a card whose bottom {@code footerHeight} pixels are a darker bar, like the shortcut bar of IntelliJ's popups. - */ - static void drawCard(Graphics2D canvas, int x, int y, int width, int height, int footerHeight) { - Graphics2D card = (Graphics2D) canvas.create(); - card.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - RoundRectangle2D outline = new RoundRectangle2D.Double(x + 0.5D, y + 0.5D, width - 1D, height - 1D, - StudioTheme.scale(StudioTheme.OVERLAY_ARC), StudioTheme.scale(StudioTheme.OVERLAY_ARC)); - card.setColor(StudioTheme.OVERLAY_BACKGROUND); - card.fill(outline); - if (footerHeight > 0) { - int footerTop = y + height - footerHeight; - Shape cardClip = card.getClip(); - card.clip(outline); - card.setColor(FOOTER_BACKGROUND); - card.fillRect(x, footerTop, width, footerHeight); - card.setColor(StudioTheme.OVERLAY_BORDER); - card.fillRect(x, footerTop, width, 1); - card.setClip(cardClip); - } - card.setColor(StudioTheme.OVERLAY_BORDER); - card.draw(outline); - card.dispose(); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/StudioStatusBar.java b/core/src/main/java/art/arcane/iris/studio/map/StudioStatusBar.java deleted file mode 100644 index 9435303a7..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/StudioStatusBar.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.BoxLayout; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JProgressBar; -import java.awt.Dimension; -import java.util.Objects; - -/** - * An IntelliJ style status bar: what is shown on the left, work in progress in the middle and where the pointer is on the right. - */ -final class StudioStatusBar extends JPanel { - private static final long serialVersionUID = 6302468216735125611L; - private static final int HEIGHT = 26; - private static final int PROGRESS_STEPS = 1_000; - - private final JLabel summary = statusLabel(); - private final JLabel activity = statusLabel(); - private final JProgressBar progress = new JProgressBar(0, PROGRESS_STEPS); - private final JLabel position = statusLabel(); - - StudioStatusBar() { - setLayout(new BoxLayout(this, BoxLayout.X_AXIS)); - setBackground(StudioTheme.PANEL_BACKGROUND); - setBorder(BorderFactory.createCompoundBorder( - BorderFactory.createMatteBorder(1, 0, 0, 0, StudioTheme.SEPARATOR), - StudioTheme.emptyBorder(0, 10, 0, 10) - )); - setPreferredSize(StudioTheme.scaledSize(0, HEIGHT)); - progress.setMaximumSize(StudioTheme.scaledSize(120, 4)); - progress.setPreferredSize(StudioTheme.scaledSize(120, 4)); - progress.setVisible(false); - allowShrinking(summary); - allowShrinking(activity); - add(summary); - add(Box.createHorizontalGlue()); - add(activity); - add(Box.createHorizontalStrut(StudioTheme.scale(8))); - add(progress); - add(Box.createHorizontalStrut(StudioTheme.scale(18))); - add(position); - } - - void showSummary(String text) { - setTextIfChanged(summary, text); - summary.setForeground(StudioTheme.SECONDARY_TEXT); - } - - void showError(String text) { - setTextIfChanged(summary, text); - summary.setForeground(StudioTheme.ERROR); - } - - void showActivity(String text) { - setTextIfChanged(activity, text); - } - - void showProgress(double completion) { - boolean working = completion < 1D; - progress.setVisible(working); - if (working) { - progress.setValue((int) Math.round(Math.max(0D, completion) * PROGRESS_STEPS)); - } - } - - void showPosition(String text) { - setTextIfChanged(position, text); - } - - // Long text gives way with an ellipsis instead of pushing the other parts of the bar out of view. - private static void allowShrinking(JLabel label) { - label.setMinimumSize(new Dimension(0, 0)); - } - - private static JLabel statusLabel() { - JLabel label = new JLabel(); - label.setFont(StudioTheme.smallFont()); - label.setForeground(StudioTheme.SECONDARY_TEXT); - return label; - } - - // Status text changes on every mouse move, and an unchanged label shouldn't trigger a relayout. - private static void setTextIfChanged(JLabel label, String text) { - String next = text == null ? "" : text; - if (!Objects.equals(label.getText(), next)) { - label.setText(next); - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/StudioTheme.java b/core/src/main/java/art/arcane/iris/studio/map/StudioTheme.java deleted file mode 100644 index 20bdaa1e2..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/StudioTheme.java +++ /dev/null @@ -1,307 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import com.formdev.flatlaf.FlatDarkLaf; -import com.formdev.flatlaf.FlatLaf; -import com.formdev.flatlaf.FlatLightLaf; -import com.formdev.flatlaf.util.UIScale; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.configuration.IrisSettings; - -import javax.swing.BorderFactory; -import javax.swing.JComponent; -import javax.swing.SwingUtilities; -import javax.swing.UIManager; -import javax.swing.border.Border; -import java.awt.Color; -import java.awt.Dimension; -import java.awt.EventQueue; -import java.awt.Font; -import java.util.HashMap; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * The colours of IntelliJ's "New UI", light and dark, shared by FlatLaf's controls and everything the studio windows - * draw themselves. The theme follows the system unless the user picked light or dark. - */ -public final class StudioTheme { - public static final Color EDITOR_BACKGROUND = new ThemeColor(0xFFFFFF, 0x1E1F22); - public static final Color PANEL_BACKGROUND = new ThemeColor(0xF7F8FA, 0x2B2D30); - static final Color HOVER_BACKGROUND = new ThemeColor(0xDFE1E5, 0x393B40); - static final Color INACTIVE_SELECTION = new ThemeColor(0xDFE1E5, 0x43454A); - static final Color SELECTION = new ThemeColor(0xD4E2FF, 0x2E436E); - public static final Color CONTROL_BORDER = new ThemeColor(0xC9CCD6, 0x4E5157); - static final Color SEPARATOR = new ThemeColor(0xEBECF0, 0x1E1F22); - public static final Color TEXT = new ThemeColor(0x000000, 0xDFE1E5); - public static final ThemeColor SECONDARY_TEXT = new ThemeColor(0x6C707E, 0x9DA0A8); - static final Color MUTED_TEXT = new ThemeColor(0x818594, 0x6F737A); - public static final Color ACCENT = new Color(0x3574F0); - static final Color LINK = new ThemeColor(0x315FBD, 0x548AF7); - public static final Color ERROR = new ThemeColor(0xDB3B4B, 0xF75464); - static final Color WARNING = new ThemeColor(0xC27D04, 0xF2C55C); - static final Color SUCCESS = new ThemeColor(0x208A3C, 0x5FB865); - static final Color OVERLAY_BACKGROUND = new ThemeColor(new Color(0xFF, 0xFF, 0xFF, 240), new Color(0x2B, 0x2D, 0x30, 236)); - static final Color OVERLAY_BORDER = new ThemeColor(0xDFE1E5, 0x43454A); - static final int OVERLAY_ARC = 10; - - private static final boolean DARK_WITHOUT_SYSTEM_PREFERENCE = true; - private static final String MATCHED_DARK_PROPERTY = "iris.studio.matchedDark"; - private static final AtomicBoolean INSTALLED = new AtomicBoolean(); - private static final ExecutorService SYSTEM_CHECK = Executors.newSingleThreadExecutor(runnable -> { - Thread thread = new Thread(runnable, "Iris Theme Check"); - thread.setDaemon(true); - return thread; - }); - private static volatile boolean dark = DARK_WITHOUT_SYSTEM_PREFERENCE; - private static volatile float pixelScale = 1F; - private static final Map SHARED_DEFAULTS = Map.ofEntries( - Map.entry("Component.focusWidth", "1"), - Map.entry("Component.innerFocusWidth", "0"), - Map.entry("Component.arc", "8"), - Map.entry("Button.arc", "8"), - Map.entry("TextComponent.arc", "8"), - Map.entry("List.selectionArc", "6"), - Map.entry("List.selectionInsets", "0,6,0,6"), - Map.entry("Tree.selectionArc", "6"), - Map.entry("Tree.selectionInsets", "0,6,0,6"), - Map.entry("Tree.border", "0,8,0,0"), - Map.entry("ScrollBar.width", "10"), - Map.entry("ScrollBar.thumbArc", "999"), - Map.entry("ScrollBar.thumbInsets", "2,2,2,2"), - Map.entry("ScrollBar.showButtons", "false"), - Map.entry("ScrollPane.border", "0,0,0,0"), - Map.entry("SplitPane.dividerSize", "1"), - Map.entry("SplitPaneDivider.style", "plain"), - Map.entry("ProgressBar.arc", "999"), - Map.entry("ProgressBar.horizontalSize", "120,4") - ); - private static final Map DARK_DEFAULTS = withShared(Map.ofEntries( - Map.entry("@background", "#2B2D30"), - Map.entry("@foreground", "#DFE1E5"), - Map.entry("@accentColor", "#3574F0"), - Map.entry("@selectionBackground", "#2E436E"), - Map.entry("@selectionInactiveBackground", "#43454A"), - Map.entry("@disabledForeground", "#6F737A"), - Map.entry("Component.borderColor", "#4E5157"), - Map.entry("Component.focusedBorderColor", "#3574F0"), - Map.entry("Button.toolbar.hoverBackground", "#393B40"), - Map.entry("Button.toolbar.pressedBackground", "#43454A"), - Map.entry("Button.toolbar.selectedBackground", "#43454A"), - Map.entry("ToggleButton.toolbar.selectedBackground", "#43454A"), - Map.entry("ScrollBar.track", "#2B2D30"), - Map.entry("SplitPane.background", "#1E1F22"), - Map.entry("Separator.foreground", "#1E1F22"), - Map.entry("ToolTip.background", "#393B40") - )); - private static final Map LIGHT_DEFAULTS = withShared(Map.ofEntries( - Map.entry("@background", "#F7F8FA"), - Map.entry("@foreground", "#000000"), - Map.entry("@accentColor", "#3574F0"), - Map.entry("@selectionBackground", "#D4E2FF"), - Map.entry("@selectionForeground", "#000000"), - Map.entry("@selectionInactiveBackground", "#DFE1E5"), - Map.entry("@selectionInactiveForeground", "#000000"), - Map.entry("@disabledForeground", "#A8ADBD"), - Map.entry("Component.borderColor", "#C9CCD6"), - Map.entry("Component.focusedBorderColor", "#3574F0"), - Map.entry("Button.toolbar.hoverBackground", "#DFE1E5"), - Map.entry("Button.toolbar.pressedBackground", "#C9CCD6"), - Map.entry("Button.toolbar.selectedBackground", "#DFE1E5"), - Map.entry("ToggleButton.toolbar.selectedBackground", "#DFE1E5"), - Map.entry("ScrollBar.track", "#F7F8FA"), - Map.entry("SplitPane.background", "#EBECF0"), - Map.entry("Separator.foreground", "#EBECF0") - )); - - private StudioTheme() { - } - - static void install() { - if (!INSTALLED.compareAndSet(false, true)) { - return; - } - try { - applyLookAndFeel(darkFor(mode())); - pixelScale = UIScale.getUserScaleFactor(); - } catch (Throwable error) { - IrisLogging.reportError(error); - IrisLogging.warn("Could not apply the Iris studio theme, the studio windows will use Java's default look."); - } - } - - static boolean isDark() { - return dark; - } - - static Mode mode() { - return Mode.fromSetting(IrisSettings.get().getGui().getTheme()); - } - - /** - * Remembers the user's choice and switches every studio window to it. - */ - static void choose(Mode next) { - IrisSettings settings = IrisSettings.get(); - settings.getGui().setTheme(next.settingName()); - settings.forceSave(); - if (next == Mode.AUTO) { - followSystem(); - return; - } - switchTo(next == Mode.DARK); - } - - // Studio windows call this when they come to the front, so a change made in the system's settings shows up. - static void followSystem() { - if (!INSTALLED.get() || mode() != Mode.AUTO) { - return; - } - SYSTEM_CHECK.execute(() -> { - boolean systemDark = SystemAppearance.prefersDark().orElse(DARK_WITHOUT_SYSTEM_PREFERENCE); - EventQueue.invokeLater(() -> switchTo(systemDark)); - }); - } - - private static boolean darkFor(Mode chosen) { - return switch (chosen) { - case LIGHT -> false; - case DARK -> true; - case AUTO -> SystemAppearance.prefersDark().orElse(DARK_WITHOUT_SYSTEM_PREFERENCE); - }; - } - - /** - * A theme switch only reaches components inside a window, so a panel swapped out at the time keeps the old theme until - * this brings it up to date. Call it when putting a panel back on screen. - */ - static T matchTheme(T component) { - if (Boolean.valueOf(dark).equals(component.getClientProperty(MATCHED_DARK_PROPERTY))) { - return component; - } - SwingUtilities.updateComponentTreeUI(component); - component.putClientProperty(MATCHED_DARK_PROPERTY, dark); - return component; - } - - private static void switchTo(boolean nextDark) { - if (nextDark == dark) { - return; - } - applyLookAndFeel(nextDark); - FlatLaf.updateUI(); - } - - private static void applyLookAndFeel(boolean nextDark) { - dark = nextDark; - FlatLaf.setGlobalExtraDefaults(nextDark ? DARK_DEFAULTS : LIGHT_DEFAULTS); - if (nextDark) { - FlatDarkLaf.setup(); - } else { - FlatLightLaf.setup(); - } - } - - private static Map withShared(Map themeDefaults) { - Map merged = new HashMap<>(SHARED_DEFAULTS); - merged.putAll(themeDefaults); - return Map.copyOf(merged); - } - - /** - * FlatLaf grows fonts and its own controls to the screen's DPI; every size the studio sets itself has to grow with them. - */ - public static int scale(int pixels) { - return Math.round(pixels * pixelScale); - } - - static double scale(double pixels) { - return pixels * pixelScale; - } - - public static Dimension scaledSize(int width, int height) { - return new Dimension(scale(width), scale(height)); - } - - public static Border emptyBorder(int top, int left, int bottom, int right) { - return BorderFactory.createEmptyBorder(scale(top), scale(left), scale(bottom), scale(right)); - } - - public static Font font() { - return themeFont("defaultFont", Font.PLAIN, 13); - } - - public static Font smallFont() { - return themeFont("small.font", Font.PLAIN, 11); - } - - public static Font boldFont() { - return font().deriveFont(Font.BOLD); - } - - public static Font titleFont() { - return font().deriveFont(Font.BOLD, font().getSize2D() + 1F); - } - - static Font sectionFont() { - return smallFont().deriveFont(Font.BOLD); - } - - static Font monospacedFont() { - return themeFont("monospaced.font", Font.PLAIN, 12); - } - - private static Font themeFont(String key, int fallbackStyle, int fallbackSize) { - Font font = UIManager.getFont(key); - return font != null ? font : new Font(Font.SANS_SERIF, fallbackStyle, fallbackSize); - } - - enum Mode { - AUTO("Match system"), - LIGHT("Light"), - DARK("Dark"); - - private final String label; - - Mode(String label) { - this.label = label; - } - - String label() { - return label; - } - - String settingName() { - return name().toLowerCase(Locale.ROOT); - } - - static Mode fromSetting(String setting) { - for (Mode mode : values()) { - if (mode.settingName().equalsIgnoreCase(setting)) { - return mode; - } - } - return AUTO; - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/StudioToolbar.java b/core/src/main/java/art/arcane/iris/studio/map/StudioToolbar.java deleted file mode 100644 index f5e529777..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/StudioToolbar.java +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import com.formdev.flatlaf.FlatClientProperties; -import com.formdev.flatlaf.icons.FlatSearchIcon; - -import javax.swing.BorderFactory; -import javax.swing.ButtonGroup; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JPopupMenu; -import javax.swing.JRadioButtonMenuItem; -import javax.swing.JScrollPane; -import javax.swing.JTextField; -import javax.swing.JToggleButton; -import javax.swing.JToolBar; -import javax.swing.ScrollPaneConstants; -import java.awt.BorderLayout; -import java.awt.Insets; - -/** - * Builds the IntelliJ style controls the studio windows share: a flat main toolbar, borderless toolbar buttons and search boxes. - */ -public final class StudioToolbar { - private static final int TOOLBAR_HEIGHT_PADDING = 5; - - private StudioToolbar() { - } - - public static JToolBar create() { - JToolBar toolbar = new JToolBar(); - toolbar.setFloatable(false); - toolbar.setRollover(true); - toolbar.setBackground(StudioTheme.PANEL_BACKGROUND); - toolbar.setBorder(BorderFactory.createCompoundBorder( - BorderFactory.createMatteBorder(0, 0, 1, 0, StudioTheme.SEPARATOR), - StudioTheme.emptyBorder(TOOLBAR_HEIGHT_PADDING, 8, TOOLBAR_HEIGHT_PADDING, 8) - )); - return toolbar; - } - - static JLabel label(String text) { - JLabel label = new JLabel(text); - label.setForeground(StudioTheme.SECONDARY_TEXT); - label.setBorder(StudioTheme.emptyBorder(0, 6, 0, 6)); - return label; - } - - public static JButton button(String text, String tooltip, Runnable action) { - JButton button = toolbarButton(text, tooltip); - button.addActionListener(event -> action.run()); - return button; - } - - /** - * Opens a menu to pick light, dark or the system's theme. - */ - public static JButton themeButton() { - JButton button = toolbarButton("Theme", "Light, dark, or whatever the system uses"); - button.addActionListener(event -> themeMenu().show(button, 0, button.getHeight())); - return button; - } - - private static JPopupMenu themeMenu() { - JPopupMenu menu = new JPopupMenu(); - ButtonGroup choices = new ButtonGroup(); - StudioTheme.Mode current = StudioTheme.mode(); - for (StudioTheme.Mode mode : StudioTheme.Mode.values()) { - JRadioButtonMenuItem item = new JRadioButtonMenuItem(mode.label(), mode == current); - item.addActionListener(event -> StudioTheme.choose(mode)); - choices.add(item); - menu.add(item); - } - return menu; - } - - private static JButton toolbarButton(String text, String tooltip) { - JButton button = new JButton(text); - button.setToolTipText(tooltip); - button.setFocusable(false); - button.setMargin(new Insets(4, 8, 4, 8)); - button.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON); - return button; - } - - public static JToggleButton toggle(String text, String tooltip) { - JToggleButton toggle = new JToggleButton(text); - toggle.setToolTipText(tooltip); - toggle.setFocusable(false); - toggle.setMargin(new Insets(4, 8, 4, 8)); - toggle.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TOOLBAR_BUTTON); - return toggle; - } - - // An underlined tab like IntelliJ's tool window tabs. - static JToggleButton tab(String text) { - JToggleButton tab = new JToggleButton(text); - tab.setFocusable(false); - tab.putClientProperty(FlatClientProperties.BUTTON_TYPE, FlatClientProperties.BUTTON_TYPE_TAB); - return tab; - } - - static void makeSearchField(JTextField field, String placeholder) { - field.putClientProperty(FlatClientProperties.PLACEHOLDER_TEXT, placeholder); - field.putClientProperty(FlatClientProperties.TEXT_FIELD_LEADING_ICON, new FlatSearchIcon()); - field.putClientProperty(FlatClientProperties.TEXT_FIELD_SHOW_CLEAR_BUTTON, true); - field.setToolTipText(placeholder); - } - - static JPanel padded(JComponent content, int top, int left, int bottom, int right) { - JPanel panel = new JPanel(new BorderLayout()); - panel.setOpaque(false); - panel.setBorder(StudioTheme.emptyBorder(top, left, bottom, right)); - panel.add(content, BorderLayout.CENTER); - return panel; - } - - public static JScrollPane scroll(JComponent content) { - JScrollPane scrollPane = new JScrollPane(content); - scrollPane.setBorder(BorderFactory.createEmptyBorder()); - scrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER); - scrollPane.getVerticalScrollBar().setUnitIncrement(18); - return scrollPane; - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/SystemAppearance.java b/core/src/main/java/art/arcane/iris/studio/map/SystemAppearance.java deleted file mode 100644 index 45795e371..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/SystemAppearance.java +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.io.IOException; -import java.io.InputStream; -import java.nio.charset.StandardCharsets; -import java.util.List; -import java.util.Locale; -import java.util.Optional; -import java.util.concurrent.TimeUnit; - -/** - * Asks the operating system whether its user prefers dark or light apps, through the same settings desktop apps - * follow: the freedesktop portal or GNOME's setting on Linux, the apps theme on Windows, the appearance on macOS. - */ -final class SystemAppearance { - private static final long COMMAND_TIMEOUT_MILLIS = 2000L; - private static final String PORTAL_DARK = "uint32 1"; - private static final String PORTAL_LIGHT = "uint32 2"; - - private SystemAppearance() { - } - - /** - * Empty when the system has no preference or could not be asked. - */ - static Optional prefersDark() { - String os = System.getProperty("os.name", "").toLowerCase(Locale.ROOT); - if (os.contains("win")) { - return windowsPrefersDark(); - } - if (os.contains("mac")) { - return macPrefersDark(); - } - return linuxPrefersDark(); - } - - private static Optional linuxPrefersDark() { - Optional portal = output(List.of("gdbus", "call", "--session", "--dest", "org.freedesktop.portal.Desktop", - "--object-path", "/org/freedesktop/portal/desktop", "--method", "org.freedesktop.portal.Settings.ReadOne", - "org.freedesktop.appearance", "color-scheme")); - if (portal.filter(answer -> answer.contains(PORTAL_DARK)).isPresent()) { - return Optional.of(true); - } - if (portal.filter(answer -> answer.contains(PORTAL_LIGHT)).isPresent()) { - return Optional.of(false); - } - Optional gnome = output(List.of("gsettings", "get", "org.gnome.desktop.interface", "color-scheme")); - if (gnome.filter(scheme -> scheme.contains("prefer-dark")).isPresent()) { - return Optional.of(true); - } - if (gnome.filter(scheme -> scheme.contains("prefer-light")).isPresent()) { - return Optional.of(false); - } - return output(List.of("gsettings", "get", "org.gnome.desktop.interface", "gtk-theme")) - .map(theme -> theme.toLowerCase(Locale.ROOT).contains("dark")); - } - - private static Optional windowsPrefersDark() { - return output(List.of("reg", "query", "HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", - "/v", "AppsUseLightTheme")) - .filter(answer -> answer.contains("AppsUseLightTheme")) - .map(answer -> answer.trim().endsWith("0x0")); - } - - // The setting only exists while macOS is dark, so a failed read means light. - private static Optional macPrefersDark() { - return Optional.of(output(List.of("defaults", "read", "-g", "AppleInterfaceStyle")) - .filter(style -> style.trim().equalsIgnoreCase("dark")) - .isPresent()); - } - - private static Optional output(List command) { - try { - Process process = new ProcessBuilder(command).redirectErrorStream(true).start(); - if (!process.waitFor(COMMAND_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS)) { - process.destroyForcibly(); - return Optional.empty(); - } - if (process.exitValue() != 0) { - return Optional.empty(); - } - try (InputStream stream = process.getInputStream()) { - return Optional.of(new String(stream.readAllBytes(), StandardCharsets.UTF_8)); - } - } catch (IOException missingCommand) { - return Optional.empty(); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - return Optional.empty(); - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/TerrainColumns.java b/core/src/main/java/art/arcane/iris/studio/map/TerrainColumns.java deleted file mode 100644 index 5f2400f1e..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/TerrainColumns.java +++ /dev/null @@ -1,30 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -/** - * Where the 3D views get their terrain columns from. Called from several sampler threads at once. - */ -interface TerrainColumns { - /** - * Fills one row of the grid, each column at its first block: its height in blocks, or NaN where it has none, and - * its colour. - */ - void sampleRow(TerrainGrid grid, int row, float[] heights, int[] colors); -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/TerrainCover.java b/core/src/main/java/art/arcane/iris/studio/map/TerrainCover.java deleted file mode 100644 index 5e00b73ae..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/TerrainCover.java +++ /dev/null @@ -1,349 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashSet; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; - -/** - * What the 3D noise view draws for one camera, and which tiles it still needs. Ground in sight wants detail tiles, - * whose columns are at most a pixel wide, and backdrop tiles a few levels coarser, which are cheap enough to cover the - * whole view and more right away. Preview tiles one level coarser than detail come between them: a quarter of the - * columns, so the whole view looks nearly finished long before the detail is in. Until it is, coarser tiles stand in - * for it, with holes where finer tiles are ready; detail left over from before zooming out stands in too, as does - * ground from before the noise changed, and backdrop left over from before zooming in. - */ -final class TerrainCover { - private static final double MOST_COLUMN_PIXELS = 1D; - // A little above one, as tiles in sight stick out past the view's edges; beyond it, columns only add faces no one can - // tell apart, and drawing them costs the frame its time. - private static final double MOST_COLUMNS_PER_PIXEL = 1.25D; - // With leftovers one level finer than detail, a backdrop's hole is cut for tiles up to TerrainHole.MOST_LEVELS_FINER - // levels finer than it, and no further. - private static final int BACKDROP_LEVELS_ABOVE_DETAIL = 3; - private static final int PREVIEW_LEVELS_ABOVE_DETAIL = 1; - // Of the view's size, on every side: enough for small moves to find their ground already sampled. - private static final double DETAIL_MARGIN_SHARE = 0.15D; - private static final double BACKDROP_MARGIN_SHARE = 0.5D; - // Detail takes at most this share of the tiles memory holds, leaving the rest for the backdrop and recent views. - private static final double DETAIL_SHARE_OF_MEMORY = 0.5D; - - private final TerrainTiles tiles; - private final Sight sight; - private final int detailLevel; - private final int previewLevel; - private final int backdropLevel; - private final List layers = new ArrayList<>(); - private final Set inUse = new HashSet<>(); - private final List wantedBackdrop = new ArrayList<>(); - private final List wantedPreview = new ArrayList<>(); - private final List wantedDetail = new ArrayList<>(); - - private TerrainCover(TerrainTiles tiles, Sight sight, int detailLevel) { - this.tiles = tiles; - this.sight = sight; - this.detailLevel = detailLevel; - this.previewLevel = detailLevel + PREVIEW_LEVELS_ABOVE_DETAIL; - this.backdropLevel = detailLevel + BACKDROP_LEVELS_ABOVE_DETAIL; - } - - /** - * Works out what to draw and asks {@code tiles} to sample what is still missing, most needed first. - */ - static Result of(TerrainTiles tiles, OrbitProjection projection, int width, int height, int coveredLeftWidth) { - TerrainSampling sampling = tiles.sampling(); - Sight sight = Sight.of(projection, coveredLeftWidth, width, height, sampling.floorY(), sampling.topY()); - TerrainCover cover = new TerrainCover(tiles, sight, detailLevelFor(sight, projection.pixelsPerBlock())); - cover.coverSight(); - tiles.sampleOnly(cover.wantedInOrder(), cover.inUse); - return new Result(List.copyOf(cover.layers), 1 << cover.detailLevel, tiles.pendingCount()); - } - - // The widest columns that still draw at most a pixel wide, unless there would be more of them in sight than pixels - // to show them, as looking at the ground from low down foreshortens it, or than memory holds. - private static int detailLevelFor(Sight sight, double pixelsPerBlock) { - int level = 0; - while ((1 << (level + 1)) * pixelsPerBlock <= MOST_COLUMN_PIXELS) { - level++; - } - long columnsPerTile = (long) TerrainTile.COLUMNS * TerrainTile.COLUMNS; - long affordableColumns = (long) (TerrainTiles.mostColumnsInMemory() * DETAIL_SHARE_OF_MEMORY); - long showableColumns = (long) (sight.pixelsWithin(DETAIL_MARGIN_SHARE) * MOST_COLUMNS_PER_PIXEL); - long mostTiles = Math.min(affordableColumns, showableColumns) / columnsPerTile; - while (sight.tilesInSight(level, DETAIL_MARGIN_SHARE).size() > mostTiles) { - level++; - } - return level; - } - - private void coverSight() { - Map> coveredByBackdrop = new LinkedHashMap<>(); - for (TerrainTile backdrop : sight.tilesInSight(backdropLevel, BACKDROP_MARGIN_SHARE)) { - coveredByBackdrop.put(backdrop, cover(backdrop, true)); - } - coverMissingBackdrop(coveredByBackdrop); - } - - /** - * Backdrop that isn't sampled yet, as right after zooming in, borrows the nearest coarser tile that is, with holes - * where the backdrop and finer ground around it are ready. Only as far up as holes can still be cut. - */ - private void coverMissingBackdrop(Map> coveredByBackdrop) { - Set standIns = new LinkedHashSet<>(); - coveredByBackdrop.forEach((backdrop, covered) -> { - if (!covered.equals(List.of(backdrop))) { - nearestSampledAncestor(backdrop).ifPresent(standIns::add); - } - }); - for (TerrainTile standIn : standIns) { - TerrainLayer layer = tiles.layerOf(standIn); - if (layer != null) { - draw(standIn, layer, fillersOf(standIn, coveredByBackdrop, standIns)); - } - } - } - - private Optional nearestSampledAncestor(TerrainTile backdrop) { - for (int levelsUp = 1; levelsUp <= TerrainHole.MOST_LEVELS_FINER; levelsUp++) { - TerrainTile ancestor = backdrop.ancestorAt(backdrop.level() + levelsUp); - if (tiles.isSampled(ancestor)) { - return Optional.of(ancestor); - } - } - return Optional.empty(); - } - - // Everything drawn inside the stand-in: the backdrop's ready ground, and finer stand-ins. - private static List fillersOf(TerrainTile standIn, Map> coveredByBackdrop, - Set standIns) { - List fillers = new ArrayList<>(); - coveredByBackdrop.forEach((backdrop, covered) -> { - if (backdrop.ancestorAt(standIn.level()).equals(standIn)) { - fillers.addAll(covered); - } - }); - for (TerrainTile finer : standIns) { - if (finer.level() < standIn.level() && finer.ancestorAt(standIn.level()).equals(standIn)) { - fillers.add(finer); - } - } - return fillers; - } - - /** - * Draws what is ready of the tile in sight, finest first, each coarser tile with the finer ready ones inside it to - * fill its hole. Ready tiles out of sight fill holes too, which keeps a hole's edge out of sight as well. - * - * @return the ready tiles, this one or finer ones inside it, that together cover it as far as they reach - */ - private List cover(TerrainTile tile, boolean inSight) { - if (tile.level() == detailLevel) { - return coverDetail(tile, inSight); - } - List coveredInside = new ArrayList<>(); - for (TerrainTile child : tile.children()) { - coveredInside.addAll(cover(child, inSight && sight.sees(child, DETAIL_MARGIN_SHARE))); - } - TerrainLayer whole = inSight ? leftoverOrBackdropOf(tile) : null; - boolean ready = whole != null || !inSight && tiles.isSampled(tile); - if (inSight && tile.level() == backdropLevel && (!ready || tiles.isStandingIn(tile))) { - wantedBackdrop.add(tile); - } - if (inSight && tile.level() == previewLevel && !ready && !coveredInside.containsAll(tile.children())) { - wantedPreview.add(tile); - } - if (!ready) { - return coveredInside; - } - // Drawn even when finer tiles fill all of it, as it still covers for them until they can be drawn themselves. - if (whole != null) { - draw(tile, whole, coveredInside); - } - return List.of(tile); - } - - // Other tiles between detail and backdrop are only left over from other zoom levels and never sampled anew, so - // ground from before the noise changed would stand in for them for good; the backdrop covers them instead. Preview - // ground standing in is left to the backdrop too, while its tile is sampled anew. - private TerrainLayer leftoverOrBackdropOf(TerrainTile tile) { - if (tile.level() != backdropLevel && tiles.isStandingIn(tile)) { - return null; - } - return tiles.layerOf(tile); - } - - private List coverDetail(TerrainTile tile, boolean inSight) { - if (!inSight) { - return tiles.isSampled(tile) ? List.of(tile) : finerLeftoversOutOfSight(tile); - } - TerrainLayer whole = tiles.layerOf(tile); - if (whole != null) { - draw(tile, whole); - if (tiles.isStandingIn(tile)) { - wantedDetail.add(tile); - } - return List.of(tile); - } - wantedDetail.add(tile); - return coverWithFinerLeftovers(tile); - } - - private List coverWithFinerLeftovers(TerrainTile tile) { - if (tile.level() == 0) { - return List.of(); - } - List covered = new ArrayList<>(); - for (TerrainTile child : tile.children()) { - if (!sight.sees(child, DETAIL_MARGIN_SHARE)) { - if (tiles.isSampled(child)) { - covered.add(child); - } - continue; - } - TerrainLayer leftover = tiles.layerOf(child); - if (leftover != null) { - draw(child, leftover); - covered.add(child); - } - } - return covered; - } - - private List finerLeftoversOutOfSight(TerrainTile tile) { - if (tile.level() == 0) { - return List.of(); - } - return tile.children().stream().filter(tiles::isSampled).toList(); - } - - private void draw(TerrainTile tile, TerrainLayer layer) { - draw(tile, layer, List.of()); - } - - private void draw(TerrainTile tile, TerrainLayer layer, List fillers) { - layers.add(new HoledLayer(tile, layer, List.copyOf(fillers))); - inUse.add(tile); - } - - private List wantedInOrder() { - Comparator nearestFirst = Comparator.comparingDouble(sight::distanceFromMiddle); - wantedBackdrop.sort(nearestFirst); - wantedPreview.sort(nearestFirst); - wantedDetail.sort(nearestFirst); - List wanted = new ArrayList<>(wantedBackdrop.size() + wantedPreview.size() + wantedDetail.size()); - wanted.addAll(wantedBackdrop); - wanted.addAll(wantedPreview); - wanted.addAll(wantedDetail); - return wanted; - } - - /** - * @param detailStep how many blocks wide the columns are that the view wants - * @param pendingTiles how many tiles are still to be sampled for it - */ - record Result(List layers, int detailStep, int pendingTiles) { - } - - /** - * What the camera sees: a tile is in sight when any part of it, from the lowest ground the noise reaches to the - * highest, lands in the view or within a margin around it. - */ - private record Sight(OrbitProjection projection, int left, int right, int bottom, int floorY, int topY) { - static Sight of(OrbitProjection projection, int coveredLeftWidth, int width, int height, int floorY, int topY) { - return new Sight(projection, Math.max(0, Math.min(width - 1, coveredLeftWidth)), width, height, floorY, topY); - } - - double pixelsWithin(double marginShare) { - double marginFactor = 1D + 2D * marginShare; - return (right - left) * marginFactor * bottom * marginFactor; - } - - List tilesInSight(int level, double marginShare) { - double marginX = (right - left) * marginShare; - double marginY = bottom * marginShare; - double minX = Double.POSITIVE_INFINITY; - double minZ = Double.POSITIVE_INFINITY; - double maxX = Double.NEGATIVE_INFINITY; - double maxZ = Double.NEGATIVE_INFINITY; - for (double screenX : new double[]{left - marginX, right + marginX}) { - for (double screenY : new double[]{-marginY, bottom + marginY}) { - for (double groundY : new double[]{floorY, topY}) { - Vec3 point = projection.pointAt(screenX, screenY, groundY); - minX = Math.min(minX, point.x()); - minZ = Math.min(minZ, point.z()); - maxX = Math.max(maxX, point.x()); - maxZ = Math.max(maxZ, point.z()); - } - } - } - TerrainTile first = TerrainTile.containing(minX, minZ, level); - TerrainTile last = TerrainTile.containing(maxX, maxZ, level); - List inSight = new ArrayList<>(); - for (int tileZ = first.tileZ(); tileZ <= last.tileZ(); tileZ++) { - for (int tileX = first.tileX(); tileX <= last.tileX(); tileX++) { - TerrainTile tile = new TerrainTile(level, tileX, tileZ); - if (sees(tile, marginShare)) { - inSight.add(tile); - } - } - } - return inSight; - } - - boolean sees(TerrainTile tile, double marginShare) { - double marginX = (right - left) * marginShare; - double marginY = bottom * marginShare; - double minScreenX = Double.POSITIVE_INFINITY; - double minScreenY = Double.POSITIVE_INFINITY; - double maxScreenX = Double.NEGATIVE_INFINITY; - double maxScreenY = Double.NEGATIVE_INFINITY; - long size = tile.sizeBlocks(); - for (long x : new long[]{tile.originX(), tile.originX() + size}) { - for (long z : new long[]{tile.originZ(), tile.originZ() + size}) { - for (int y : new int[]{floorY, topY}) { - double screenX = projection.screenX(x, y, z); - double screenY = projection.screenY(x, y, z); - minScreenX = Math.min(minScreenX, screenX); - minScreenY = Math.min(minScreenY, screenY); - maxScreenX = Math.max(maxScreenX, screenX); - maxScreenY = Math.max(maxScreenY, screenY); - } - } - } - return maxScreenX >= left - marginX && minScreenX <= right + marginX - && maxScreenY >= -marginY && minScreenY <= bottom + marginY; - } - - double distanceFromMiddle(TerrainTile tile) { - double half = tile.sizeBlocks() / 2D; - double middleY = (floorY + topY) / 2D; - double x = tile.originX() + half; - double z = tile.originZ() + half; - return Math.hypot(projection.screenX(x, middleY, z) - projection.screenCenterX(), - projection.screenY(x, middleY, z) - projection.screenCenterY()); - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/TerrainGrid.java b/core/src/main/java/art/arcane/iris/studio/map/TerrainGrid.java deleted file mode 100644 index bf8d408e4..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/TerrainGrid.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -/** - * The block columns a stretch of terrain is sampled at: {@code columns} by {@code rows} from the origin, each - * {@code step} blocks wide and deep. Heights stay in blocks whatever the step. - */ -record TerrainGrid(int originX, int originZ, int columns, int rows, int step) { -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/TerrainHeightSlider.java b/core/src/main/java/art/arcane/iris/studio/map/TerrainHeightSlider.java deleted file mode 100644 index d8c9aaaab..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/TerrainHeightSlider.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import javax.swing.JComponent; -import java.util.function.IntConsumer; - -/** - * A slider floating on the right of the 3D noise view that sets how many blocks the highest noise rises above the - * lowest. Its steps grow with the height, so low terrain is as easy to set as a tall one. - */ -final class TerrainHeightSlider { - private static final String TOOLTIP = "How many blocks the highest noise rises above the lowest"; - private static final int LOWEST_BLOCKS = 1; - private static final int TALLEST_BLOCKS = 4064; - private static final int DEFAULT_BLOCKS = 64; - private static final int POSITIONS = 1000; - - private final FloatingSlider slider = new FloatingSlider(TOOLTIP, this::showHeightAt); - private final IntConsumer onHeightChanged; - private int blocks = DEFAULT_BLOCKS; - - /** - * @param onHeightChanged told the height in blocks whenever the user moves the slider - */ - TerrainHeightSlider(IntConsumer onHeightChanged) { - this.onHeightChanged = onHeightChanged; - slider.showQuietly(0, POSITIONS, positionOf(DEFAULT_BLOCKS)); - slider.showLabel(Integer.toString(blocks)); - } - - /** - * The view with this slider floating over its right edge, halfway down. - */ - JComponent floatingOver(JComponent view) { - return slider.floatingOver(view); - } - - int blocks() { - return blocks; - } - - // Noise measured in blocks keeps its own heights, so the slider has nothing to set for it. - void setUsable(boolean usable) { - slider.setVisible(usable); - } - - private void showHeightAt(int position) { - int nextBlocks = blocksAt(position); - if (nextBlocks == blocks) { - return; - } - blocks = nextBlocks; - slider.showLabel(Integer.toString(blocks)); - onHeightChanged.accept(blocks); - } - - private static int blocksAt(int position) { - double share = position / (double) POSITIONS; - return (int) Math.round(Math.exp(Math.log(LOWEST_BLOCKS) + share * (Math.log(TALLEST_BLOCKS) - Math.log(LOWEST_BLOCKS)))); - } - - private static int positionOf(int heightBlocks) { - double share = (Math.log(heightBlocks) - Math.log(LOWEST_BLOCKS)) / (Math.log(TALLEST_BLOCKS) - Math.log(LOWEST_BLOCKS)); - return (int) Math.round(share * POSITIONS); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/TerrainHole.java b/core/src/main/java/art/arcane/iris/studio/map/TerrainHole.java deleted file mode 100644 index e1fe16970..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/TerrainHole.java +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.util.Collection; - -/** - * The part of a tile left out for finer tiles inside it to fill. Finer tiles are at most {@link #MOST_LEVELS_FINER} - * levels finer, so a hole always follows the edges of square cells of {@link #CELL_COLUMNS} columns, and no face crosses - * one: whether a face shows is the same along all of it, which lets the graphics card decide it per face, every frame. - */ -final class TerrainHole { - static final int MOST_LEVELS_FINER = 4; - static final int CELLS_ACROSS = 1 << MOST_LEVELS_FINER; - static final int CELL_COLUMNS = TerrainTile.COLUMNS / CELLS_ACROSS; - static final int WORDS = CELLS_ACROSS * CELLS_ACROSS / Integer.SIZE; - static final TerrainHole NONE = new TerrainHole(new int[WORDS]); - private static final int ALL_CELLS_OF_WORD = -1; - - // One bit per cell, row by row. - private final int[] hiddenCells; - - private TerrainHole(int[] hiddenCells) { - this.hiddenCells = hiddenCells; - } - - /** - * The hole in {@code tile} that these finer tiles inside it fill. A tile finer than a cell can't be cut out, so it - * leaves no hole and only overlaps the coarser ground. - */ - static TerrainHole of(TerrainTile tile, Collection fillers) { - if (fillers.isEmpty()) { - return NONE; - } - int[] hidden = new int[WORDS]; - for (TerrainTile filler : fillers) { - ColumnArea area = tile.columnsUnder(filler); - if (area.toColumn() - area.fromColumn() < CELL_COLUMNS) { - continue; - } - for (int row = area.fromRow(); row < area.toRow(); row += CELL_COLUMNS) { - for (int column = area.fromColumn(); column < area.toColumn(); column += CELL_COLUMNS) { - int cell = cellOf(column, row); - hidden[cell / Integer.SIZE] |= 1 << (cell % Integer.SIZE); - } - } - } - return new TerrainHole(hidden); - } - - private static int cellOf(int column, int row) { - return row / CELL_COLUMNS * CELLS_ACROSS + column / CELL_COLUMNS; - } - - // Columns beyond the tile's edge are never hidden: the tile's own edge sides already reach the floor. - boolean hides(int column, int row) { - if (column < 0 || row < 0 || column >= TerrainTile.COLUMNS || row >= TerrainTile.COLUMNS) { - return false; - } - int cell = cellOf(column, row); - return (hiddenCells[cell / Integer.SIZE] & 1 << (cell % Integer.SIZE)) != 0; - } - - boolean hidesAll() { - for (int word : hiddenCells) { - if (word != ALL_CELLS_OF_WORD) { - return false; - } - } - return true; - } - - /** - * Whether a face shows with this hole: none of a hidden column's do, and a column next to the hole shows its hole - * wall, reaching down to the floor, instead of its usual side. The graphics card's face shader decides the same. - */ - boolean shows(BlockFaces faces, int face) { - int column = faces.firstColumn(face); - int row = faces.firstRow(face); - if (hides(column, row)) { - return false; - } - BlockFaces.Facing facing = faces.facing(face); - if (facing == BlockFaces.Facing.TOP) { - return true; - } - return faces.isHoleWall(face) == hides(column + facing.normalX, row + facing.normalZ); - } - - int[] hiddenCells() { - return hiddenCells.clone(); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/TerrainLayer.java b/core/src/main/java/art/arcane/iris/studio/map/TerrainLayer.java deleted file mode 100644 index 8980450fc..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/TerrainLayer.java +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -/** - * Terrain as the 3D noise view draws it: its columns and their block faces, for any hole finer terrain cuts in it. - */ -record TerrainLayer(NoiseTerrain terrain, BlockFaces faces) { - /** - * @param floorY how far down sides on the terrain's edge or next to a hole reach, so they meet the terrain beside it - * whatever its height - */ - static TerrainLayer of(NoiseTerrain terrain, int floorY) { - int reachedFloorY = terrain.isEmpty() ? floorY : Math.min(floorY, terrain.baseY()); - return new TerrainLayer(terrain, BlockFaces.of(terrain, reachedFloorY)); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/TerrainSampling.java b/core/src/main/java/art/arcane/iris/studio/map/TerrainSampling.java deleted file mode 100644 index 0e1705d0c..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/TerrainSampling.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.volmlib.util.function.NoiseProvider; - -import java.util.function.DoubleUnaryOperator; - -/** - * How the 3D views turn noise or a world into terrain, kept with the terrain so detail sampled later matches it. - * - * @param floorY where sides on the edge of the sampled ground end - * @param topY a block above the highest ground expected - * @param waterLevel the height water fills up to, or NaN when there is no water - */ -record TerrainSampling(TerrainColumns columns, int floorY, int topY, double waterLevel) { - // The noise's colour range sets how low and high its terrain goes; the odd value outside it reaches a bit further. - static TerrainSampling ofNoise(NoiseProvider noise, DoubleUnaryOperator heightOf, NoiseColorScale colorScale, double waterLevel) { - int floorY = (int) Math.floor(heightOf.applyAsDouble(colorScale.minimum())) - 1; - int topY = BlockFaces.blockTop(heightOf.applyAsDouble(colorScale.maximum())); - return new TerrainSampling(new NoiseColumns(noise, heightOf, colorScale), floorY, topY, waterLevel); - } - - boolean hasWater() { - return Double.isFinite(waterLevel); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/TerrainTile.java b/core/src/main/java/art/arcane/iris/studio/map/TerrainTile.java deleted file mode 100644 index 31043e4a7..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/TerrainTile.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.util.List; - -/** - * A square of terrain sampled in one go: {@link #COLUMNS} by {@link #COLUMNS} columns, each {@code 2^level} blocks - * wide. Tiles of a level line up edge to edge, and each one covers exactly four of the level below, so finer tiles can - * stand in for parts of a coarser one. - */ -record TerrainTile(int level, int tileX, int tileZ) { - static final int COLUMNS = 128; - - static TerrainTile containing(double worldX, double worldZ, int level) { - long sizeBlocks = sizeBlocks(level); - return new TerrainTile(level, (int) Math.floorDiv((long) Math.floor(worldX), sizeBlocks), - (int) Math.floorDiv((long) Math.floor(worldZ), sizeBlocks)); - } - - static long sizeBlocks(int level) { - return (long) COLUMNS << level; - } - - int step() { - return 1 << level; - } - - long sizeBlocks() { - return sizeBlocks(level); - } - - long originX() { - return tileX * sizeBlocks(); - } - - long originZ() { - return tileZ * sizeBlocks(); - } - - TerrainGrid grid() { - return new TerrainGrid((int) originX(), (int) originZ(), COLUMNS, COLUMNS, step()); - } - - List children() { - int finer = level - 1; - int childX = tileX * 2; - int childZ = tileZ * 2; - return List.of(new TerrainTile(finer, childX, childZ), new TerrainTile(finer, childX + 1, childZ), - new TerrainTile(finer, childX, childZ + 1), new TerrainTile(finer, childX + 1, childZ + 1)); - } - - /** - * The tile of a coarser level that this one lies inside. - */ - TerrainTile ancestorAt(int coarserLevel) { - int levelsUp = coarserLevel - level; - return new TerrainTile(coarserLevel, tileX >> levelsUp, tileZ >> levelsUp); - } - - /** - * This tile's columns that a finer tile inside it covers. - */ - ColumnArea columnsUnder(TerrainTile finer) { - int fromColumn = (int) ((finer.originX() - originX()) / step()); - int fromRow = (int) ((finer.originZ() - originZ()) / step()); - int across = (int) (finer.sizeBlocks() / step()); - return new ColumnArea(fromColumn, fromRow, fromColumn + across, fromRow + across); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/TerrainTiles.java b/core/src/main/java/art/arcane/iris/studio/map/TerrainTiles.java deleted file mode 100644 index 76588bf25..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/TerrainTiles.java +++ /dev/null @@ -1,272 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.generation.stream.ProvisionalSampling; -import art.arcane.iris.spi.IrisLogging; - -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.TimeUnit; - -/** - * Tiles of one noise, sampled on worker threads in the order last asked for, and kept as long as memory allows. Tiles - * no longer asked for are not sampled, so moving the camera never waits on ground it has left behind. Ground the view - * showed before the noise or its heights changed stands in until its tile is sampled anew, so the view never empties - * while it catches up. - */ -final class TerrainTiles { - private static final long FIRST_RETRY_NANOS = TimeUnit.MILLISECONDS.toNanos(500L); - private static final long MAX_RETRY_NANOS = TimeUnit.SECONDS.toNanos(8L); - // The map runs inside the server, so the tiles stay well clear of what the server itself needs. - private static final double SHARE_OF_HEAP = 0.25D; - // A column's height and colour, and its share of the block faces drawn for it. - private static final long ESTIMATED_BYTES_PER_COLUMN = 64L; - - private final TerrainSampling sampling; - private final ExecutorService workers; - private final int workerCount; - private final Runnable onTileSampled; - private final int mostTiles = mostTilesInMemory(); - private final Object lock = new Object(); - // Least recently asked for first. - private final LinkedHashMap sampled = new LinkedHashMap<>(16, 0.75F, true); - private final Map standIns; - private final Map retries = new HashMap<>(); - private final Set inProgress = new HashSet<>(); - private List wanted = List.of(); - private Set inUse = Set.of(); - private int nextWanted; - private int runningWorkers; - private boolean closed; - - /** - * @param onTileSampled told, on a worker thread, whenever another tile is ready - * @param standIns ground shown in place of tiles until they are sampled, such as {@link #layersInUse} of the - * tiles these replace - */ - TerrainTiles(TerrainSampling sampling, ExecutorService workers, int workerCount, Runnable onTileSampled, - Map standIns) { - this.sampling = sampling; - this.workers = workers; - this.workerCount = workerCount; - this.onTileSampled = onTileSampled; - this.standIns = new HashMap<>(standIns); - } - - static long mostColumnsInMemory() { - return (long) (Runtime.getRuntime().maxMemory() * SHARE_OF_HEAP) / ESTIMATED_BYTES_PER_COLUMN; - } - - private static int mostTilesInMemory() { - return (int) Math.max(1L, mostColumnsInMemory() / ((long) TerrainTile.COLUMNS * TerrainTile.COLUMNS)); - } - - TerrainSampling sampling() { - return sampling; - } - - /** - * The tile as a whole layer, or what stands in for it, or null while there is neither. - */ - TerrainLayer layerOf(TerrainTile tile) { - synchronized (lock) { - TerrainLayer layer = sampled.get(tile); - return layer != null ? layer : standIns.get(tile); - } - } - - /** - * Whether {@link #layerOf} has ground for the tile. Unlike layerOf, asking doesn't count as using the tile, so it - * isn't kept in memory any longer for it. - */ - boolean isSampled(TerrainTile tile) { - synchronized (lock) { - return sampled.containsKey(tile) || standIns.containsKey(tile); - } - } - - // Ground that only stands in still wants sampling. - boolean isStandingIn(TerrainTile tile) { - synchronized (lock) { - return !sampled.containsKey(tile) && standIns.containsKey(tile); - } - } - - /** - * The ground last drawn from these tiles, to stand in for the tiles that replace them. - */ - Map layersInUse() { - synchronized (lock) { - Map layers = new HashMap<>(); - for (TerrainTile tile : inUse) { - TerrainLayer layer = sampled.containsKey(tile) ? sampled.get(tile) : standIns.get(tile); - if (layer != null) { - layers.put(tile, layer); - } - } - return layers; - } - } - - /** - * Samples these tiles, first to last, instead of any asked for before. Tiles beyond what memory holds are forgotten, - * those asked for least recently first, but never any in {@code inUse}. - */ - void sampleOnly(List nextWanted, Set inUse) { - synchronized (lock) { - if (closed) { - return; - } - wanted = nextWanted; - this.nextWanted = 0; - this.inUse = Set.copyOf(inUse); - Set retained = new HashSet<>(nextWanted); - retained.addAll(inUse); - retries.keySet().removeIf(tile -> !retained.contains(tile)); - standIns.keySet().removeIf(tile -> !retained.contains(tile)); - forgetBeyondMemory(inUse); - startWorkers(); - } - } - - int pendingCount() { - synchronized (lock) { - int waiting = 0; - for (TerrainTile tile : wanted) { - if (!sampled.containsKey(tile) && !inProgress.contains(tile)) { - waiting++; - } - } - return waiting + inProgress.size(); - } - } - - long retryDelayNanos() { - synchronized (lock) { - long earliest = Long.MAX_VALUE; - for (TerrainTile tile : wanted) { - Retry retry = retries.get(tile); - if (retry != null && !inProgress.contains(tile)) { - earliest = Math.min(earliest, retry.readyAtNanos()); - } - } - return earliest == Long.MAX_VALUE ? -1L : Math.max(0L, earliest - System.nanoTime()); - } - } - - void close() { - synchronized (lock) { - closed = true; - wanted = List.of(); - sampled.clear(); - standIns.clear(); - retries.clear(); - } - } - - private void forgetBeyondMemory(Set inUse) { - Iterator> oldestFirst = sampled.entrySet().iterator(); - while (sampled.size() > mostTiles && oldestFirst.hasNext()) { - if (!inUse.contains(oldestFirst.next().getKey())) { - oldestFirst.remove(); - } - } - } - - private void startWorkers() { - while (runningWorkers < workerCount && nextWanted < wanted.size()) { - runningWorkers++; - try { - workers.execute(this::sampleWhileWanted); - } catch (RejectedExecutionException rejected) { - runningWorkers--; - if (!workers.isShutdown()) { - throw rejected; - } - return; - } - } - } - - private void sampleWhileWanted() { - TerrainTile tile; - while ((tile = takeNextWanted()) != null) { - long revision = ProvisionalSampling.revision(); - TerrainLayer layer = sampleSafely(tile); - boolean provisional = revision != ProvisionalSampling.revision(); - synchronized (lock) { - inProgress.remove(tile); - if (closed) { - runningWorkers--; - return; - } - if (provisional) { - standIns.put(tile, layer); - Retry previous = retries.get(tile); - long delay = previous == null ? FIRST_RETRY_NANOS : Math.min(MAX_RETRY_NANOS, previous.delayNanos() * 2L); - retries.put(tile, new Retry(System.nanoTime() + delay, delay)); - } else { - sampled.put(tile, layer); - standIns.remove(tile); - retries.remove(tile); - } - } - onTileSampled.run(); - } - } - - private TerrainTile takeNextWanted() { - synchronized (lock) { - while (!closed && nextWanted < wanted.size()) { - TerrainTile tile = wanted.get(nextWanted++); - Retry retry = retries.get(tile); - if (retry != null && System.nanoTime() < retry.readyAtNanos()) { - continue; - } - if (!sampled.containsKey(tile) && inProgress.add(tile)) { - return tile; - } - } - runningWorkers--; - return null; - } - } - - // Noise that fails somewhere shows a gap there rather than stopping the whole view. - private TerrainLayer sampleSafely(TerrainTile tile) { - try { - NoiseTerrain terrain = NoiseTerrain.sample(sampling, tile.grid()); - return TerrainLayer.of(terrain, sampling.floorY()); - } catch (RuntimeException error) { - IrisLogging.reportError(error); - return TerrainLayer.of(NoiseTerrain.empty(tile.grid()), sampling.floorY()); - } - } - - private record Retry(long readyAtNanos, long delayNanos) { - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/ThemeColor.java b/core/src/main/java/art/arcane/iris/studio/map/ThemeColor.java deleted file mode 100644 index c924d2c9e..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/ThemeColor.java +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import java.awt.Color; - -/** - * A colour with a light and a dark version that always answers with the one of the current theme, like IntelliJ's - * JBColor. Components keep the same colour object across a theme switch and simply paint in the other version. - */ -final class ThemeColor extends Color { - private static final long serialVersionUID = 2286435620386470207L; - private final Color light; - private final Color dark; - - ThemeColor(int lightRgb, int darkRgb) { - this(new Color(lightRgb), new Color(darkRgb)); - } - - ThemeColor(Color light, Color dark) { - super(dark.getRGB(), true); - this.light = light; - this.dark = dark; - } - - // Every other colour query of Color, and Java2D's painting, go through this one. - @Override - public int getRGB() { - return current().getRGB(); - } - - String toHtml() { - return String.format("#%06X", getRGB() & 0xFFFFFF); - } - - private Color current() { - return StudioTheme.isDark() ? dark : light; - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/ViewportWidthPanel.java b/core/src/main/java/art/arcane/iris/studio/map/ViewportWidthPanel.java deleted file mode 100644 index 312f43dec..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/ViewportWidthPanel.java +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import javax.swing.JPanel; -import javax.swing.Scrollable; -import javax.swing.SwingConstants; -import java.awt.Dimension; -import java.awt.Rectangle; - -/** - * Follows the scroll pane's width, so its content stretches or squeezes to fit instead of scrolling sideways. - */ -final class ViewportWidthPanel extends JPanel implements Scrollable { - private static final long serialVersionUID = 6086542174870301352L; - private static final int SCROLL_STEP = 18; - - @Override - public Dimension getPreferredScrollableViewportSize() { - return getPreferredSize(); - } - - @Override - public int getScrollableUnitIncrement(Rectangle visibleRect, int orientation, int direction) { - return StudioTheme.scale(SCROLL_STEP); - } - - @Override - public int getScrollableBlockIncrement(Rectangle visibleRect, int orientation, int direction) { - return orientation == SwingConstants.VERTICAL ? visibleRect.height : visibleRect.width; - } - - @Override - public boolean getScrollableTracksViewportWidth() { - return true; - } - - @Override - public boolean getScrollableTracksViewportHeight() { - return false; - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/VisionRenderController.java b/core/src/main/java/art/arcane/iris/studio/map/VisionRenderController.java deleted file mode 100644 index 619fa86fd..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/VisionRenderController.java +++ /dev/null @@ -1,744 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.studio.map.components.MapTileRenderer; -import art.arcane.iris.studio.map.components.MapLabels; -import art.arcane.iris.studio.map.components.MapLayer; -import art.arcane.iris.studio.map.components.MapTile; - -import java.awt.EventQueue; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Iterator; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.concurrent.ArrayBlockingQueue; -import java.util.concurrent.Callable; -import java.util.concurrent.CancellationException; -import java.util.concurrent.Future; -import java.util.concurrent.LinkedBlockingQueue; -import java.util.concurrent.RejectedExecutionException; -import java.util.concurrent.ThreadFactory; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.Consumer; -import java.util.function.LongSupplier; - -/** - * Renders the map as tiles on fixed zoom levels, so zooming within a level and panning reuse tiles that are already drawn. - * Tiles keep rendering while the view moves, as long as they are still on screen. - */ -final class VisionRenderController implements AutoCloseable { - static final int TILE_PIXELS = 64; - static final double MINIMUM_VIEW_BLOCKS_PER_PIXEL = 1D / 8D; - static final double MAXIMUM_BLOCKS_PER_PIXEL = 4_096D; - static final long FIRST_RETRY_NANOS = TimeUnit.MILLISECONDS.toNanos(500L); - static final long LAST_RETRY_NANOS = TimeUnit.SECONDS.toNanos(8L); - - private static final double MINIMUM_RENDER_BLOCKS_PER_PIXEL = 1D; - private static final int MAXIMUM_VISIBLE_TILES = 32_768; - private static final int PROBE_QUEUE_CAPACITY = 1; - private static final int COARSER_FALLBACK_LEVELS = 6; - private static final long CACHE_BYTES = 256L * 1024L * 1024L; - - private final Runnable listener; - private final LongSupplier nanoTime; - private final int workerCount; - private final ThreadPoolExecutor renderExecutor; - private final ThreadPoolExecutor probeExecutor; - private final WeightedTileCache cache; - private final Set tilesInFlight = new HashSet<>(); - private final AtomicInteger activeWorkers = new AtomicInteger(); - private final AtomicLong viewSequence = new AtomicLong(); - private final AtomicLong probeSequence = new AtomicLong(); - private final AtomicBoolean closed = new AtomicBoolean(); - private final AtomicBoolean publicationQueued = new AtomicBoolean(); - private final AtomicBoolean publicationDirty = new AtomicBoolean(); - private volatile Frame currentFrame; - private Future activeProbe; - - VisionRenderController(Runnable listener) { - this(listener, System::nanoTime); - } - - VisionRenderController(Runnable listener, LongSupplier nanoTime) { - this.listener = Objects.requireNonNull(listener, "listener"); - this.nanoTime = Objects.requireNonNull(nanoTime, "nanoTime"); - int processors = Math.max(1, Runtime.getRuntime().availableProcessors()); - this.workerCount = Math.max(1, Math.min(6, processors / 2)); - AtomicInteger threadSequence = new AtomicInteger(); - this.renderExecutor = new ThreadPoolExecutor( - workerCount, - workerCount, - 30L, - TimeUnit.SECONDS, - new LinkedBlockingQueue<>(), - daemonFactory("Iris Vision Render", Thread.NORM_PRIORITY, threadSequence) - ); - this.renderExecutor.allowCoreThreadTimeOut(true); - this.probeExecutor = new ThreadPoolExecutor( - 1, - 1, - 0L, - TimeUnit.MILLISECONDS, - new ArrayBlockingQueue<>(PROBE_QUEUE_CAPACITY), - daemonFactory("Iris Vision Probe", Thread.MIN_PRIORITY, threadSequence), - new ThreadPoolExecutor.DiscardOldestPolicy() - ); - this.cache = new WeightedTileCache(CACHE_BYTES); - MapHost.interruptOnPluginShutdown(renderExecutor); - MapHost.interruptOnPluginShutdown(probeExecutor); - } - - // Snapping to powers of two keeps every zoom within a level on the same tiles; nearest keeps tiles within 1.41x of screen size. - static double renderBlocksPerPixel(double viewBlocksPerPixel) { - double level = Math.pow(2D, Math.round(Math.log(viewBlocksPerPixel) / Math.log(2D))); - return Math.max(MINIMUM_RENDER_BLOCKS_PER_PIXEL, Math.min(MAXIMUM_BLOCKS_PER_PIXEL, level)); - } - - synchronized Frame request(RenderSpec spec) { - Objects.requireNonNull(spec, "spec"); - if (closed.get()) { - throw new IllegalStateException("Vision render controller is closed"); - } - double renderScale = renderBlocksPerPixel(spec.blocksPerPixel()); - List tiles = visibleTiles(spec, renderScale); - Frame frame = new Frame(viewSequence.incrementAndGet(), spec, renderScale, tiles); - for (VisibleTile tile : tiles) { - tile.state = cachedTileServing(tile.key()); - } - currentFrame = frame; - cancelProbe(); - startWorkers(); - publish(); - return frame; - } - - synchronized void retryProvisional(Frame frame) { - if (closed.get() || frame == null || frame != currentFrame) { - return; - } - frame.nextCandidate = 0; - startWorkers(); - } - - synchronized void suspend() { - currentFrame = null; - cancelProbe(); - } - - /** - * A tile from another zoom level covering the given one, to draw while the real tile renders. - */ - Fallback fallback(Frame frame, VisibleTile tile) { - Fallback complete = fallback(tile.key(), false); - return complete != null || tile.tile() != null ? complete : fallback(tile.key(), true); - } - - private Fallback fallback(TileKey key, boolean provisional) { - MapTile withoutHeights = fallbackTile(key.withHeights(false), provisional); - if (withoutHeights != null) { - return new Fallback(List.of(new FallbackPiece(withoutHeights, 0, 0, TILE_PIXELS, 0D, 0D, 1D))); - } - Fallback coarser = coarserFallback(key, provisional); - return coarser != null ? coarser : finerFallback(key, provisional); - } - - // A tile drawn with heights serves just as well where no heights are needed, so turning shading off redraws nothing. - private TileState cachedTileServing(TileKey key) { - CacheEntry exact = cache.get(key); - if (exact != null || key.heights()) { - return exact == null ? null : exact.state(); - } - CacheEntry shaded = cache.get(key.withHeights(true)); - return shaded != null && !shaded.state().provisional() ? shaded.state() : null; - } - - private MapTile fallbackTile(TileKey key, boolean provisional) { - CacheEntry entry = cache.get(key); - return entry != null && entry.state().provisional() == provisional ? entry.state().tile() : null; - } - - Progress progress(Frame frame) { - if (frame == null) { - return new Progress(0, 0, 0); - } - int ready = 0; - for (VisibleTile tile : frame.tiles()) { - if (tile.tile() != null && !tile.provisional()) { - ready++; - } - } - return new Progress(frame.tiles().size(), ready, activeWorkers.get()); - } - - synchronized void submitProbe(Frame frame, Callable probe, Consumer consumer) { - Objects.requireNonNull(probe, "probe"); - Objects.requireNonNull(consumer, "consumer"); - if (frame == null || closed.get() || currentFrame != frame) { - return; - } - cancelProbe(); - long probeRevision = probeSequence.get(); - try { - activeProbe = probeExecutor.submit(() -> runProbe(probeRevision, probe, consumer)); - } catch (RejectedExecutionException ignored) { - probeExecutor.getQueue().clear(); - } - } - - private void cancelProbe() { - probeSequence.incrementAndGet(); - if (activeProbe != null) { - activeProbe.cancel(true); - activeProbe = null; - } - probeExecutor.getQueue().clear(); - } - - @Override - public synchronized void close() { - if (!closed.compareAndSet(false, true)) { - return; - } - currentFrame = null; - cancelProbe(); - renderExecutor.shutdownNow(); - probeExecutor.shutdownNow(); - cache.clear(); - tilesInFlight.clear(); - } - - static List visibleTiles(RenderSpec spec, double renderScale) { - Objects.requireNonNull(spec, "spec"); - double blocksPerPixel = spec.blocksPerPixel(); - double tileSpan = TILE_PIXELS * renderScale; - double halfWidth = spec.width() * blocksPerPixel * 0.5D; - double halfHeight = spec.height() * blocksPerPixel * 0.5D; - long minimumX = floorTile(spec.centerX() - halfWidth, tileSpan); - long maximumX = floorTile(Math.nextDown(spec.centerX() + halfWidth), tileSpan); - long minimumZ = floorTile(spec.centerZ() - halfHeight, tileSpan); - long maximumZ = floorTile(Math.nextDown(spec.centerZ() + halfHeight), tileSpan); - long tileCount = Math.multiplyExact(maximumX - minimumX + 1L, maximumZ - minimumZ + 1L); - if (tileCount > MAXIMUM_VISIBLE_TILES) { - throw new IllegalArgumentException("Vision viewport contains too many tiles"); - } - - ArrayList tiles = new ArrayList<>((int) tileCount); - double centerTileX = spec.centerX() / tileSpan; - double centerTileZ = spec.centerZ() / tileSpan; - for (long tileZ = minimumZ; tileZ <= maximumZ; tileZ++) { - for (long tileX = minimumX; tileX <= maximumX; tileX++) { - double deltaX = tileX + 0.5D - centerTileX; - double deltaZ = tileZ + 0.5D - centerTileZ; - TileKey key = new TileKey(spec.contentRevision(), spec.layer(), spec.heights(), renderScale, tileX, tileZ); - tiles.add(new VisibleTile(key, deltaX * deltaX + deltaZ * deltaZ)); - } - } - tiles.sort(Comparator.comparingDouble(VisibleTile::distanceSquared) - .thenComparingLong(VisibleTile::tileZ) - .thenComparingLong(VisibleTile::tileX)); - return List.copyOf(tiles); - } - - private static long floorTile(double coordinate, double tileSpan) { - double tile = Math.floor(coordinate / tileSpan); - if (tile < Long.MIN_VALUE || tile > Long.MAX_VALUE) { - throw new IllegalArgumentException("Vision viewport exceeds tile coordinate range"); - } - return (long) tile; - } - - private static ThreadFactory daemonFactory(String name, int priority, AtomicInteger sequence) { - return (Runnable runnable) -> { - Thread thread = new Thread(runnable, name + " " + sequence.incrementAndGet()); - thread.setDaemon(true); - thread.setPriority(priority); - thread.setUncaughtExceptionHandler((Thread failedThread, Throwable error) -> IrisLogging.reportError(error)); - return thread; - }; - } - - private void startWorkers() { - while (!closed.get()) { - int active = activeWorkers.get(); - if (active >= workerCount || !hasWork()) { - return; - } - if (!activeWorkers.compareAndSet(active, active + 1)) { - continue; - } - try { - renderExecutor.execute(this::renderUntilIdle); - } catch (RejectedExecutionException ignored) { - activeWorkers.decrementAndGet(); - return; - } - } - } - - // Each worker keeps taking the most central missing tile of whatever frame is current, until the screen is covered. - private void renderUntilIdle() { - try { - TileJob job; - while ((job = claimNextTile()) != null) { - render(job); - } - } finally { - activeWorkers.decrementAndGet(); - } - startWorkers(); - } - - private synchronized boolean hasWork() { - Frame frame = currentFrame; - return frame != null && frame.nextMissing(tilesInFlight, false, nanoTime.getAsLong()) != null; - } - - private synchronized TileJob claimNextTile() { - Frame frame = currentFrame; - if (frame == null || closed.get()) { - return null; - } - VisibleTile tile = frame.nextMissing(tilesInFlight, true, nanoTime.getAsLong()); - if (tile == null) { - return null; - } - tilesInFlight.add(tile.key()); - CacheEntry cached = cache.get(tile.key()); - return new TileJob(frame.spec().renderer(), tile.key(), cached == null ? null : cached.work(), tile.state); - } - - private synchronized void release(TileKey key, boolean cancelled) { - tilesInFlight.remove(key); - Frame frame = currentFrame; - VisibleTile visible = frame == null ? null : frame.tile(key); - if (cancelled && visible != null && visible.needsRender(nanoTime.getAsLong(), frame.spec().renderer().previewRevision(), - frame.spec().renderer().riverRevision())) { - frame.nextCandidate = 0; - } - } - - private void render(TileJob job) { - TileKey key = job.key(); - boolean cancelled = false; - try { - long previewRevision = job.renderer().previewRevision(); - long riverRevision = job.renderer().riverRevision(); - double tileSpan = TILE_PIXELS * key.blocksPerPixel(); - MapTileRenderer.TileRender work = job.work(); - if (work == null) { - work = job.renderer().prepareTile(key.tileX() * tileSpan, key.tileZ() * tileSpan, - key.blocksPerPixel(), TILE_PIXELS, key.layer(), key.heights()); - } - MapTile tile = work.render(() -> !isWanted(key)); - boolean provisional = !work.complete(); - TileState previous = job.previous(); - long delay = 0L; - if (provisional) { - delay = previous == null || previous.retryDelay() == 0L - ? FIRST_RETRY_NANOS : Math.min(LAST_RETRY_NANOS, previous.retryDelay() * 2L); - } - long completedAt = nanoTime.getAsLong(); - boolean retained = work.retainsWater(); - TileState state = new TileState(tile, provisional, delay, completedAt + delay, - completedAt + FIRST_RETRY_NANOS, previewRevision, riverRevision, retained); - synchronized (this) { - if (closed.get()) { - return; - } - cache.put(key, state, provisional || retained ? work : null); - if (isWanted(key)) { - currentFrame.tile(key).state = state; - } - } - publish(); - } catch (CancellationException ignored) { - cancelled = true; - cache.discardWork(key); - } catch (Throwable error) { - IrisLogging.debug("Vision tile render failed: " + error.getClass().getSimpleName() + ": " + error.getMessage()); - } finally { - release(key, cancelled); - } - } - - private boolean isWanted(TileKey key) { - Frame frame = currentFrame; - return !closed.get() && frame != null && frame.tile(key) != null; - } - - private Fallback coarserFallback(TileKey key, boolean provisional) { - for (int level = 1; level <= COARSER_FALLBACK_LEVELS; level++) { - long scale = 1L << level; - int sourceSize = TILE_PIXELS >> level; - double parentScale = key.blocksPerPixel() * scale; - if (sourceSize < 1 || parentScale > MAXIMUM_BLOCKS_PER_PIXEL) { - return null; - } - long parentX = Math.floorDiv(key.tileX(), scale); - long parentZ = Math.floorDiv(key.tileZ(), scale); - MapTile parent = fallbackTile(new TileKey(key.contentRevision(), key.layer(), key.heights(), parentScale, - parentX, parentZ), provisional); - if (parent != null) { - int sourceX = (int) (key.tileX() - parentX * scale) * sourceSize; - int sourceZ = (int) (key.tileZ() - parentZ * scale) * sourceSize; - return new Fallback(List.of(new FallbackPiece(parent, sourceX, sourceZ, sourceSize, 0D, 0D, 1D))); - } - } - return null; - } - - private Fallback finerFallback(TileKey key, boolean provisional) { - double childScale = key.blocksPerPixel() / 2D; - if (childScale < MINIMUM_RENDER_BLOCKS_PER_PIXEL) { - return null; - } - List pieces = new ArrayList<>(4); - for (int childZ = 0; childZ < 2; childZ++) { - for (int childX = 0; childX < 2; childX++) { - MapTile child = fallbackTile(new TileKey(key.contentRevision(), key.layer(), key.heights(), childScale, - key.tileX() * 2L + childX, key.tileZ() * 2L + childZ), provisional); - if (child != null) { - pieces.add(new FallbackPiece(child, 0, 0, TILE_PIXELS, childX * 0.5D, childZ * 0.5D, 0.5D)); - } - } - } - return pieces.isEmpty() ? null : new Fallback(List.copyOf(pieces)); - } - - private void runProbe(long probeRevision, Callable probe, Consumer consumer) { - try { - if (!isProbeCurrent(probeRevision)) { - return; - } - T result = probe.call(); - if (!isProbeCurrent(probeRevision)) { - return; - } - EventQueue.invokeLater(() -> { - if (isProbeCurrent(probeRevision)) { - consumer.accept(result); - } - }); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - } catch (Throwable error) { - IrisLogging.debug("Vision probe failed: " + error.getClass().getSimpleName() + ": " + error.getMessage()); - } - } - - private boolean isProbeCurrent(long probeRevision) { - return !closed.get() && probeSequence.get() == probeRevision; - } - - private void publish() { - if (closed.get()) { - return; - } - publicationDirty.set(true); - queuePublication(); - } - - private void queuePublication() { - if (!publicationQueued.compareAndSet(false, true)) { - return; - } - EventQueue.invokeLater(() -> { - try { - if (publicationDirty.getAndSet(false) && !closed.get()) { - listener.run(); - } - } finally { - publicationQueued.set(false); - if (publicationDirty.get() && !closed.get()) { - queuePublication(); - } - } - }); - } - - record RenderSpec( - MapTileRenderer renderer, - MapLayer layer, - long contentRevision, - double centerX, - double centerZ, - double blocksPerPixel, - int width, - int height, - boolean heights - ) { - RenderSpec { - Objects.requireNonNull(renderer, "renderer"); - Objects.requireNonNull(layer, "layer"); - if (!Double.isFinite(centerX) || !Double.isFinite(centerZ)) { - throw new IllegalArgumentException("Vision center must be finite"); - } - if (!Double.isFinite(blocksPerPixel) - || blocksPerPixel < MINIMUM_VIEW_BLOCKS_PER_PIXEL - || blocksPerPixel > MAXIMUM_BLOCKS_PER_PIXEL) { - throw new IllegalArgumentException("Vision scale is outside the supported range"); - } - if (width < 1 || height < 1) { - throw new IllegalArgumentException("Vision viewport must be positive"); - } - } - } - - static final class Frame { - private final long viewRevision; - private final RenderSpec spec; - private final double renderBlocksPerPixel; - private final List tiles; - private final Map tilesByKey; - private int nextCandidate; - - private Frame(long viewRevision, RenderSpec spec, double renderBlocksPerPixel, List tiles) { - this.viewRevision = viewRevision; - this.spec = Objects.requireNonNull(spec, "spec"); - this.renderBlocksPerPixel = renderBlocksPerPixel; - this.tiles = tiles; - this.tilesByKey = new HashMap<>(tiles.size() * 2); - for (VisibleTile tile : tiles) { - tilesByKey.put(tile.key(), tile); - } - } - - long viewRevision() { - return viewRevision; - } - - RenderSpec spec() { - return spec; - } - - double renderBlocksPerPixel() { - return renderBlocksPerPixel; - } - - List tiles() { - return tiles; - } - - private VisibleTile tile(TileKey key) { - return tilesByKey.get(key); - } - - /** - * The tile covering a world position together with the pixel of it there, or null when that tile is not drawn yet. - */ - TilePixel pixelAt(double worldX, double worldZ) { - double tileSpan = TILE_PIXELS * renderBlocksPerPixel; - long tileX = (long) Math.floor(worldX / tileSpan); - long tileZ = (long) Math.floor(worldZ / tileSpan); - VisibleTile visible = tilesByKey.get(new TileKey(spec.contentRevision(), spec.layer(), spec.heights(), - renderBlocksPerPixel, tileX, tileZ)); - MapTile tile = visible == null ? null : visible.tile(); - if (tile == null) { - return null; - } - int pixelX = pixelWithin(worldX - tileX * tileSpan); - int pixelZ = pixelWithin(worldZ - tileZ * tileSpan); - return new TilePixel(tile, pixelX, pixelZ); - } - - private int pixelWithin(double offsetBlocks) { - return Math.max(0, Math.min(TILE_PIXELS - 1, (int) Math.floor(offsetBlocks / renderBlocksPerPixel))); - } - - // Tiles are sorted centre first, and everything before the cursor is drawn or claimed, so each search resumes there. - private VisibleTile nextMissing(Set inFlight, boolean advance, long now) { - long previewRevision = spec.renderer().previewRevision(); - long riverRevision = spec.renderer().riverRevision(); - for (int index = nextCandidate; index < tiles.size(); index++) { - VisibleTile tile = tiles.get(index); - if (tile.needsRender(now, previewRevision, riverRevision) && !inFlight.contains(tile.key())) { - if (advance) { - nextCandidate = index + 1; - } - return tile; - } - } - if (advance) { - nextCandidate = tiles.size(); - } - return null; - } - } - - static final class VisibleTile { - private final TileKey key; - private final double distanceSquared; - private volatile TileState state; - - private VisibleTile(TileKey key, double distanceSquared) { - this.key = key; - this.distanceSquared = distanceSquared; - } - - TileKey key() { - return key; - } - - long tileX() { - return key.tileX(); - } - - long tileZ() { - return key.tileZ(); - } - - double distanceSquared() { - return distanceSquared; - } - - MapTile tile() { - TileState current = state; - return current == null ? null : current.tile(); - } - - boolean provisional() { - TileState current = state; - return current != null && current.provisional(); - } - - private boolean needsRender(long now, long previewRevision, long riverRevision) { - TileState current = state; - if (current == null) { - return true; - } - if (current.provisional()) { - return now - current.retryAt() >= 0L - || previewRevision != current.previewRevision() && now - current.earliestRetryAt() >= 0L; - } - return current.retained() && riverRevision != current.riverRevision() && now - current.earliestRetryAt() >= 0L; - } - } - - /** - * @param heights whether the tile also carries terrain heights, for shading - */ - record TileKey(long contentRevision, MapLayer layer, boolean heights, double blocksPerPixel, long tileX, long tileZ) { - TileKey { - Objects.requireNonNull(layer, "layer"); - if (!Double.isFinite(blocksPerPixel) || blocksPerPixel <= 0D) { - throw new IllegalArgumentException("Vision cache scale must be finite and positive"); - } - } - - TileKey withHeights(boolean nextHeights) { - return new TileKey(contentRevision, layer, nextHeights, blocksPerPixel, tileX, tileZ); - } - } - - record TilePixel(MapTile tile, int pixelX, int pixelZ) { - MapLabels.Label subject() { - return tile.labels().label(tile.subjectAt(pixelX, pixelZ)); - } - - MapLabels.Label region() { - return tile.labels().label(tile.regionAt(pixelX, pixelZ)); - } - } - - /** - * Pieces of cached tiles that together cover a missing tile; offsets and size are fractions of the tile. - */ - record Fallback(List pieces) { - } - - record FallbackPiece(MapTile tile, int sourceX, int sourceZ, int sourceSize, double offsetX, double offsetZ, - double size) { - } - - record Progress(int total, int ready, int activeWorkers) { - double completion() { - if (total == 0) { - return 1D; - } - return Math.min(1D, ready / (double) total); - } - } - - private record TileJob(MapTileRenderer renderer, TileKey key, MapTileRenderer.TileRender work, TileState previous) { - } - - private record TileState(MapTile tile, boolean provisional, long retryDelay, long retryAt, long earliestRetryAt, - long previewRevision, long riverRevision, boolean retained) { - } - - private static final class WeightedTileCache { - private final long maximumBytes; - private final LinkedHashMap entries; - private long bytes; - - private WeightedTileCache(long maximumBytes) { - this.maximumBytes = maximumBytes; - this.entries = new LinkedHashMap<>(128, 0.75F, true); - } - - synchronized CacheEntry get(TileKey key) { - return entries.get(key); - } - - synchronized void put(TileKey key, TileState state, MapTileRenderer.TileRender work) { - long tileBytes = state.tile().bytes() + (work == null ? 0L : work.bytes()); - CacheEntry previous = entries.put(key, new CacheEntry(state, work, tileBytes)); - if (previous != null) { - bytes -= previous.bytes(); - } - bytes += tileBytes; - while (bytes > maximumBytes && !entries.isEmpty()) { - Iterator> iterator = entries.entrySet().iterator(); - Map.Entry eldest = iterator.next(); - bytes -= eldest.getValue().bytes(); - iterator.remove(); - } - } - - synchronized void clear() { - entries.clear(); - bytes = 0L; - } - - synchronized void discardWork(TileKey key) { - CacheEntry entry = entries.get(key); - if (entry == null || entry.work() == null) { - return; - } - long retainedBytes = entry.state().tile().bytes(); - entries.put(key, new CacheEntry(entry.state(), null, retainedBytes)); - bytes -= entry.bytes() - retainedBytes; - } - } - - private record CacheEntry(TileState state, MapTileRenderer.TileRender work, long bytes) { - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/VisionViewport.java b/core/src/main/java/art/arcane/iris/studio/map/VisionViewport.java deleted file mode 100644 index 7db8a890d..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/VisionViewport.java +++ /dev/null @@ -1,60 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -record VisionViewport(double centerX, double centerZ, double blocksPerPixel) { - VisionViewport { - if (!Double.isFinite(centerX) || !Double.isFinite(centerZ)) { - throw new IllegalArgumentException("Vision viewport center must be finite"); - } - if (!Double.isFinite(blocksPerPixel) || blocksPerPixel <= 0D) { - throw new IllegalArgumentException("Vision viewport scale must be finite and positive"); - } - } - - double worldX(double screenX, int width) { - return centerX + (screenX - width * 0.5D) * blocksPerPixel; - } - - double worldZ(double screenZ, int height) { - return centerZ + (screenZ - height * 0.5D) * blocksPerPixel; - } - - VisionViewport zoomAt( - double screenX, - double screenZ, - int width, - int height, - double factor, - double minimumScale, - double maximumScale - ) { - if (!Double.isFinite(factor) || factor <= 0D) { - throw new IllegalArgumentException("Vision zoom factor must be finite and positive"); - } - double anchorX = worldX(screenX, width); - double anchorZ = worldZ(screenZ, height); - double nextScale = Math.max(minimumScale, Math.min(maximumScale, blocksPerPixel * factor)); - return new VisionViewport( - anchorX - (screenX - width * 0.5D) * nextScale, - anchorZ - (screenZ - height * 0.5D) * nextScale, - nextScale - ); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/WorldColoring.java b/core/src/main/java/art/arcane/iris/studio/map/WorldColoring.java deleted file mode 100644 index b5409d4ba..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/WorldColoring.java +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.studio.map.components.MapLabels; -import art.arcane.iris.studio.render.RenderType; -import art.arcane.iris.generation.runtime.IrisComplex; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.generation.biome.IrisBiome; -import art.arcane.iris.generation.terrain.IrisRegion; - -/** - * What the 3D world view colours its ground by. - */ -enum WorldColoring { - BIOMES("Biomes", "Colour the ground by its biome") { - @Override - WorldSubject subjectAt(Engine engine, double x, double z) { - IrisBiome biome = engine.getComplex().getTrueBiomeStream().get(x, z); - return new WorldSubject(MapLabels.Kind.BIOME, biome.getLoadKey(), biome.getName(), - biome.getColor(engine, RenderType.BIOME).getRGB() & 0xFFFFFF); - } - }, - REGIONS("Regions", "Colour the ground by its region") { - @Override - WorldSubject subjectAt(Engine engine, double x, double z) { - IrisComplex complex = engine.getComplex(); - IrisRegion region = complex.getRegionStream().get(x, z); - return new WorldSubject(MapLabels.Kind.REGION, region.getLoadKey(), region.getName(), - region.getColor(complex, RenderType.REGION).getRGB() & 0xFFFFFF); - } - }; - - private final String label; - private final String description; - - WorldColoring(String label, String description) { - this.label = label; - this.description = description; - } - - /** - * @return what colours the ground here, or null when this colouring doesn't apply to the world - */ - abstract WorldSubject subjectAt(Engine engine, double x, double z); - - String label() { - return label; - } - - String description() { - return description; - } - - /** - * A biome or region as the ground shows it. - * - * @param key told apart by, and shown when names clash - */ - record WorldSubject(MapLabels.Kind kind, String key, String name, int color) { - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/WorldColumns.java b/core/src/main/java/art/arcane/iris/studio/map/WorldColumns.java deleted file mode 100644 index 3be8f38d5..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/WorldColumns.java +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.volmlib.util.stream.ProceduralStream; - -/** - * The world's terrain as the engine plans it, without carving or objects: each column at its terrain height, coloured - * by the chosen colouring. - */ -record WorldColumns(Engine engine, WorldColoring coloring) implements TerrainColumns { - private static final int UNCOLORED = 0x000000; - - @Override - public void sampleRow(TerrainGrid grid, int row, float[] heights, int[] colors) { - ProceduralStream terrainHeights = engine.getComplex().getHeightStream(); - double worldZ = grid.originZ() + (double) row * grid.step(); - for (int column = 0; column < grid.columns(); column++) { - double worldX = grid.originX() + (double) column * grid.step(); - int index = row * grid.columns() + column; - heights[index] = (float) terrainHeights.getDouble(worldX, worldZ); - WorldColoring.WorldSubject subject = coloring.subjectAt(engine, worldX, worldZ); - colors[index] = subject == null ? UNCOLORED : subject.color(); - } - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/WorldExplorer.java b/core/src/main/java/art/arcane/iris/studio/map/WorldExplorer.java deleted file mode 100644 index c161c183e..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/WorldExplorer.java +++ /dev/null @@ -1,494 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.studio.map.components.MapLabels; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.generation.stream.ProvisionalSampling; -import art.arcane.volmlib.util.format.Form; -import art.arcane.volmlib.util.stream.ProceduralStream; - -import javax.swing.ButtonGroup; -import javax.swing.JComponent; -import javax.swing.JToggleButton; -import javax.swing.Timer; -import java.awt.EventQueue; -import java.awt.Point; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.util.ArrayList; -import java.util.Comparator; -import java.util.EnumMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.ThreadPoolExecutor; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.DoubleBinaryOperator; -import java.util.function.Function; -import java.util.function.Supplier; -import java.util.stream.Collectors; - -/** - * The map's 3D world view: the terrain the engine plans, without caves or objects, coloured by biome, region or how - * HYBRID terrain picked each biome. The legend counts what the view shows and the status bar names what is under the - * pointer. - */ -final class WorldExplorer { - private static final int MOST_WORKERS = 12; - private static final String CAMERA_HINT = "Drag to orbit · Right-drag to pan · Scroll to zoom · R resets"; - private static final int POINTER_SETTLE_MILLIS = 60; - private static final int CENSUS_SETTLE_MILLIS = 250; - private static final int FIRST_RETRY_MILLIS = 500; - private static final int MAX_RETRY_MILLIS = 8_000; - // Enough for each share to be within about a percent. - private static final int MOST_CENSUS_SPOTS = 2_500; - // Heights sampled around where the view opens, to tell how low and high its ground goes. - private static final int HEIGHT_PROBES_ACROSS = 9; - private static final double HEIGHT_PROBE_REACH_BLOCKS = 2_048D; - private static final int FLOOR_MARGIN_BLOCKS = 32; - private static final int TOP_MARGIN_BLOCKS = 96; - - private final Supplier engineSource; - private final OrbitViewport viewport = new OrbitViewport("Iris World Terrain Viewer", null); - private final int workerCount = Math.min(MOST_WORKERS, Math.max(1, Runtime.getRuntime().availableProcessors() / 2)); - private final ThreadPoolExecutor renderWorkers = NoiseExplorerGUI.createWorkers("Iris World Terrain Worker", workerCount); - private final ThreadPoolExecutor samplers = NoiseExplorerGUI.createWorkers("Iris World Terrain Sampler", workerCount); - // Counting what is in view takes a while, so the pointer is looked up on a thread of its own. - private final ExecutorService lookups = singleThread("Iris World Lookup"); - private final ExecutorService counter = singleThread("Iris World Census"); - private final NoiseTerrainView terrainView; - private final StudioStatusBar statusBar = new StudioStatusBar(); - private final MapLegendPanel legend = MapLegendPanel.listingOnly(); - private final Map coloringButtons = new EnumMap<>(WorldColoring.class); - private final AtomicLong pointerRevision = new AtomicLong(); - private final AtomicLong censusRevision = new AtomicLong(); - private final AtomicLong samplingRevision = new AtomicLong(); - private final Timer pointerTimer = singleShot(POINTER_SETTLE_MILLIS, this::lookUpPointer); - private final Timer censusTimer = singleShot(CENSUS_SETTLE_MILLIS, this::countInView); - private final Timer measurementRetryTimer = singleShot(FIRST_RETRY_MILLIS, this::retryMeasurement); - private WorldColoring coloring = WorldColoring.BIOMES; - private Engine sampledEngine; - // How low and high the sampled world's ground goes; the colouring is swapped in for each sampling. - private TerrainSampling measured; - private WorldSampleRequest measurementRequest; - private int measurementRetryMillis = FIRST_RETRY_MILLIS; - private Point pointer; - private String pointedAt; - private boolean visible; - private boolean closed; - - WorldExplorer(Supplier engineSource) { - this.engineSource = engineSource; - this.terrainView = new NoiseTerrainView(viewport, renderWorkers, samplers, workerCount); - terrainView.onProgress(this::viewProgressed); - MapHost.interruptOnPluginShutdown(renderWorkers); - MapHost.interruptOnPluginShutdown(samplers); - MapHost.interruptOnPluginShutdown(lookups); - MapHost.interruptOnPluginShutdown(counter); - followPointer(); - refreshStatus(); - } - - JComponent view() { - return viewport; - } - - StudioStatusBar statusBar() { - return statusBar; - } - - MapLegendPanel legend() { - return legend; - } - - List controls() { - ButtonGroup group = new ButtonGroup(); - for (WorldColoring choice : WorldColoring.values()) { - JToggleButton button = StudioToolbar.toggle(choice.label(), choice.description()); - button.setSelected(choice == coloring); - button.addActionListener(event -> colorBy(choice)); - group.add(button); - coloringButtons.put(choice, button); - } - return List.copyOf(coloringButtons.values()); - } - - /** - * Shows the world around this point, keeping the camera when the view already shows the same world there. - */ - void show(double centerX, double centerZ, boolean recenter) { - if (closed) { - return; - } - visible = true; - if (recenter || sampledEngine == null || sampledEngine != engineSource.get()) { - terrainView.centerOn(centerX, centerZ); - sampleWorld(centerX, centerZ); - } else { - terrainView.resume(); - if (measurementRequest != null) { - measurementRetryTimer.restart(); - } - } - viewport.requestFocusInWindow(); - } - - void hide() { - visible = false; - pointerTimer.stop(); - censusTimer.stop(); - measurementRetryTimer.stop(); - terrainView.hide(); - } - - /** - * Samples the world anew, for a pack that changed on disk. - */ - void refresh(double centerX, double centerZ) { - if (closed) { - return; - } - if (visible) { - sampleWorld(centerX, centerZ); - } else { - invalidateSampling(); - } - } - - void resetCamera() { - viewport.resetCamera(); - } - - void setCoveredLeftWidth(int width) { - viewport.setCoveredLeftWidth(width); - } - - void close() { - if (closed) { - return; - } - closed = true; - visible = false; - invalidateSampling(); - terrainView.close(); - lookups.shutdownNow(); - counter.shutdownNow(); - renderWorkers.shutdownNow(); - samplers.shutdownNow(); - viewport.close(); - } - - private void colorBy(WorldColoring nextColoring) { - if (closed || nextColoring == coloring) { - return; - } - coloring = nextColoring; - legend.show(coloring.label() + " in view", List.of(), null); - if (sampledEngine != null) { - terrainView.show(samplingOf(sampledEngine, measured)); - } - refreshStatus(); - viewport.requestFocusInWindow(); - } - - // How low and high the ground goes is measured off the Swing thread, as it samples the terrain itself. - private void sampleWorld(double centerX, double centerZ) { - if (closed) { - return; - } - invalidateSampling(); - Engine engine = engineSource.get(); - if (engine == null || engine.isClosed() || engine.isClosing()) { - viewport.showMessage("No active Iris engine"); - return; - } - WorldSampleRequest request = new WorldSampleRequest(samplingRevision.get(), engine, centerX, centerZ); - measurementRequest = request; - if (!viewport.isShowingScene()) { - viewport.showLoading("Sampling the world"); - } - sampleMeasurement(request); - } - - private void invalidateSampling() { - samplingRevision.incrementAndGet(); - pointerRevision.incrementAndGet(); - censusRevision.incrementAndGet(); - measurementRequest = null; - measurementRetryMillis = FIRST_RETRY_MILLIS; - measurementRetryTimer.stop(); - pointerTimer.stop(); - censusTimer.stop(); - sampledEngine = null; - measured = null; - terrainView.invalidate(); - } - - private void retryMeasurement() { - WorldSampleRequest request = measurementRequest; - if (!closed && visible && request != null) { - sampleMeasurement(request); - } - } - - private void sampleMeasurement(WorldSampleRequest request) { - lookups.execute(() -> { - if (request.revision() != samplingRevision.get()) { - return; - } - long revision = ProvisionalSampling.revision(); - TerrainSampling sampling = measuredSampling(request.engine(), request.centerX(), request.centerZ()); - boolean provisional = revision != ProvisionalSampling.revision(); - EventQueue.invokeLater(() -> showSampled(request, sampling, provisional)); - }); - } - - private void showSampled(WorldSampleRequest request, TerrainSampling sampling, boolean provisional) { - Engine engine = request.engine(); - if (closed || request != measurementRequest || request.revision() != samplingRevision.get() - || engine != engineSource.get() || engine.isClosed() || engine.isClosing()) { - return; - } - boolean changed = measured == null || sampledEngine != engine || measured.floorY() != sampling.floorY() - || measured.topY() != sampling.topY() || measured.waterLevel() != sampling.waterLevel(); - sampledEngine = engine; - measured = sampling; - if (changed) { - terrainView.show(samplingOf(engine, sampling)); - if (!visible) { - terrainView.hide(); - } - } - if (provisional && visible) { - measurementRetryTimer.setInitialDelay(measurementRetryMillis); - measurementRetryTimer.restart(); - measurementRetryMillis = Math.min(MAX_RETRY_MILLIS, measurementRetryMillis * 2); - } else if (!provisional) { - measurementRequest = null; - measurementRetryTimer.stop(); - } - refreshStatus(); - } - - private TerrainSampling measuredSampling(Engine engine, double centerX, double centerZ) { - ProceduralStream heights = engine.getComplex().getHeightStream(); - double fluidHeight = engine.getComplex().getFluidHeight(); - double lowest = fluidHeight; - double highest = fluidHeight; - double spacing = 2D * HEIGHT_PROBE_REACH_BLOCKS / (HEIGHT_PROBES_ACROSS - 1); - for (int row = 0; row < HEIGHT_PROBES_ACROSS; row++) { - for (int column = 0; column < HEIGHT_PROBES_ACROSS; column++) { - double height = heights.getDouble(centerX - HEIGHT_PROBE_REACH_BLOCKS + column * spacing, - centerZ - HEIGHT_PROBE_REACH_BLOCKS + row * spacing); - lowest = Math.min(lowest, height); - highest = Math.max(highest, height); - } - } - int floorY = Math.max(0, (int) Math.floor(lowest) - FLOOR_MARGIN_BLOCKS); - int topY = Math.min(engine.getHeight(), (int) Math.ceil(highest) + TOP_MARGIN_BLOCKS); - return new TerrainSampling(new WorldColumns(engine, coloring), floorY, topY, fluidHeight); - } - - private TerrainSampling samplingOf(Engine engine, TerrainSampling measured) { - return new TerrainSampling(new WorldColumns(engine, coloring), measured.floorY(), measured.topY(), measured.waterLevel()); - } - - private void viewProgressed() { - if (closed || !visible) { - return; - } - refreshStatus(); - censusTimer.restart(); - } - - private void followPointer() { - MouseAdapter mouse = new MouseAdapter() { - @Override - public void mouseMoved(MouseEvent event) { - if (closed || !visible) { - return; - } - pointer = event.getPoint(); - pointerTimer.restart(); - } - - @Override - public void mouseDragged(MouseEvent event) { - mouseMoved(event); - } - - @Override - public void mouseExited(MouseEvent event) { - pointer = null; - pointerRevision.incrementAndGet(); - pointedAt = null; - refreshStatus(); - } - }; - viewport.addMouseListener(mouse); - viewport.addMouseMotionListener(mouse); - } - - private void lookUpPointer() { - Point at = pointer; - Engine engine = sampledEngine; - GroundSight sight = terrainView.groundSight(); - if (closed || !visible || at == null || engine == null || sight == null) { - return; - } - long revision = pointerRevision.incrementAndGet(); - lookups.execute(() -> { - String description = describeGroundAt(engine, sight, at); - EventQueue.invokeLater(() -> { - if (!closed && visible && revision == pointerRevision.get()) { - pointedAt = description; - refreshStatus(); - } - }); - }); - } - - private static String describeGroundAt(Engine engine, GroundSight sight, Point at) { - try { - Optional ground = sight.groundAt(at.x, at.y, surfaceOf(engine)); - if (ground.isEmpty()) { - return null; - } - Vec3 spot = ground.get(); - double terrainHeight = engine.getComplex().getHeightStream().getDouble(spot.x(), spot.z()); - return subjectsAt(engine, spot.x(), spot.z()) + " X " + Form.f((int) Math.floor(spot.x())) - + " Y " + Form.f(engine.getMinHeight() + (int) Math.floor(terrainHeight)) - + " Z " + Form.f((int) Math.floor(spot.z())); - } catch (RuntimeException error) { - IrisLogging.reportError(error); - return null; - } - } - - private static String subjectsAt(Engine engine, double x, double z) { - List names = new ArrayList<>(); - for (WorldColoring each : WorldColoring.values()) { - WorldColoring.WorldSubject subject = each.subjectAt(engine, x, z); - if (subject != null) { - names.add(subject.name()); - } - } - return String.join(" · ", names); - } - - // Water hides the ground under it, so a line of sight stops on its surface. - private static DoubleBinaryOperator surfaceOf(Engine engine) { - ProceduralStream heights = engine.getComplex().getHeightStream(); - double fluidHeight = engine.getComplex().getFluidHeight(); - return (x, z) -> Math.max(heights.getDouble(x, z), fluidHeight); - } - - private void countInView() { - Engine engine = sampledEngine; - GroundSight sight = terrainView.groundSight(); - if (closed || !visible || engine == null || sight == null) { - return; - } - WorldColoring counted = coloring; - long revision = censusRevision.incrementAndGet(); - long worldRevision = samplingRevision.get(); - counter.execute(() -> { - if (revision != censusRevision.get()) { - return; - } - List shares = countSafely(engine, sight, counted); - EventQueue.invokeLater(() -> { - if (worldRevision == samplingRevision.get()) { - showCensus(counted, shares); - } - }); - }); - } - - // A count of a view the camera has since left still beats an empty legend, as long as it counts what the ground shows. - private void showCensus(WorldColoring counted, List shares) { - if (!closed && counted == coloring) { - legend.show(counted.label() + " in view", shares, null); - } - } - - private static List countSafely(Engine engine, GroundSight sight, WorldColoring coloring) { - try { - return count(engine, sight, coloring); - } catch (RuntimeException error) { - IrisLogging.reportError(error); - return List.of(); - } - } - - private static List count(Engine engine, GroundSight sight, WorldColoring coloring) { - List spots = sight.groundInView(MOST_CENSUS_SPOTS, surfaceOf(engine)); - Map counts = spots.stream() - .map(spot -> coloring.subjectAt(engine, spot.x(), spot.z())) - .filter(Objects::nonNull) - .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); - long total = counts.values().stream().mapToLong(Long::longValue).sum(); - List shares = new ArrayList<>(counts.size()); - short id = 0; - for (Map.Entry entry : counts.entrySet()) { - WorldColoring.WorldSubject subject = entry.getKey(); - MapLabels.Label label = new MapLabels.Label(id++, subject.kind(), subject.key(), subject.name(), subject); - shares.add(new MapCensus.Share(label, subject.color(), entry.getValue() / (double) total)); - } - shares.sort(Comparator.comparingDouble(MapCensus.Share::fraction).reversed().thenComparing(share -> share.label().name())); - return shares; - } - - private void refreshStatus() { - statusBar.showSummary(summary()); - int pending = terrainView.pendingTiles(); - statusBar.showActivity(pending == 0 ? "" : "Sampling " + pending + (pending == 1 ? " tile" : " tiles")); - statusBar.showPosition(pointedAt == null ? CAMERA_HINT : pointedAt); - } - - private String summary() { - int detailStep = terrainView.detailStep(); - if (detailStep == 0) { - return coloring.label() + " · sampling"; - } - return coloring.label() + " · " + (detailStep == 1 ? "full detail" : "1 column per " + detailStep + " blocks"); - } - - private static ExecutorService singleThread(String name) { - return Executors.newSingleThreadExecutor(task -> { - Thread thread = new Thread(task, name); - thread.setDaemon(true); - return thread; - }); - } - - private static Timer singleShot(int delayMillis, Runnable action) { - Timer timer = new Timer(delayMillis, event -> action.run()); - timer.setRepeats(false); - return timer; - } - - private record WorldSampleRequest(long revision, Engine engine, double centerX, double centerZ) { - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/XwaylandWindowManagerHint.java b/core/src/main/java/art/arcane/iris/studio/map/XwaylandWindowManagerHint.java deleted file mode 100644 index 4de8dba35..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/XwaylandWindowManagerHint.java +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map; - -import com.sun.jna.platform.linux.LibC; -import art.arcane.iris.spi.IrisLogging; - -import java.util.Arrays; -import java.util.List; -import java.util.Locale; -import java.util.Map; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Java does not recognise the non-reparenting Xwayland window managers of compositors such as niri, sway and Hyprland. - * It waits for a reparent that never comes and paints only a corner of each window. Java reads this hint from the - * native environment once, at the first decorated window, so it is set through libc before Iris opens any window. - */ -final class XwaylandWindowManagerHint { - private static final String NON_REPARENTING_VARIABLE = "_JAVA_AWT_WM_NONREPARENTING"; - private static final int KEEP_EXISTING_VALUE = 0; - private static final List REPARENTING_DESKTOPS = List.of("GNOME", "KDE"); - private static final AtomicBoolean APPLIED = new AtomicBoolean(); - - private XwaylandWindowManagerHint() { - } - - static void apply() { - if (!APPLIED.compareAndSet(false, true) || !isNeeded(System.getenv(), System.getProperty("os.name", ""))) { - return; - } - - try { - if (LibC.INSTANCE.setenv(NON_REPARENTING_VARIABLE, "1", KEEP_EXISTING_VALUE) != 0) { - warnUnapplied(); - } - } catch (Throwable e) { - IrisLogging.reportError(e); - warnUnapplied(); - } - } - - static boolean isNeeded(Map environment, String osName) { - return osName.toLowerCase(Locale.ROOT).contains("linux") - && isSet(environment, "WAYLAND_DISPLAY") - && isSet(environment, "DISPLAY") - && !isSet(environment, NON_REPARENTING_VARIABLE) - && !isReparentingDesktop(environment.get("XDG_CURRENT_DESKTOP")); - } - - private static boolean isReparentingDesktop(String currentDesktop) { - if (currentDesktop == null) { - return false; - } - - return Arrays.stream(currentDesktop.split(":")) - .map(desktop -> desktop.trim().toUpperCase(Locale.ROOT)) - .anyMatch(REPARENTING_DESKTOPS::contains); - } - - private static boolean isSet(Map environment, String variable) { - String value = environment.get(variable); - return value != null && !value.isBlank(); - } - - private static void warnUnapplied() { - IrisLogging.warn("Iris could not adjust Java for this Wayland desktop, so its windows may stay blank. " - + "Start the server with %s=1 set to fix that.", NON_REPARENTING_VARIABLE); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/map/components/Renderer.java b/core/src/main/java/art/arcane/iris/studio/map/components/Renderer.java deleted file mode 100644 index 91ce07715..000000000 --- a/core/src/main/java/art/arcane/iris/studio/map/components/Renderer.java +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Bukkit Servers - * Copyright (c) 2022 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.map.components; - -import java.awt.Color; - -@FunctionalInterface -public interface Renderer { - Color draw(double x, double z); -} diff --git a/core/src/main/java/art/arcane/iris/studio/view/PregenMapPanel.java b/core/src/main/java/art/arcane/iris/studio/view/PregenMapPanel.java deleted file mode 100644 index 44319fd40..000000000 --- a/core/src/main/java/art/arcane/iris/studio/view/PregenMapPanel.java +++ /dev/null @@ -1,331 +0,0 @@ -package art.arcane.iris.studio.view; - -import art.arcane.iris.localization.DesktopUiMessages; -import art.arcane.iris.localization.IrisLanguage; -import art.arcane.iris.studio.map.StudioTheme; -import art.arcane.volmlib.util.localization.MessageArgument; - -import javax.swing.JPanel; -import javax.swing.SwingUtilities; -import javax.swing.ToolTipManager; -import java.awt.Color; -import java.awt.Cursor; -import java.awt.FontMetrics; -import java.awt.Graphics; -import java.awt.Graphics2D; -import java.awt.Point; -import java.awt.Rectangle; -import java.awt.RenderingHints; -import java.awt.event.MouseAdapter; -import java.awt.event.MouseEvent; -import java.awt.event.MouseWheelEvent; -import java.awt.geom.AffineTransform; -import java.awt.geom.Rectangle2D; -import java.awt.image.BufferedImage; -import java.awt.image.DataBufferInt; - -final class PregenMapPanel extends JPanel { - private static final double MIN_ZOOM = 0.25D; - private static final double MAX_ZOOM = 128D; - private static final double ZOOM_STEP = 1.25D; - - private final PregenRenderSnapshot.Bounds bounds; - private final PregenMapState state; - private final PregenMapState.View view; - private final BufferedImage image; - private final String[] shortcuts; - private volatile boolean disposed; - private Runnable viewListener; - private Point drag; - private Point hover; - private double centerX = 0.5D; - private double centerZ = 0.5D; - private double zoom = 1D; - private int coveredLeftWidth; - private boolean gridVisible; - private boolean helpVisible; - - PregenMapPanel(PregenMapState state) { - this.state = state; - bounds = state.bounds(); - image = new BufferedImage(state.width(), state.height(), BufferedImage.TYPE_INT_RGB); - image.setAccelerationPriority(0F); - view = state.attach(((DataBufferInt) image.getRaster().getDataBuffer()).getData()); - shortcuts = IrisLanguage.plain(DesktopUiMessages.PREGEN_SHORTCUT_DETAILS).split("\n"); - setBackground(StudioTheme.EDITOR_BACKGROUND); - setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); - setFocusable(true); - installNavigation(); - ToolTipManager.sharedInstance().registerComponent(this); - } - - void submit(int chunkX, int chunkZ, Color color) { - if (!disposed) { - state.submit(chunkX, chunkZ, color); - } - } - - boolean flush() { - return !disposed && view.flush(); - } - - void disposeMap() { - disposed = true; - viewListener = null; - ToolTipManager.sharedInstance().unregisterComponent(this); - view.close(); - } - - void setViewListener(Runnable listener) { - viewListener = listener; - } - - void setCoveredLeftWidth(int width) { - coveredLeftWidth = Math.max(0, width); - changed(); - } - - void resetView() { - centerX = 0.5D; - centerZ = 0.5D; - zoom = 1D; - changed(); - } - - double zoom() { - return zoom; - } - - void zoomIn() { - zoomAt(ZOOM_STEP, (getWidth() + coveredLeftWidth) / 2D, getHeight() / 2D); - } - - void zoomOut() { - zoomAt(1D / ZOOM_STEP, (getWidth() + coveredLeftWidth) / 2D, getHeight() / 2D); - } - - void zoomAt(double factor, double anchorX, double anchorY) { - Rectangle2D.Double before = mapArea(); - double mapX = (anchorX - before.x) / before.width; - double mapZ = (anchorY - before.y) / before.height; - zoom = Math.clamp(zoom * factor, MIN_ZOOM, MAX_ZOOM); - Rectangle2D.Double after = mapArea(); - centerX += mapX - (anchorX - after.x) / after.width; - centerZ += mapZ - (anchorY - after.y) / after.height; - changed(); - } - - void panBy(double pixelsX, double pixelsY) { - Rectangle2D.Double area = mapArea(); - centerX -= pixelsX / area.width; - centerZ -= pixelsY / area.height; - changed(); - } - - void toggleGrid() { - gridVisible = !gridVisible; - repaint(); - } - - boolean isGridVisible() { - return gridVisible; - } - - void toggleHelp() { - helpVisible = !helpVisible; - repaint(); - } - - void dismissHelp() { - helpVisible = false; - repaint(); - } - - String hoverCoordinates() { - return hover == null ? null : coordinatesAt(hover.x, hover.y); - } - - @Override - public String getToolTipText(MouseEvent event) { - return coordinatesAt(event.getX(), event.getY()); - } - - @Override - protected void paintComponent(Graphics graphics) { - super.paintComponent(graphics); - Graphics2D canvas = (Graphics2D) graphics.create(); - try { - Rectangle2D.Double area = mapArea(); - canvas.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR); - AffineTransform transform = AffineTransform.getTranslateInstance(area.x, area.y); - transform.scale(area.width / image.getWidth(), area.height / image.getHeight()); - canvas.drawImage(image, transform, null); - if (gridVisible) { - paintGrid(canvas, area); - } - canvas.setColor(StudioTheme.CONTROL_BORDER); - canvas.draw(area); - paintHover(canvas, area); - if (helpVisible) { - paintHelp(canvas); - } - } finally { - canvas.dispose(); - } - } - - static Rectangle fit(PregenRenderSnapshot.Bounds bounds, int width, int height) { - int availableWidth = Math.max(1, width - 2); - int availableHeight = Math.max(1, height - 2); - double scale = Math.min((double) availableWidth / bounds.width(), (double) availableHeight / bounds.height()); - int mapWidth = Math.max(1, (int) Math.floor(bounds.width() * scale)); - int mapHeight = Math.max(1, (int) Math.floor(bounds.height() * scale)); - return new Rectangle((width - mapWidth) / 2, (height - mapHeight) / 2, mapWidth, mapHeight); - } - - private Rectangle2D.Double mapArea() { - Rectangle fit = fit(bounds, Math.max(1, getWidth() - coveredLeftWidth), getHeight()); - double width = fit.width * zoom; - double height = fit.height * zoom; - return new Rectangle2D.Double(coveredLeftWidth + fit.getCenterX() - centerX * width, - fit.getCenterY() - centerZ * height, width, height); - } - - private String coordinatesAt(int x, int y) { - if (disposed || x < coveredLeftWidth) { - return null; - } - Rectangle2D.Double area = mapArea(); - if (!area.contains(x, y)) { - return null; - } - long chunkX = bounds.minX() + (long) Math.floor((x - area.x) * bounds.width() / area.width); - long chunkZ = bounds.minZ() + (long) Math.floor((y - area.y) * bounds.height() / area.height); - return IrisLanguage.plain(DesktopUiMessages.PREGEN_CHUNK_COORDINATES, - MessageArgument.trusted("x", chunkX), MessageArgument.trusted("z", chunkZ)); - } - - private void installNavigation() { - MouseAdapter navigation = new MouseAdapter() { - @Override - public void mousePressed(MouseEvent event) { - if (SwingUtilities.isLeftMouseButton(event)) { - requestFocusInWindow(); - drag = event.getPoint(); - setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR)); - } - } - - @Override - public void mouseReleased(MouseEvent event) { - drag = null; - setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR)); - } - - @Override - public void mouseDragged(MouseEvent event) { - if (drag != null) { - hover = event.getPoint(); - panBy(event.getX() - drag.x, event.getY() - drag.y); - drag = hover; - } - } - - @Override - public void mouseMoved(MouseEvent event) { - hover = event.getPoint(); - changed(); - } - - @Override - public void mouseExited(MouseEvent event) { - hover = null; - changed(); - } - - @Override - public void mouseWheelMoved(MouseWheelEvent event) { - zoomAt(Math.pow(ZOOM_STEP, -event.getPreciseWheelRotation()), event.getX(), event.getY()); - } - }; - addMouseListener(navigation); - addMouseMotionListener(navigation); - addMouseWheelListener(navigation); - } - - private void paintGrid(Graphics2D canvas, Rectangle2D.Double area) { - if (!area.intersects(0, 0, getWidth(), getHeight())) { - return; - } - double chunkWidth = area.width / bounds.width(); - double chunkHeight = area.height / bounds.height(); - long step = Math.min(chunkWidth, chunkHeight) >= 24D ? 1 : 32; - while (step * Math.min(chunkWidth, chunkHeight) < 24D) { - step *= 2; - } - canvas.setColor(StudioTheme.CONTROL_BORDER); - long minX = Math.max(bounds.minX(), (long) Math.floor(bounds.minX() - area.x / chunkWidth)); - long maxX = Math.min((long) bounds.maxX() + 1, (long) Math.ceil(bounds.minX() + (getWidth() - area.x) / chunkWidth)); - long minZ = Math.max(bounds.minZ(), (long) Math.floor(bounds.minZ() - area.y / chunkHeight)); - long maxZ = Math.min((long) bounds.maxZ() + 1, (long) Math.ceil(bounds.minZ() + (getHeight() - area.y) / chunkHeight)); - int top = (int) Math.max(0, area.y); - int bottom = (int) Math.min(getHeight(), area.getMaxY()); - int left = (int) Math.max(0, area.x); - int right = (int) Math.min(getWidth(), area.getMaxX()); - for (long x = Math.ceilDiv(minX, step) * step; x <= maxX; x += step) { - int screenX = (int) Math.round(area.x + (x - bounds.minX()) * chunkWidth); - canvas.drawLine(screenX, top, screenX, bottom); - } - for (long z = Math.ceilDiv(minZ, step) * step; z <= maxZ; z += step) { - int screenZ = (int) Math.round(area.y + (z - bounds.minZ()) * chunkHeight); - canvas.drawLine(left, screenZ, right, screenZ); - } - } - - private void paintHover(Graphics2D canvas, Rectangle2D.Double area) { - if (hover == null || hover.x < coveredLeftWidth || !area.contains(hover)) { - return; - } - double chunkWidth = area.width / bounds.width(); - double chunkHeight = area.height / bounds.height(); - if (Math.min(chunkWidth, chunkHeight) < 4D) { - return; - } - double x = area.x + Math.floor((hover.x - area.x) / chunkWidth) * chunkWidth; - double y = area.y + Math.floor((hover.y - area.y) / chunkHeight) * chunkHeight; - canvas.setColor(StudioTheme.ACCENT); - canvas.draw(new Rectangle2D.Double(x, y, chunkWidth, chunkHeight)); - } - - private void paintHelp(Graphics2D canvas) { - canvas.setFont(StudioTheme.font()); - FontMetrics metrics = canvas.getFontMetrics(); - int padding = StudioTheme.scale(14); - int width = 0; - for (String line : shortcuts) { - width = Math.max(width, metrics.stringWidth(line)); - } - width += padding * 2; - int height = metrics.getHeight() * shortcuts.length + padding * 2; - int x = Math.max(coveredLeftWidth + padding, getWidth() - width - padding); - int arc = StudioTheme.scale(10); - canvas.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); - canvas.setColor(StudioTheme.PANEL_BACKGROUND); - canvas.fillRoundRect(x, padding, width, height, arc, arc); - canvas.setColor(StudioTheme.CONTROL_BORDER); - canvas.drawRoundRect(x, padding, width, height, arc, arc); - canvas.setColor(StudioTheme.TEXT); - int baseline = padding * 2 + metrics.getAscent(); - for (String line : shortcuts) { - canvas.drawString(line, x + padding, baseline); - baseline += metrics.getHeight(); - } - } - - private void changed() { - if (viewListener != null) { - viewListener.run(); - } - repaint(); - } -} diff --git a/core/src/main/java/art/arcane/iris/studio/view/PregenRenderer.java b/core/src/main/java/art/arcane/iris/studio/view/PregenRenderer.java deleted file mode 100644 index d71a29f95..000000000 --- a/core/src/main/java/art/arcane/iris/studio/view/PregenRenderer.java +++ /dev/null @@ -1,560 +0,0 @@ -/* - * Iris is a World Generator for Minecraft Servers - * Copyright (c) 2026 Arcane Arts (Volmit Software) - * - * This program is free software: you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program. If not, see . - */ - -package art.arcane.iris.studio.view; - -import art.arcane.iris.configuration.IrisSettings; -import art.arcane.iris.localization.DesktopUiMessages; -import art.arcane.iris.localization.IrisLanguage; -import art.arcane.iris.spi.IrisLogging; -import art.arcane.iris.studio.map.IslandOverlay; -import art.arcane.iris.studio.map.IslandPanel; -import art.arcane.iris.studio.map.MapHost; -import art.arcane.iris.studio.map.StudioTheme; -import art.arcane.iris.studio.map.StudioToolbar; -import art.arcane.volmlib.util.format.Form; -import art.arcane.volmlib.util.localization.MessageArgument; -import art.arcane.volmlib.util.localization.TextKey; - -import javax.swing.AbstractAction; -import javax.swing.BorderFactory; -import javax.swing.Box; -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JFrame; -import javax.swing.JLabel; -import javax.swing.JPanel; -import javax.swing.JProgressBar; -import javax.swing.JScrollPane; -import javax.swing.JTextArea; -import javax.swing.JToggleButton; -import javax.swing.JToolBar; -import javax.swing.KeyStroke; -import javax.swing.Scrollable; -import javax.swing.SwingUtilities; -import javax.swing.Timer; -import javax.swing.text.DefaultCaret; -import javax.swing.text.JTextComponent; -import java.awt.BorderLayout; -import java.awt.Color; -import java.awt.Component; -import java.awt.Dimension; -import java.awt.Font; -import java.awt.Frame; -import java.awt.GridBagConstraints; -import java.awt.GridBagLayout; -import java.awt.GridLayout; -import java.awt.Insets; -import java.awt.KeyboardFocusManager; -import java.awt.LayoutManager; -import java.awt.Rectangle; -import java.awt.event.ActionEvent; -import java.awt.event.ComponentAdapter; -import java.awt.event.ComponentEvent; -import java.awt.event.KeyEvent; -import java.awt.event.WindowAdapter; -import java.awt.event.WindowEvent; -import java.util.Objects; - -public final class PregenRenderer extends JPanel { - private static final long serialVersionUID = 2094606939770332040L; - private static final Color BACKGROUND = StudioTheme.EDITOR_BACKGROUND; - private static final Color BORDER = StudioTheme.CONTROL_BORDER; - private static final Color SURFACE = StudioTheme.PANEL_BACKGROUND; - private static final Color TEXT = StudioTheme.TEXT; - private static final Color MUTED = StudioTheme.SECONDARY_TEXT; - private static final Color ACCENT = StudioTheme.ACCENT; - private static final Color ERROR = StudioTheme.ERROR; - static final Color GENERATING = new Color(204, 168, 107); - static final Color GENERATED = new Color(101, 194, 149); - static final Color EXISTS = new Color(93, 133, 112); - static final Color NETWORK = new Color(157, 138, 176); - static final Color NETWORK_GENERATING = new Color(129, 112, 145); - - private final PregenRenderSource source; - private final Runnable onPause; - private final PregenMapPanel map; - private final Timer repaintTimer; - private final JLabel worldLabel = label("", StudioTheme.titleFont(), TEXT); - private final JLabel phaseLabel = label("", StudioTheme.font(), MUTED); - private final JLabel countLabel = label("", StudioTheme.font(), TEXT); - private final JLabel percentLabel = label("", StudioTheme.titleFont(), TEXT); - private final JLabel currentValue = label("", StudioTheme.boldFont(), TEXT); - private final JLabel overallValue = label("", StudioTheme.boldFont(), TEXT); - private final JLabel thirtyValue = label("", StudioTheme.boldFont(), TEXT); - private final JLabel sixtyValue = label("", StudioTheme.boldFont(), TEXT); - private final JLabel etaValue = label("", StudioTheme.boldFont(), TEXT); - private final JLabel elapsedValue = label("", StudioTheme.boldFont(), TEXT); - private final JLabel memoryValue = label("", StudioTheme.boldFont(), TEXT); - private final JLabel pressureValue = label("", StudioTheme.boldFont(), TEXT); - private final JLabel methodLabel = label("", StudioTheme.smallFont(), MUTED); - private final JTextArea failureLabel = wrappedText("", StudioTheme.font(), ERROR, SURFACE); - private String controlFailure; - private final JButton pauseButton = StudioToolbar.button("", "", this::togglePause); - private final JToggleButton gridToggle = StudioToolbar.toggle(text(DesktopUiMessages.PREGEN_GRID), - text(DesktopUiMessages.PREGEN_GRID_HINT)); - private final JLabel coordinatesLabel = label("", StudioTheme.smallFont(), MUTED); - private final JLabel zoomLabel = label("", StudioTheme.smallFont(), MUTED); - private final JProgressBar progressBar = new JProgressBar(0, 10_000); - private volatile boolean renderingEnabled; - private volatile boolean disposed; - private volatile JFrame frame; - private PregenRenderSnapshot displayedSnapshot; - - private PregenRenderer(PregenRenderSource source, Runnable onPause) { - this.source = Objects.requireNonNull(source, "Generation view source"); - this.onPause = onPause; - failureLabel.setFocusable(true); - PregenRenderSnapshot initial = source.renderSnapshot(); - map = new PregenMapPanel(source.renderMapState()); - setLayout(new BorderLayout()); - setBackground(BACKGROUND); - map.getAccessibleContext().setAccessibleName(text(DesktopUiMessages.PREGEN_MAP)); - map.setViewListener(this::updateMapStatus); - IslandPanel sidebar = new IslandPanel(statusArea(initial.bounds())); - sidebar.addComponentListener(new ComponentAdapter() { - @Override - public void componentResized(ComponentEvent event) { - map.setCoveredLeftWidth(sidebar.getWidth()); - } - }); - add(toolbar(), BorderLayout.NORTH); - add(new IslandOverlay(sidebar, map, StudioTheme.scale(300), StudioTheme.scale(260), - StudioTheme.scale(300)), BorderLayout.CENTER); - add(statusBar(), BorderLayout.SOUTH); - installControls(); - updateMapStatus(); - repaintTimer = new Timer(IrisSettings.get().getGui().isMaximumPregenGuiFPS() ? 4 : 250, - event -> refresh()); - refresh(); - } - - public static PregenRenderer open(String title, PregenRenderSource source, Runnable onPause) { - if (!SwingUtilities.isEventDispatchThread()) { - throw new IllegalStateException("The pregeneration window must open on the Swing event thread"); - } - JFrame frame = MapHost.createFrame(title); - PregenRenderer renderer = new PregenRenderer(source, onPause); - renderer.frame = frame; - renderer.renderingEnabled = true; - frame.setContentPane(renderer); - frame.setSize(MapHost.fitToScreen(StudioTheme.scaledSize(1240, 800))); - frame.setMinimumSize(StudioTheme.scaledSize(820, 520)); - frame.setLocationRelativeTo(null); - frame.addWindowListener(new WindowAdapter() { - @Override - public void windowClosed(WindowEvent event) { - renderer.disposeRenderer(); - } - }); - frame.addWindowStateListener(event -> renderer.setRenderingEnabled((event.getNewState() & Frame.ICONIFIED) == 0)); - frame.setVisible(true); - renderer.repaintTimer.start(); - return renderer; - } - - public boolean isVisibleFrame() { - return renderingEnabled && !disposed; - } - - public void close() { - if (!SwingUtilities.isEventDispatchThread()) { - SwingUtilities.invokeLater(this::close); - return; - } - JFrame activeFrame = frame; - if (activeFrame != null) { - activeFrame.dispose(); - } else { - disposeRenderer(); - } - } - - private JToolBar toolbar() { - JToolBar toolbar = StudioToolbar.create(); - worldLabel.setBorder(StudioTheme.emptyBorder(0, 6, 0, 14)); - worldLabel.setMaximumSize(StudioTheme.scaledSize(220, 36)); - worldLabel.setMinimumSize(StudioTheme.scaledSize(80, 24)); - toolbar.add(worldLabel); - toolbar.add(pauseButton); - toolbar.addSeparator(); - toolbar.add(StudioToolbar.button(text(DesktopUiMessages.PREGEN_FIT), - text(DesktopUiMessages.PREGEN_FIT_HINT), map::resetView)); - toolbar.add(StudioToolbar.button("−", text(DesktopUiMessages.PREGEN_ZOOM_OUT), map::zoomOut)); - toolbar.add(StudioToolbar.button("+", text(DesktopUiMessages.PREGEN_ZOOM_IN), map::zoomIn)); - gridToggle.addActionListener(event -> toggleGrid()); - toolbar.add(gridToggle); - toolbar.add(Box.createHorizontalGlue()); - toolbar.add(StudioToolbar.themeButton()); - toolbar.add(StudioToolbar.button(text(DesktopUiMessages.PREGEN_SHORTCUTS), - text(DesktopUiMessages.PREGEN_SHORTCUTS_HINT), map::toggleHelp)); - for (Component control : toolbar.getComponents()) { - if (control instanceof JButton || control instanceof JToggleButton) { - control.setFocusable(true); - } - } - return toolbar; - } - - private JPanel statusBar() { - JPanel status = panel(new BorderLayout(12, 0), SURFACE); - status.setBorder(StudioTheme.emptyBorder(5, 12, 5, 12)); - status.add(coordinatesLabel, BorderLayout.CENTER); - status.add(zoomLabel, BorderLayout.EAST); - status.setToolTipText(text(DesktopUiMessages.PREGEN_WINDOW_HINT)); - return status; - } - - private void updateMapStatus() { - String coordinates = map.hoverCoordinates(); - coordinatesLabel.setText(coordinates == null ? text(DesktopUiMessages.PREGEN_NAVIGATION_HINT) : coordinates); - zoomLabel.setText(text(DesktopUiMessages.PREGEN_ZOOM, - MessageArgument.trusted("zoom", Form.pc(map.zoom(), 0)))); - } - - private JScrollPane statusArea(PregenRenderSnapshot.Bounds bounds) { - JPanel status = new StatusPanel(); - status.setBackground(SURFACE); - status.setBorder(StudioTheme.emptyBorder(14, 12, 12, 12)); - GridBagConstraints constraints = new GridBagConstraints(); - constraints.gridx = 0; - constraints.gridy = 0; - constraints.weightx = 1; - constraints.fill = GridBagConstraints.HORIZONTAL; - constraints.anchor = GridBagConstraints.NORTHWEST; - constraints.insets = new Insets(0, 0, StudioTheme.scale(12), 0); - status.add(label(text(DesktopUiMessages.PREGEN_TITLE), StudioTheme.titleFont(), TEXT), constraints); - constraints.gridy++; - status.add(phaseLabel, constraints); - constraints.gridy++; - JPanel progress = panel(new BorderLayout(0, StudioTheme.scale(8)), SURFACE); - progress.add(percentLabel, BorderLayout.NORTH); - progressBar.setForeground(ACCENT); - progressBar.setBackground(BACKGROUND); - progressBar.setBorderPainted(false); - progressBar.setPreferredSize(StudioTheme.scaledSize(1, 4)); - progressBar.setFocusable(false); - progress.add(progressBar, BorderLayout.CENTER); - progress.add(countLabel, BorderLayout.SOUTH); - status.add(progress, constraints); - constraints.gridy++; - status.add(failureLabel, constraints); - constraints.gridy++; - status.add(metricRow(DesktopUiMessages.PREGEN_CURRENT, currentValue), constraints); - constraints.gridy++; - status.add(metricRow(DesktopUiMessages.PREGEN_ETA, etaValue), constraints); - constraints.gridy++; - status.add(metricRow(DesktopUiMessages.PREGEN_OVERALL, overallValue), constraints); - constraints.gridy++; - status.add(metricRow(DesktopUiMessages.PREGEN_THIRTY, thirtyValue), constraints); - constraints.gridy++; - status.add(metricRow(DesktopUiMessages.PREGEN_SIXTY, sixtyValue), constraints); - constraints.gridy++; - status.add(metricRow(DesktopUiMessages.PREGEN_ELAPSED, elapsedValue), constraints); - constraints.gridy++; - status.add(metricRow(DesktopUiMessages.PREGEN_MEMORY_LABEL, memoryValue), constraints); - constraints.gridy++; - status.add(metricRow(DesktopUiMessages.PREGEN_PRESSURE, pressureValue), constraints); - constraints.gridy++; - status.add(methodLabel, constraints); - constraints.gridy++; - status.add(legend(), constraints); - constraints.gridy++; - status.add(wrappedText(text(DesktopUiMessages.PREGEN_BOUNDS, - MessageArgument.trusted("minX", Form.f(bounds.minX())), - MessageArgument.trusted("maxX", Form.f(bounds.maxX())), - MessageArgument.trusted("minZ", Form.f(bounds.minZ())), - MessageArgument.trusted("maxZ", Form.f(bounds.maxZ()))), StudioTheme.smallFont(), MUTED, SURFACE), constraints); - constraints.gridy++; - status.add(wrappedText(text(DesktopUiMessages.PREGEN_WINDOW_HINT), StudioTheme.smallFont(), MUTED, SURFACE), constraints); - constraints.gridy++; - constraints.weighty = 1; - status.add(panel(new BorderLayout(), SURFACE), constraints); - JScrollPane scroll = StudioToolbar.scroll(status); - scroll.getViewport().setBackground(SURFACE); - return scroll; - } - - private JPanel legend() { - JPanel legend = panel(new GridLayout(0, 2, StudioTheme.scale(12), StudioTheme.scale(7)), SURFACE); - legend.setBorder(StudioTheme.emptyBorder(8, 0, 4, 0)); - legend.add(legendItem(DesktopUiMessages.PREGEN_WAITING, PregenMapState.WAITING)); - legend.add(legendItem(DesktopUiMessages.PREGEN_GENERATING, GENERATING)); - legend.add(legendItem(DesktopUiMessages.PREGEN_READY, GENERATED)); - legend.add(legendItem(DesktopUiMessages.PREGEN_EXISTING, EXISTS)); - legend.add(legendItem(DesktopUiMessages.PREGEN_NETWORK, NETWORK)); - legend.setToolTipText(text(DesktopUiMessages.PREGEN_TERRAIN_HINT)); - return legend; - } - - private JPanel legendItem(TextKey key, Color color) { - JPanel item = panel(new BorderLayout(StudioTheme.scale(7), 0), SURFACE); - JPanel swatch = panel(new BorderLayout(), color); - swatch.setPreferredSize(StudioTheme.scaledSize(10, 10)); - swatch.setBorder(BorderFactory.createLineBorder(BORDER)); - JPanel marker = panel(new BorderLayout(), SURFACE); - marker.add(swatch, BorderLayout.NORTH); - item.add(marker, BorderLayout.WEST); - item.add(wrappedText(text(key), StudioTheme.smallFont(), MUTED, SURFACE), BorderLayout.CENTER); - return item; - } - - private JPanel metricRow(TextKey title, JLabel value) { - JPanel row = panel(new BorderLayout(StudioTheme.scale(8), 0), SURFACE); - row.add(wrappedText(text(title), StudioTheme.smallFont(), MUTED, SURFACE), BorderLayout.CENTER); - row.add(value, BorderLayout.EAST); - return row; - } - - private void installControls() { - pauseButton.setFocusable(true); - pauseButton.putClientProperty("html.disable", Boolean.TRUE); - pauseButton.getInputMap(JComponent.WHEN_FOCUSED).put( - KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "activatePause"); - pauseButton.getActionMap().put("activatePause", new AbstractAction() { - @Override - public void actionPerformed(ActionEvent event) { - pauseButton.doClick(); - } - }); - bind(KeyStroke.getKeyStroke(KeyEvent.VK_P, 0, true), "pause", this::togglePause); - bind(KeyStroke.getKeyStroke(KeyEvent.VK_R, 0), "reset-view", map::resetView); - bind(KeyStroke.getKeyStroke(KeyEvent.VK_BACK_SLASH, 0), "reset-zoom", map::resetView); - bind(KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, 0), "zoom-in", map::zoomIn); - bind(KeyStroke.getKeyStroke(KeyEvent.VK_EQUALS, KeyEvent.SHIFT_DOWN_MASK), "zoom-in-plus", map::zoomIn); - bind(KeyStroke.getKeyStroke(KeyEvent.VK_ADD, 0), "zoom-in-keypad", map::zoomIn); - bind(KeyStroke.getKeyStroke(KeyEvent.VK_MINUS, 0), "zoom-out", map::zoomOut); - bind(KeyStroke.getKeyStroke(KeyEvent.VK_SUBTRACT, 0), "zoom-out-keypad", map::zoomOut); - bind(KeyStroke.getKeyStroke(KeyEvent.VK_G, 0), "grid", this::toggleGrid); - bind(KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0), "pan-left", () -> map.panBy(64, 0)); - bind(KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0), "pan-right", () -> map.panBy(-64, 0)); - bind(KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0), "pan-up", () -> map.panBy(0, 64)); - bind(KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0), "pan-down", () -> map.panBy(0, -64)); - bind(KeyStroke.getKeyStroke(KeyEvent.VK_SLASH, 0), "help", map::toggleHelp); - bind(KeyStroke.getKeyStroke(KeyEvent.VK_SLASH, KeyEvent.SHIFT_DOWN_MASK), "help-question", map::toggleHelp); - bind(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "dismiss", map::dismissHelp); - } - - private void bind(KeyStroke key, String name, Runnable action) { - getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(key, name); - getActionMap().put(name, new AbstractAction() { - @Override - public void actionPerformed(ActionEvent event) { - if (!(KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner() instanceof JTextComponent)) { - action.run(); - } - } - }); - } - - private void toggleGrid() { - map.toggleGrid(); - gridToggle.setSelected(map.isGridVisible()); - } - - private void togglePause() { - if (onPause == null || !pauseButton.isEnabled()) { - return; - } - try { - onPause.run(); - controlFailure = null; - displayedSnapshot = null; - refresh(); - } catch (RuntimeException failure) { - IrisLogging.reportError("Unable to change pregeneration pause state.", failure); - controlFailure = text(DesktopUiMessages.PREGEN_CONTROL_FAILED) + "\n" - + Objects.toString(failure.getMessage(), failure.getClass().getSimpleName()); - updateStatus(source.renderSnapshot()); - } - } - - private void refresh() { - if (disposed) { - return; - } - PregenRenderSnapshot snapshot = source.renderSnapshot(); - if (!snapshot.equals(displayedSnapshot)) { - updateStatus(snapshot); - displayedSnapshot = snapshot; - } - if (map.flush()) { - map.repaint(); - } - } - - private void updateStatus(PregenRenderSnapshot snapshot) { - PregeneratorJob.PregenProgress progress = snapshot.progress(); - boolean initializing = snapshot.phase() == PregenRenderSnapshot.Phase.INITIALIZING; - boolean paused = snapshot.phase() == PregenRenderSnapshot.Phase.PAUSED; - worldLabel.setText(progress.worldName() == null ? text(DesktopUiMessages.PREGEN_TITLE) : progress.worldName()); - worldLabel.setToolTipText(worldLabel.getText()); - phaseLabel.setText(text(switch (snapshot.phase()) { - case INITIALIZING -> DesktopUiMessages.PREGEN_INITIALIZING; - case GENERATING -> DesktopUiMessages.PREGEN_GENERATING; - case PAUSED -> DesktopUiMessages.PREGEN_PAUSED; - case SAVING -> DesktopUiMessages.PREGEN_SAVING; - case STOPPING -> DesktopUiMessages.PREGEN_STOPPING; - case COMPLETED -> DesktopUiMessages.PREGEN_COMPLETED; - case ERROR -> DesktopUiMessages.PREGEN_ERROR; - })); - phaseLabel.setForeground(snapshot.phase() == PregenRenderSnapshot.Phase.ERROR ? ERROR : MUTED); - countLabel.setText(text(DesktopUiMessages.PREGEN_PROGRESS, - MessageArgument.trusted("generated", Form.f(progress.generated())), - MessageArgument.trusted("total", Form.f(progress.totalChunks())))); - percentLabel.setText(text(DesktopUiMessages.PREGEN_PERCENT, - MessageArgument.trusted("percent", Form.pc(Math.max(0D, Math.min(1D, progress.percent() / 100D)), 1)))); - progressBar.setValue((int) Math.max(0D, Math.min(10_000D, progress.percent() * 100D))); - progressBar.getAccessibleContext().setAccessibleName(countLabel.getText()); - map.getAccessibleContext().setAccessibleDescription(countLabel.getText() + ". " + phaseLabel.getText()); - pauseButton.setText(text(paused ? DesktopUiMessages.PREGEN_RESUME : DesktopUiMessages.PREGEN_PAUSE)); - pauseButton.setToolTipText(text(paused ? DesktopUiMessages.PREGEN_RESUME_HINT : DesktopUiMessages.PREGEN_PAUSE_HINT)); - pauseButton.setEnabled(onPause != null && switch (snapshot.phase()) { - case GENERATING, PAUSED, SAVING -> true; - default -> false; - }); - currentValue.setText(initializing ? pending() : rate(progress.chunksPerSecond())); - overallValue.setText(initializing ? pending() : rate(progress.overallChunksPerSecond())); - thirtyValue.setText(initializing ? pending() : rate(progress.thirtySecondChunksPerSecond())); - sixtyValue.setText(initializing ? pending() : rate(progress.sixtySecondChunksPerSecond())); - etaValue.setText((snapshot.phase() != PregenRenderSnapshot.Phase.GENERATING - && snapshot.phase() != PregenRenderSnapshot.Phase.SAVING - && snapshot.phase() != PregenRenderSnapshot.Phase.COMPLETED) || progress.eta() < 0 - || (progress.eta() == 0 && progress.chunksRemaining() > 0) - ? pending() : Form.duration(progress.eta(), 2)); - elapsedValue.setText(initializing ? pending() : Form.duration(progress.elapsed(), 2)); - memoryValue.setText(snapshot.usedMemoryBytes() < 0 ? pending() : text(DesktopUiMessages.PREGEN_MEMORY_USAGE, - MessageArgument.trusted("used", Form.memSize(snapshot.usedMemoryBytes(), 1)), - MessageArgument.trusted("usage", Form.pc(snapshot.memoryUsage(), 0)))); - pressureValue.setText(text(DesktopUiMessages.PREGEN_PRESSURE_VALUE, - MessageArgument.trusted("rate", Form.memSize(snapshot.allocationBytesPerSecond(), 0)))); - String method = progress.method() == null ? pending() : progress.method(); - if (snapshot.cached()) { - method = text(DesktopUiMessages.PREGEN_CACHED, MessageArgument.untrusted("method", method)); - } - methodLabel.setText(text(DesktopUiMessages.PREGEN_METHOD, MessageArgument.untrusted("method", method))); - methodLabel.setToolTipText(methodLabel.getText()); - String failureSummary = progress.failed() > 0 ? text(DesktopUiMessages.PREGEN_FAILED, - MessageArgument.trusted("count", Form.f(progress.failed()))) : ""; - if (snapshot.failure() != null) { - failureSummary += (failureSummary.isEmpty() ? "" : "\n") - + text(DesktopUiMessages.PREGEN_ERROR_DETAILS) + "\n" + snapshot.failure(); - } - if (controlFailure != null) { - failureSummary += (failureSummary.isEmpty() ? "" : "\n") + controlFailure; - } - if (!failureSummary.equals(failureLabel.getText())) { - failureLabel.setText(failureSummary); - } - failureLabel.setVisible(!failureSummary.isEmpty()); - } - - private void setRenderingEnabled(boolean enabled) { - renderingEnabled = enabled && !disposed; - if (renderingEnabled) { - refresh(); - repaintTimer.start(); - } else { - repaintTimer.stop(); - } - } - - private void disposeRenderer() { - if (disposed) { - return; - } - disposed = true; - renderingEnabled = false; - frame = null; - repaintTimer.stop(); - map.disposeMap(); - } - - private static JPanel panel(LayoutManager layout, Color background) { - JPanel panel = new JPanel(layout); - panel.setBackground(background); - return panel; - } - - private static JLabel label(String text, Font font, Color foreground) { - JLabel label = new JLabel(text); - label.putClientProperty("html.disable", Boolean.TRUE); - label.setFont(font); - label.setForeground(foreground); - return label; - } - - private static JTextArea wrappedText(String text, Font font, Color foreground, Color background) { - JTextArea area = new JTextArea(); - DefaultCaret caret = (DefaultCaret) area.getCaret(); - caret.setUpdatePolicy(DefaultCaret.NEVER_UPDATE); - area.setText(text); - area.setEditable(false); - area.setFocusable(false); - area.setLineWrap(true); - area.setWrapStyleWord(true); - area.setFont(font); - area.setForeground(foreground); - area.setBackground(background); - area.setBorder(BorderFactory.createEmptyBorder()); - return area; - } - - private static String pending() { - return text(DesktopUiMessages.PREGEN_METHOD_PENDING); - } - - private static String rate(double rate) { - return text(DesktopUiMessages.PREGEN_RATE, MessageArgument.trusted("rate", Form.f(rate, 1))); - } - - private static String text(TextKey key, MessageArgument... arguments) { - return IrisLanguage.plain(key, arguments); - } - - private static final class StatusPanel extends JPanel implements Scrollable { - private StatusPanel() { - super(new GridBagLayout()); - } - - @Override - public Dimension getPreferredScrollableViewportSize() { - return getPreferredSize(); - } - - @Override - public int getScrollableUnitIncrement(Rectangle visible, int orientation, int direction) { - return 16; - } - - @Override - public int getScrollableBlockIncrement(Rectangle visible, int orientation, int direction) { - return Math.max(16, visible.height - 16); - } - - @Override - public boolean getScrollableTracksViewportWidth() { - return true; - } - - @Override - public boolean getScrollableTracksViewportHeight() { - return getParent() != null && getPreferredSize().height < getParent().getHeight(); - } - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/map/FrameCrossfadeTest.java b/core/src/test/java/art/arcane/iris/studio/map/FrameCrossfadeTest.java deleted file mode 100644 index 6f952b7ec..000000000 --- a/core/src/test/java/art/arcane/iris/studio/map/FrameCrossfadeTest.java +++ /dev/null @@ -1,119 +0,0 @@ -package art.arcane.iris.studio.map; - -import org.junit.After; -import org.junit.Test; - -import javax.swing.SwingUtilities; -import javax.swing.Timer; -import java.lang.reflect.Field; -import java.util.concurrent.TimeUnit; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; - -public final class FrameCrossfadeTest { - private final FrameCrossfade crossfade = new FrameCrossfade(() -> { - }); - - @After - public void stopRepaintTimer() throws Exception { - SwingUtilities.invokeAndWait(crossfade::clear); - } - - @Test - public void heldFrameStaysFullyVisibleUntilTheNextFrameArrives() { - NoiseRenderCoordinator.Result frame = frame(); - - crossfade.hold(frame); - - assertSame(frame, crossfade.outgoing()); - assertEquals(1F, crossfade.outgoingOpacity(), 0F); - } - - @Test - public void heldFrameFadesOnceTheNextFrameArrives() throws Exception { - SwingUtilities.invokeAndWait(() -> { - crossfade.hold(frame()); - crossfade.reveal(); - }); - Thread.sleep(20L); - - SwingUtilities.invokeAndWait(() -> assertTrue(crossfade.outgoing() == null || crossfade.outgoingOpacity() < 1F)); - } - - @Test - public void fadingStopsAndReleasesTheFrameWithoutPainting() throws Exception { - Timer timer = (Timer) field("repaintTimer"); - SwingUtilities.invokeAndWait(() -> { - crossfade.hold(frame()); - crossfade.reveal(); - assertTrue(timer.isRunning()); - }); - - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(2L); - while (timer.isRunning() && System.nanoTime() < deadline) { - Thread.sleep(10L); - } - SwingUtilities.invokeAndWait(() -> { }); - - assertFalse("Hidden views must stop scheduling fade repaints", timer.isRunning()); - assertNull(field("outgoing")); - } - - @Test - public void holdingDuringFadeStopsRepaintsUntilAnotherFrameArrives() throws Exception { - Timer timer = (Timer) field("repaintTimer"); - NoiseRenderCoordinator.Result frame = frame(); - SwingUtilities.invokeAndWait(() -> { - crossfade.hold(frame); - crossfade.reveal(); - crossfade.hold(null); - - assertFalse("A held frame must not keep the fade timer running", timer.isRunning()); - assertSame(frame, crossfade.outgoing()); - assertEquals(1F, crossfade.outgoingOpacity(), 0F); - - crossfade.reveal(); - assertTrue(timer.isRunning()); - }); - } - - @Test - public void switchingAgainBeforeAnythingDrewKeepsTheFrameHeld() { - NoiseRenderCoordinator.Result frame = frame(); - crossfade.hold(frame); - - crossfade.hold(null); - - assertSame(frame, crossfade.outgoing()); - } - - @Test - public void frameWithoutAHeldFrameHasNothingToFade() { - crossfade.reveal(); - - assertNull(crossfade.outgoing()); - } - - @Test - public void clearDropsTheHeldFrame() { - crossfade.hold(frame()); - - crossfade.clear(); - - assertNull(crossfade.outgoing()); - } - - private static NoiseRenderCoordinator.Result frame() { - return new NoiseRenderCoordinator.Result(null, null, 1D, 1L, 0D, 1D, 0.5D, 0L, 0L, 0L); - } - - private Object field(String name) throws Exception { - Field field = FrameCrossfade.class.getDeclaredField(name); - field.setAccessible(true); - return field.get(crossfade); - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/map/GpuLibraryTest.java b/core/src/test/java/art/arcane/iris/studio/map/GpuLibraryTest.java deleted file mode 100644 index 8ae079bef..000000000 --- a/core/src/test/java/art/arcane/iris/studio/map/GpuLibraryTest.java +++ /dev/null @@ -1,48 +0,0 @@ -package art.arcane.iris.studio.map; - -import org.junit.Test; - -import java.io.File; -import java.lang.reflect.Method; -import java.net.URL; -import java.net.URLClassLoader; -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Pattern; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public class GpuLibraryTest { - @Test - public void missingNativeLibrariesUseSoftwareEvenWhenBindingClassesExist() throws Exception { - List classpath = new ArrayList<>(); - for (String entry : System.getProperty("java.class.path").split(Pattern.quote(File.pathSeparator))) { - if (!new File(entry).getName().contains("-natives-")) { - classpath.add(new File(entry).toURI().toURL()); - } - } - ClassLoader loader = GpuLibrary.class.getClassLoader(); - while (loader != null) { - if (loader instanceof URLClassLoader urls) { - for (URL url : urls.getURLs()) { - if (!new File(url.getPath()).getName().contains("-natives-")) { - classpath.add(url); - } - } - } - loader = loader.getParent(); - } - assertFalse(classpath.isEmpty()); - try (URLClassLoader isolated = new URLClassLoader(classpath.toArray(URL[]::new), ClassLoader.getPlatformClassLoader())) { - assertEquals("org.lwjgl.system.MemoryStack", Class.forName("org.lwjgl.system.MemoryStack", false, isolated).getName()); - assertTrue(Class.forName("org.lwjgl.system.jawt.JAWT", false, isolated).getClassLoader() == isolated); - Class library = Class.forName(GpuLibrary.class.getName(), true, isolated); - Method available = library.getDeclaredMethod("isLoaded"); - available.setAccessible(true); - - assertEquals(Boolean.FALSE, available.invoke(null)); - } - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/map/ImageMapExplorerTest.java b/core/src/test/java/art/arcane/iris/studio/map/ImageMapExplorerTest.java deleted file mode 100644 index 8d1c02b7f..000000000 --- a/core/src/test/java/art/arcane/iris/studio/map/ImageMapExplorerTest.java +++ /dev/null @@ -1,20 +0,0 @@ -package art.arcane.iris.studio.map; - -import art.arcane.iris.generation.runtime.Engine; -import org.junit.Test; - -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.verifyNoMoreInteractions; - -public class ImageMapExplorerTest { - @Test - public void exportRequestsHotloadWithoutMutatingTheActiveGenerationData() { - Engine engine = mock(Engine.class); - - ImageMapExplorer.reloadActiveEngine(engine); - - verify(engine).hotloadSilently(); - verifyNoMoreInteractions(engine); - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/map/ImageMapStudioModelTest.java b/core/src/test/java/art/arcane/iris/studio/map/ImageMapStudioModelTest.java deleted file mode 100644 index cf935c4f2..000000000 --- a/core/src/test/java/art/arcane/iris/studio/map/ImageMapStudioModelTest.java +++ /dev/null @@ -1,168 +0,0 @@ -package art.arcane.iris.studio.map; - -import art.arcane.iris.generation.image.IrisImageMap; -import art.arcane.iris.generation.image.IrisImageMapOrigin; -import art.arcane.iris.generation.image.IrisImageMapMask; -import art.arcane.iris.generation.image.IrisImageMapMaskOperation; -import art.arcane.iris.generation.image.IrisImageMapRotation; -import art.arcane.iris.generation.image.IrisImageMapType; -import art.arcane.iris.world.IrisWorldBoundary; -import art.arcane.iris.world.IrisWorldBoundaryCenter; -import art.arcane.volmlib.util.collection.KMap; -import org.junit.Test; - -import java.awt.geom.Point2D; -import java.awt.image.BufferedImage; -import java.nio.file.Path; -import java.util.List; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertThrows; -import static org.junit.Assert.assertTrue; - -public class ImageMapStudioModelTest { - private static final double EPSILON = 0.000001D; - - @Test - public void inspectsCanonicalSixteenBitGrayscaleMetadata() { - BufferedImage image = new BufferedImage(3, 2, BufferedImage.TYPE_USHORT_GRAY); - - ImageMapStudioModel.SourceMetadata metadata = ImageMapStudioModel.inspect( - Path.of("source.png"), image, "png" - ); - - assertEquals(3, metadata.width()); - assertEquals(2, metadata.height()); - assertEquals(6L, metadata.pixels()); - assertEquals("png", metadata.format()); - assertEquals("GRAYSCALE", metadata.colorMode()); - assertEquals(16, metadata.bitDepth()); - assertFalse(metadata.alpha()); - assertTrue(metadata.summary().contains("PNG")); - assertTrue(metadata.summary().contains("profile not inspected")); - } - - @Test - public void normalizesResourceKeysAndRejectsAmbiguousLegendRows() { - assertEquals("terrain/my-map", ImageMapStudioModel.safeKey(" Terrain/My Map.PNG ")); - assertEquals("image-map", ImageMapStudioModel.safeKey("..")); - - KMap legend = ImageMapStudioModel.legend(List.of( - new ImageMapStudioModel.LegendRow("#00aaFF", "minecraft:water") - )); - assertEquals("minecraft:water", legend.get("#00AAFF")); - assertThrows(IllegalArgumentException.class, () -> ImageMapStudioModel.legend(List.of( - new ImageMapStudioModel.LegendRow("#000000", "minecraft:stone"), - new ImageMapStudioModel.LegendRow("#000000", "minecraft:deepslate") - ))); - assertThrows(IllegalArgumentException.class, () -> ImageMapStudioModel.legend(List.of( - new ImageMapStudioModel.LegendRow("000000", "minecraft:stone") - ))); - } - - @Test - public void mapsSourceCoordinatesThroughMirrorRotationScaleAndOrigins() { - IrisImageMap definition = new IrisImageMap() - .setBlocksPerPixel(2D) - .setOrigin(new IrisImageMapOrigin(10D, 20D)) - .setSourceOrigin(new IrisImageMapOrigin(1D, 1D)) - .setMirrorX(true) - .setRotation(IrisImageMapRotation.DEG_90); - - Point2D.Double world = ImageMapStudioModel.sourceToWorld(definition, 2D, 1D); - - assertEquals(10D, world.x, EPSILON); - assertEquals(18D, world.y, EPSILON); - } - - @Test - public void reportsScaleAndBoundaryCoverageWarnings() { - IrisImageMap definition = new IrisImageMap() - .setBlocksPerPixel(0.5D) - .setOrigin(new IrisImageMapOrigin()) - .setSourceOrigin(new IrisImageMapOrigin()); - IrisWorldBoundary boundary = new IrisWorldBoundary() - .setCenter(new IrisWorldBoundaryCenter(2D, 2D)) - .setSize(20D); - - List warnings = ImageMapStudioModel.warnings(definition, 4, 4, boundary); - - assertTrue(warnings.stream().anyMatch(value -> value.contains("Sub-block"))); - assertTrue(warnings.stream().anyMatch(value -> value.contains("complete chunk"))); - assertTrue(warnings.stream().anyMatch(value -> value.contains("not fully covered"))); - assertTrue(warnings.stream().anyMatch(value -> value.contains("substantially smaller"))); - } - - @Test - public void acceptsAnExactSourceAndWorldBoundaryFit() { - IrisImageMap definition = new IrisImageMap() - .setBlocksPerPixel(1D) - .setOrigin(new IrisImageMapOrigin()) - .setSourceOrigin(new IrisImageMapOrigin()); - IrisWorldBoundary boundary = new IrisWorldBoundary() - .setCenter(new IrisWorldBoundaryCenter(8D, 8D)) - .setSize(16D); - - List warnings = ImageMapStudioModel.warnings(definition, 16, 16, boundary); - - assertTrue(warnings.isEmpty()); - } - - @Test - public void clearsSettingsThatAreInvalidForTheSelectedType() { - IrisImageMap height = new IrisImageMap() - .setType(IrisImageMapType.GRAYSCALE_HEIGHT) - .setColorTolerance(12D) - .setColors(new KMap<>(Map.of("#000000", "iris:test"))); - IrisImageMap color = new IrisImageMap() - .setType(IrisImageMapType.COLOR_MAP) - .setInverted(true) - .setCurveExponent(2D) - .setSmoothingRadius(4) - .setColors(new KMap<>(Map.of("#000000", "iris:test"))); - IrisImageMap mask = new IrisImageMap() - .setType(IrisImageMapType.GRAYSCALE_MASK) - .setMinimumHeight(12D) - .setMaximumHeight(42D) - .setThreshold(0.7D) - .setFalloff(0.2D) - .setColors(new KMap<>(Map.of("#000000", "iris:test"))); - - ImageMapStudioModel.normalizeTypeSettings(height); - ImageMapStudioModel.normalizeTypeSettings(color); - ImageMapStudioModel.normalizeTypeSettings(mask); - - assertEquals(0D, height.getColorTolerance(), 0D); - assertTrue(height.getColors().isEmpty()); - assertFalse(color.isInverted()); - assertEquals(1D, color.getCurveExponent(), 0D); - assertEquals(0, color.getSmoothingRadius()); - assertEquals("iris:test", color.getColors().get("#000000")); - assertEquals(-64D, mask.getMinimumHeight(), 0D); - assertEquals(320D, mask.getMaximumHeight(), 0D); - assertEquals(0.5D, mask.getThreshold(), 0D); - assertEquals(0D, mask.getFalloff(), 0D); - assertTrue(mask.getColors().isEmpty()); - } - - @Test - public void parsesOrderedComposedMaskRowsWithUnitRangeValidation() { - List rows = List.of( - ImageMapStudioModel.maskRow("land", "multiply", false, "0", "1"), - ImageMapStudioModel.maskRow("roads", IrisImageMapMaskOperation.SUBTRACT, true, 0.5D, 0.25D) - ); - - List masks = ImageMapStudioModel.masks(rows); - - assertEquals(2, masks.size()); - assertEquals("land", masks.get(0).getMap()); - assertEquals(IrisImageMapMaskOperation.MULTIPLY, masks.get(0).getOperation()); - assertEquals(IrisImageMapMaskOperation.SUBTRACT, masks.get(1).getOperation()); - assertTrue(masks.get(1).isInverted()); - assertEquals("roads", ImageMapStudioModel.maskRows(masks).get(1).map()); - assertThrows(IllegalArgumentException.class, - () -> ImageMapStudioModel.maskRow("bad", "ADD", false, 1.1D, 0D)); - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/map/ImageMapStudioPreviewPanelTest.java b/core/src/test/java/art/arcane/iris/studio/map/ImageMapStudioPreviewPanelTest.java deleted file mode 100644 index 8700d8a99..000000000 --- a/core/src/test/java/art/arcane/iris/studio/map/ImageMapStudioPreviewPanelTest.java +++ /dev/null @@ -1,146 +0,0 @@ -package art.arcane.iris.studio.map; - -import art.arcane.iris.generation.image.CompiledIrisImageMap; -import art.arcane.iris.generation.image.IrisImageMapRuntime; -import art.arcane.iris.generation.image.IrisImageMapMaskSampler; -import art.arcane.iris.generation.image.IrisImage; -import art.arcane.iris.generation.image.IrisImageMap; -import art.arcane.iris.generation.image.IrisImageMapApplication; -import art.arcane.iris.generation.image.IrisImageMapMask; -import art.arcane.iris.generation.image.IrisImageMapMaskOperation; -import art.arcane.iris.generation.image.IrisImageMapOutOfBounds; -import art.arcane.iris.generation.image.IrisImageMapType; -import art.arcane.volmlib.util.collection.KMap; -import org.junit.Test; - -import java.awt.Color; -import java.awt.image.BufferedImage; -import java.util.List; -import java.util.Map; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; - -public class ImageMapStudioPreviewPanelTest { - @Test - public void rendersAnInspectedSourceWithoutACompiledSemanticType() { - BufferedImage source = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); - source.setRGB(0, 0, 0xFFFF0000); - ImageMapStudioPreviewPanel panel = new ImageMapStudioPreviewPanel(); - try { - panel.setSource(source); - - BufferedImage rendered = panel.renderSourceSnapshot(64, 64); - - assertEquals(0xFFFF0000, rendered.getRGB(32, 32)); - } finally { - panel.close(); - } - } - - @Test - public void rendersRuntimeInterpretedHeightDataWithoutAFrame() { - BufferedImage source = new BufferedImage(2, 1, BufferedImage.TYPE_BYTE_GRAY); - source.getRaster().setSample(0, 0, 0, 0); - source.getRaster().setSample(1, 0, 0, 255); - IrisImageMap definition = new IrisImageMap() - .setSource("test") - .setType(IrisImageMapType.GRAYSCALE_HEIGHT) - .setOutOfBounds(IrisImageMapOutOfBounds.CLAMP) - .setMinimumHeight(0D) - .setMaximumHeight(255D); - CompiledIrisImageMap compiled = CompiledIrisImageMap.compile( - definition, new IrisImage(source, "png") - ); - ImageMapStudioPreviewPanel panel = new ImageMapStudioPreviewPanel(); - try { - panel.setPreview( - source, compiled, IrisImageMapMaskSampler.empty(), null, - IrisImageMapApplication.TERRAIN_HEIGHT, -64, (worldX, worldZ) -> 0D - ); - - BufferedImage interpreted = panel.renderInterpretedSnapshot(64, 32); - - assertNotEquals(interpreted.getRGB(4, 16), interpreted.getRGB(59, 16)); - } finally { - panel.close(); - } - } - - @Test - public void blendsMaskedHeightAgainstTheProceduralRuntimeBaseline() { - BufferedImage source = new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_GRAY); - source.getRaster().setSample(0, 0, 0, 255); - IrisImageMap definition = new IrisImageMap() - .setSource("height") - .setType(IrisImageMapType.GRAYSCALE_HEIGHT) - .setOutOfBounds(IrisImageMapOutOfBounds.CLAMP) - .setMinimumHeight(0D) - .setMaximumHeight(100D); - CompiledIrisImageMap compiled = CompiledIrisImageMap.compile(definition, new IrisImage(source, "png")); - IrisImageMapMaskSampler maskSampler = maskSampler(128); - ImageMapStudioPreviewPanel panel = new ImageMapStudioPreviewPanel(); - try { - panel.setPreview( - source, compiled, maskSampler, null, - IrisImageMapApplication.TERRAIN_HEIGHT, -64, (worldX, worldZ) -> 20D - ); - - BufferedImage interpreted = panel.renderInterpretedSnapshot(64, 32); - double weight = 128D / 255D; - double expectedHeight = -64D + IrisImageMapRuntime.blendTerrainHeight(164D, 20D, weight); - - assertEquals( - ImageMapStudioModel.heightColor(expectedHeight, 0D, 100D), - interpreted.getRGB(32, 16) - ); - } finally { - panel.close(); - } - } - - @Test - public void usesTheRuntimeCategoricalMaskCutoff() { - BufferedImage source = new BufferedImage(1, 1, BufferedImage.TYPE_INT_RGB); - source.setRGB(0, 0, 0xFFFF0000); - IrisImageMap definition = new IrisImageMap() - .setSource("biome") - .setType(IrisImageMapType.COLOR_MAP) - .setOutOfBounds(IrisImageMapOutOfBounds.CLAMP) - .setColors(new KMap<>(Map.of("#FF0000", "iris:test"))); - CompiledIrisImageMap compiled = CompiledIrisImageMap.compile(definition, new IrisImage(source, "png")); - ImageMapStudioPreviewPanel below = new ImageMapStudioPreviewPanel(); - ImageMapStudioPreviewPanel above = new ImageMapStudioPreviewPanel(); - try { - below.setPreview( - source, compiled, maskSampler(127), null, - IrisImageMapApplication.BIOME, -64, null - ); - above.setPreview( - source, compiled, maskSampler(128), null, - IrisImageMapApplication.BIOME, -64, null - ); - - assertEquals(new Color(12, 15, 22).getRGB(), below.renderInterpretedSnapshot(64, 32).getRGB(32, 16)); - assertEquals( - ImageMapStudioModel.targetColor("iris:test"), - above.renderInterpretedSnapshot(64, 32).getRGB(32, 16) - ); - } finally { - below.close(); - above.close(); - } - } - - private static IrisImageMapMaskSampler maskSampler(int sample) { - BufferedImage source = new BufferedImage(1, 1, BufferedImage.TYPE_BYTE_GRAY); - source.getRaster().setSample(0, 0, 0, sample); - IrisImageMap definition = new IrisImageMap() - .setSource("mask") - .setType(IrisImageMapType.GRAYSCALE_MASK) - .setOutOfBounds(IrisImageMapOutOfBounds.CLAMP); - CompiledIrisImageMap compiled = CompiledIrisImageMap.compile(definition, new IrisImage(source, "png")); - IrisImageMapMask mask = new IrisImageMapMask().setOperation(IrisImageMapMaskOperation.MULTIPLY); - return new IrisImageMapMaskSampler(List.of(IrisImageMapMaskSampler.layer(compiled, mask))); - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/map/MapCavePoolRefreshTest.java b/core/src/test/java/art/arcane/iris/studio/map/MapCavePoolRefreshTest.java deleted file mode 100644 index 89e5ceddf..000000000 --- a/core/src/test/java/art/arcane/iris/studio/map/MapCavePoolRefreshTest.java +++ /dev/null @@ -1,197 +0,0 @@ -package art.arcane.iris.studio.map; - -import art.arcane.iris.generation.biome.IrisBiome; -import art.arcane.iris.generation.hydrology.engine.HydrologyPlanPreview; -import art.arcane.iris.generation.hydrology.engine.HydrologyRuntime; -import art.arcane.iris.generation.hydrology.query.HydrologyFeatureType; -import art.arcane.iris.generation.hydrology.raster.ChunkWaterRaster; -import art.arcane.iris.generation.runtime.IrisComplex; -import art.arcane.iris.generation.runtime.IrisEngine; -import art.arcane.iris.generation.terrain.IrisRegion; -import art.arcane.iris.studio.map.components.MapLayer; -import art.arcane.iris.studio.map.components.MapStyle; -import art.arcane.iris.studio.map.components.MapTile; -import art.arcane.iris.studio.map.components.MapTileRenderer; -import art.arcane.iris.studio.map.components.TileType; -import art.arcane.iris.studio.render.IrisRenderer; -import art.arcane.iris.world.history.ChunkGenerationSemantics; -import art.arcane.iris.world.history.GenerationHistory; -import art.arcane.iris.world.history.GenerationHistoryRuntimeRouter; -import art.arcane.volmlib.util.stream.ProceduralStream; -import art.arcane.volmlib.util.stream.interpolation.Interpolated; -import org.junit.Test; - -import java.util.Optional; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.BooleanSupplier; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotEquals; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class MapCavePoolRefreshTest { - private static final int POOL_X = 20; - private static final int POOL_Z = 24; - private static final int POOL = IrisRenderer.hydrologyFeatureColor(HydrologyFeatureType.CAVE_POOL) & 0xFFFFFF; - - @Test - public void completeTilesPickUpRecordedCavePools() throws Exception { - Scene scene = new Scene(); - AtomicLong time = new AtomicLong(); - try (VisionRenderController controller = new VisionRenderController(() -> { }, time::get)) { - VisionRenderController.Frame frame = controller.request(spec(scene.renderer, 4D)); - await(() -> controller.progress(frame).ready() == 1 && controller.progress(frame).activeWorkers() == 0); - assertNotEquals(POOL, pixel(frame, 4D)); - long sampled = scene.samples.get(); - - scene.record(); - controller.retryProvisional(frame); - await(() -> controller.progress(frame).activeWorkers() == 0); - assertNotEquals("refreshes wait for the retry cadence", POOL, pixel(frame, 4D)); - time.set(VisionRenderController.FIRST_RETRY_NANOS); - await(() -> { - controller.retryProvisional(frame); - return pixel(frame, 4D) == POOL; - }); - - assertEquals("a refresh redraws only the water", sampled, scene.samples.get()); - assertEquals(1, controller.progress(frame).ready()); - } - } - - @Test - public void coarseTilesKeepNoWaterState() throws Exception { - Scene scene = new Scene(); - MapTileRenderer.TileRender detailed = settle(scene.renderer.prepareTile(0D, 0D, 4D, VisionRenderController.TILE_PIXELS, - MapLayer.of(TileType.RIVER), false)); - MapTileRenderer.TileRender coarse = settle(scene.renderer.prepareTile(0D, 0D, 8D, VisionRenderController.TILE_PIXELS, - MapLayer.of(TileType.RIVER), false)); - assertTrue(detailed.retainsWater()); - assertTrue(detailed.bytes() > 0L); - assertFalse(coarse.retainsWater()); - assertEquals(0L, coarse.bytes()); - - AtomicLong time = new AtomicLong(); - try (VisionRenderController controller = new VisionRenderController(() -> { }, time::get)) { - VisionRenderController.Frame frame = controller.request(spec(scene.renderer, 8D)); - await(() -> controller.progress(frame).ready() == 1 && controller.progress(frame).activeWorkers() == 0); - MapTile drawn = frame.tiles().getFirst().tile(); - - scene.record(); - time.set(VisionRenderController.FIRST_RETRY_NANOS); - controller.retryProvisional(frame); - await(() -> controller.progress(frame).activeWorkers() == 0); - - assertSame(drawn, frame.tiles().getFirst().tile()); - assertNotEquals(POOL, pixel(frame, 8D)); - } - } - - @Test - public void poolsRecordedAfterARasterLandsStillRefresh() throws Exception { - Scene scene = new Scene(); - AtomicBoolean landed = new AtomicBoolean(); - when(scene.runtime.rasterPreview(anyInt(), anyInt())) - .thenAnswer(invocation -> landed.get() ? ChunkWaterRaster.EMPTY : ChunkWaterRaster.PROVISIONAL); - AtomicLong time = new AtomicLong(); - try (VisionRenderController controller = new VisionRenderController(() -> { }, time::get)) { - VisionRenderController.Frame frame = controller.request(spec(scene.renderer, 2D)); - await(() -> frame.tiles().getFirst().tile() != null && controller.progress(frame).activeWorkers() == 0); - assertTrue(frame.tiles().getFirst().provisional()); - - landed.set(true); - scene.preview.incrementAndGet(); - time.addAndGet(VisionRenderController.FIRST_RETRY_NANOS); - await(() -> { - controller.retryProvisional(frame); - return controller.progress(frame).ready() == 1 && controller.progress(frame).activeWorkers() == 0; - }); - assertNotEquals("the chunk records its pool after its raster lands", POOL, pixel(frame, 2D)); - - scene.record(); - time.addAndGet(VisionRenderController.FIRST_RETRY_NANOS); - await(() -> { - controller.retryProvisional(frame); - return pixel(frame, 2D) == POOL; - }); - } - } - - private static MapTileRenderer.TileRender settle(MapTileRenderer.TileRender work) throws Exception { - await(() -> { - work.render(() -> false); - return work.complete(); - }); - return work; - } - - private static int pixel(VisionRenderController.Frame frame, double blocksPerPixel) { - MapTile tile = frame.tiles().getFirst().tile(); - return tile.image(MapStyle.PLAIN).getRGB((int) (POOL_X / blocksPerPixel), (int) (POOL_Z / blocksPerPixel)) & 0xFFFFFF; - } - - private static VisionRenderController.RenderSpec spec(MapTileRenderer renderer, double blocksPerPixel) { - double centre = VisionRenderController.TILE_PIXELS * blocksPerPixel / 2D; - return new VisionRenderController.RenderSpec(renderer, MapLayer.of(TileType.RIVER), 1L, centre, centre, blocksPerPixel, - VisionRenderController.TILE_PIXELS, VisionRenderController.TILE_PIXELS, false); - } - - private static void await(BooleanSupplier condition) throws Exception { - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5L); - while (!condition.getAsBoolean()) { - assertTrue("condition never held", System.nanoTime() < deadline); - Thread.sleep(5L); - } - } - - private static final class Scene { - private final AtomicLong samples = new AtomicLong(); - private final AtomicLong preview = new AtomicLong(); - private final AtomicLong water = new AtomicLong(); - private final AtomicBoolean recorded = new AtomicBoolean(); - private final HydrologyRuntime runtime = mock(HydrologyRuntime.class); - private final MapTileRenderer renderer; - - private Scene() { - when(runtime.enabled()).thenReturn(true); - when(runtime.planPreview(anyInt(), anyInt(), anyInt(), anyInt())).thenReturn(HydrologyPlanPreview.EMPTY); - when(runtime.rasterPreview(anyInt(), anyInt())).thenReturn(ChunkWaterRaster.EMPTY); - when(runtime.previewRevision()).thenAnswer(invocation -> preview.get()); - IrisEngine engine = mock(IrisEngine.class); - IrisComplex complex = mock(IrisComplex.class); - when(engine.getComplex()).thenReturn(complex); - when(engine.getHeight()).thenReturn(256); - when(complex.getHydrologyRuntime()).thenReturn(runtime); - IrisBiome biome = new IrisBiome(); - biome.setColor("#738249"); - IrisRegion region = new IrisRegion(); - when(complex.getBaseBiomeStream()).thenReturn(ProceduralStream.of((x, z) -> biome, Interpolated.of(b -> 0D, d -> biome))); - when(complex.getRegionStream()).thenReturn(ProceduralStream.of((x, z) -> { - samples.incrementAndGet(); - return region; - }, Interpolated.of(r -> 0D, d -> region))); - GenerationHistory history = mock(GenerationHistory.class); - GenerationHistoryRuntimeRouter router = mock(GenerationHistoryRuntimeRouter.class); - when(engine.getGenerationHistoryRuntimeRouter()).thenReturn(Optional.of(router)); - when(router.history()).thenReturn(history); - when(history.riverRevision()).thenAnswer(invocation -> water.get()); - ChunkGenerationSemantics pool = ChunkGenerationSemantics.builder(1, 1, 1L) - .addRiverFeature("water", HydrologyFeatureType.CAVE_POOL, 7L, POOL_X, 12, POOL_Z).build(); - when(history.semantics(anyInt(), anyInt())).thenReturn(Optional.empty()); - when(history.semantics(1, 1)).thenAnswer(invocation -> recorded.get() ? Optional.of(pool) : Optional.empty()); - renderer = new MapTileRenderer(engine); - } - - private void record() { - recorded.set(true); - water.incrementAndGet(); - } - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/map/NoiseExplorerGUITest.java b/core/src/test/java/art/arcane/iris/studio/map/NoiseExplorerGUITest.java deleted file mode 100644 index 41e7a662b..000000000 --- a/core/src/test/java/art/arcane/iris/studio/map/NoiseExplorerGUITest.java +++ /dev/null @@ -1,109 +0,0 @@ -package art.arcane.iris.studio.map; - -import art.arcane.iris.configuration.IrisSettings; -import art.arcane.iris.generation.runtime.MeteredCache; -import art.arcane.iris.generation.runtime.PreservationRegistry; -import art.arcane.iris.spi.IrisServices; -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.studio.view.GuiHost; -import art.arcane.iris.testsupport.PlatformLeakGuard; -import org.junit.ClassRule; -import org.junit.Test; - -import javax.swing.SwingUtilities; -import java.util.ArrayList; -import java.util.List; -import java.util.UUID; -import java.lang.reflect.Method; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.atomic.AtomicReference; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.junit.Assert.assertSame; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public final class NoiseExplorerGUITest { - @ClassRule - public static final PlatformLeakGuard PLATFORM_GUARD = PlatformLeakGuard.clean(); - - @Test - public void hotloadKeepsTheWorldThatOpenedTheNoiseView() throws Exception { - UUID worldId = UUID.randomUUID(); - Engine refreshed = mock(Engine.class); - Engine otherWorld = mock(Engine.class); - IrisSettings previousSettings = IrisSettings.settings; - IrisSettings.settings = new IrisSettings(); - GuiHost.Provider previous = GuiHost.get(); - GuiHost.Provider provider = mock(GuiHost.Provider.class); - when(provider.findEngine(worldId)).thenReturn(refreshed); - when(provider.findActiveEngine()).thenReturn(otherWorld); - AtomicReference opened = new AtomicReference<>(); - GuiHost.set(provider); - try { - SwingUtilities.invokeAndWait(() -> opened.set(NoiseExplorerGUI.createNoiseExplorer(new PaletteExplorerStart(null, worldId, null, null, 0, 0)))); - Method lookup = NoiseExplorerGUI.class.getDeclaredMethod("engineAfterHotload"); - lookup.setAccessible(true); - assertSame(refreshed, lookup.invoke(opened.get())); - } finally { - NoiseExplorerGUI explorer = opened.get(); - if (explorer != null) { - SwingUtilities.invokeAndWait(explorer::close); - } - GuiHost.set(previous); - IrisSettings.settings = previousSettings; - } - } - - @Test - public void allExecutorsRegisterForPreservationAndCloseWithWindow() throws Exception { - PreservationRegistry previous = IrisServices.getOrNull(PreservationRegistry.class); - IrisSettings previousSettings = IrisSettings.settings; - RecordingPreservationRegistry preservation = new RecordingPreservationRegistry(); - AtomicReference explorerReference = new AtomicReference<>(); - IrisServices.register(PreservationRegistry.class, preservation); - IrisSettings.settings = new IrisSettings(); - try { - SwingUtilities.invokeAndWait(() -> explorerReference.set(NoiseExplorerGUI.createNoiseExplorer(null))); - - assertFalse(preservation.executors.isEmpty()); - SwingUtilities.invokeAndWait(explorerReference.get()::close); - for (ExecutorService executor : preservation.executors) { - assertTrue(executor.isShutdown()); - } - } finally { - NoiseExplorerGUI explorer = explorerReference.get(); - if (explorer != null) { - SwingUtilities.invokeAndWait(explorer::close); - } - if (previous == null) { - IrisServices.remove(PreservationRegistry.class); - } else { - IrisServices.register(PreservationRegistry.class, previous); - } - IrisSettings.settings = previousSettings; - } - } - - private static final class RecordingPreservationRegistry implements PreservationRegistry { - private final List executors = new ArrayList<>(); - - @Override - public void register(Thread thread) { - } - - @Override - public void register(ExecutorService service) { - executors.add(service); - } - - @Override - public void registerCache(MeteredCache cache) { - } - - @Override - public void dereference() { - } - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/map/NoisePaletteTest.java b/core/src/test/java/art/arcane/iris/studio/map/NoisePaletteTest.java deleted file mode 100644 index 25a7b243f..000000000 --- a/core/src/test/java/art/arcane/iris/studio/map/NoisePaletteTest.java +++ /dev/null @@ -1,36 +0,0 @@ -package art.arcane.iris.studio.map; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotEquals; - -public final class NoisePaletteTest { - @Test - public void invalidSamplesUseVisibleDiagnosticColor() { - assertEquals(NoisePalette.INVALID_COLOR, NoisePalette.TERRAIN.color(Double.NaN)); - assertEquals(NoisePalette.INVALID_COLOR, NoisePalette.TERRAIN.color(Double.POSITIVE_INFINITY)); - } - - @Test - public void paletteClipsValuesToItsDocumentedRange() { - assertEquals(NoisePalette.SIGNED.color(-1D), NoisePalette.SIGNED.color(-10D)); - assertEquals(NoisePalette.SIGNED.color(1D), NoisePalette.SIGNED.color(10D)); - assertNotEquals(NoisePalette.SIGNED.color(-1D), NoisePalette.SIGNED.color(1D)); - } - - @Test - public void finiteHotPathAndCachedDisplayColorsMatchCanonicalLookup() { - for (NoisePalette palette : NoisePalette.values()) { - for (int index = -200; index <= 200; index++) { - double value = index / 100D; - assertEquals(palette.color(value), palette.colorFinite(value)); - double normalized = (value - palette.minimum()) / (palette.maximum() - palette.minimum()); - assertEquals( - palette.colorNormalized(normalized), - palette.displayColorNormalized(normalized).getRGB() & 0xFFFFFF - ); - } - } - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/map/NoiseRenderCoordinatorTest.java b/core/src/test/java/art/arcane/iris/studio/map/NoiseRenderCoordinatorTest.java deleted file mode 100644 index 6021d52e2..000000000 --- a/core/src/test/java/art/arcane/iris/studio/map/NoiseRenderCoordinatorTest.java +++ /dev/null @@ -1,419 +0,0 @@ -package art.arcane.iris.studio.map; - -import art.arcane.volmlib.util.function.NoiseProvider; -import org.junit.Test; - -import javax.swing.SwingUtilities; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -public final class NoiseRenderCoordinatorTest { - @Test - public void adaptiveStepNeverExceedsHardSampleBudget() { - int sampleStep = NoiseRenderCoordinator.sampleStepForBudget(3840, 2160, 400_000L); - - assertTrue(sampleStep > 1); - assertTrue(NoiseRenderCoordinator.sampleCount(3840, 2160, sampleStep) <= 400_000L); - assertEquals(1, NoiseRenderCoordinator.sampleStepForBudget(320, 200, 64_000L)); - } - - @Test - public void timedBudgetStaysSmallForSlowSourcesAndCapsFastSources() { - assertEquals(24_000L, NoiseRenderCoordinator.timeBoundSampleBudget( - 18_000L, - 2_000D, - 500D, - 24_000L, - 120_000L - )); - assertEquals(120_000L, NoiseRenderCoordinator.timeBoundSampleBudget( - 18_000L, - 10D, - 500D, - 24_000L, - 120_000L - )); - } - - @Test - public void eachRefinementPassMakesVisibleProgressEvenForSlowSources() { - assertEquals(7, NoiseRenderCoordinator.nextRefinementStep(1440, 770, 7, 24_000L)); - assertEquals(2, NoiseRenderCoordinator.nextRefinementStep(1440, 770, 2, 24_000L)); - assertEquals(1, NoiseRenderCoordinator.nextRefinementStep(320, 200, 3, 400_000L)); - int boundedStep = NoiseRenderCoordinator.nextRefinementStep(3840, 2160, 64, 48_000L); - assertTrue(NoiseRenderCoordinator.sampleCount(3840, 2160, boundedStep) <= 48_000L); - } - - @Test - public void sameRevisionRefinementSupersedesAnInFlightPreview() throws Exception { - CountDownLatch previewStarted = new CountDownLatch(1); - CountDownLatch releasePreview = new CountDownLatch(1); - CountDownLatch completed = new CountDownLatch(1); - List completedSteps = new ArrayList<>(); - AtomicReference failure = new AtomicReference<>(); - NoiseRenderCoordinator coordinator = new NoiseRenderCoordinator(2, new NoiseRenderCoordinator.Listener() { - @Override - public void onRenderStarted(NoiseRenderCoordinator.Request request) { - if (request.sampleStep() == 4) { - previewStarted.countDown(); - } - } - - @Override - public void onRenderCompleted(NoiseRenderCoordinator.Result result) { - completedSteps.add(result.request().sampleStep()); - completed.countDown(); - } - - @Override - public void onRenderFailed(NoiseRenderCoordinator.Request request, Throwable error) { - failure.set(error); - completed.countDown(); - } - }); - try { - AtomicBoolean firstSample = new AtomicBoolean(true); - NoiseProvider previewSampler = (x, z) -> { - if (firstSample.compareAndSet(true, false)) { - try { - releasePreview.await(3L, TimeUnit.SECONDS); - } catch (InterruptedException error) { - Thread.currentThread().interrupt(); - } - } - return 0.25D; - }; - NoiseRenderCoordinator.Request preview = new NoiseRenderCoordinator.Request( - 7L, - previewSampler, - new NoiseViewport(0D, 0D, 1D), - NoisePalette.TERRAIN, - 64, - 32, - 4 - ); - NoiseRenderCoordinator.Request refinement = new NoiseRenderCoordinator.Request( - 7L, - (x, z) -> 0.75D, - new NoiseViewport(0D, 0D, 1D), - NoisePalette.TERRAIN, - 64, - 32, - 2 - ); - - coordinator.request(preview); - assertTrue(previewStarted.await(3L, TimeUnit.SECONDS)); - coordinator.request(refinement); - releasePreview.countDown(); - - assertTrue(completed.await(3L, TimeUnit.SECONDS)); - assertEquals(null, failure.get()); - assertEquals(List.of(2), completedSteps); - } finally { - releasePreview.countDown(); - coordinator.close(); - } - } - - @Test - public void samplingRunsOffEdtAndStopsWhenRenderCompletes() throws Exception { - CountDownLatch completed = new CountDownLatch(1); - AtomicReference result = new AtomicReference<>(); - AtomicReference failure = new AtomicReference<>(); - AtomicReference samplingThread = new AtomicReference<>(); - AtomicBoolean sampledOnEdt = new AtomicBoolean(); - AtomicBoolean renderFinished = new AtomicBoolean(); - CountDownLatch sampledAfterCompletion = new CountDownLatch(1); - AtomicInteger samples = new AtomicInteger(); - NoiseRenderCoordinator coordinator = new NoiseRenderCoordinator(2, new NoiseRenderCoordinator.Listener() { - @Override - public void onRenderStarted(NoiseRenderCoordinator.Request request) { - } - - @Override - public void onRenderCompleted(NoiseRenderCoordinator.Result rendered) { - result.set(rendered); - completed.countDown(); - } - - @Override - public void onRenderFailed(NoiseRenderCoordinator.Request request, Throwable error) { - failure.set(error); - completed.countDown(); - } - }); - try { - NoiseProvider sampler = (x, z) -> { - samples.incrementAndGet(); - if (renderFinished.get()) { - sampledAfterCompletion.countDown(); - } - samplingThread.compareAndSet(null, Thread.currentThread().getName()); - sampledOnEdt.compareAndSet(false, SwingUtilities.isEventDispatchThread()); - return x + z; - }; - NoiseRenderCoordinator.Request request = new NoiseRenderCoordinator.Request( - 1L, - sampler, - new NoiseViewport(0D, 0D, 1D), - NoisePalette.SIGNED, - 17, - 11, - 1 - ); - - SwingUtilities.invokeAndWait(() -> coordinator.request(request)); - - assertTrue(completed.await(3L, TimeUnit.SECONDS)); - assertEquals(null, failure.get()); - assertNotNull(result.get()); - assertEquals(187, samples.get()); - assertFalse(sampledOnEdt.get()); - assertTrue(samplingThread.get().startsWith("Iris Noise Renderer")); - int completedSamples = samples.get(); - renderFinished.set(true); - assertFalse(sampledAfterCompletion.await(150L, TimeUnit.MILLISECONDS)); - assertEquals(completedSamples, samples.get()); - } finally { - coordinator.close(); - } - } - - @Test - public void samplingTraversesEachBandInRowMajorOrder() throws Exception { - CountDownLatch completed = new CountDownLatch(1); - List coordinates = new ArrayList<>(); - AtomicReference failure = new AtomicReference<>(); - NoiseRenderCoordinator coordinator = new NoiseRenderCoordinator(1, new NoiseRenderCoordinator.Listener() { - @Override - public void onRenderStarted(NoiseRenderCoordinator.Request request) { - } - - @Override - public void onRenderCompleted(NoiseRenderCoordinator.Result result) { - completed.countDown(); - } - - @Override - public void onRenderFailed(NoiseRenderCoordinator.Request request, Throwable error) { - failure.set(error); - completed.countDown(); - } - }); - try { - NoiseProvider sampler = (x, z) -> { - coordinates.add(x + "," + z); - return 0.5D; - }; - coordinator.request(new NoiseRenderCoordinator.Request( - 1L, - sampler, - new NoiseViewport(0D, 0D, 1D), - NoisePalette.TERRAIN, - 6, - 4, - 2 - )); - - assertTrue(completed.await(3L, TimeUnit.SECONDS)); - assertEquals(null, failure.get()); - assertEquals(List.of("-2.0,-1.0", "0.0,-1.0", "2.0,-1.0", "-2.0,1.0", "0.0,1.0", "2.0,1.0"), coordinates); - } finally { - coordinator.close(); - } - } - - @Test - public void newerRevisionDiscardsStaleResult() throws Exception { - CountDownLatch firstSample = new CountDownLatch(1); - CountDownLatch releaseFirst = new CountDownLatch(1); - CountDownLatch latestCompleted = new CountDownLatch(1); - List completedRevisions = new ArrayList<>(); - AtomicReference failure = new AtomicReference<>(); - AtomicInteger staleSamples = new AtomicInteger(); - NoiseRenderCoordinator coordinator = new NoiseRenderCoordinator(1, new NoiseRenderCoordinator.Listener() { - @Override - public void onRenderStarted(NoiseRenderCoordinator.Request request) { - } - - @Override - public void onRenderCompleted(NoiseRenderCoordinator.Result result) { - completedRevisions.add(result.request().revision()); - if (result.request().revision() == 2L) { - latestCompleted.countDown(); - } - } - - @Override - public void onRenderFailed(NoiseRenderCoordinator.Request request, Throwable error) { - failure.set(error); - latestCompleted.countDown(); - } - }); - try { - AtomicBoolean block = new AtomicBoolean(true); - NoiseProvider slowSampler = (x, z) -> { - staleSamples.incrementAndGet(); - if (block.compareAndSet(true, false)) { - firstSample.countDown(); - while (releaseFirst.getCount() > 0L) { - Thread.onSpinWait(); - } - } - return 0.25D; - }; - NoiseRenderCoordinator.Request stale = new NoiseRenderCoordinator.Request( - 1L, - slowSampler, - new NoiseViewport(0D, 0D, 1D), - NoisePalette.TERRAIN, - 512, - 1, - 1 - ); - NoiseRenderCoordinator.Request latest = new NoiseRenderCoordinator.Request( - 2L, - (x, z) -> 0.75D, - new NoiseViewport(0D, 0D, 1D), - NoisePalette.TERRAIN, - 512, - 1, - 1 - ); - - coordinator.request(stale); - assertTrue(firstSample.await(3L, TimeUnit.SECONDS)); - coordinator.request(latest); - - assertTrue(latestCompleted.await(3L, TimeUnit.SECONDS)); - assertEquals(null, failure.get()); - assertEquals(List.of(2L), completedRevisions); - assertTrue(staleSamples.get() <= 32); - } finally { - releaseFirst.countDown(); - coordinator.close(); - } - } - - @Test - public void closeReturnsImmediatelyWhenSamplerIgnoresInterruption() throws Exception { - CountDownLatch sampleStarted = new CountDownLatch(1); - AtomicBoolean releaseSampler = new AtomicBoolean(); - AtomicBoolean daemonWorker = new AtomicBoolean(); - NoiseRenderCoordinator coordinator = new NoiseRenderCoordinator(1, new NoiseRenderCoordinator.Listener() { - @Override - public void onRenderStarted(NoiseRenderCoordinator.Request request) { - } - - @Override - public void onRenderCompleted(NoiseRenderCoordinator.Result result) { - } - - @Override - public void onRenderFailed(NoiseRenderCoordinator.Request request, Throwable error) { - } - }); - try { - coordinator.request(new NoiseRenderCoordinator.Request( - 1L, - (x, z) -> { - daemonWorker.set(Thread.currentThread().isDaemon()); - sampleStarted.countDown(); - while (!releaseSampler.get()) { - Thread.onSpinWait(); - } - return 0.5D; - }, - new NoiseViewport(0D, 0D, 1D), - NoisePalette.TERRAIN, - 32, - 32, - 1 - )); - assertTrue(sampleStarted.await(1L, TimeUnit.SECONDS)); - - long started = System.nanoTime(); - coordinator.close(); - long closeMillis = TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - started); - - assertTrue(closeMillis < 200L); - assertTrue(daemonWorker.get()); - } finally { - releaseSampler.set(true); - coordinator.close(); - } - } - - @Test - public void latestMultiBandViewCompletesAfterThreeInterruptIgnoringGenerations() throws Exception { - CountDownLatch latestCompleted = new CountDownLatch(1); - AtomicReference failure = new AtomicReference<>(); - AtomicBoolean releaseStale = new AtomicBoolean(); - NoiseRenderCoordinator coordinator = new NoiseRenderCoordinator(2, new NoiseRenderCoordinator.Listener() { - @Override - public void onRenderStarted(NoiseRenderCoordinator.Request request) { - } - - @Override - public void onRenderCompleted(NoiseRenderCoordinator.Result result) { - if (result.request().revision() == 4L) { - latestCompleted.countDown(); - } - } - - @Override - public void onRenderFailed(NoiseRenderCoordinator.Request request, Throwable error) { - failure.set(error); - latestCompleted.countDown(); - } - }); - try { - for (long revision = 1L; revision <= 3L; revision++) { - CountDownLatch staleStarted = new CountDownLatch(2); - coordinator.request(new NoiseRenderCoordinator.Request( - revision, - (x, z) -> { - staleStarted.countDown(); - while (!releaseStale.get()) { - Thread.onSpinWait(); - } - return 0.25D; - }, - new NoiseViewport(0D, 0D, 1D), - NoisePalette.TERRAIN, - 8, - 4, - 1 - )); - assertTrue(staleStarted.await(1L, TimeUnit.SECONDS)); - } - - coordinator.request(new NoiseRenderCoordinator.Request( - 4L, - (x, z) -> 0.75D, - new NoiseViewport(0D, 0D, 1D), - NoisePalette.TERRAIN, - 8, - 4, - 1 - )); - - assertTrue(latestCompleted.await(3L, TimeUnit.SECONDS)); - assertEquals(null, failure.get()); - } finally { - releaseStale.set(true); - coordinator.close(); - } - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/map/NoiseTerrainViewTest.java b/core/src/test/java/art/arcane/iris/studio/map/NoiseTerrainViewTest.java deleted file mode 100644 index 30bfc8c46..000000000 --- a/core/src/test/java/art/arcane/iris/studio/map/NoiseTerrainViewTest.java +++ /dev/null @@ -1,89 +0,0 @@ -package art.arcane.iris.studio.map; - -import art.arcane.iris.generation.stream.ProvisionalSampling; -import org.junit.Test; - -import javax.swing.SwingUtilities; -import java.util.Arrays; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; - -public final class NoiseTerrainViewTest { - @Test - public void stationaryViewRetriesProvisionalTerrainWithoutCameraChanges() throws Exception { - AtomicReference firstGrid = new AtomicReference<>(); - AtomicInteger attempts = new AtomicInteger(); - CountDownLatch retried = new CountDownLatch(1); - TerrainSampling sampling = new TerrainSampling((grid, row, heights, colors) -> { - firstGrid.compareAndSet(null, grid); - if (grid.equals(firstGrid.get())) { - if (row == 0 && attempts.incrementAndGet() > 1) { - retried.countDown(); - } - if (attempts.get() == 1) { - ProvisionalSampling.mark(); - } - } - Arrays.fill(heights, row * grid.columns(), (row + 1) * grid.columns(), 20F); - }, 0, 64, Double.NaN); - ExecutorService workers = Executors.newSingleThreadExecutor(); - ExecutorService renderers = Executors.newSingleThreadExecutor(); - AtomicReference viewport = new AtomicReference<>(); - AtomicReference view = new AtomicReference<>(); - try { - SwingUtilities.invokeAndWait(() -> { - OrbitViewport opened = new OrbitViewport("Terrain refresh test", null); - opened.setSize(640, 480); - viewport.set(opened); - NoiseTerrainView shown = new NoiseTerrainView(opened, renderers, workers, 1); - view.set(shown); - shown.show(sampling); - }); - assertTrue(retried.await(5, TimeUnit.SECONDS)); - } finally { - SwingUtilities.invokeAndWait(() -> { - view.get().close(); - viewport.get().close(); - }); - workers.shutdownNow(); - renderers.shutdownNow(); - assertTrue(workers.awaitTermination(3, TimeUnit.SECONDS)); - assertTrue(renderers.awaitTermination(3, TimeUnit.SECONDS)); - } - } - - @Test - public void closedViewIgnoresSubsequentRefreshes() throws Exception { - AtomicInteger samples = new AtomicInteger(); - TerrainSampling sampling = new TerrainSampling((grid, row, heights, colors) -> samples.incrementAndGet(), - 0, 64, Double.NaN); - ExecutorService workers = Executors.newSingleThreadExecutor(); - ExecutorService renderers = Executors.newSingleThreadExecutor(); - try { - SwingUtilities.invokeAndWait(() -> { - OrbitViewport viewport = new OrbitViewport("Closed terrain test", null); - viewport.setSize(32, 32); - NoiseTerrainView view = new NoiseTerrainView(viewport, renderers, workers, 1); - view.close(); - view.close(); - view.show(sampling); - view.resume(); - viewport.close(); - }); - workers.shutdown(); - assertTrue(workers.awaitTermination(3, TimeUnit.SECONDS)); - assertEquals(0, samples.get()); - } finally { - workers.shutdownNow(); - renderers.shutdownNow(); - assertTrue(renderers.awaitTermination(3, TimeUnit.SECONDS)); - } - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/map/NoiseViewportTest.java b/core/src/test/java/art/arcane/iris/studio/map/NoiseViewportTest.java deleted file mode 100644 index 98db96ce8..000000000 --- a/core/src/test/java/art/arcane/iris/studio/map/NoiseViewportTest.java +++ /dev/null @@ -1,31 +0,0 @@ -package art.arcane.iris.studio.map; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public final class NoiseViewportTest { - @Test - public void zoomKeepsCursorWorldPositionFixed() { - NoiseViewport viewport = new NoiseViewport(120D, -35D, 2.5D); - double worldX = viewport.worldX(713D, 1200); - double worldZ = viewport.worldZ(147D, 700); - - NoiseViewport zoomed = viewport.zoomAt(713D, 147D, 1200, 700, 0.4D); - - assertEquals(worldX, zoomed.worldX(713D, 1200), 0.000000001D); - assertEquals(worldZ, zoomed.worldZ(147D, 700), 0.000000001D); - assertEquals(1D, zoomed.blocksPerPixel(), 0D); - } - - @Test - public void panMovesCenterByPixelDeltaAtCurrentScale() { - NoiseViewport viewport = new NoiseViewport(10D, 20D, 2D); - - NoiseViewport panned = viewport.panPixels(7D, -3D); - - assertEquals(-4D, panned.centerX(), 0D); - assertEquals(26D, panned.centerZ(), 0D); - assertEquals(2D, panned.blocksPerPixel(), 0D); - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/map/ObjectExplorerLifecycleTest.java b/core/src/test/java/art/arcane/iris/studio/map/ObjectExplorerLifecycleTest.java deleted file mode 100644 index 889745632..000000000 --- a/core/src/test/java/art/arcane/iris/studio/map/ObjectExplorerLifecycleTest.java +++ /dev/null @@ -1,224 +0,0 @@ -package art.arcane.iris.studio.map; - -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.pack.loading.IrisData; -import art.arcane.iris.structure.object.IrisObject; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import javax.swing.JLabel; -import javax.swing.SwingUtilities; -import javax.swing.Timer; -import java.lang.reflect.Field; -import java.util.ArrayList; -import java.util.List; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public class ObjectExplorerLifecycleTest { - private final List explorers = new ArrayList<>(); - private final TextureFuture textureFuture = new TextureFuture(); - private Object previousTextures; - - @Before - public void installTextures() throws Exception { - Field shared = field(BlockTextures.class, "shared"); - previousTextures = shared.get(null); - shared.set(null, textureFuture); - } - - @After - public void closeExplorers() throws Exception { - SwingUtilities.invokeAndWait(() -> explorers.forEach(ObjectExplorer::close)); - textureFuture.completeExceptionally(new IllegalStateException("Test texture download ended")); - for (ObjectExplorer explorer : explorers) { - executor(explorer, "loader").awaitTermination(3, TimeUnit.SECONDS); - executor(explorer, "thumbnailPainter").awaitTermination(3, TimeUnit.SECONDS); - } - SwingUtilities.invokeAndWait(() -> { }); - field(BlockTextures.class, "shared").set(null, previousTextures); - } - - @Test - public void closingWhileTexturesArePendingReleasesTheLoaderWithoutCancellingSharedTextures() throws Exception { - Catalog catalog = new Catalog(); - ObjectExplorer explorer = open(catalog); - assertTrue(textureFuture.started.await(3, TimeUnit.SECONDS)); - - SwingUtilities.invokeAndWait(explorer::close); - - assertTrue("Texture waiting retained the closed preview's loader", executor(explorer, "loader").awaitTermination(3, TimeUnit.SECONDS)); - assertFalse(textureFuture.isDone()); - assertEquals(0, catalog.reads.get()); - } - - @Test - public void textureSuccessAfterClosureDoesNotPublishOrRestartLoading() throws Exception { - Catalog catalog = new Catalog(); - ObjectExplorer explorer = open(catalog); - assertTrue(textureFuture.started.await(3, TimeUnit.SECONDS)); - SwingUtilities.invokeAndWait(explorer::close); - - textureFuture.complete(textures()); - assertTrue(executor(explorer, "loader").awaitTermination(3, TimeUnit.SECONDS)); - SwingUtilities.invokeAndWait(() -> { }); - - assertEquals(0, catalog.reads.get()); - assertNull(field(ObjectExplorer.class, "textures").get(explorer)); - assertStopped(explorer); - } - - @Test - public void textureFailureAfterClosureDoesNotPublishAnError() throws Exception { - ObjectExplorer explorer = open(new Catalog()); - assertTrue(textureFuture.started.await(3, TimeUnit.SECONDS)); - SwingUtilities.invokeAndWait(explorer::close); - - textureFuture.completeExceptionally(new IllegalStateException("Texture download failed")); - assertTrue(executor(explorer, "loader").awaitTermination(3, TimeUnit.SECONDS)); - SwingUtilities.invokeAndWait(() -> { }); - - JLabel summary = (JLabel) field(StudioStatusBar.class, "summary").get(explorer.statusBar()); - assertEquals("", summary.getText()); - assertStopped(explorer); - } - - @Test - public void repeatedClosureAndLateOpenDoNotSubmitWorkOrRestartTimers() throws Exception { - ObjectExplorer explorer = open(new Catalog()); - assertTrue(textureFuture.started.await(3, TimeUnit.SECONDS)); - - SwingUtilities.invokeAndWait(() -> { - explorer.close(); - explorer.close(); - explorer.open(); - }); - - assertTrue(executor(explorer, "loader").awaitTermination(3, TimeUnit.SECONDS)); - assertStopped(explorer); - } - - @Test - public void anotherPreviewStillReceivesTheSharedTexturesAfterOneCloses() throws Exception { - Catalog firstCatalog = new Catalog(); - Catalog secondCatalog = new Catalog(); - ObjectExplorer first = open(firstCatalog); - ObjectExplorer second = open(secondCatalog); - assertTrue(textureFuture.bothStarted.await(3, TimeUnit.SECONDS)); - SwingUtilities.invokeAndWait(first::close); - assertFalse(textureFuture.isCancelled()); - - textureFuture.complete(textures()); - assertTrue(secondCatalog.read.await(3, TimeUnit.SECONDS)); - SwingUtilities.invokeAndWait(() -> { }); - - assertEquals(0, firstCatalog.reads.get()); - assertEquals(1, secondCatalog.reads.get()); - assertTrue(executor(first, "loader").awaitTermination(3, TimeUnit.SECONDS)); - assertFalse(executor(second, "loader").isShutdown()); - } - - @Test - public void closingStopsVariantGalleryAnimation() throws Exception { - ObjectExplorer explorer = open(new Catalog()); - ObjectVariantGallery gallery = (ObjectVariantGallery) field(ObjectExplorer.class, "gallery").get(explorer); - SwingUtilities.invokeAndWait(() -> { - gallery.showVariants("Variants", 2, 0); - explorer.close(); - }); - - assertFalse(((Timer) field(ObjectVariantGallery.class, "loadingTicker").get(gallery)).isRunning()); - } - - private ObjectExplorer open(Catalog catalog) throws Exception { - Engine engine = mock(Engine.class); - SwingUtilities.invokeAndWait(() -> { - ObjectExplorer explorer = new ObjectExplorer(engine, null, catalog); - explorers.add(explorer); - explorer.open(); - }); - return explorers.getLast(); - } - - private static BlockTextures textures() { - BlockTextures textures = mock(BlockTextures.class); - MinecraftBiomeColors colors = mock(MinecraftBiomeColors.class); - when(textures.biomeColors()).thenReturn(colors); - return textures; - } - - private static void assertStopped(ObjectExplorer explorer) throws Exception { - OrbitViewport viewport = (OrbitViewport) field(ObjectExplorer.class, "viewport").get(explorer); - assertFalse(((Timer) field(OrbitViewport.class, "loadingTicker").get(viewport)).isRunning()); - assertFalse(((Timer) field(OrbitViewport.class, "loadingCloser").get(viewport)).isRunning()); - assertTrue(executor(viewport, "renderThread").isShutdown()); - } - - private static ExecutorService executor(Object owner, String name) throws Exception { - return (ExecutorService) field(owner.getClass(), name).get(owner); - } - - private static Field field(Class owner, String name) throws Exception { - Field field = owner.getDeclaredField(name); - field.setAccessible(true); - return field; - } - - private static final class TextureFuture extends CompletableFuture { - private final CountDownLatch started = new CountDownLatch(1); - private final CountDownLatch bothStarted = new CountDownLatch(2); - - @Override - public BlockTextures get() throws InterruptedException, ExecutionException { - started.countDown(); - bothStarted.countDown(); - return super.get(); - } - - @Override - public BlockTextures join() { - started.countDown(); - bothStarted.countDown(); - return super.join(); - } - } - - private static final class Catalog implements ObjectSource { - private final AtomicInteger reads = new AtomicInteger(); - private final CountDownLatch read = new CountDownLatch(1); - - @Override - public String noun() { - return "object"; - } - - @Override - public EmptyState emptyState() { - return null; - } - - @Override - public List keys(IrisData data) { - reads.incrementAndGet(); - read.countDown(); - return List.of(); - } - - @Override - public List variants(IrisData data, String key) { - return List.of(); - } - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/map/OrbitViewportLifecycleTest.java b/core/src/test/java/art/arcane/iris/studio/map/OrbitViewportLifecycleTest.java deleted file mode 100644 index 409f6b8a4..000000000 --- a/core/src/test/java/art/arcane/iris/studio/map/OrbitViewportLifecycleTest.java +++ /dev/null @@ -1,97 +0,0 @@ -package art.arcane.iris.studio.map; - -import org.junit.Test; - -import javax.swing.SwingUtilities; -import javax.swing.Timer; -import java.awt.image.BufferedImage; -import java.lang.reflect.Field; -import java.util.OptionalDouble; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -public class OrbitViewportLifecycleTest { - @Test - public void closedViewportIgnoresLateLoadingAndScenes() throws Exception { - AtomicReference holder = new AtomicReference<>(); - SwingUtilities.invokeAndWait(() -> { - OrbitViewport viewport = new OrbitViewport("Closed viewport test", "Empty"); - holder.set(viewport); - viewport.setSize(32, 32); - viewport.close(); - viewport.close(); - viewport.showLoading("Late textures"); - viewport.show(new DelayedScene()); - }); - OrbitViewport viewport = holder.get(); - assertFalse(((Timer) field(viewport, "loadingTicker")).isRunning()); - assertNull(field(viewport, "scene")); - } - - @Test - public void renderCompletingAfterClosureDoesNotPublishOrRequestAnotherFrame() throws Exception { - DelayedScene scene = new DelayedScene(); - AtomicReference holder = new AtomicReference<>(); - SwingUtilities.invokeAndWait(() -> { - OrbitViewport viewport = new OrbitViewport("Closing viewport test", "Empty"); - holder.set(viewport); - viewport.setSize(32, 32); - viewport.showLoading("Blocks"); - viewport.show(scene); - }); - OrbitViewport viewport = holder.get(); - try { - assertTrue(scene.started.await(3, TimeUnit.SECONDS)); - SwingUtilities.invokeAndWait(viewport::close); - scene.release.countDown(); - assertTrue(((ExecutorService) field(viewport, "renderThread")).awaitTermination(3, TimeUnit.SECONDS)); - SwingUtilities.invokeAndWait(() -> { }); - - assertNull(field(viewport, "picture")); - assertFalse(((Timer) field(viewport, "loadingTicker")).isRunning()); - assertFalse(((Timer) field(viewport, "loadingCloser")).isRunning()); - } finally { - scene.release.countDown(); - SwingUtilities.invokeAndWait(viewport::close); - } - } - - private static Object field(Object owner, String name) throws Exception { - Field field = owner.getClass().getDeclaredField(name); - field.setAccessible(true); - return field.get(owner); - } - - private static final class DelayedScene implements OrbitScene { - private final CountDownLatch started = new CountDownLatch(1); - private final CountDownLatch release = new CountDownLatch(1); - - @Override - public boolean isEmpty() { - return false; - } - - @Override - public OrbitPicture render(OrbitCamera camera, int width, int height, int coveredLeftWidth) { - started.countDown(); - while (release.getCount() != 0) { - try { - assertTrue(release.await(3, TimeUnit.SECONDS)); - } catch (InterruptedException ignored) { - } - } - return OrbitPicture.whole(new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB), OptionalDouble.empty()).stillCatchingUp(); - } - - @Override - public OrbitProjection projection(OrbitCamera camera, int width, int height, int coveredLeftWidth) { - return null; - } - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/map/TerrainCoverTest.java b/core/src/test/java/art/arcane/iris/studio/map/TerrainCoverTest.java deleted file mode 100644 index cf7c50b37..000000000 --- a/core/src/test/java/art/arcane/iris/studio/map/TerrainCoverTest.java +++ /dev/null @@ -1,90 +0,0 @@ -package art.arcane.iris.studio.map; - -import org.junit.Test; - -import java.util.List; -import java.util.Map; -import java.util.concurrent.AbstractExecutorService; -import java.util.concurrent.TimeUnit; - -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; - -public final class TerrainCoverTest { - private static final int WIDTH = 1200; - private static final int HEIGHT = 800; - private static final TerrainSampling FLAT = new TerrainSampling((grid, row, heights, colors) -> { - }, 0, 64, Double.NaN); - private static final OrbitProjection PROJECTION = NoiseTerrainScene.projectionFrom(Vec3.ZERO, NoiseTerrainScene.START, - WIDTH, HEIGHT, 0); - - @Test - public void backdropNotSampledYetBorrowsTheNearestSampledCoarserTile() { - TerrainTile coarser = TerrainTile.containing(0D, 0D, backdropLevel() + 1); - - List drawn = drawnTiles(Map.of(coarser, flatLayer(coarser))); - - assertTrue(drawn.contains(coarser)); - } - - @Test - public void tilesTooCoarseToCutHolesInDoNotStandIn() { - TerrainTile tooCoarse = TerrainTile.containing(0D, 0D, backdropLevel() + TerrainHole.MOST_LEVELS_FINER + 1); - - List drawn = drawnTiles(Map.of(tooCoarse, flatLayer(tooCoarse))); - - assertFalse(drawn.contains(tooCoarse)); - } - - private static int backdropLevel() { - TerrainCover.Result nothingSampled = TerrainCover.of(tilesWith(Map.of()), PROJECTION, WIDTH, HEIGHT, 0); - int detailLevel = Integer.numberOfTrailingZeros(nothingSampled.detailStep()); - return detailLevel + 3; - } - - private static List drawnTiles(Map sampled) { - return TerrainCover.of(tilesWith(sampled), PROJECTION, WIDTH, HEIGHT, 0).layers().stream() - .map(HoledLayer::tile) - .toList(); - } - - private static TerrainTiles tilesWith(Map sampled) { - return new TerrainTiles(FLAT, new NeverRuns(), 1, () -> { - }, sampled); - } - - private static TerrainLayer flatLayer(TerrainTile tile) { - return TerrainLayer.of(NoiseTerrain.empty(tile.grid()), FLAT.floorY()); - } - - // Keeps the wanted tiles unsampled, so each test decides exactly what is ready. - private static final class NeverRuns extends AbstractExecutorService { - @Override - public void execute(Runnable command) { - } - - @Override - public void shutdown() { - } - - @Override - public List shutdownNow() { - return List.of(); - } - - @Override - public boolean isShutdown() { - return false; - } - - @Override - public boolean isTerminated() { - return false; - } - - @Override - public boolean awaitTermination(long timeout, TimeUnit unit) { - return true; - } - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/map/TerrainTilesTest.java b/core/src/test/java/art/arcane/iris/studio/map/TerrainTilesTest.java deleted file mode 100644 index 353d21021..000000000 --- a/core/src/test/java/art/arcane/iris/studio/map/TerrainTilesTest.java +++ /dev/null @@ -1,72 +0,0 @@ -package art.arcane.iris.studio.map; - -import art.arcane.iris.generation.stream.ProvisionalSampling; -import org.junit.Test; - -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertTrue; - -public final class TerrainTilesTest { - @Test - public void provisionalTerrainStandsInUntilACompleteRetryReplacesIt() throws Exception { - AtomicBoolean provisional = new AtomicBoolean(true); - AtomicInteger attempts = new AtomicInteger(); - CountDownLatch first = new CountDownLatch(1); - CountDownLatch second = new CountDownLatch(1); - TerrainSampling sampling = new TerrainSampling((grid, row, heights, colors) -> { - if (row == 0) { - attempts.incrementAndGet(); - } - if (provisional.get()) { - ProvisionalSampling.mark(); - } - Arrays.fill(heights, row * grid.columns(), (row + 1) * grid.columns(), provisional.get() ? 10F : 20F); - }, 0, 64, Double.NaN); - ExecutorService workers = Executors.newSingleThreadExecutor(); - TerrainTile tile = new TerrainTile(0, 0, 0); - TerrainTiles tiles = new TerrainTiles(sampling, workers, 1, () -> { - if (attempts.get() == 1) { - first.countDown(); - } else { - second.countDown(); - } - }, Map.of()); - try { - tiles.sampleOnly(List.of(tile), Set.of(tile)); - assertTrue(first.await(3, TimeUnit.SECONDS)); - assertNotNull(tiles.layerOf(tile)); - assertTrue(tiles.isStandingIn(tile)); - assertEquals(10F, tiles.layerOf(tile).terrain().height(0, 0), 0F); - - provisional.set(false); - tiles.sampleOnly(List.of(tile), Set.of(tile)); - assertFalse(second.await(100, TimeUnit.MILLISECONDS)); - assertEquals(1, attempts.get()); - Thread.sleep(500L); - tiles.sampleOnly(List.of(tile), Set.of(tile)); - - assertTrue(second.await(3, TimeUnit.SECONDS)); - assertFalse(tiles.isStandingIn(tile)); - assertEquals(20F, tiles.layerOf(tile).terrain().height(0, 0), 0F); - tiles.sampleOnly(List.of(tile), Set.of(tile)); - assertEquals(2, attempts.get()); - } finally { - tiles.close(); - workers.shutdownNow(); - assertTrue(workers.awaitTermination(3, TimeUnit.SECONDS)); - } - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/map/VisionRenderControllerTest.java b/core/src/test/java/art/arcane/iris/studio/map/VisionRenderControllerTest.java deleted file mode 100644 index 94db0984c..000000000 --- a/core/src/test/java/art/arcane/iris/studio/map/VisionRenderControllerTest.java +++ /dev/null @@ -1,465 +0,0 @@ -package art.arcane.iris.studio.map; - -import art.arcane.iris.studio.map.components.MapLayer; -import art.arcane.iris.studio.map.components.MapTile; -import art.arcane.iris.studio.map.components.MapTileRenderer; -import art.arcane.iris.studio.map.components.TileType; -import org.junit.Test; - -import java.awt.EventQueue; -import java.util.concurrent.CancellationException; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicLong; -import java.util.function.BooleanSupplier; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertSame; -import static org.junit.Assert.assertTrue; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyBoolean; -import static org.mockito.ArgumentMatchers.anyDouble; -import static org.mockito.ArgumentMatchers.anyInt; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class VisionRenderControllerTest { - @Test - public void provisionalTilesRetryWithBackoffAndConvergeWithoutMoving() throws Exception { - MapTileRenderer.TileRender work = mock(MapTileRenderer.TileRender.class); - MapTileRenderer renderer = renderer(work); - MapTile tile = mock(MapTile.class); - AtomicInteger attempts = new AtomicInteger(); - when(work.render(any())) - .thenAnswer(invocation -> { - attempts.incrementAndGet(); - return tile; - }); - when(work.complete()).thenAnswer(invocation -> attempts.get() >= 3); - try (VisionRenderController controller = new VisionRenderController(() -> { })) { - VisionRenderController.Frame frame = controller.request(spec(renderer, 1L)); - await(() -> frame.tiles().getFirst().tile() != null); - controller.retryProvisional(frame); - assertEquals(1, attempts.get()); - await(() -> { - controller.retryProvisional(frame); - return attempts.get() == 2 && controller.progress(frame).activeWorkers() == 0; - }); - controller.retryProvisional(frame); - assertEquals(2, attempts.get()); - assertEquals(0, controller.progress(frame).ready()); - await(() -> { - controller.retryProvisional(frame); - return controller.progress(frame).ready() == 1; - }); - assertEquals(3, attempts.get()); - assertSame(tile, controller.request(spec(renderer, 1L)).tiles().getFirst().tile()); - verify(renderer).prepareTile(anyDouble(), anyDouble(), anyDouble(), anyInt(), any(), anyBoolean()); - } - } - - @Test - public void resizeZoomAndSuspendRetainProvisionalImageWorkAndBackoff() throws Exception { - MapTileRenderer.TileRender work = mock(MapTileRenderer.TileRender.class); - MapTileRenderer renderer = renderer(work); - MapTile incomplete = mock(MapTile.class); - MapTile complete = mock(MapTile.class); - AtomicInteger attempts = new AtomicInteger(); - when(work.render(any())) - .thenAnswer(invocation -> { - if (attempts.incrementAndGet() == 1) { - return incomplete; - } - return complete; - }); - when(work.complete()).thenAnswer(invocation -> attempts.get() >= 2); - try (VisionRenderController controller = new VisionRenderController(() -> { })) { - VisionRenderController.Frame first = controller.request(spec(renderer, 1L)); - await(() -> first.tiles().getFirst().tile() != null && controller.progress(first).activeWorkers() == 0); - assertSame(incomplete, first.tiles().getFirst().tile()); - VisionRenderController.Frame resized = controller.request(new VisionRenderController.RenderSpec(renderer, - MapLayer.of(TileType.RIVER), 1L, 32D, 32D, 1D, 48, 48, false)); - assertSame(incomplete, resized.tiles().getFirst().tile()); - assertTrue(resized.tiles().getFirst().provisional()); - VisionRenderController.Frame zoomed = controller.request(new VisionRenderController.RenderSpec(renderer, - MapLayer.of(TileType.RIVER), 1L, 32D, 32D, 1.15D, 48, 48, false)); - assertSame(incomplete, zoomed.tiles().getFirst().tile()); - controller.suspend(); - VisionRenderController.Frame second = controller.request(spec(renderer, 1L)); - assertSame(incomplete, second.tiles().getFirst().tile()); - assertEquals(0, controller.progress(second).ready()); - assertEquals(1, attempts.get()); - await(() -> { - controller.retryProvisional(second); - return controller.progress(second).ready() == 1; - }); - assertEquals(2, attempts.get()); - verify(renderer).prepareTile(anyDouble(), anyDouble(), anyDouble(), anyInt(), any(), anyBoolean()); - VisionRenderController.Frame third = controller.request(spec(renderer, 1L)); - assertSame(complete, third.tiles().getFirst().tile()); - assertEquals(2, attempts.get()); - } - } - - @Test - public void contentRevisionInvalidatesFinalTiles() throws Exception { - MapTile tile = mock(MapTile.class); - MapTileRenderer.TileRender work = finished(tile); - MapTileRenderer renderer = renderer(work); - AtomicInteger attempts = new AtomicInteger(); - when(work.render(any())) - .thenAnswer(invocation -> { - attempts.incrementAndGet(); - return tile; - }); - try (VisionRenderController controller = new VisionRenderController(() -> { })) { - VisionRenderController.Frame first = controller.request(spec(renderer, 1L)); - await(() -> first.tiles().getFirst().tile() != null); - VisionRenderController.Frame second = controller.request(spec(renderer, 2L)); - await(() -> second.tiles().getFirst().tile() != null); - assertEquals(2, attempts.get()); - } - } - - @Test - public void zoomRetainsCompleteWaterTilesWhileDetailedTilesAreProvisional() throws Exception { - MapTileRenderer renderer = mock(MapTileRenderer.class); - MapTile overview = mock(MapTile.class); - MapTile incomplete = mock(MapTile.class); - MapTileRenderer.TileRender overviewWork = finished(overview); - MapTileRenderer.TileRender detailWork = mock(MapTileRenderer.TileRender.class); - when(detailWork.render(any())).thenReturn(incomplete); - when(renderer.prepareTile(anyDouble(), anyDouble(), anyDouble(), anyInt(), any(), anyBoolean())) - .thenAnswer(invocation -> { - double scale = invocation.getArgument(2); - if (scale < 4D) { - return detailWork; - } - return overviewWork; - }); - try (VisionRenderController controller = new VisionRenderController(() -> { })) { - VisionRenderController.Frame coarse = controller.request(new VisionRenderController.RenderSpec(renderer, - MapLayer.of(TileType.RIVER), 1L, 128D, 128D, 4D, 64, 64, false)); - await(() -> controller.progress(coarse).ready() == 1); - - VisionRenderController.Frame fine = controller.request(spec(renderer, 1L)); - await(() -> fine.tiles().getFirst().tile() != null); - VisionRenderController.VisibleTile visible = fine.tiles().getFirst(); - assertTrue(visible.provisional()); - assertEquals(0, controller.progress(fine).ready()); - VisionRenderController.Fallback retained = controller.fallback(fine, visible); - assertNotNull(retained); - assertSame(overview, retained.pieces().getFirst().tile()); - assertEquals(16, retained.pieces().getFirst().sourceSize()); - - VisionRenderController.Frame returned = controller.request(new VisionRenderController.RenderSpec(renderer, - MapLayer.of(TileType.RIVER), 1L, 128D, 128D, 4D, 64, 64, false)); - assertSame(overview, returned.tiles().getFirst().tile()); - assertFalse(returned.tiles().getFirst().provisional()); - } - } - - @Test - public void closeRejectsLatePublication() throws Exception { - MapTileRenderer.TileRender work = mock(MapTileRenderer.TileRender.class); - MapTileRenderer renderer = renderer(work); - CountDownLatch entered = new CountDownLatch(1); - CountDownLatch release = new CountDownLatch(1); - when(work.render(any())) - .thenAnswer(invocation -> { - entered.countDown(); - while (release.getCount() != 0L) { - try { - release.await(); - } catch (InterruptedException ignored) { - } - } - return mock(MapTile.class); - }); - VisionRenderController controller = new VisionRenderController(() -> { }); - VisionRenderController.Frame frame = controller.request(spec(renderer, 1L)); - try { - assertTrue(entered.await(5L, TimeUnit.SECONDS)); - controller.close(); - controller.close(); - } finally { - release.countDown(); - controller.close(); - } - await(() -> controller.progress(frame).activeWorkers() == 0); - assertNull(frame.tiles().getFirst().tile()); - } - - @Test - public void resizeAndSameLevelZoomReuseFinalTiles() throws Exception { - MapTile tile = mock(MapTile.class); - MapTileRenderer.TileRender work = finished(tile); - MapTileRenderer renderer = renderer(work); - try (VisionRenderController controller = new VisionRenderController(() -> { })) { - VisionRenderController.Frame first = controller.request(new VisionRenderController.RenderSpec(renderer, - MapLayer.of(TileType.RIVER), 1L, 32D, 32D, 1D, 48, 48, false)); - await(() -> controller.progress(first).ready() == 1); - VisionRenderController.Frame resized = controller.request(spec(renderer, 1L)); - assertSame(tile, resized.tiles().getFirst().tile()); - VisionRenderController.Frame zoomed = controller.request(new VisionRenderController.RenderSpec(renderer, - MapLayer.of(TileType.RIVER), 1L, 32D, 32D, 0.9D, 64, 64, false)); - assertSame(tile, zoomed.tiles().getFirst().tile()); - assertEquals(1, controller.progress(zoomed).ready()); - verify(work).render(any()); - verify(renderer).prepareTile(anyDouble(), anyDouble(), anyDouble(), anyInt(), any(), anyBoolean()); - } - } - - @Test - public void contentRevisionInvalidatesProvisionalWork() throws Exception { - MapTile tile = mock(MapTile.class); - MapTileRenderer.TileRender work = mock(MapTileRenderer.TileRender.class); - MapTileRenderer renderer = renderer(work); - when(work.render(any())).thenReturn(tile); - try (VisionRenderController controller = new VisionRenderController(() -> { })) { - VisionRenderController.Frame first = controller.request(spec(renderer, 1L)); - await(() -> first.tiles().getFirst().tile() != null); - VisionRenderController.Frame second = controller.request(spec(renderer, 2L)); - await(() -> second.tiles().getFirst().tile() != null); - verify(renderer, times(2)).prepareTile(anyDouble(), anyDouble(), anyDouble(), anyInt(), any(), anyBoolean()); - } - } - - @Test - public void missingDetailUsesProvisionalOverviewWithoutMarkingItFinal() throws Exception { - MapTileRenderer renderer = mock(MapTileRenderer.class); - MapTile overview = mock(MapTile.class); - MapTileRenderer.TileRender overviewWork = mock(MapTileRenderer.TileRender.class); - when(overviewWork.render(any())).thenReturn(overview); - CountDownLatch entered = new CountDownLatch(1); - MapTileRenderer.TileRender detailWork = cancellable(entered); - when(renderer.prepareTile(anyDouble(), anyDouble(), anyDouble(), anyInt(), any(), anyBoolean())) - .thenAnswer(invocation -> (double) invocation.getArgument(2) < 4D ? detailWork : overviewWork); - try (VisionRenderController controller = new VisionRenderController(() -> { })) { - VisionRenderController.Frame coarse = controller.request(new VisionRenderController.RenderSpec(renderer, - MapLayer.of(TileType.RIVER), 1L, 128D, 128D, 4D, 64, 64, false)); - await(() -> coarse.tiles().getFirst().tile() != null); - VisionRenderController.Frame fine = controller.request(spec(renderer, 1L)); - assertTrue(entered.await(5L, TimeUnit.SECONDS)); - assertNull(fine.tiles().getFirst().tile()); - VisionRenderController.Fallback fallback = controller.fallback(fine, fine.tiles().getFirst()); - assertNotNull(fallback); - assertSame(overview, fallback.pieces().getFirst().tile()); - assertEquals(0, controller.progress(fine).ready()); - } - } - - @Test - public void zoomingOutKeepsCompleteFinerTilesOverProvisionalExactTile() throws Exception { - MapTileRenderer renderer = mock(MapTileRenderer.class); - MapTile fineTile = mock(MapTile.class); - MapTile coarseTile = mock(MapTile.class); - MapTileRenderer.TileRender fineWork = finished(fineTile); - MapTileRenderer.TileRender coarseWork = mock(MapTileRenderer.TileRender.class); - when(coarseWork.render(any())).thenReturn(coarseTile); - when(renderer.prepareTile(anyDouble(), anyDouble(), anyDouble(), anyInt(), any(), anyBoolean())) - .thenAnswer(invocation -> (double) invocation.getArgument(2) < 2D ? fineWork : coarseWork); - try (VisionRenderController controller = new VisionRenderController(() -> { })) { - VisionRenderController.Frame fine = controller.request(spec(renderer, 1L)); - await(() -> controller.progress(fine).ready() == 1); - VisionRenderController.Frame coarse = controller.request(new VisionRenderController.RenderSpec(renderer, - MapLayer.of(TileType.RIVER), 1L, 64D, 64D, 2D, 64, 64, false)); - await(() -> coarse.tiles().getFirst().tile() != null); - VisionRenderController.Fallback fallback = controller.fallback(coarse, coarse.tiles().getFirst()); - assertNotNull(fallback); - assertSame(fineTile, fallback.pieces().getFirst().tile()); - assertEquals(0.5D, fallback.pieces().getFirst().size(), 0D); - } - } - - @Test - public void suspendedViewCancelsSamplingAndProbeButKeepsCompletedTiles() throws Exception { - MapTile tile = mock(MapTile.class); - MapTileRenderer renderer = mock(MapTileRenderer.class); - CountDownLatch sampling = new CountDownLatch(1); - MapTileRenderer.TileRender pending = cancellable(sampling); - MapTileRenderer.TileRender complete = finished(tile); - when(renderer.prepareTile(anyDouble(), anyDouble(), anyDouble(), anyInt(), any(), anyBoolean())) - .thenReturn(complete, pending); - CountDownLatch probing = new CountDownLatch(1); - CountDownLatch interrupted = new CountDownLatch(1); - AtomicInteger published = new AtomicInteger(); - try (VisionRenderController controller = new VisionRenderController(() -> { })) { - VisionRenderController.Frame first = controller.request(spec(renderer, 1L)); - await(() -> controller.progress(first).ready() == 1); - VisionRenderController.Frame next = controller.request(new VisionRenderController.RenderSpec(renderer, - MapLayer.of(TileType.RIVER), 1L, 96D, 32D, 1D, 64, 64, false)); - assertTrue(sampling.await(5L, TimeUnit.SECONDS)); - controller.submitProbe(next, () -> { - probing.countDown(); - try { - new CountDownLatch(1).await(); - return "late"; - } catch (InterruptedException error) { - interrupted.countDown(); - throw error; - } - }, value -> published.incrementAndGet()); - assertTrue(probing.await(5L, TimeUnit.SECONDS)); - controller.suspend(); - assertTrue(interrupted.await(5L, TimeUnit.SECONDS)); - await(() -> controller.progress(next).activeWorkers() == 0); - EventQueue.invokeAndWait(() -> { }); - assertEquals(0, published.get()); - assertNull(next.tiles().getFirst().tile()); - VisionRenderController.Frame resumed = controller.request(spec(renderer, 1L)); - assertSame(tile, resumed.tiles().getFirst().tile()); - verify(renderer, times(2)).prepareTile(anyDouble(), anyDouble(), anyDouble(), anyInt(), any(), anyBoolean()); - } - } - - @Test - public void retainedWorkCountsAgainstCacheBudgetAndIsReleasedWhenComplete() throws Exception { - MapTile tile = mock(MapTile.class); - when(tile.bytes()).thenReturn(1L); - MapTileRenderer.TileRender work = mock(MapTileRenderer.TileRender.class); - MapTileRenderer renderer = renderer(work); - AtomicInteger attempts = new AtomicInteger(); - when(work.render(any())).thenAnswer(invocation -> { - attempts.incrementAndGet(); - return tile; - }); - when(work.complete()).thenAnswer(invocation -> attempts.get() >= 2); - when(work.bytes()).thenReturn(256L * 1024L * 1024L); - try (VisionRenderController controller = new VisionRenderController(() -> { })) { - VisionRenderController.Frame first = controller.request(spec(renderer, 1L)); - await(() -> first.tiles().getFirst().tile() != null); - VisionRenderController.Frame second = controller.request(spec(renderer, 1L)); - await(() -> controller.progress(second).ready() == 1); - VisionRenderController.Frame third = controller.request(spec(renderer, 1L)); - assertSame(tile, third.tiles().getFirst().tile()); - verify(renderer, times(2)).prepareTile(anyDouble(), anyDouble(), anyDouble(), anyInt(), any(), anyBoolean()); - assertEquals(2, attempts.get()); - } - } - - @Test - public void cancelledRetryReleasesWorkAndKeepsPublishedImage() throws Exception { - MapTile incomplete = mock(MapTile.class); - MapTile complete = mock(MapTile.class); - CountDownLatch entered = new CountDownLatch(1); - MapTileRenderer.TileRender partial = mock(MapTileRenderer.TileRender.class); - MapTileRenderer.TileRender replacement = finished(complete); - AtomicInteger attempts = new AtomicInteger(); - when(partial.render(any())).thenAnswer(invocation -> { - if (attempts.incrementAndGet() == 1) { - return incomplete; - } - BooleanSupplier cancelled = invocation.getArgument(0); - entered.countDown(); - await(cancelled); - throw new CancellationException(); - }); - MapTileRenderer renderer = mock(MapTileRenderer.class); - when(renderer.prepareTile(anyDouble(), anyDouble(), anyDouble(), anyInt(), any(), anyBoolean())) - .thenReturn(partial, replacement); - try (VisionRenderController controller = new VisionRenderController(() -> { })) { - VisionRenderController.Frame first = controller.request(spec(renderer, 1L)); - await(() -> first.tiles().getFirst().tile() != null); - await(() -> { - controller.retryProvisional(first); - return entered.getCount() == 0L; - }); - controller.suspend(); - await(() -> controller.progress(first).activeWorkers() == 0); - assertSame(incomplete, first.tiles().getFirst().tile()); - VisionRenderController.Frame resumed = controller.request(spec(renderer, 1L)); - await(() -> controller.progress(resumed).ready() == 1); - assertSame(complete, resumed.tiles().getFirst().tile()); - verify(renderer, times(2)).prepareTile(anyDouble(), anyDouble(), anyDouble(), anyInt(), any(), anyBoolean()); - } - } - - @Test - public void previewReadinessWakesBackoffAtBoundedCadenceIncludingCompletionDuringRender() throws Exception { - MapTile tile = mock(MapTile.class); - MapTileRenderer.TileRender work = mock(MapTileRenderer.TileRender.class); - MapTileRenderer renderer = renderer(work); - AtomicLong time = new AtomicLong(); - AtomicLong readiness = new AtomicLong(); - AtomicInteger attempts = new AtomicInteger(); - when(renderer.previewRevision()).thenAnswer(invocation -> readiness.get()); - when(work.render(any())).thenAnswer(invocation -> { - if (attempts.incrementAndGet() == 3) { - readiness.incrementAndGet(); - } - return tile; - }); - when(work.complete()).thenAnswer(invocation -> attempts.get() >= 4); - try (VisionRenderController controller = new VisionRenderController(() -> { }, time::get)) { - VisionRenderController.Frame frame = controller.request(spec(renderer, 1L)); - await(() -> attempts.get() == 1 && controller.progress(frame).activeWorkers() == 0); - time.set(VisionRenderController.FIRST_RETRY_NANOS); - controller.retryProvisional(frame); - await(() -> attempts.get() == 2 && controller.progress(frame).activeWorkers() == 0); - time.addAndGet(VisionRenderController.FIRST_RETRY_NANOS); - controller.retryProvisional(frame); - assertEquals(2, attempts.get()); - readiness.incrementAndGet(); - controller.retryProvisional(frame); - await(() -> attempts.get() == 3 && controller.progress(frame).activeWorkers() == 0); - time.addAndGet(VisionRenderController.FIRST_RETRY_NANOS - 1L); - controller.retryProvisional(frame); - assertEquals(3, attempts.get()); - time.incrementAndGet(); - controller.retryProvisional(frame); - await(() -> controller.progress(frame).ready() == 1); - assertEquals(4, attempts.get()); - verify(renderer).prepareTile(anyDouble(), anyDouble(), anyDouble(), anyInt(), any(), anyBoolean()); - } - } - - private static MapTileRenderer.TileRender cancellable(CountDownLatch entered) { - MapTileRenderer.TileRender work = mock(MapTileRenderer.TileRender.class); - when(work.render(any())).thenAnswer(invocation -> { - BooleanSupplier cancelled = invocation.getArgument(0); - entered.countDown(); - while (!cancelled.getAsBoolean() && !Thread.currentThread().isInterrupted()) { - try { - Thread.sleep(1L); - } catch (InterruptedException error) { - Thread.currentThread().interrupt(); - } - } - throw new CancellationException(); - }); - return work; - } - - private static MapTileRenderer renderer(MapTileRenderer.TileRender work) { - MapTileRenderer renderer = mock(MapTileRenderer.class); - when(renderer.prepareTile(anyDouble(), anyDouble(), anyDouble(), anyInt(), any(), anyBoolean())).thenReturn(work); - return renderer; - } - - private static MapTileRenderer.TileRender finished(MapTile tile) { - MapTileRenderer.TileRender work = mock(MapTileRenderer.TileRender.class); - when(work.render(any())).thenReturn(tile); - when(work.complete()).thenReturn(true); - return work; - } - - private static VisionRenderController.RenderSpec spec(MapTileRenderer renderer, long revision) { - return new VisionRenderController.RenderSpec(renderer, MapLayer.of(TileType.RIVER), revision, - 32D, 32D, 1D, 64, 64, false); - } - - private static void await(BooleanSupplier condition) throws Exception { - long deadline = System.nanoTime() + TimeUnit.SECONDS.toNanos(5L); - while (!condition.getAsBoolean() && System.nanoTime() < deadline) { - Thread.sleep(5L); - } - assertTrue("render did not converge", condition.getAsBoolean()); - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/map/VisionViewportTest.java b/core/src/test/java/art/arcane/iris/studio/map/VisionViewportTest.java deleted file mode 100644 index 117d6dbb6..000000000 --- a/core/src/test/java/art/arcane/iris/studio/map/VisionViewportTest.java +++ /dev/null @@ -1,33 +0,0 @@ -package art.arcane.iris.studio.map; - -import org.junit.Test; - -import static org.junit.Assert.assertEquals; - -public final class VisionViewportTest { - @Test - public void granularZoomKeepsTheCursorWorldCoordinateFixed() { - VisionViewport viewport = new VisionViewport(-21_672D, -10_148D, 256D); - double cursorWorldX = viewport.worldX(1_194D, 1_440); - double cursorWorldZ = viewport.worldZ(283D, 792); - - VisionViewport zoomed = viewport.zoomAt(1_194D, 283D, 1_440, 792, Math.pow(2D, -0.08D), 1D, 4_096D); - - assertEquals(cursorWorldX, zoomed.worldX(1_194D, 1_440), 0.000000001D); - assertEquals(cursorWorldZ, zoomed.worldZ(283D, 792), 0.000000001D); - assertEquals(242.19075756175255D, zoomed.blocksPerPixel(), 0.000000001D); - } - - @Test - public void zoomClampingStillKeepsTheCursorAnchored() { - VisionViewport viewport = new VisionViewport(800D, -400D, 2D); - double cursorWorldX = viewport.worldX(925D, 1_200); - double cursorWorldZ = viewport.worldZ(127D, 700); - - VisionViewport zoomed = viewport.zoomAt(925D, 127D, 1_200, 700, 0.001D, 1D, 4_096D); - - assertEquals(1D, zoomed.blocksPerPixel(), 0D); - assertEquals(cursorWorldX, zoomed.worldX(925D, 1_200), 0.000000001D); - assertEquals(cursorWorldZ, zoomed.worldZ(127D, 700), 0.000000001D); - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/map/WorldExplorerTest.java b/core/src/test/java/art/arcane/iris/studio/map/WorldExplorerTest.java deleted file mode 100644 index ec8e36acf..000000000 --- a/core/src/test/java/art/arcane/iris/studio/map/WorldExplorerTest.java +++ /dev/null @@ -1,111 +0,0 @@ -package art.arcane.iris.studio.map; - -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.generation.runtime.IrisComplex; -import art.arcane.iris.generation.stream.ProvisionalSampling; -import art.arcane.volmlib.util.stream.ProceduralStream; -import org.junit.Test; - -import javax.swing.SwingUtilities; -import java.lang.reflect.Field; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; - -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -public final class WorldExplorerTest { - @Test - public void closedExplorerIgnoresShowAndRefresh() throws Exception { - Engine engine = mock(Engine.class); - SwingUtilities.invokeAndWait(() -> { - WorldExplorer explorer = new WorldExplorer(() -> engine); - explorer.close(); - explorer.close(); - explorer.show(0D, 0D, true); - explorer.refresh(0D, 0D); - }); - } - - @Test - public void hiddenHotloadDiscardsPendingWorldMeasurement() throws Exception { - CountDownLatch started = new CountDownLatch(1); - CountDownLatch release = new CountDownLatch(1); - Engine engine = engineWithHeights(ProceduralStream.ofDouble((x, z) -> { - started.countDown(); - try { - assertTrue(release.await(3, TimeUnit.SECONDS)); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); - } - return 64D; - })); - AtomicReference opened = new AtomicReference<>(); - try { - SwingUtilities.invokeAndWait(() -> { - WorldExplorer explorer = new WorldExplorer(() -> engine); - opened.set(explorer); - explorer.show(0D, 0D, true); - }); - assertTrue(started.await(3, TimeUnit.SECONDS)); - SwingUtilities.invokeAndWait(() -> { - opened.get().hide(); - opened.get().refresh(0D, 0D); - }); - release.countDown(); - ((ExecutorService) field(opened.get(), "lookups")).submit(() -> { }).get(3, TimeUnit.SECONDS); - SwingUtilities.invokeAndWait(() -> { }); - assertNull(field(opened.get(), "sampledEngine")); - } finally { - release.countDown(); - SwingUtilities.invokeAndWait(() -> opened.get().close()); - } - } - - @Test - public void provisionalWorldBoundsAreMeasuredAgainWithoutInteraction() throws Exception { - AtomicInteger samples = new AtomicInteger(); - CountDownLatch retried = new CountDownLatch(1); - Engine engine = engineWithHeights(ProceduralStream.ofDouble((x, z) -> { - int sample = samples.incrementAndGet(); - if (sample <= 81) { - ProvisionalSampling.mark(); - } else { - retried.countDown(); - } - return 64D; - })); - AtomicReference opened = new AtomicReference<>(); - try { - SwingUtilities.invokeAndWait(() -> { - WorldExplorer explorer = new WorldExplorer(() -> engine); - opened.set(explorer); - explorer.show(0D, 0D, true); - }); - assertTrue(retried.await(3, TimeUnit.SECONDS)); - } finally { - SwingUtilities.invokeAndWait(() -> opened.get().close()); - } - } - - private static Engine engineWithHeights(ProceduralStream heights) { - Engine engine = mock(Engine.class); - IrisComplex complex = mock(IrisComplex.class); - when(engine.getComplex()).thenReturn(complex); - when(engine.getHeight()).thenReturn(256); - when(complex.getHeightStream()).thenReturn(heights); - when(complex.getFluidHeight()).thenReturn(64D); - return engine; - } - - private static Object field(Object owner, String name) throws Exception { - Field field = owner.getClass().getDeclaredField(name); - field.setAccessible(true); - return field.get(owner); - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/view/DesktopGuiLaunchTest.java b/core/src/test/java/art/arcane/iris/studio/view/DesktopGuiLaunchTest.java deleted file mode 100644 index f876d9b91..000000000 --- a/core/src/test/java/art/arcane/iris/studio/view/DesktopGuiLaunchTest.java +++ /dev/null @@ -1,90 +0,0 @@ -package art.arcane.iris.studio.view; - -import art.arcane.iris.configuration.IrisSettings; -import art.arcane.iris.studio.map.MapWindow; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.awt.AWTEvent; -import java.awt.EventQueue; -import java.awt.Toolkit; -import java.util.concurrent.atomic.AtomicReference; - -import static org.junit.Assert.assertNull; - -public class DesktopGuiLaunchTest { - private IrisSettings previousSettings; - private boolean previousSuppressed; - private RecordingEventQueue events; - - @Before - public void suppressDesktop() throws Exception { - previousSettings = IrisSettings.settings; - IrisSettings.settings = new IrisSettings(); - previousSuppressed = GuiHost.isDesktopSuppressed(); - GuiHost.suppressDesktop(true); - events = new RecordingEventQueue(); - Toolkit.getDefaultToolkit().getSystemEventQueue().push(events); - EventQueue.invokeAndWait(() -> { - }); - } - - @After - public void restoreDesktop() throws Exception { - EventQueue.invokeAndWait(events::remove); - GuiHost.suppressDesktop(previousSuppressed); - IrisSettings.settings = previousSettings; - } - - @Test - public void mapLaunchDoesNotCreateAWindowWithoutDesktop() throws Exception { - MapWindow.openMap(null); - - assertNoDesktopFailure(); - } - - @Test - public void noiseLaunchDoesNotCreateAWindowWithoutDesktop() throws Exception { - MapWindow.openNoise(null); - - assertNoDesktopFailure(); - } - - @Test - public void generatorLaunchDoesNotCreateAWindowWithoutDesktop() throws Exception { - MapWindow.openNoise(null, new MapWindow.NoiseSelection("test", null, 12345L)); - - assertNoDesktopFailure(); - } - - @Test - public void imageMapLaunchDoesNotReadEngineWithoutDesktop() throws Exception { - MapWindow.openImageMaps(null); - - assertNoDesktopFailure(); - } - - private void assertNoDesktopFailure() throws Exception { - EventQueue.invokeAndWait(() -> { - }); - assertNull("Desktop launch raised an exception on the AWT event thread", events.failure.get()); - } - - private static final class RecordingEventQueue extends EventQueue { - private final AtomicReference failure = new AtomicReference<>(); - - @Override - protected void dispatchEvent(AWTEvent event) { - try { - super.dispatchEvent(event); - } catch (Throwable error) { - failure.compareAndSet(null, error); - } - } - - private void remove() { - pop(); - } - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/view/GuiHostServerGuiLaunchTest.java b/core/src/test/java/art/arcane/iris/studio/view/GuiHostServerGuiLaunchTest.java deleted file mode 100644 index 4c186c335..000000000 --- a/core/src/test/java/art/arcane/iris/studio/view/GuiHostServerGuiLaunchTest.java +++ /dev/null @@ -1,63 +0,0 @@ -package art.arcane.iris.studio.view; - -import art.arcane.iris.configuration.IrisSettings; -import org.junit.After; -import org.junit.Before; -import org.junit.Test; - -import java.awt.GraphicsEnvironment; - -import static org.junit.Assert.assertEquals; - -public class GuiHostServerGuiLaunchTest { - private IrisSettings previousSettings; - private boolean previousSuppressed; - - @Before - public void before() { - previousSettings = IrisSettings.settings; - previousSuppressed = GuiHost.isDesktopSuppressed(); - IrisSettings.settings = new IrisSettings(); - } - - @After - public void after() { - GuiHost.suppressDesktop(previousSuppressed); - IrisSettings.settings = previousSettings; - } - - @Test - public void serverGuiLaunchIsDisabledWhenNotRequested() { - GuiHost.suppressDesktop(false); - IrisSettings.settings.getGui().setUseServerLaunchedGuis(true); - - assertEquals(GuiHost.ServerGuiLaunch.DISABLED, GuiHost.serverGuiLaunch(false)); - } - - @Test - public void serverGuiLaunchIsDisabledWhenSettingIsOff() { - GuiHost.suppressDesktop(false); - IrisSettings.settings.getGui().setUseServerLaunchedGuis(false); - - assertEquals(GuiHost.ServerGuiLaunch.DISABLED, GuiHost.serverGuiLaunch(true)); - } - - @Test - public void serverGuiLaunchIsUnavailableWhenDesktopIsSuppressed() { - GuiHost.suppressDesktop(true); - IrisSettings.settings.getGui().setUseServerLaunchedGuis(true); - - assertEquals(GuiHost.ServerGuiLaunch.UNAVAILABLE, GuiHost.serverGuiLaunch(true)); - } - - @Test - public void serverGuiLaunchOpensOnlyWithADisplayEnvironment() { - GuiHost.suppressDesktop(false); - IrisSettings.settings.getGui().setUseServerLaunchedGuis(true); - - GuiHost.ServerGuiLaunch expected = GraphicsEnvironment.isHeadless() - ? GuiHost.ServerGuiLaunch.UNAVAILABLE - : GuiHost.ServerGuiLaunch.OPEN; - assertEquals(expected, GuiHost.serverGuiLaunch(true)); - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/view/GuiHostTest.java b/core/src/test/java/art/arcane/iris/studio/view/GuiHostTest.java deleted file mode 100644 index 338c4e28f..000000000 --- a/core/src/test/java/art/arcane/iris/studio/view/GuiHostTest.java +++ /dev/null @@ -1,71 +0,0 @@ -package art.arcane.iris.studio.view; - -import org.junit.Assume; -import org.junit.Test; -import org.mockito.ArgumentCaptor; - -import javax.swing.JFrame; -import javax.swing.SwingUtilities; -import java.awt.GraphicsEnvironment; -import java.awt.desktop.QuitResponse; -import java.awt.event.WindowEvent; -import java.awt.event.WindowListener; -import java.util.concurrent.atomic.AtomicInteger; -import java.util.concurrent.atomic.AtomicReference; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.atLeastOnce; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; - -public class GuiHostTest { - @Test - public void desktopQuitDisposesManagedWindowsWithoutStoppingServer() throws Exception { - JFrame frame = mock(JFrame.class); - ArgumentCaptor listenerCaptor = ArgumentCaptor.forClass(WindowListener.class); - GuiHost.prepareFrame(frame); - AtomicInteger cancelled = new AtomicInteger(); - AtomicInteger performed = new AtomicInteger(); - QuitResponse response = new QuitResponse() { - @Override - public void performQuit() { - performed.incrementAndGet(); - } - - @Override - public void cancelQuit() { - cancelled.incrementAndGet(); - } - }; - - GuiHost.closeDesktopWindowsAndCancelQuit(response); - SwingUtilities.invokeAndWait(() -> { - }); - - assertEquals(1, cancelled.get()); - assertEquals(0, performed.get()); - verify(frame).dispose(); - verify(frame, atLeastOnce()).addWindowListener(listenerCaptor.capture()); - listenerCaptor.getValue().windowClosed(mock(WindowEvent.class)); - } - - @Test - public void preparedFramesDisposeWhenClosed() throws Exception { - Assume.assumeFalse(GraphicsEnvironment.isHeadless()); - AtomicReference frameReference = new AtomicReference<>(); - SwingUtilities.invokeAndWait(() -> { - JFrame frame = new JFrame("Iris lifecycle test"); - GuiHost.prepareFrame(frame); - frame.setVisible(true); - frameReference.set(frame); - }); - - JFrame frame = frameReference.get(); - assertEquals(JFrame.DISPOSE_ON_CLOSE, frame.getDefaultCloseOperation()); - assertTrue(frame.isDisplayable()); - SwingUtilities.invokeAndWait(() -> frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING))); - assertFalse(frame.isDisplayable()); - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/view/PregenMapPanelTest.java b/core/src/test/java/art/arcane/iris/studio/view/PregenMapPanelTest.java deleted file mode 100644 index 97fa9eea3..000000000 --- a/core/src/test/java/art/arcane/iris/studio/view/PregenMapPanelTest.java +++ /dev/null @@ -1,241 +0,0 @@ -package art.arcane.iris.studio.view; - -import art.arcane.iris.world.pregen.PregenTask; -import art.arcane.volmlib.util.math.Position2; -import org.junit.Test; - -import javax.swing.SwingUtilities; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.Rectangle; -import java.awt.event.MouseEvent; -import java.awt.event.MouseWheelEvent; -import java.awt.image.BufferedImage; -import java.lang.reflect.Field; - -import static org.junit.Assert.assertArrayEquals; -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -public class PregenMapPanelTest { - @Test - public void singleChunkAndInclusiveFinalEdgesReceivePixels() throws Exception { - PregenMapPanel single = panel(new PregenRenderSnapshot.Bounds(5, -9, 5, -9)); - single.submit(5, -9, Color.GREEN); - flush(single); - assertEquals(Color.GREEN.getRGB(), image(single).getRGB(0, 0)); - - PregenMapPanel rectangle = panel(new PregenRenderSnapshot.Bounds(-2, -3, 1, -1)); - rectangle.submit(1, -1, Color.RED); - rectangle.submit(-2, -3, Color.BLUE); - flush(rectangle); - assertEquals(Color.RED.getRGB(), image(rectangle).getRGB(3, 2)); - assertEquals(Color.BLUE.getRGB(), image(rectangle).getRGB(0, 0)); - } - - @Test - public void largeMapsStayBoundedAndEverySubmittedChunkCanReachAPixel() throws Exception { - PregenMapPanel panel = panel(new PregenRenderSnapshot.Bounds(Integer.MIN_VALUE, -10, Integer.MAX_VALUE, 10)); - panel.submit(Integer.MAX_VALUE, 10, Color.GREEN); - panel.submit(0, 0, Color.RED); - flush(panel); - - assertEquals(1024, image(panel).getWidth()); - assertEquals(21, image(panel).getHeight()); - assertEquals(Color.GREEN.getRGB(), image(panel).getRGB(1023, 20)); - assertEquals(Color.RED.getRGB(), image(panel).getRGB(512, 10)); - } - - @Test - public void duplicateAndOutOfBoundsSubmissionsDoNotRequestAnotherFrame() throws Exception { - PregenMapPanel panel = panel(new PregenRenderSnapshot.Bounds(0, 0, 1, 1)); - panel.submit(2, 0, Color.GREEN); - SwingUtilities.invokeAndWait(() -> assertFalse(panel.flush())); - panel.submit(0, 0, Color.GREEN); - SwingUtilities.invokeAndWait(() -> assertTrue(panel.flush())); - panel.submit(0, 0, Color.GREEN); - SwingUtilities.invokeAndWait(() -> assertFalse(panel.flush())); - SwingUtilities.invokeAndWait(panel::disposeMap); - panel.submit(0, 0, Color.RED); - SwingUtilities.invokeAndWait(() -> assertFalse(panel.flush())); - } - - @Test - public void pixelUpdatesRetainTheirLatestValueUntilTheViewFlushes() throws Exception { - PregenMapPanel panel = panel(new PregenRenderSnapshot.Bounds(0, 0, 10_000, 0)); - for (int index = 0; index < 100_000; index++) { - panel.submit(index % 10_001, 0, Color.RED); - } - panel.submit(10_000, 0, Color.GREEN); - flush(panel); - assertEquals(Color.GREEN.getRGB(), image(panel).getRGB(1023, 0)); - assertEquals(1024, image(panel).getWidth()); - } - - @Test - public void mapFitPreservesRectangularChunkAspect() { - Rectangle wide = PregenMapPanel.fit(new PregenRenderSnapshot.Bounds(0, 0, 3, 1), 802, 602); - assertEquals(new Rectangle(1, 101, 800, 400), wide); - Rectangle tall = PregenMapPanel.fit(new PregenRenderSnapshot.Bounds(0, 0, 1, 3), 802, 602); - assertEquals(new Rectangle(251, 1, 300, 600), tall); - } - - @Test - public void hoverCoordinatesFollowPaintedRectangularBoundsAndLetterboxing() throws Exception { - PregenMapPanel wide = panel(new PregenRenderSnapshot.Bounds(-2, -3, 1, -2)); - SwingUtilities.invokeAndWait(() -> wide.setSize(802, 602)); - assertEquals("Chunk X -2 · Z -3", tooltip(wide, 1, 101)); - assertEquals("Chunk X -2 · Z -3", tooltip(wide, 200, 300)); - assertEquals("Chunk X -1 · Z -2", tooltip(wide, 201, 301)); - assertEquals("Chunk X 1 · Z -2", tooltip(wide, 800, 500)); - assertNull(tooltip(wide, 0, 300)); - assertNull(tooltip(wide, 801, 300)); - assertNull(tooltip(wide, 400, 100)); - assertNull(tooltip(wide, 400, 501)); - SwingUtilities.invokeAndWait(wide::disposeMap); - assertNull(tooltip(wide, 400, 300)); - - PregenMapPanel tall = panel(new PregenRenderSnapshot.Bounds(-7, -2, -6, 1)); - SwingUtilities.invokeAndWait(() -> tall.setSize(802, 602)); - assertEquals("Chunk X -7 · Z -2", tooltip(tall, 251, 1)); - assertEquals("Chunk X -6 · Z 1", tooltip(tall, 550, 600)); - assertNull(tooltip(tall, 250, 300)); - assertNull(tooltip(tall, 551, 300)); - SwingUtilities.invokeAndWait(tall::disposeMap); - } - - @Test - public void hoverCoordinatesPreserveSingleChunkAndExtremeIntegerBoundsAfterResize() throws Exception { - PregenMapPanel single = panel(new PregenRenderSnapshot.Bounds(5, -9, 5, -9)); - SwingUtilities.invokeAndWait(() -> single.setSize(64, 64)); - assertEquals("Chunk X 5 · Z -9", tooltip(single, 1, 1)); - assertEquals("Chunk X 5 · Z -9", tooltip(single, 62, 62)); - SwingUtilities.invokeAndWait(() -> single.setSize(128, 64)); - assertNull(tooltip(single, 1, 1)); - assertEquals("Chunk X 5 · Z -9", tooltip(single, 33, 1)); - SwingUtilities.invokeAndWait(single::disposeMap); - - PregenMapPanel extreme = panel(new PregenRenderSnapshot.Bounds( - Integer.MIN_VALUE, -10, Integer.MAX_VALUE, 10)); - SwingUtilities.invokeAndWait(() -> extreme.setSize(1026, 3)); - assertEquals("Chunk X -2147483648 · Z -10", tooltip(extreme, 1, 1)); - assertEquals("Chunk X 0 · Z -10", tooltip(extreme, 513, 1)); - assertEquals("Chunk X 2143289344 · Z -10", tooltip(extreme, 1024, 1)); - assertNull(tooltip(extreme, 1025, 1)); - SwingUtilities.invokeAndWait(extreme::disposeMap); - } - - @Test - public void wheelZoomPreservesTheChunkUnderThePointerAndRetainedPixels() throws Exception { - PregenMapPanel panel = panel(new PregenRenderSnapshot.Bounds(-32, -32, 31, 31)); - SwingUtilities.invokeAndWait(() -> panel.setSize(802, 602)); - panel.submit(-7, -19, Color.GREEN); - flush(panel); - BufferedImage retained = image(panel); - String before = tooltip(panel, 337, 123); - SwingUtilities.invokeAndWait(() -> panel.dispatchEvent(new MouseWheelEvent(panel, - MouseEvent.MOUSE_WHEEL, 1L, 0, 337, 123, 0, false, - MouseWheelEvent.WHEEL_UNIT_SCROLL, 3, -4))); - assertEquals(before, tooltip(panel, 337, 123)); - assertTrue(panel.zoom() > 1D); - assertTrue(retained == image(panel)); - assertEquals(Color.GREEN.getRGB(), image(panel).getRGB(25, 13)); - SwingUtilities.invokeAndWait(panel::disposeMap); - } - - @Test - public void draggingPansTheMapAndResetFitsBesideTheSidebar() throws Exception { - PregenMapPanel panel = panel(new PregenRenderSnapshot.Bounds(-32, -32, 31, 31)); - SwingUtilities.invokeAndWait(() -> { - panel.setSize(1000, 600); - panel.setCoveredLeftWidth(300); - }); - String initial = tooltip(panel, 650, 300); - assertNull(tooltip(panel, 250, 300)); - SwingUtilities.invokeAndWait(() -> { - panel.dispatchEvent(new MouseEvent(panel, MouseEvent.MOUSE_PRESSED, 1L, - MouseEvent.BUTTON1_DOWN_MASK, 650, 300, 1, false, MouseEvent.BUTTON1)); - panel.dispatchEvent(new MouseEvent(panel, MouseEvent.MOUSE_DRAGGED, 2L, - MouseEvent.BUTTON1_DOWN_MASK, 710, 350, 0, false, MouseEvent.NOBUTTON)); - panel.dispatchEvent(new MouseEvent(panel, MouseEvent.MOUSE_RELEASED, 3L, - 0, 710, 350, 1, false, MouseEvent.BUTTON1)); - }); - assertEquals(initial, tooltip(panel, 710, 350)); - assertFalse(initial.equals(tooltip(panel, 650, 300))); - SwingUtilities.invokeAndWait(() -> { - panel.zoomIn(); - panel.resetView(); - }); - assertEquals(1D, panel.zoom(), 0D); - assertEquals(initial, tooltip(panel, 650, 300)); - SwingUtilities.invokeAndWait(panel::disposeMap); - } - - @Test - public void zoomBoundsAndGridPaintingHandleExtremeMapCoordinates() throws Exception { - PregenMapPanel panel = panel(new PregenRenderSnapshot.Bounds( - Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE)); - SwingUtilities.invokeAndWait(() -> { - panel.setSize(820, 520); - panel.toggleGrid(); - for (int index = 0; index < 100; index++) { - panel.zoomIn(); - } - assertEquals(128D, panel.zoom(), 0D); - BufferedImage target = new BufferedImage(820, 520, BufferedImage.TYPE_INT_RGB); - Graphics2D canvas = target.createGraphics(); - try { - panel.paint(canvas); - panel.panBy(1_000_000, -1_000_000); - panel.paint(canvas); - for (int index = 0; index < 100; index++) { - panel.zoomOut(); - } - assertEquals(0.25D, panel.zoom(), 0D); - panel.resetView(); - panel.paint(canvas); - } finally { - canvas.dispose(); - panel.disposeMap(); - } - }); - } - - private static String tooltip(PregenMapPanel panel, int x, int y) throws Exception { - String[] result = new String[1]; - SwingUtilities.invokeAndWait(() -> result[0] = panel.getToolTipText( - new MouseEvent(panel, MouseEvent.MOUSE_MOVED, 0L, 0, x, y, 0, false))); - return result[0]; - } - - @Test - public void arithmeticTaskBoundsMatchActualRectangularTraversal() { - PregenTask task = PregenTask.builder().center(new Position2(-17, 35)).radiusX(9).radiusZ(37).build(); - int[] actual = {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE}; - task.iterateAllChunks((x, z) -> { - actual[0] = Math.min(actual[0], x); - actual[1] = Math.min(actual[1], z); - actual[2] = Math.max(actual[2], x); - actual[3] = Math.max(actual[3], z); - }); - assertArrayEquals(actual, task.chunkBounds()); - } - - private static PregenMapPanel panel(PregenRenderSnapshot.Bounds bounds) throws Exception { - PregenMapPanel[] result = new PregenMapPanel[1]; - SwingUtilities.invokeAndWait(() -> result[0] = new PregenMapPanel(new PregenMapState(bounds))); - return result[0]; - } - - private static void flush(PregenMapPanel panel) throws Exception { - SwingUtilities.invokeAndWait(panel::flush); - } - - private static BufferedImage image(PregenMapPanel panel) throws Exception { - Field field = PregenMapPanel.class.getDeclaredField("image"); - field.setAccessible(true); - return (BufferedImage) field.get(panel); - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/view/PregenMapRetentionTest.java b/core/src/test/java/art/arcane/iris/studio/view/PregenMapRetentionTest.java deleted file mode 100644 index 89fe9b5e4..000000000 --- a/core/src/test/java/art/arcane/iris/studio/view/PregenMapRetentionTest.java +++ /dev/null @@ -1,164 +0,0 @@ -package art.arcane.iris.studio.view; - -import art.arcane.iris.generation.runtime.Engine; -import art.arcane.iris.spi.IrisServices; -import art.arcane.iris.world.pregen.CachedPregenMethod; -import art.arcane.iris.world.pregen.PregenCache; -import art.arcane.iris.world.pregen.PregenSavedChunkStatus; -import art.arcane.iris.world.pregen.PregenTask; -import art.arcane.iris.world.pregen.PregeneratorMethod; -import art.arcane.volmlib.util.math.Position2; -import org.junit.Test; -import org.mockito.MockedStatic; - -import javax.swing.SwingUtilities; -import java.awt.Color; -import java.awt.Graphics2D; -import java.awt.image.BufferedImage; -import java.lang.reflect.Field; -import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ExecutorService; -import java.util.concurrent.Executors; -import java.util.concurrent.Future; -import java.util.concurrent.TimeUnit; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.CALLS_REAL_METHODS; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.mockStatic; -import static org.mockito.Mockito.verifyNoInteractions; -import static org.mockito.Mockito.when; - -public class PregenMapRetentionTest { - @Test - public void existingStartingChunksPublishedBeforeAttachmentAppearInActualPaintAndReopenedView() throws Exception { - Fixture fixture = new Fixture(); - fixture.job.onChunkExistsInRegionGen(-16, -16); - fixture.job.onChunkGenerated(-17, -16, false); - verifyNoInteractions(fixture.engine); - - PregenMapPanel first = panel(fixture.state); - assertEquals(PregenRenderer.EXISTS.getRGB(), paint(first, fixture.state).getRGB(17, 17)); - assertEquals(PregenRenderer.GENERATED.getRGB(), paint(first, fixture.state).getRGB(16, 17)); - SwingUtilities.invokeAndWait(first::disposeMap); - fixture.job.onChunkGenerated(-16, -17, true); - PregenMapPanel reopened = panel(fixture.state); - assertEquals(PregenRenderer.EXISTS.getRGB(), paint(reopened, fixture.state).getRGB(17, 17)); - assertEquals(PregenRenderer.GENERATED.getRGB(), paint(reopened, fixture.state).getRGB(17, 16)); - SwingUtilities.invokeAndWait(reopened::disposeMap); - } - - @Test - public void whollyCachedNegativeRegionPublishesAllChunksBeforeGuiOpens() throws Exception { - Fixture fixture = new Fixture(); - PregenCache cache = mock(PregenCache.class); - when(cache.sync()).thenReturn(cache); - when(cache.isRegionCached(-1, -1)).thenReturn(true); - PregeneratorMethod backend = mock(PregeneratorMethod.class); - CachedPregenMethod cached = new CachedPregenMethod(new CachedPregenMethod.Configuration( - backend, cache, fixture.task, new PregenSavedChunkStatus((x, z) -> true))); - try (MockedStatic services = mockStatic(IrisServices.class)) { - cached.generateRegion(-1, -1, fixture.job); - } - verifyNoInteractions(backend); - PregenMapPanel panel = panel(fixture.state); - BufferedImage rendered = paint(panel, fixture.state); - for (int x = 1; x < 32; x++) { - for (int z = 1; z < 32; z++) { - assertEquals(PregenRenderer.GENERATED.getRGB(), rendered.getRGB(x + 1, z + 1)); - } - } - SwingUtilities.invokeAndWait(panel::disposeMap); - } - - @Test - public void shutdownSkippedRegionsStayWaitingInsteadOfBeingPaintedAsExisting() throws Exception { - Fixture fixture = new Fixture(); - fixture.job.onRegionSkipped(-1, -1); - PregenMapPanel panel = panel(fixture.state); - assertEquals(PregenMapState.WAITING.getRGB(), paint(panel, fixture.state).getRGB(17, 17)); - SwingUtilities.invokeAndWait(panel::disposeMap); - } - - @Test - public void concurrentPublicationAndIndependentViewsKeepTheFinalRaster() throws Exception { - PregenMapState state = new PregenMapState(new PregenRenderSnapshot.Bounds(-8, -8, 7, 7)); - PregenMapPanel first = panel(state); - PregenMapPanel second = panel(state); - CountDownLatch started = new CountDownLatch(1); - ExecutorService worker = Executors.newSingleThreadExecutor(); - try { - Future updates = worker.submit(() -> { - started.countDown(); - for (int round = 0; round < 100; round++) { - for (int x = -8; x < 8; x++) { - for (int z = -8; z < 8; z++) { - state.submit(x, z, (round & 1) == 0 ? Color.RED : Color.GREEN); - } - } - } - }); - assertTrue(started.await(5, TimeUnit.SECONDS)); - for (int round = 0; round < 10; round++) { - SwingUtilities.invokeAndWait(first::flush); - } - updates.get(5, TimeUnit.SECONDS); - BufferedImage one = paint(first, state); - BufferedImage two = paint(second, state); - for (int x = 2; x < 16; x++) { - for (int z = 2; z < 16; z++) { - assertEquals(Color.GREEN.getRGB(), one.getRGB(x, z)); - assertEquals(one.getRGB(x, z), two.getRGB(x, z)); - } - } - } finally { - worker.shutdownNow(); - SwingUtilities.invokeAndWait(first::disposeMap); - SwingUtilities.invokeAndWait(second::disposeMap); - } - } - - private static PregenMapPanel panel(PregenMapState state) throws Exception { - PregenMapPanel[] result = new PregenMapPanel[1]; - SwingUtilities.invokeAndWait(() -> result[0] = new PregenMapPanel(state)); - return result[0]; - } - - private static BufferedImage paint(PregenMapPanel panel, PregenMapState state) throws Exception { - BufferedImage image = new BufferedImage(state.width() + 2, state.height() + 2, BufferedImage.TYPE_INT_RGB); - SwingUtilities.invokeAndWait(() -> { - panel.flush(); - panel.setSize(image.getWidth(), image.getHeight()); - Graphics2D graphics = image.createGraphics(); - try { - panel.paint(graphics); - } finally { - graphics.dispose(); - } - }); - return image; - } - - private static final class Fixture { - private final PregeneratorJob job = mock(PregeneratorJob.class, CALLS_REAL_METHODS); - private final Engine engine = mock(Engine.class); - private final PregenTask task = PregenTask.builder().center(new Position2(-256, -256)) - .radiusX(256).radiusZ(256).build(); - private final PregenMapState state; - - private Fixture() throws Exception { - int[] bounds = task.chunkBounds(); - state = new PregenMapState(new PregenRenderSnapshot.Bounds(bounds[0], bounds[1], bounds[2], bounds[3])); - set("mapState", state); - set("task", task); - set("engine", engine); - } - - private void set(String name, Object value) throws Exception { - Field field = PregeneratorJob.class.getDeclaredField(name); - field.setAccessible(true); - field.set(job, value); - } - } -} diff --git a/core/src/test/java/art/arcane/iris/studio/view/PregenRendererTest.java b/core/src/test/java/art/arcane/iris/studio/view/PregenRendererTest.java deleted file mode 100644 index bc267ed20..000000000 --- a/core/src/test/java/art/arcane/iris/studio/view/PregenRendererTest.java +++ /dev/null @@ -1,274 +0,0 @@ -package art.arcane.iris.studio.view; - -import art.arcane.iris.configuration.IrisSettings; -import art.arcane.iris.localization.DesktopUiMessages; -import art.arcane.iris.localization.IrisLanguage; -import art.arcane.iris.spi.IrisLogging; -import org.junit.Test; -import org.mockito.MockedStatic; - -import javax.swing.JButton; -import javax.swing.JComponent; -import javax.swing.JLabel; -import javax.swing.JTextArea; -import javax.swing.JToggleButton; -import javax.swing.JViewport; -import javax.swing.KeyStroke; -import javax.swing.SwingUtilities; -import java.awt.Component; -import java.awt.Container; -import java.awt.event.ActionEvent; -import java.awt.event.KeyEvent; -import java.lang.reflect.Constructor; -import java.lang.reflect.Field; -import java.lang.reflect.Method; -import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicInteger; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.mockStatic; - -public class PregenRendererTest { - @Test - public void smallWindowOpensAtTheProgressHeaderWithoutScrollingAway() throws Exception { - PregenRenderer[] result = new PregenRenderer[1]; - onEdt(() -> { - result[0] = renderer(new Source(), () -> { }); - result[0].setSize(820, 520); - layout(result[0]); - }); - try { - onEdt(() -> layout(result[0])); - onEdt(() -> assertScrollAtTop(result[0])); - } finally { - onEdt(result[0]::close); - } - } - - @Test - public void mapShortcutsZoomPanResetAndKeepGridControlSynchronized() throws Exception { - onEdt(() -> { - PregenRenderer renderer = renderer(new Source(), () -> { }); - try { - PregenMapPanel map = field(renderer, "map", PregenMapPanel.class); - map.setSize(1000, 600); - map.setCoveredLeftWidth(300); - shortcut(renderer, KeyEvent.VK_EQUALS); - assertTrue(map.zoom() > 1D); - shortcut(renderer, KeyEvent.VK_LEFT); - shortcut(renderer, KeyEvent.VK_R); - assertEquals(1D, map.zoom(), 0D); - shortcut(renderer, KeyEvent.VK_G); - assertTrue(map.isGridVisible()); - JToggleButton grid = field(renderer, "gridToggle", JToggleButton.class); - assertTrue(grid.isSelected()); - grid.doClick(0); - assertFalse(map.isGridVisible()); - assertFalse(grid.isSelected()); - shortcut(renderer, KeyEvent.VK_SLASH); - shortcut(renderer, KeyEvent.VK_ESCAPE); - } finally { - renderer.close(); - } - }); - } - - @Test - public void keyboardAndButtonActivationToggleExactlyOnceAndTerminalControlsAreDisabled() throws Exception { - onEdt(() -> { - Source source = new Source(); - AtomicInteger calls = new AtomicInteger(); - PregenRenderer renderer = renderer(source, () -> { - calls.incrementAndGet(); - source.snapshot = snapshot(source.snapshot.phase() == PregenRenderSnapshot.Phase.PAUSED - ? PregenRenderSnapshot.Phase.GENERATING : PregenRenderSnapshot.Phase.PAUSED, null, 0); - }); - try { - JButton button = field(renderer, "pauseButton", JButton.class); - Object pauseAction = renderer.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) - .get(KeyStroke.getKeyStroke(KeyEvent.VK_P, 0, true)); - renderer.getActionMap().get(pauseAction).actionPerformed(new ActionEvent(renderer, 0, "P")); - assertEquals(1, calls.get()); - assertEquals(PregenRenderSnapshot.Phase.PAUSED, source.snapshot.phase()); - Object enterAction = button.getInputMap(JComponent.WHEN_FOCUSED) - .get(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0)); - button.getActionMap().get(enterAction).actionPerformed(new ActionEvent(button, 0, "Enter")); - assertEquals(2, calls.get()); - button.doClick(0); - assertEquals(3, calls.get()); - for (PregenRenderSnapshot.Phase phase : new PregenRenderSnapshot.Phase[]{ - PregenRenderSnapshot.Phase.STOPPING, PregenRenderSnapshot.Phase.COMPLETED, - PregenRenderSnapshot.Phase.ERROR}) { - source.snapshot = snapshot(phase, null, 0); - refresh(renderer); - assertFalse(button.isEnabled()); - renderer.getActionMap().get(pauseAction).actionPerformed(new ActionEvent(renderer, 0, "P")); - button.getActionMap().get(enterAction).actionPerformed(new ActionEvent(button, 0, "Enter")); - button.doClick(0); - assertEquals(3, calls.get()); - } - } finally { - renderer.close(); - } - }); - } - - @Test - public void initializingAndPausedEtaRemainPending() throws Exception { - onEdt(() -> { - Source source = new Source(); - source.snapshot = snapshot(PregenRenderSnapshot.Phase.INITIALIZING, null, 0); - PregenRenderer renderer = renderer(source, () -> { }); - try { - JLabel eta = field(renderer, "etaValue", JLabel.class); - String pending = IrisLanguage.plain(DesktopUiMessages.PREGEN_METHOD_PENDING); - assertEquals(pending, eta.getText()); - source.snapshot = snapshot(PregenRenderSnapshot.Phase.PAUSED, null, 0); - refresh(renderer); - assertEquals(pending, eta.getText()); - for (PregenRenderSnapshot.Phase phase : new PregenRenderSnapshot.Phase[]{ - PregenRenderSnapshot.Phase.ERROR, PregenRenderSnapshot.Phase.STOPPING}) { - source.snapshot = snapshot(phase, null, 0); - refresh(renderer); - assertEquals(pending, eta.getText()); - } - source.snapshot = snapshot(PregenRenderSnapshot.Phase.GENERATING, null, 0); - refresh(renderer); - assertFalse(pending.equals(eta.getText())); - } finally { - renderer.close(); - } - }); - } - - @Test - public void failureDetailsAndPauseFailureRemainVisibleUntilSuccessfulRetry() throws Exception { - onEdt(() -> { - Source source = new Source(); - source.snapshot = snapshot(PregenRenderSnapshot.Phase.GENERATING, "chunk save failed", 1); - AtomicBoolean failPause = new AtomicBoolean(true); - PregenRenderer renderer = renderer(source, () -> { - if (failPause.get()) { - throw new IllegalStateException("scheduler refused pause"); - } - }); - try (MockedStatic logging = mockStatic(IrisLogging.class, invocation -> { - if (invocation.getMethod().getName().equals("reportError") - && invocation.getMethod().getParameterCount() == 2 - && invocation.getMethod().getParameterTypes()[0] == String.class - && invocation.getMethod().getParameterTypes()[1] == Throwable.class) { - return null; - } - return invocation.callRealMethod(); - })) { - JButton button = field(renderer, "pauseButton", JButton.class); - JTextArea details = field(renderer, "failureLabel", JTextArea.class); - assertTrue(details.getLineWrap()); - assertTrue(details.getText().contains("chunk save failed")); - int selectionStart = details.getText().indexOf("chunk save failed"); - details.select(selectionStart, selectionStart + "chunk save failed".length()); - PregenRenderSnapshot previous = source.snapshot; - source.snapshot = new PregenRenderSnapshot(previous.bounds(), previous.progress(), - previous.phase(), previous.cached(), previous.usedMemoryBytes() + 1024, - previous.memoryUsage(), previous.allocationBytesPerSecond(), previous.failure()); - refresh(renderer); - assertEquals("chunk save failed", details.getSelectedText()); - assertEquals(selectionStart, details.getSelectionStart()); - button.doClick(0); - assertTrue(details.getText().contains("scheduler refused pause")); - source.snapshot = snapshot(PregenRenderSnapshot.Phase.GENERATING, null, 2); - refresh(renderer); - assertTrue(details.getText().contains("scheduler refused pause")); - failPause.set(false); - button.doClick(0); - assertFalse(details.getText().contains("scheduler refused pause")); - } finally { - renderer.close(); - } - }); - } - - private static PregenRenderer renderer(Source source, Runnable pause) throws Exception { - Constructor constructor = PregenRenderer.class.getDeclaredConstructor( - PregenRenderSource.class, Runnable.class); - constructor.setAccessible(true); - return constructor.newInstance(source, pause); - } - - private static void refresh(PregenRenderer renderer) throws Exception { - Method refresh = PregenRenderer.class.getDeclaredMethod("refresh"); - refresh.setAccessible(true); - refresh.invoke(renderer); - } - - private static void shortcut(PregenRenderer renderer, int keyCode) { - Object action = renderer.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW) - .get(KeyStroke.getKeyStroke(keyCode, 0)); - renderer.getActionMap().get(action).actionPerformed(new ActionEvent(renderer, 0, "shortcut")); - } - - private static void layout(Container container) { - container.doLayout(); - for (Component component : container.getComponents()) { - if (component instanceof Container child) { - layout(child); - } - } - } - - private static void assertScrollAtTop(Container container) { - for (Component component : container.getComponents()) { - if (component instanceof JViewport viewport) { - assertEquals(0, viewport.getViewPosition().y); - } - if (component instanceof Container child) { - assertScrollAtTop(child); - } - } - } - - private static T field(PregenRenderer renderer, String name, Class type) throws Exception { - Field field = PregenRenderer.class.getDeclaredField(name); - field.setAccessible(true); - return type.cast(field.get(renderer)); - } - - private static void onEdt(CheckedTask task) throws Exception { - SwingUtilities.invokeAndWait(() -> { - try (MockedStatic settings = mockStatic(IrisSettings.class)) { - settings.when(IrisSettings::get).thenReturn(new IrisSettings()); - task.run(); - } catch (Exception failure) { - throw new IllegalStateException(failure); - } - }); - } - - private static PregenRenderSnapshot snapshot(PregenRenderSnapshot.Phase phase, String failure, long failed) { - return new PregenRenderSnapshot(new PregenRenderSnapshot.Bounds(-32, -32, 32, 32), - new PregeneratorJob.PregenProgress(25, 25, 100, 20, 18, 17, 16, - 75, 4, 3000, 1000, "native", phase == PregenRenderSnapshot.Phase.PAUSED, - failed, "Example world", "example"), phase, false, 1024, 0.25, 256, failure); - } - - private interface CheckedTask { - void run() throws Exception; - } - - private static final class Source implements PregenRenderSource { - private PregenRenderSnapshot snapshot = snapshot(PregenRenderSnapshot.Phase.GENERATING, null, 0); - private final PregenMapState map = new PregenMapState(snapshot.bounds()); - - @Override - public PregenRenderSnapshot renderSnapshot() { - return snapshot; - } - - @Override - public PregenMapState renderMapState() { - return map; - } - } -} diff --git a/studio/src/renderer/src/bridge/BridgeClient.ts b/studio/src/renderer/src/bridge/BridgeClient.ts index 131520ec5..4d7673a95 100644 --- a/studio/src/renderer/src/bridge/BridgeClient.ts +++ b/studio/src/renderer/src/bridge/BridgeClient.ts @@ -8,6 +8,7 @@ import type { BlockSource, EditorState, GraphEdit, + ImageMapDetails, MapHover, MapLabel, MapTile, @@ -18,6 +19,7 @@ import type { PatternEntry, PatternTile, PickInspection, + PregenStatus, ProfileFormState, SavedStart, SavedTile, @@ -276,6 +278,36 @@ export class BridgeClient { return decodePattern(await response.arrayBuffer()) } + pregen(signal?: AbortSignal): Promise { + return this.json('pregen', { signal }) + } + + /** The running pregeneration's chunks, one pixel each. */ + async pregenMap(signal?: AbortSignal): Promise { + const response = await this.fetch('pregen-map', { signal }) + return response.blob() + } + + /** Pauses the pregeneration, or resumes it when it is paused. */ + async pregenPause(): Promise { + await this.json('pregen-pause', { method: 'POST' }) + } + + /** The pack's image maps, listed like scene entries. */ + imageMaps(): Promise { + return this.json('image-maps') + } + + imageMap(key: string, signal?: AbortSignal): Promise { + return this.json(`image-map?${new URLSearchParams({ key })}`, { signal }) + } + + /** The image map painted over the world area it covers, {@code pixels} across its longer side. */ + async imageMapPreview(key: string, pixels: number, signal?: AbortSignal): Promise { + const response = await this.fetch(`image-map-preview?${new URLSearchParams({ key, size: String(pixels) })}`, { signal }) + return response.blob() + } + /** The worlds saved on the server's disk. */ savedWorlds(): Promise { return this.json('saved-worlds') diff --git a/studio/src/renderer/src/bridge/types.ts b/studio/src/renderer/src/bridge/types.ts index ff56e57b5..178f6cb5d 100644 --- a/studio/src/renderer/src/bridge/types.ts +++ b/studio/src/renderer/src/bridge/types.ts @@ -194,6 +194,56 @@ export interface PatternTile { export const NO_PATTERN_BLOCK = -1 +/** How far the running pregeneration is; times are in milliseconds. */ +export interface PregenProgress { + percent: number + generated: number + totalChunks: number + chunksPerSecond: number + overallChunksPerSecond: number + thirtySecondChunksPerSecond: number + sixtySecondChunksPerSecond: number + chunksRemaining: number + chunksInFlight: number + eta: number + elapsed: number + method: string + paused: boolean + failed: number + worldName: string +} + +export type PregenPhase = 'INITIALIZING' | 'GENERATING' | 'PAUSED' | 'SAVING' | 'STOPPING' | 'COMPLETED' | 'ERROR' + +export interface PregenSnapshot { + bounds: { minX: number; minZ: number; maxX: number; maxZ: number } + progress: PregenProgress + phase: PregenPhase + cached: boolean + usedMemoryBytes: number + memoryUsage: number + failure: string | null +} + +/** The server's pregeneration; `snapshot` is null while none runs. */ +export interface PregenStatus { + active: boolean + snapshot: PregenSnapshot | null +} + +/** An image map of the pack and what it covers. */ +export interface ImageMapDetails { + key: string + type: string + source: string + width: number + height: number + blocksPerPixel: number + /** The world area it covers: minimum X, minimum Z, maximum X, maximum Z. */ + bounds: [number, number, number, number] + facts: string[] +} + /** A world saved on the server's disk, a dimension folder of region files. */ export interface SavedWorldInfo { /** Its folder below the server's level folder. */ diff --git a/studio/src/renderer/src/studio/ImageMapStudio.tsx b/studio/src/renderer/src/studio/ImageMapStudio.tsx new file mode 100644 index 000000000..7b90f45e0 --- /dev/null +++ b/studio/src/renderer/src/studio/ImageMapStudio.tsx @@ -0,0 +1,109 @@ +import { useEffect, useState } from 'react' +import type { BridgeClient } from '../bridge/BridgeClient' +import type { ImageMapDetails, SceneEntry } from '../bridge/types' +import { EntryBrowser } from './EntryBrowser' +import { Panel, SidebarPanel, ViewIsland } from './Sidebar' + +const PREVIEW_PIXELS = 1024 +const NUMBER = new Intl.NumberFormat('en-US') + +interface ImageMapStudioProps { + title: string + client: BridgeClient + /** Changes when the pack reloads, so the maps are read again. */ + packRevision: number + onSummary(summary: string | null): void + tell(message: string): void +} + +/** The pack's image maps: the list on the left, the chosen one painted over the world area it covers in the middle, what it is on the right. */ +export function ImageMapStudio({ title, client, packRevision, onSummary, tell }: ImageMapStudioProps): React.JSX.Element { + const entries = useImageMapEntries(client, packRevision, tell) + const [chosen, setChosen] = useState(null) + const entry = entries.find((candidate) => candidate.key === chosen) ?? entries[0] ?? null + const { details, picture } = useImageMap(client, entry?.key ?? null, packRevision, tell) + + useEffect(() => onSummary(entry === null ? null : entry.key), [entry, onSummary]) + useEffect(() => () => onSummary(null), [onSummary]) + + return ( + <> + +
+ {picture !== null && {entry?.name} + {entry === null &&

This pack has no image maps. Put them in the pack's imageMaps folder.

} +
+
+ + + + {details !== null && } + + ) +} + +function Facts({ details }: { details: ImageMapDetails }): React.JSX.Element { + const [minimumX, minimumZ, maximumX, maximumZ] = details.bounds + return ( +
+

+ {details.type} +

+

+ Covers X {NUMBER.format(Math.round(minimumX))} to {NUMBER.format(Math.round(maximumX))}, Z {NUMBER.format(Math.round(minimumZ))} to {NUMBER.format(Math.round(maximumZ))} +

+ {details.facts.map((fact) => ( +

+ {fact} +

+ ))} +
+ ) +} + +function useImageMapEntries(client: BridgeClient, packRevision: number, tell: (message: string) => void): SceneEntry[] { + const [entries, setEntries] = useState([]) + useEffect(() => { + let active = true + client + .imageMaps() + .then((found) => active && setEntries(found)) + .catch((failure: Error) => active && tell(failure.message)) + return () => { + active = false + } + }, [client, packRevision, tell]) + return entries +} + +function useImageMap(client: BridgeClient, key: string | null, packRevision: number, tell: (message: string) => void): { details: ImageMapDetails | null; picture: string | null } { + const [details, setDetails] = useState(null) + const [picture, setPicture] = useState(null) + useEffect(() => { + setDetails(null) + setPicture(null) + if (key === null) { + return + } + const stop = new AbortController() + let url: string | null = null + client + .imageMap(key, stop.signal) + .then(setDetails) + .catch((failure: Error) => !stop.signal.aborted && tell(failure.message)) + client + .imageMapPreview(key, PREVIEW_PIXELS, stop.signal) + .then((blob) => { + url = URL.createObjectURL(blob) + setPicture(url) + }) + .catch((failure: Error) => !stop.signal.aborted && tell(failure.message)) + return () => { + stop.abort() + if (url !== null) { + URL.revokeObjectURL(url) + } + } + }, [client, key, packRevision, tell]) + return { details, picture } +} diff --git a/studio/src/renderer/src/studio/MapStudio.tsx b/studio/src/renderer/src/studio/MapStudio.tsx index 21de9f47a..25fadf8db 100644 --- a/studio/src/renderer/src/studio/MapStudio.tsx +++ b/studio/src/renderer/src/studio/MapStudio.tsx @@ -12,7 +12,9 @@ import { Legend } from './Legend' import { MapCanvas, type CanvasPoint } from './MapCanvas' import { PickInspector } from './PickInspector' import { RegionPreviewList } from './RegionPreviewList' +import { ImageMapStudio } from './ImageMapStudio' import { NoiseStudio } from './NoiseStudio' +import { PregenStudio } from './PregenStudio' import { PatternStudio } from './PatternStudio' import { SavedWorldStudio } from './SavedWorldStudio' import { SceneStudio } from './SceneStudio' @@ -235,6 +237,10 @@ export function MapStudio({ client, world, theme, onDisconnect }: MapStudioProps ) : viewId === SAVED_WORLD.id ? ( + ) : viewId === PREGEN_VIEW_ID ? ( + + ) : viewId === IMAGE_MAPS_VIEW_ID ? ( + ) : viewId === NOISE.id ? ( ) : ( @@ -347,7 +353,9 @@ const NOISE: ViewInfo = { group: 'PACK', groupLabel: 'Pack' } -const APP_VIEW_IDS = new Set([WORLD_3D.id, SAVED_WORLD.id, NOISE.id]) +const IMAGE_MAPS_VIEW_ID = 'imageMaps' +const PREGEN_VIEW_ID = 'pregen' +const APP_VIEW_IDS = new Set([WORLD_3D.id, SAVED_WORLD.id, NOISE.id, IMAGE_MAPS_VIEW_ID, PREGEN_VIEW_ID]) function withAppViews(serverViews: ViewInfo[]): ViewInfo[] { const afterRegions = serverViews.findIndex((candidate) => candidate.id === 'regions') + 1 diff --git a/studio/src/renderer/src/studio/PregenStudio.tsx b/studio/src/renderer/src/studio/PregenStudio.tsx new file mode 100644 index 000000000..76f73c582 --- /dev/null +++ b/studio/src/renderer/src/studio/PregenStudio.tsx @@ -0,0 +1,131 @@ +import { useEffect, useState } from 'react' +import { Button } from '@/components/ui/button' +import type { BridgeClient } from '../bridge/BridgeClient' +import type { PregenSnapshot } from '../bridge/types' +import { Panel, ViewIsland } from './Sidebar' + +const POLL_MILLIS = 1000 +const MILLIS_PER_SECOND = 1000 +const SECONDS_PER_MINUTE = 60 +const MINUTES_PER_HOUR = 60 +const PERCENT = 100 +const NUMBER = new Intl.NumberFormat('en-US') +const RATE = new Intl.NumberFormat('en-US', { maximumFractionDigits: 1 }) +const PHASE_LABELS = { + INITIALIZING: 'Starting', + GENERATING: 'Generating', + PAUSED: 'Paused', + SAVING: 'Saving', + STOPPING: 'Stopping', + COMPLETED: 'Done', + ERROR: 'Failed' +} as const + +interface PregenStudioProps { + title: string + client: BridgeClient + onSummary(summary: string | null): void + tell(message: string): void +} + +/** The running pregeneration: its chunks as they are generated in the middle, its progress on the right. */ +export function PregenStudio({ title, client, onSummary, tell }: PregenStudioProps): React.JSX.Element { + const { snapshot, picture } = usePregen(client, tell) + + useEffect(() => onSummary(snapshot === null ? null : `${PHASE_LABELS[snapshot.phase]} · ${snapshot.progress.worldName}`), [snapshot, onSummary]) + useEffect(() => () => onSummary(null), [onSummary]) + + return ( + <> + +
+ {picture !== null && Chunks of the pregeneration} + {snapshot === null &&

No pregeneration is running. Start one with /iris pregen start.

} +
+
+ {snapshot !== null && void client.pregenPause().catch((failure: Error) => tell(failure.message))} />} + + ) +} + +function Progress({ snapshot, onPause }: { snapshot: PregenSnapshot; onPause(): void }): React.JSX.Element { + const { progress } = snapshot + const canPause = snapshot.phase === 'GENERATING' || snapshot.phase === 'PAUSED' + return ( +
+

{PHASE_LABELS[snapshot.phase]}

+
+
+
+ + + + + + + + + + {progress.failed > 0 && } + {snapshot.failure !== null &&

{snapshot.failure}

} + {canPause && ( + + )} +
+ ) +} + +function Row({ label, value }: { label: string; value: string }): React.JSX.Element { + return ( +
+ {label} + {value} +
+ ) +} + +function duration(millis: number): string { + const totalSeconds = Math.max(0, Math.round(millis / MILLIS_PER_SECOND)) + const hours = Math.floor(totalSeconds / (SECONDS_PER_MINUTE * MINUTES_PER_HOUR)) + const minutes = Math.floor(totalSeconds / SECONDS_PER_MINUTE) % MINUTES_PER_HOUR + const seconds = totalSeconds % SECONDS_PER_MINUTE + return hours > 0 ? `${hours}h ${minutes}m` : minutes > 0 ? `${minutes}m ${seconds}s` : `${seconds}s` +} + +/** The pregeneration's status and map, read again every second while the view is shown. */ +function usePregen(client: BridgeClient, tell: (message: string) => void): { snapshot: PregenSnapshot | null; picture: string | null } { + const [snapshot, setSnapshot] = useState(null) + const [picture, setPicture] = useState(null) + useEffect(() => { + const stop = new AbortController() + let url: string | null = null + const show = (next: string | null): void => { + if (url !== null) { + URL.revokeObjectURL(url) + } + url = next + setPicture(next) + } + const refresh = async (): Promise => { + try { + const status = await client.pregen(stop.signal) + setSnapshot(status.snapshot) + show(status.active ? URL.createObjectURL(await client.pregenMap(stop.signal)) : null) + } catch (failure) { + if (!stop.signal.aborted) { + tell(failure instanceof Error ? failure.message : String(failure)) + } + } + } + void refresh() + const timer = window.setInterval(() => void refresh(), POLL_MILLIS) + return () => { + stop.abort() + window.clearInterval(timer) + show(null) + } + }, [client, tell]) + return { snapshot, picture } +} diff --git a/studio/src/renderer/src/studio/ViewList.tsx b/studio/src/renderer/src/studio/ViewList.tsx index 5a1922b8b..ed990afd4 100644 --- a/studio/src/renderer/src/studio/ViewList.tsx +++ b/studio/src/renderer/src/studio/ViewList.tsx @@ -29,7 +29,9 @@ const VIEW_ICONS: Record = { 'iris:decorant/decorators': 'decoration', 'iris:objects': 'views/objects', 'iris:objects/procedural': 'views/procedural', - noise: 'views/noise' + noise: 'views/noise', + imageMaps: 'grid', + pregen: 'lightning' } const FALLBACK_ICON: IdeIconName = 'blocks' /** Inset, because the stripe scrolls and so clips anything drawn outside its buttons. */