mirror of
https://github.com/VolmitSoftware/Iris.git
synced 2026-11-28 00:34:19 +00:00
Merge weighted references into listed caves
# Conflicts: # core/src/main/java/art/arcane/iris/generation/terrain/IrisRegion.java # core/src/main/java/art/arcane/iris/pack/datapack/export/compile/cave/CaveSelection.java # core/src/test/java/art/arcane/iris/generation/terrain/IrisDimensionReachableBiomesTest.java # core/src/test/java/art/arcane/iris/pack/schema/SchemaBuilderIdentityTest.java
This commit is contained in:
commit
1f27af6938
518 files changed
+30591
-30887
No files matched your search
+3
-3
@@ -570,7 +570,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
|
||||
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
|
||||
area::isInside, cells -> {});
|
||||
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
|
||||
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
|
||||
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
|
||||
|
||||
assertTrue(state(blocks, 4, 96, 0).isAir());
|
||||
assertEquals(1, pathGround.size());
|
||||
@@ -619,7 +619,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
|
||||
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
|
||||
area::isInside, cells -> {});
|
||||
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
|
||||
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
|
||||
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
|
||||
|
||||
assertEquals(2, pathGround.size());
|
||||
for (NativeStructureTemplateOccupancy.LowestCell cell : pathGround.values()) {
|
||||
@@ -675,7 +675,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
|
||||
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
|
||||
area::isInside, cells -> {});
|
||||
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
|
||||
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
|
||||
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
|
||||
|
||||
assertEquals(2, pathGround.size());
|
||||
for (NativeStructureTemplateOccupancy.LowestCell cell : pathGround.values()) {
|
||||
|
||||
+3
-3
@@ -570,7 +570,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
|
||||
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
|
||||
area::isInside, cells -> {});
|
||||
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
|
||||
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
|
||||
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
|
||||
|
||||
assertTrue(state(blocks, 4, 96, 0).isAir());
|
||||
assertEquals(1, pathGround.size());
|
||||
@@ -619,7 +619,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
|
||||
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
|
||||
area::isInside, cells -> {});
|
||||
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
|
||||
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
|
||||
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
|
||||
|
||||
assertEquals(2, pathGround.size());
|
||||
for (NativeStructureTemplateOccupancy.LowestCell cell : pathGround.values()) {
|
||||
@@ -675,7 +675,7 @@ public class NativeStructurePostProcessorSurfaceTerrainTest {
|
||||
NativeStructurePostProcessorSurfaceTerrainTest::forbiddenTemplateManager,
|
||||
area::isInside, cells -> {});
|
||||
Map<Long, NativeStructureTemplateOccupancy.LowestCell> pathGround =
|
||||
NativeStructureTemplateOccupancy.lowestProcessedSolidCells(occupancy.cells());
|
||||
NativeStructureTemplateOccupancy.lowestFoundationCells(occupancy.cells());
|
||||
|
||||
assertEquals(2, pathGround.size());
|
||||
for (NativeStructureTemplateOccupancy.LowestCell cell : pathGround.values()) {
|
||||
|
||||
@@ -28,8 +28,7 @@ import art.arcane.volmlib.util.director.annotations.Director;
|
||||
import art.arcane.volmlib.util.director.annotations.Param;
|
||||
import art.arcane.iris.localization.C;
|
||||
|
||||
import java.awt.Desktop;
|
||||
import java.awt.GraphicsEnvironment;
|
||||
import art.arcane.iris.studio.workspace.FileOpener;
|
||||
|
||||
|
||||
import art.arcane.iris.localization.IrisLanguage;
|
||||
@@ -51,15 +50,10 @@ public class CommandEdit implements DirectorExecutor {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (GraphicsEnvironment.isHeadless()) {
|
||||
if (!FileOpener.isDesktopAvailable()) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANNOT_OPEN_FILES_HEADLESS_ENVIRONMENTS));
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!Desktop.isDesktopSupported()) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_DESKTOP_IS_NOT_SUPPORTED_BY_THIS_ENVIRONMENT));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -74,7 +68,7 @@ public class CommandEdit implements DirectorExecutor {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANNOT_FIND_FILE_PERHAPS_IT_WAS_NOT_LOADED_DIRECTLY_FROM));
|
||||
return;
|
||||
}
|
||||
Desktop.getDesktop().open(biome.getLoadFile());
|
||||
FileOpener.open(biome.getLoadFile());
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_OPENING_VSCODE, MessageArgument.untrusted("value", biome.getTypeName()), MessageArgument.untrusted("value2", biome.getLoadFile().getName().split("\\Q.\\E")[0])));
|
||||
} catch (Throwable e) {
|
||||
Iris.reportError(e);
|
||||
@@ -92,7 +86,7 @@ public class CommandEdit implements DirectorExecutor {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANNOT_FIND_FILE_PERHAPS_IT_WAS_NOT_LOADED_DIRECTLY_FROM_2));
|
||||
return;
|
||||
}
|
||||
Desktop.getDesktop().open(region.getLoadFile());
|
||||
FileOpener.open(region.getLoadFile());
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_OPENING_VSCODE_2, MessageArgument.untrusted("value", region.getTypeName()), MessageArgument.untrusted("value2", region.getLoadFile().getName().split("\\Q.\\E")[0])));
|
||||
} catch (Throwable e) {
|
||||
Iris.reportError(e);
|
||||
@@ -110,7 +104,7 @@ public class CommandEdit implements DirectorExecutor {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_CANNOT_FIND_FILE_PERHAPS_IT_WAS_NOT_LOADED_DIRECTLY_FROM_3));
|
||||
return;
|
||||
}
|
||||
Desktop.getDesktop().open(dimension.getLoadFile());
|
||||
FileOpener.open(dimension.getLoadFile());
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_EDIT_OPENING_VSCODE_3, MessageArgument.untrusted("value", dimension.getTypeName()), MessageArgument.untrusted("value2", dimension.getLoadFile().getName().split("\\Q.\\E")[0])));
|
||||
} catch (Throwable e) {
|
||||
Iris.reportError(e);
|
||||
|
||||
@@ -21,9 +21,10 @@ package art.arcane.iris.command;
|
||||
import art.arcane.iris.Iris;
|
||||
import art.arcane.iris.platform.bukkit.BukkitPlatform;
|
||||
import art.arcane.iris.configuration.IrisSettings;
|
||||
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.spi.IrisLogging;
|
||||
import art.arcane.iris.studio.bridge.StudioBridge;
|
||||
import art.arcane.iris.studio.bridge.StudioBridges;
|
||||
import art.arcane.iris.studio.bridge.StudioWindow;
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.studio.workspace.IrisProject;
|
||||
import art.arcane.iris.studio.workspace.IrisCodeWorkspace;
|
||||
@@ -267,16 +268,12 @@ public class CommandStudio implements DirectorExecutor {
|
||||
|
||||
@Director(description = "Open the noise explorer (External GUI)", descriptionKey = "iris.director.commandstudio.director.open_noise_explorer_external_gui", aliases = {"nmap"})
|
||||
public void noise(
|
||||
@Param(description = "Optional pack generator to preview", descriptionKey = "iris.director.commandstudio.param.optional_pack_generator_preview", defaultValue = "null", contextual = true, contextualOverride = true)
|
||||
IrisGenerator generator,
|
||||
@Param(description = "The seed to preview the generator with", descriptionKey = "iris.director.commandstudio.param.seed_preview_generator_with", defaultValue = "12345")
|
||||
long seed
|
||||
@Param(name = "world", description = "The Iris world whose pack the noise explorer reads", descriptionKey = "iris.director.commandstudio.param.world_open_generator", contextual = true, contextualOverride = true)
|
||||
World world
|
||||
) {
|
||||
if (noGUI()) return;
|
||||
VolmitSender commandSender = sender();
|
||||
UUID openerId = commandSender.isPlayer() ? commandSender.player().getUniqueId() : null;
|
||||
MapWindow.NoiseSelection selection = new MapWindow.NoiseSelection(generator == null ? null : generator.getLoadKey(), generator, seed);
|
||||
withPlayerContext(opener -> openNoiseAtPlayer(commandSender, openerId, opener, selection));
|
||||
if (openStudioApp(world)) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_NOISE_EXPLORER));
|
||||
}
|
||||
}
|
||||
|
||||
@Director(description = "Open the image-map studio (External GUI)", descriptionKey = "iris.director.commandstudio.director.open_image_map_studio_external_gui", aliases = {"imap"})
|
||||
@@ -284,16 +281,9 @@ public class CommandStudio implements DirectorExecutor {
|
||||
@Param(name = "world", description = "The Iris world whose active pack receives image-map exports", descriptionKey = "iris.director.commandstudio.param.world_open_image_map_studio", contextual = true, contextualOverride = true)
|
||||
World world
|
||||
) {
|
||||
if (noGUI()) {
|
||||
return;
|
||||
if (openStudioApp(world)) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_IMAGE_MAP_STUDIO));
|
||||
}
|
||||
if (!IrisToolbelt.isIrisWorld(world)) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_NEED_BE_SPECIFY_IRIS_GENERATED_WORLD));
|
||||
return;
|
||||
}
|
||||
|
||||
requestMapStart(world, MapWindow::openImageMaps);
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_IMAGE_MAP_STUDIO));
|
||||
}
|
||||
|
||||
@Director(description = "Show loot if a chest were right here", descriptionKey = "iris.director.commandstudio.director.show_loot_if_chest_were_right_here", origin = DirectorOrigin.PLAYER, sync = true)
|
||||
@@ -377,7 +367,7 @@ public class CommandStudio implements DirectorExecutor {
|
||||
boolean progressShown = false;
|
||||
int c = -1;
|
||||
try {
|
||||
engine.getDimension().getRegions().forEach(key -> data.put(key, new AtomicInteger(0)));
|
||||
engine.getDimension().getRegionKeys().forEach(key -> data.put(key, new AtomicInteger(0)));
|
||||
multiBurst = new MultiBurst("Region Sampler");
|
||||
var executor = multiBurst.burst(Math.min(radius * radius, 1 << 20));
|
||||
sender.sendMessage(IrisLanguage.text(BukkitCommandMessages.COMMAND_STUDIO_GENERATING_DATA));
|
||||
@@ -425,65 +415,38 @@ public class CommandStudio implements DirectorExecutor {
|
||||
@Param(name = "world", description = "The world to open the generator for", descriptionKey = "iris.director.commandstudio.param.world_open_generator", contextual = true, contextualOverride = true)
|
||||
World world
|
||||
) {
|
||||
if (noGUI()) return;
|
||||
if (openStudioApp(world)) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP));
|
||||
}
|
||||
}
|
||||
|
||||
@Director(description = "Open the Iris Studio app on a world", descriptionKey = "iris.director.commandstudio.director.render_world_map_external_gui", aliases = "app")
|
||||
public void studioApp(
|
||||
@Param(name = "world", description = "The world to open the generator for", descriptionKey = "iris.director.commandstudio.param.world_open_generator", contextual = true, contextualOverride = true)
|
||||
World world
|
||||
) {
|
||||
if (openStudioApp(world)) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP));
|
||||
}
|
||||
}
|
||||
|
||||
/** Opens the app on the world, or logs its link when no app is set up; false, after telling the sender why, when it could not. */
|
||||
private boolean openStudioApp(World world) {
|
||||
if (!IrisToolbelt.isIrisWorld(world)) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_NEED_BE_SPECIFY_IRIS_GENERATED_WORLD));
|
||||
return;
|
||||
return false;
|
||||
}
|
||||
|
||||
requestMapStart(world, MapWindow::openMap);
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_MAP));
|
||||
}
|
||||
|
||||
// The map opens where the player stands when they are in that world, otherwise at the world origin.
|
||||
private PaletteExplorerStart mapStartIn(World world, Player opener, UUID openerId) {
|
||||
Location center = opener != null && opener.getWorld().equals(world) ? opener.getLocation() : null;
|
||||
return new PaletteExplorerStart(
|
||||
IrisToolbelt.access(world).getEngine(),
|
||||
world.getUID(),
|
||||
openerId,
|
||||
null,
|
||||
center == null ? 0D : center.getX(),
|
||||
center == null ? 0D : center.getZ()
|
||||
);
|
||||
}
|
||||
|
||||
private void requestMapStart(World world, Consumer<PaletteExplorerStart> launch) {
|
||||
UUID openerId = sender().isPlayer() ? player().getUniqueId() : null;
|
||||
withPlayerContext(opener -> launch.accept(mapStartIn(world, opener, openerId)));
|
||||
}
|
||||
|
||||
private void openNoiseAtPlayer(VolmitSender commandSender, UUID openerId, Player opener, MapWindow.NoiseSelection selection) {
|
||||
World world = opener == null ? null : opener.getWorld();
|
||||
PlatformChunkGenerator worldGenerator = world == null ? null : IrisToolbelt.access(world);
|
||||
Engine engine = worldGenerator == null ? GuiHost.get().findActiveEngine() : worldGenerator.getEngine();
|
||||
if (engine == null) {
|
||||
commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_NEED_BE_SPECIFY_IRIS_GENERATED_WORLD));
|
||||
return;
|
||||
}
|
||||
PaletteExplorerStart start = worldGenerator == null
|
||||
? new PaletteExplorerStart(engine, null, openerId, null, 0D, 0D)
|
||||
: mapStartIn(world, opener, openerId);
|
||||
MapWindow.openNoise(start, selection);
|
||||
commandSender.sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_OPENING_NOISE_EXPLORER));
|
||||
}
|
||||
|
||||
private void withPlayerContext(Consumer<Player> action) {
|
||||
Player opener = sender().isPlayer() ? player() : null;
|
||||
if (opener == null) {
|
||||
action.accept(null);
|
||||
return;
|
||||
}
|
||||
AtomicBoolean completed = new AtomicBoolean();
|
||||
Consumer<Player> complete = player -> {
|
||||
if (completed.compareAndSet(false, true)) {
|
||||
action.accept(player);
|
||||
PlatformChunkGenerator generator = IrisToolbelt.access(world);
|
||||
try {
|
||||
StudioBridge bridge = StudioBridges.open(world.getName(), generator::getEngine, openerId);
|
||||
if (!StudioWindow.show(bridge)) {
|
||||
IrisLogging.info("Iris Studio link for %s: %s", world.getName(), bridge.link());
|
||||
}
|
||||
};
|
||||
Runnable retired = () -> complete.accept(null);
|
||||
if (!J.runEntity(opener, () -> complete.accept(opener.isOnline() ? opener : null), 0, retired)) {
|
||||
retired.run();
|
||||
return true;
|
||||
} catch (IOException error) {
|
||||
IrisLogging.warn("Could not open the studio bridge: %s", error.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -953,21 +916,6 @@ public class CommandStudio implements DirectorExecutor {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if server GUIs are not enabled
|
||||
*/
|
||||
private boolean noGUI() {
|
||||
if (!IrisSettings.get().getGui().isUseServerLaunchedGuis()) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_YOU_MUST_HAVE_SERVER_LAUNCHED_GUIS_ENABLED_SETTINGS));
|
||||
return true;
|
||||
}
|
||||
if (!GuiHost.isAvailable()) {
|
||||
sender().sendMessage(IrisLanguage.text(BukkitCommandMessagesExtended.COMMAND_STUDIO_DESKTOP_UNAVAILABLE));
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return true if no studio is open or the player is not in one
|
||||
*/
|
||||
|
||||
-83
@@ -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<String> messages = new ArrayList<>();
|
||||
|
||||
private RecordingSender() {
|
||||
super(null);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void sendMessage(String message) {
|
||||
messages.add(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
-99
@@ -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<Runnable> task = new AtomicReference<>();
|
||||
AtomicReference<PaletteExplorerStart> 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<GuiHost> host = mockStatic(GuiHost.class);
|
||||
MockedStatic<IrisToolbelt> toolbelt = mockStatic(IrisToolbelt.class);
|
||||
MockedStatic<J> scheduling = mockStatic(J.class);
|
||||
MockedStatic<MapWindow> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -31,7 +31,7 @@ import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeCommandSource;
|
||||
import art.arcane.volmlib.nativelib.terrain.NativeBlockPoint;
|
||||
import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeEditPlayer;
|
||||
|
||||
import java.awt.Desktop;
|
||||
import art.arcane.iris.studio.workspace.FileOpener;
|
||||
import java.io.File;
|
||||
|
||||
final class ModdedEditCommands {
|
||||
@@ -110,7 +110,7 @@ final class ModdedEditCommands {
|
||||
}
|
||||
|
||||
private static int openJson(NativeCommandSource source, IrisRegistrant registrant) {
|
||||
if (!GuiHost.isAvailable() || !Desktop.isDesktopSupported()) {
|
||||
if (!GuiHost.isAvailable() || !FileOpener.isDesktopAvailable()) {
|
||||
IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_CANNOT_OPEN_FILES_HERE, MessageArgument.untrusted("value", ModdedGuiHost.guiUnavailableReason())));
|
||||
return 0;
|
||||
}
|
||||
@@ -120,7 +120,7 @@ final class ModdedEditCommands {
|
||||
}
|
||||
File file = registrant.getLoadFile();
|
||||
try {
|
||||
Desktop.getDesktop().open(file);
|
||||
FileOpener.open(file);
|
||||
} catch (Throwable e) {
|
||||
ModdedIrisLog.error("Iris edit failed to open {}", file, e);
|
||||
IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.IRIS_MODDED_COMMANDS_COULD_NOT_OPEN, MessageArgument.untrusted("value", file.getName()), MessageArgument.untrusted("value2", e.getClass().getSimpleName())));
|
||||
|
||||
+37
-66
@@ -23,8 +23,10 @@ import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeWorldView;
|
||||
|
||||
import art.arcane.iris.modded.ModdedIrisLog;
|
||||
import art.arcane.iris.configuration.IrisSettings;
|
||||
import art.arcane.iris.studio.map.MapWindow;
|
||||
import art.arcane.iris.studio.map.PaletteExplorerStart;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.studio.bridge.StudioBridge;
|
||||
import art.arcane.iris.studio.bridge.StudioBridges;
|
||||
import art.arcane.iris.studio.bridge.StudioWindow;
|
||||
import art.arcane.iris.studio.view.GuiHost;
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.pack.StructurePackageClosure;
|
||||
@@ -74,7 +76,7 @@ import art.arcane.volmlib.nativelib.terrain.NativeWorld;
|
||||
import art.arcane.volmlib.nativelib.minecraft26_2.modded.NativeProtocolPlayer;
|
||||
import org.zeroturnaround.zip.ZipUtil;
|
||||
|
||||
import java.awt.Desktop;
|
||||
import art.arcane.iris.studio.workspace.FileOpener;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
@@ -226,11 +228,7 @@ public final class ModdedStudioCommands {
|
||||
|
||||
private static LiteralArgumentBuilder<NativeCommandSource> noiseTree(String name) {
|
||||
return NativeCommandRegistration.literal(name)
|
||||
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> noise(context.getSource(), null, 12345L)))
|
||||
.then(NativeCommandRegistration.argument("generator", StringArgumentType.word()).suggests(GENERATOR_KEYS)
|
||||
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> noise(context.getSource(), StringArgumentType.getString(context, "generator"), 12345L)))
|
||||
.then(NativeCommandRegistration.argument("seed", LongArgumentType.longArg())
|
||||
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> noise(context.getSource(), StringArgumentType.getString(context, "generator"), LongArgumentType.getLong(context, "seed"))))));
|
||||
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> noise(context.getSource())));
|
||||
}
|
||||
|
||||
private static LiteralArgumentBuilder<NativeCommandSource> mapTree(String name) {
|
||||
@@ -243,85 +241,58 @@ public final class ModdedStudioCommands {
|
||||
.executes(ModdedCommandTree.localized((CommandContext<NativeCommandSource> context) -> imageMap(context.getSource())));
|
||||
}
|
||||
|
||||
private static int noise(NativeCommandSource source, String generatorKey, long seed) {
|
||||
NativeWorld level = source.world();
|
||||
Engine engine = IrisModdedCommands.engineFor(level);
|
||||
if (!GuiHost.isAvailable() || !IrisSettings.get().getGui().isUseServerLaunchedGuis()) {
|
||||
IrisModdedCommands.fail(source, guiUnavailableMessage());
|
||||
return 0;
|
||||
}
|
||||
if (engine != null) {
|
||||
NativeProtocolPlayer player = source.player();
|
||||
ModdedGuiHost.bindContext(worldView(source.server(), level), engine, player == null ? null : player.id());
|
||||
}
|
||||
Engine mapEngine = engine != null ? engine : GuiHost.get().findActiveEngine();
|
||||
if ((generatorKey == null || generatorKey.isBlank()) && mapEngine != null) {
|
||||
MapWindow.openNoise(mapStart(mapEngine, source.player()), new MapWindow.NoiseSelection(null, null, seed));
|
||||
IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_NOISE_EXPLORER_ON_SERVER_DISPLAY));
|
||||
return 1;
|
||||
}
|
||||
private static int noise(NativeCommandSource source) {
|
||||
Engine engine = IrisModdedCommands.engineFor(source.world());
|
||||
if (engine == null) {
|
||||
IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_THIS_DIMENSION_IS_NOT_GENERATED_BY_IRIS_RUN_IRIS_STUDIO));
|
||||
return 0;
|
||||
}
|
||||
IrisGenerator generator = engine.getData().getGeneratorLoader().load(generatorKey.trim());
|
||||
if (generator == null) {
|
||||
IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_UNKNOWN_GENERATOR_PACK, MessageArgument.untrusted("generatorKey", generatorKey), MessageArgument.untrusted("value", engine.getDimension().getLoadKey())));
|
||||
return 0;
|
||||
}
|
||||
String selectedGeneratorKey = generatorKey.trim();
|
||||
MapWindow.openNoise(mapStart(engine, source.player()), new MapWindow.NoiseSelection(selectedGeneratorKey, generator, seed));
|
||||
IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_NOISE_EXPLORER_GENERATOR_SEED, MessageArgument.untrusted("value", generatorKey.trim()), MessageArgument.untrusted("seed", seed)));
|
||||
return 1;
|
||||
return openStudioApp(source, engine, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_NOISE_EXPLORER_ON_SERVER_DISPLAY));
|
||||
}
|
||||
|
||||
private static int map(NativeCommandSource source) {
|
||||
NativeWorld level = source.world();
|
||||
Engine engine = IrisModdedCommands.engineFor(level);
|
||||
Engine engine = IrisModdedCommands.engineFor(source.world());
|
||||
if (engine == null) {
|
||||
IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_THIS_DIMENSION_IS_NOT_GENERATED_BY_IRIS_STAND_IRIS_STUDIO));
|
||||
return 0;
|
||||
}
|
||||
if (!GuiHost.isAvailable() || !IrisSettings.get().getGui().isUseServerLaunchedGuis()) {
|
||||
IrisModdedCommands.fail(source, guiUnavailableMessage());
|
||||
return 0;
|
||||
}
|
||||
NativeProtocolPlayer player = source.player();
|
||||
ModdedGuiHost.bindContext(worldView(source.server(), level), engine, player == null ? null : player.id());
|
||||
MapWindow.openMap(mapStart(engine, player));
|
||||
IrisModdedCommands.ok(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_VISION_MAP_ON_SERVER_DISPLAY, MessageArgument.untrusted("value", level.name())));
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Modded worlds have no Bukkit world id; the map finds the engine again through the bound GUI context.
|
||||
private static PaletteExplorerStart mapStart(Engine engine, NativeProtocolPlayer player) {
|
||||
IrisWorld world = engine.getWorld();
|
||||
NativeWorld level = world == null ? null : world.platformWorld();
|
||||
boolean inWorld = player != null && player.connected() && level != null && player.inWorld(level);
|
||||
return new PaletteExplorerStart(engine, null, player == null ? null : player.id(), null,
|
||||
inWorld ? player.x() : 0D, inWorld ? player.z() : 0D);
|
||||
return openStudioApp(source, engine, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_VISION_MAP_ON_SERVER_DISPLAY, MessageArgument.untrusted("value", source.world().name())));
|
||||
}
|
||||
|
||||
private static int imageMap(NativeCommandSource source) {
|
||||
NativeWorld level = source.world();
|
||||
Engine engine = IrisModdedCommands.engineFor(level);
|
||||
Engine engine = IrisModdedCommands.engineFor(source.world());
|
||||
if (engine == null) {
|
||||
IrisModdedCommands.fail(source, IrisLanguage.plain(
|
||||
ModdedCommandMessages.MODDED_STUDIO_COMMANDS_IMAGE_MAP_REQUIRES_IRIS_DIMENSION
|
||||
));
|
||||
return 0;
|
||||
}
|
||||
if (!GuiHost.isAvailable() || !IrisSettings.get().getGui().isUseServerLaunchedGuis()) {
|
||||
return openStudioApp(source, engine, IrisLanguage.plain(
|
||||
ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_IMAGE_MAP_STUDIO_ON_SERVER_DISPLAY,
|
||||
MessageArgument.untrusted("value", source.world().name())
|
||||
));
|
||||
}
|
||||
|
||||
/** Opens the studio app on the source's world, or logs its link when no app is set up. */
|
||||
private static int openStudioApp(NativeCommandSource source, Engine engine, String openedMessage) {
|
||||
if (GuiHost.isDesktopSuppressed()) {
|
||||
IrisModdedCommands.fail(source, guiUnavailableMessage());
|
||||
return 0;
|
||||
}
|
||||
NativeWorld level = source.world();
|
||||
NativeProtocolPlayer player = source.player();
|
||||
ModdedGuiHost.bindContext(worldView(source.server(), level), engine, player == null ? null : player.id());
|
||||
MapWindow.openImageMaps(mapStart(engine, player));
|
||||
IrisModdedCommands.ok(source, IrisLanguage.plain(
|
||||
ModdedCommandMessages.MODDED_STUDIO_COMMANDS_OPENING_IMAGE_MAP_STUDIO_ON_SERVER_DISPLAY,
|
||||
MessageArgument.untrusted("value", level.name())
|
||||
));
|
||||
UUID openerId = player == null ? null : player.id();
|
||||
ModdedGuiHost.bindContext(worldView(source.server(), level), engine, openerId);
|
||||
try {
|
||||
StudioBridge bridge = StudioBridges.open(level.name(), () -> engine, openerId);
|
||||
if (!StudioWindow.show(bridge)) {
|
||||
IrisLogging.info("Iris Studio link for %s: %s", level.name(), bridge.link());
|
||||
}
|
||||
} catch (IOException error) {
|
||||
IrisModdedCommands.fail(source, "Could not open the studio bridge: " + error.getMessage());
|
||||
return 0;
|
||||
}
|
||||
IrisModdedCommands.ok(source, openedMessage);
|
||||
return 1;
|
||||
}
|
||||
|
||||
@@ -349,12 +320,12 @@ public final class ModdedStudioCommands {
|
||||
if (!open) {
|
||||
return 1;
|
||||
}
|
||||
if (!GuiHost.isAvailable() || !Desktop.isDesktopSupported()) {
|
||||
if (!GuiHost.isAvailable() || !FileOpener.isDesktopAvailable()) {
|
||||
IrisModdedCommands.fail(source, guiUnavailableMessage());
|
||||
return 0;
|
||||
}
|
||||
try {
|
||||
Desktop.getDesktop().open(workspace);
|
||||
FileOpener.open(workspace);
|
||||
} catch (Throwable e) {
|
||||
ModdedIrisLog.error("Iris workspace open failed for {}", workspace, e);
|
||||
IrisModdedCommands.fail(source, IrisLanguage.plain(ModdedCommandMessages.MODDED_STUDIO_COMMANDS_COULD_NOT_OPEN, MessageArgument.untrusted("value", workspace.getName()), MessageArgument.untrusted("value2", e.getClass().getSimpleName())));
|
||||
@@ -1156,7 +1127,7 @@ public final class ModdedStudioCommands {
|
||||
int diameter = radius * 2;
|
||||
int totalTasks = diameter * diameter;
|
||||
KMap<String, AtomicInteger> counts = new KMap<>();
|
||||
engine.getDimension().getRegions().forEach((String key) -> counts.put(key, new AtomicInteger(0)));
|
||||
engine.getDimension().getRegionKeys().forEach((String key) -> counts.put(key, new AtomicInteger(0)));
|
||||
// finally-scoped: a throw mid-scan previously leaked the sampler's whole
|
||||
// ForkJoinPool (close() is the only thing that shuts it down).
|
||||
MultiBurst burst = new MultiBurst("Region Sampler");
|
||||
|
||||
+3
-2
@@ -1,6 +1,7 @@
|
||||
package art.arcane.iris.modded;
|
||||
|
||||
import art.arcane.iris.generation.biome.IrisBiome;
|
||||
import art.arcane.iris.generation.biome.IrisBiomeEntry;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.generation.runtime.DimensionStackLayout;
|
||||
import art.arcane.iris.generation.terrain.IrisDimension;
|
||||
@@ -174,9 +175,9 @@ public class ModdedBiomePolicyTest {
|
||||
isles.setLoadKey("isles");
|
||||
IrisBiome meadow = new IrisBiome().setDerivative("minecraft:plains");
|
||||
meadow.setLoadKey("meadow");
|
||||
IrisRegion main = new IrisRegion().setLandBiomes(new KList<>("meadow"));
|
||||
IrisRegion main = new IrisRegion().setLandBiomes(IrisBiomeEntry.plainList("meadow"));
|
||||
main.setLoadKey("main");
|
||||
IrisRegion archipelago = new IrisRegion().setLandBiomes(new KList<>("isles"));
|
||||
IrisRegion archipelago = new IrisRegion().setLandBiomes(IrisBiomeEntry.plainList("isles"));
|
||||
archipelago.setLoadKey("archipelago");
|
||||
IrisDimension dimension = mock(IrisDimension.class);
|
||||
when(dimension.getReachableBiomes(any())).thenReturn(new KList<>(meadow, isles));
|
||||
|
||||
@@ -404,6 +404,8 @@ public class IrisSettings {
|
||||
public boolean disableTimeAndWeather = true;
|
||||
public boolean entitySpawning = true;
|
||||
public boolean autoStartDefaultStudio = false;
|
||||
public String studioApp = "";
|
||||
public String electron = "electron";
|
||||
}
|
||||
|
||||
@Data
|
||||
|
||||
@@ -33,6 +33,8 @@ import art.arcane.iris.generation.terrain.InferredType;
|
||||
import art.arcane.iris.generation.terrain.IrisDimension;
|
||||
import art.arcane.iris.generation.terrain.IrisTerrain3D;
|
||||
import art.arcane.iris.pack.validation.CompatPools;
|
||||
import art.arcane.iris.pack.value.Weighted;
|
||||
import art.arcane.iris.pack.value.WeightedReference;
|
||||
import art.arcane.iris.structure.object.IrisObjectPlacement;
|
||||
import art.arcane.iris.structure.placement.IrisStructurePlacement;
|
||||
import art.arcane.iris.world.entity.IrisEffect;
|
||||
@@ -120,6 +122,7 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
|
||||
private final transient AtomicCache<Integer> maxWithObjectHeight = new AtomicCache<>();
|
||||
private final transient AtomicCache<IrisBiome> realCarveBiome = new AtomicCache<>();
|
||||
private final transient AtomicCache<KList<IrisBiome>> realChildren = new AtomicCache<>();
|
||||
private final transient AtomicCache<KList<Weighted<IrisBiome>>> weightedChildren = new AtomicCache<>();
|
||||
private final transient IrisBiomeLayerHeightCache layerHeightGenerators = new IrisBiomeLayerHeightCache();
|
||||
private final transient IrisBiomeLayerHeightCache layerCeilingHeightGenerators = new IrisBiomeLayerHeightCache();
|
||||
private final transient IrisBiomeLayerHeightCache layerSeaHeightGenerators = new IrisBiomeLayerHeightCache();
|
||||
@@ -194,10 +197,9 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
|
||||
@DependsOn({"children"})
|
||||
@Description("If this biome has children biomes, and the gen layer chooses one of this biomes children, How will it be shaped?")
|
||||
private IrisGeneratorStyle childStyle = NoiseStyle.CELLULAR_IRIS_DOUBLE.style();
|
||||
@RegistryListResource(IrisBiome.class)
|
||||
@ArrayType(min = 1, type = String.class)
|
||||
@Description("List any biome names (file names without.json) here as children. Portions of this biome can sometimes morph into their children. Iris supports cyclic relationships such as A > B > A > B. Iris will stop checking 4 biomes down the tree.")
|
||||
private KList<String> children = new KList<>();
|
||||
@ArrayType(min = 1, type = IrisBiomeEntry.class)
|
||||
@Description("List any biome names (file names without.json) here as children, or objects with a biome and a weight. Portions of this biome can sometimes morph into their children. Iris supports cyclic relationships such as A > B > A > B. Iris will stop checking 4 biomes down the tree. When any child is written as an object, the list is weighted: the parent itself only stays in the mix if it is listed too.")
|
||||
private KList<IrisBiomeEntry> children = new KList<>();
|
||||
@RegistryListResource(IrisBiome.class)
|
||||
@Description("Registers the referenced biome with this pack's reachable biome set. It is NOT applied as a substitute under carvings; cave biomes come from the region's caveBiomes list.")
|
||||
private String carvingBiome = "";
|
||||
@@ -634,22 +636,39 @@ public class IrisBiome extends IrisRegistrant implements Rarity {
|
||||
return IrisBiomeDerivatives.getCustomBiome(this, rng, engine, x, y, z);
|
||||
}
|
||||
|
||||
public KList<String> getChildKeys() {
|
||||
return WeightedReference.keys(children);
|
||||
}
|
||||
|
||||
public boolean hasWeightedChildren() {
|
||||
return WeightedReference.anyWrittenAsObject(children);
|
||||
}
|
||||
|
||||
public KList<IrisBiome> getRealChildren(DataProvider g) {
|
||||
return realChildren.aquire(() ->
|
||||
{
|
||||
IrisData data = g == null ? null : g.getData();
|
||||
return CompatPools.load(data == null ? null : data.getBiomeLoader(), getChildren(), data,
|
||||
return CompatPools.load(data == null ? null : data.getBiomeLoader(), getChildKeys(), data,
|
||||
"biome", getLoadKey(), "children", null);
|
||||
});
|
||||
}
|
||||
|
||||
public KList<Weighted<IrisBiome>> getWeightedChildren(DataProvider g) {
|
||||
return weightedChildren.aquire(() ->
|
||||
{
|
||||
IrisData data = g == null ? null : g.getData();
|
||||
return CompatPools.loadWeighted(data == null ? null : data.getBiomeLoader(), children, data,
|
||||
"biome", getLoadKey(), "children", null);
|
||||
});
|
||||
}
|
||||
|
||||
public KList<String> getAllChildren(DataProvider g, int limit) {
|
||||
KSet<String> m = new KSet<>();
|
||||
m.addAll(getChildren());
|
||||
m.addAll(getChildKeys());
|
||||
limit--;
|
||||
|
||||
if (limit > 0) {
|
||||
for (String i : getChildren()) {
|
||||
for (String i : getChildKeys()) {
|
||||
IrisBiome b = g.getData().getBiomeLoader().load(i);
|
||||
m.addAll(b.getAllChildren(g, limit));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package art.arcane.iris.generation.biome;
|
||||
|
||||
import art.arcane.iris.pack.schema.annotation.MaxNumber;
|
||||
import art.arcane.iris.pack.schema.annotation.MinNumber;
|
||||
import art.arcane.iris.pack.schema.annotation.RegistryListResource;
|
||||
import art.arcane.iris.pack.schema.annotation.Required;
|
||||
import art.arcane.iris.pack.value.Weighted;
|
||||
import art.arcane.iris.pack.value.WeightedReference;
|
||||
import art.arcane.iris.pack.value.WeightedReferenceAdapter;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.documentation.Description;
|
||||
import com.google.gson.annotations.JsonAdapter;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@Description("A biome in a list a noise picks from")
|
||||
@Data
|
||||
@JsonAdapter(IrisBiomeEntry.Adapter.class)
|
||||
public class IrisBiomeEntry implements WeightedReference {
|
||||
@Required
|
||||
@RegistryListResource(IrisBiome.class)
|
||||
@Description("The biome (file name without .json)")
|
||||
private String biome;
|
||||
@MinNumber(Weighted.MIN_WEIGHT)
|
||||
@MaxNumber(Weighted.MAX_WEIGHT)
|
||||
@Description("A weight of two is just as if this entry were listed twice in a row, making the biome more common. The noise picks along the list in the order it is written.")
|
||||
private int weight = 1;
|
||||
private transient boolean writtenAsObject;
|
||||
|
||||
public IrisBiomeEntry(String biome, int weight, boolean writtenAsObject) {
|
||||
this.biome = biome;
|
||||
this.weight = weight;
|
||||
this.writtenAsObject = writtenAsObject;
|
||||
}
|
||||
|
||||
public static IrisBiomeEntry plain(String biome) {
|
||||
return new IrisBiomeEntry(biome, Weighted.MIN_WEIGHT, false);
|
||||
}
|
||||
|
||||
public static KList<IrisBiomeEntry> plainList(String... biomes) {
|
||||
KList<IrisBiomeEntry> entries = new KList<>();
|
||||
for (String biome : biomes) {
|
||||
entries.add(plain(biome));
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getReferenceKey() {
|
||||
return biome;
|
||||
}
|
||||
|
||||
public static final class Adapter extends WeightedReferenceAdapter<IrisBiomeEntry> {
|
||||
public Adapter() {
|
||||
super("biome");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected IrisBiomeEntry create(String key, int weight, boolean writtenAsObject) {
|
||||
return new IrisBiomeEntry(key, weight, writtenAsObject);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -293,13 +293,13 @@ public final class IrisImageMapRuntime {
|
||||
if (region == null) {
|
||||
continue;
|
||||
}
|
||||
if (region.getLandBiomes().contains(biomeKey)) {
|
||||
if (region.getLandBiomeKeys().contains(biomeKey)) {
|
||||
types.add(InferredType.LAND);
|
||||
}
|
||||
if (region.getSeaBiomes().contains(biomeKey)) {
|
||||
if (region.getSeaBiomeKeys().contains(biomeKey)) {
|
||||
types.add(InferredType.SEA);
|
||||
}
|
||||
if (region.getShoreBiomes().contains(biomeKey)) {
|
||||
if (region.getShoreBiomeKeys().contains(biomeKey)) {
|
||||
types.add(InferredType.SHORE);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -71,16 +71,16 @@ public final class BiomeLocator implements Locator<IrisBiome> {
|
||||
Set<String> caveHosts = new HashSet<>();
|
||||
boolean surfaceAllowed = GenerationFindCatalog.hasRetainedSurfaceBiome(engine, key);
|
||||
for (IrisRegion region : engine.getDimension().getAllRegions(engine)) {
|
||||
for (String root : region.getLandBiomes()) {
|
||||
for (String root : region.getLandBiomeKeys()) {
|
||||
surfaceAllowed |= caveBranch(engine, root).contains(key);
|
||||
}
|
||||
for (String root : region.getSeaBiomes()) {
|
||||
for (String root : region.getSeaBiomeKeys()) {
|
||||
surfaceAllowed |= caveBranch(engine, root).contains(key);
|
||||
}
|
||||
for (String root : region.getShoreBiomes()) {
|
||||
for (String root : region.getShoreBiomeKeys()) {
|
||||
surfaceAllowed |= caveBranch(engine, root).contains(key);
|
||||
}
|
||||
for (String root : region.getCaveBiomes()) {
|
||||
for (String root : region.getCaveBiomeKeys()) {
|
||||
Set<String> branch = caveBranch(engine, root);
|
||||
if (branch.contains(key)) {
|
||||
caveHosts.addAll(branch);
|
||||
@@ -122,7 +122,7 @@ public final class BiomeLocator implements Locator<IrisBiome> {
|
||||
}
|
||||
IrisBiome biome = engine.getData().getBiomeLoader().load(candidate);
|
||||
if (biome != null) {
|
||||
pending.addAll(biome.getChildren());
|
||||
pending.addAll(biome.getChildKeys());
|
||||
}
|
||||
}
|
||||
return visited;
|
||||
|
||||
@@ -115,7 +115,7 @@ public final class BiomeSearchFilter {
|
||||
if (region == null) {
|
||||
continue;
|
||||
}
|
||||
for (String key : region.getCaveBiomes()) {
|
||||
for (String key : region.getCaveBiomeKeys()) {
|
||||
if (target(key)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -385,7 +385,7 @@ public final class HintedLocator<T> implements Locator<T> {
|
||||
|
||||
KSet<String> caveRegions = new KSet<>();
|
||||
for (IrisRegion region : engine.getDimension().getAllRegions(engine)) {
|
||||
if (region != null && region.getCaveBiomes().contains(biomeKey)) {
|
||||
if (region != null && region.getCaveBiomeKeys().contains(biomeKey)) {
|
||||
caveRegions.add(region.getLoadKey());
|
||||
}
|
||||
}
|
||||
@@ -417,7 +417,7 @@ public final class HintedLocator<T> implements Locator<T> {
|
||||
KSet<String> caveRegions = new KSet<>();
|
||||
|
||||
for (IrisRegion region : engine.getDimension().getAllRegions(engine)) {
|
||||
if (region != null && region.getCaveBiomes().contains(biomeKey)) {
|
||||
if (region != null && region.getCaveBiomeKeys().contains(biomeKey)) {
|
||||
caveRegions.add(region.getLoadKey());
|
||||
}
|
||||
}
|
||||
@@ -445,7 +445,7 @@ public final class HintedLocator<T> implements Locator<T> {
|
||||
}
|
||||
}
|
||||
|
||||
if (!engine.getDimension().getRegions().contains(regionKey)) {
|
||||
if (!engine.getDimension().getRegionKeys().contains(regionKey)) {
|
||||
return SearchPlan.impossible();
|
||||
}
|
||||
|
||||
@@ -482,21 +482,21 @@ public final class HintedLocator<T> implements Locator<T> {
|
||||
|
||||
boolean hosted = false;
|
||||
|
||||
for (String root : region.getLandBiomes()) {
|
||||
for (String root : region.getLandBiomeKeys()) {
|
||||
if (source.closurePlacesObject(root, objectKey)) {
|
||||
landHosts.add(root);
|
||||
hosted = true;
|
||||
}
|
||||
}
|
||||
|
||||
for (String root : region.getSeaBiomes()) {
|
||||
for (String root : region.getSeaBiomeKeys()) {
|
||||
if (source.closurePlacesObject(root, objectKey)) {
|
||||
seaHosts.add(root);
|
||||
hosted = true;
|
||||
}
|
||||
}
|
||||
|
||||
for (String root : region.getShoreBiomes()) {
|
||||
for (String root : region.getShoreBiomeKeys()) {
|
||||
if (source.closurePlacesObject(root, objectKey)) {
|
||||
shoreHosts.add(root);
|
||||
hosted = true;
|
||||
@@ -546,21 +546,21 @@ public final class HintedLocator<T> implements Locator<T> {
|
||||
|
||||
boolean hosted = false;
|
||||
|
||||
for (String root : region.getLandBiomes()) {
|
||||
for (String root : region.getLandBiomeKeys()) {
|
||||
if (source.closureContains(root, biomeKeys)) {
|
||||
landHosts.add(root);
|
||||
hosted = true;
|
||||
}
|
||||
}
|
||||
|
||||
for (String root : region.getSeaBiomes()) {
|
||||
for (String root : region.getSeaBiomeKeys()) {
|
||||
if (source.closureContains(root, biomeKeys)) {
|
||||
seaHosts.add(root);
|
||||
hosted = true;
|
||||
}
|
||||
}
|
||||
|
||||
for (String root : region.getShoreBiomes()) {
|
||||
for (String root : region.getShoreBiomeKeys()) {
|
||||
if (source.closureContains(root, biomeKeys)) {
|
||||
shoreHosts.add(root);
|
||||
hosted = true;
|
||||
@@ -689,7 +689,7 @@ public final class HintedLocator<T> implements Locator<T> {
|
||||
continue;
|
||||
}
|
||||
|
||||
for (String child : biome.getChildren()) {
|
||||
for (String child : biome.getChildKeys()) {
|
||||
if (child != null && !visited.contains(child)) {
|
||||
queue.add(child);
|
||||
}
|
||||
@@ -720,7 +720,7 @@ public final class HintedLocator<T> implements Locator<T> {
|
||||
continue;
|
||||
}
|
||||
biomes.add(biome);
|
||||
for (String child : biome.getChildren()) {
|
||||
for (String child : biome.getChildKeys()) {
|
||||
if (child != null && !visited.contains(child)) {
|
||||
queue.add(child);
|
||||
}
|
||||
@@ -755,7 +755,7 @@ public final class HintedLocator<T> implements Locator<T> {
|
||||
return true;
|
||||
}
|
||||
|
||||
for (String child : biome.getChildren()) {
|
||||
for (String child : biome.getChildKeys()) {
|
||||
if (child != null && !visited.contains(child)) {
|
||||
queue.add(child);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.generation.mantle;
|
||||
|
||||
import art.arcane.iris.generation.cave.IrisCaveProfile;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.generation.runtime.IrisEngineMantle;
|
||||
import art.arcane.volmlib.util.mantle.runtime.Mantle;
|
||||
import art.arcane.volmlib.util.matter.Matter;
|
||||
import art.arcane.volmlib.util.matter.MatterCavern;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
/**
|
||||
* Carves one cave profile with the engine's own carver over a square of flat ground, in a mantle of its own so the
|
||||
* world's is left alone, and says which blocks it opened.
|
||||
*/
|
||||
public final class CaveProfilePreview {
|
||||
private static final int CHUNK_BLOCKS = 16;
|
||||
private static final int CHUNK_COLUMNS = CHUNK_BLOCKS * CHUNK_BLOCKS;
|
||||
private static final int PREFETCH_CHUNKS = 0;
|
||||
private static final int ACCESS_CHUNKS = 1;
|
||||
|
||||
private CaveProfilePreview() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The carved space of a square, {@code size} blocks across and a whole number of chunks, from {@code bottomY} up to
|
||||
* and including {@code surfaceY}, both in engine-local Y (0 is the bottom of the dimension).
|
||||
*
|
||||
* @return one flag per block, {@code (y - bottomY) * size² + z * size + x}
|
||||
*/
|
||||
public static boolean[] carve(Engine engine, IrisCaveProfile profile, int originX, int size, int bottomY, int surfaceY)
|
||||
throws IOException {
|
||||
int height = surfaceY - bottomY + 1;
|
||||
boolean[] carved = new boolean[height * size * size];
|
||||
Path folder = Files.createTempDirectory("iris-cave-preview");
|
||||
Mantle<Matter> mantle = IrisEngineMantle.createMantle(engine, folder, engine::getData);
|
||||
try {
|
||||
IrisCaveCarver3D carver = new IrisCaveCarver3D(engine, profile);
|
||||
int[] surface = new int[CHUNK_COLUMNS];
|
||||
Arrays.fill(surface, surfaceY);
|
||||
double[] weights = new double[CHUNK_COLUMNS];
|
||||
Arrays.fill(weights, 1D);
|
||||
int firstChunkX = Math.floorDiv(originX, CHUNK_BLOCKS);
|
||||
int chunks = size / CHUNK_BLOCKS;
|
||||
for (int chunkZ = 0; chunkZ < chunks; chunkZ++) {
|
||||
for (int chunkX = 0; chunkX < chunks; chunkX++) {
|
||||
int worldChunkX = firstChunkX + chunkX;
|
||||
try (MantleWriter writer = new MantleWriter(engine.getMantle(), mantle, worldChunkX, chunkZ, PREFETCH_CHUNKS, ACCESS_CHUNKS, false)) {
|
||||
carver.carve(writer, worldChunkX, chunkZ, weights, 0D, 0D, null, surface);
|
||||
}
|
||||
readCarved(mantle, carved, worldChunkX, chunkZ, chunkX, chunkZ, size, bottomY, surfaceY);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
mantle.close();
|
||||
deleteQuietly(folder);
|
||||
}
|
||||
return carved;
|
||||
}
|
||||
|
||||
private static void readCarved(Mantle<Matter> mantle, boolean[] carved, int worldChunkX, int worldChunkZ, int chunkX, int chunkZ,
|
||||
int size, int bottomY, int surfaceY) {
|
||||
for (int y = bottomY; y <= surfaceY; y++) {
|
||||
for (int z = 0; z < CHUNK_BLOCKS; z++) {
|
||||
for (int x = 0; x < CHUNK_BLOCKS; x++) {
|
||||
MatterCavern cavern = mantle.get(worldChunkX * CHUNK_BLOCKS + x, y, worldChunkZ * CHUNK_BLOCKS + z, MatterCavern.class);
|
||||
if (cavern == null) {
|
||||
continue;
|
||||
}
|
||||
int cell = (y - bottomY) * size * size + (chunkZ * CHUNK_BLOCKS + z) * size + chunkX * CHUNK_BLOCKS + x;
|
||||
carved[cell] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static void deleteQuietly(Path folder) {
|
||||
try (Stream<Path> paths = Files.walk(folder)) {
|
||||
paths.sorted(Comparator.reverseOrder()).forEach(path -> path.toFile().delete());
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
}
|
||||
+38
-24
@@ -1,6 +1,7 @@
|
||||
package art.arcane.iris.generation.runtime;
|
||||
|
||||
import art.arcane.iris.generation.stream.GenerationStreams;
|
||||
import art.arcane.iris.generation.stream.WeightedStream;
|
||||
|
||||
import art.arcane.iris.configuration.IrisSettings;
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
@@ -221,14 +222,8 @@ public final class DimensionTerrainContext implements DataProvider {
|
||||
ProceduralStream<Double> regionStyleStream = dimension.getRegionStyle()
|
||||
.create(rng.nextParallelRNG(883), dimensionData).stream()
|
||||
.zoom(dimension.getRegionZoom());
|
||||
KList<IrisRegion> regionPool = new KList<>();
|
||||
for (IrisRegion region : dimensionData.getRegionLoader().loadAll(dimension.getRegions())) {
|
||||
if (!region.isCompatExcluded()) {
|
||||
regionPool.add(region);
|
||||
}
|
||||
}
|
||||
ProceduralStream<IrisRegion> proceduralRegionStream = focusRegion == null
|
||||
? regionStyleStream.selectRarity(regionPool)
|
||||
? selectRegions(dimension, dimensionData, regionStyleStream)
|
||||
: ProceduralStream.of(
|
||||
(x, z) -> focusRegion,
|
||||
Interpolated.of(value -> 0D, value -> focusRegion)
|
||||
@@ -503,6 +498,35 @@ public final class DimensionTerrainContext implements DataProvider {
|
||||
return mappedBlock == null ? proceduralBlock : mappedBlock;
|
||||
}
|
||||
|
||||
static ProceduralStream<IrisRegion> selectRegions(
|
||||
IrisDimension dimension,
|
||||
IrisData data,
|
||||
ProceduralStream<Double> regionStyleStream
|
||||
) {
|
||||
if (dimension.hasWeightedRegions()) {
|
||||
return new WeightedStream<>(regionStyleStream, dimension.getWeightedRegions(data));
|
||||
}
|
||||
KList<IrisRegion> regionPool = new KList<>();
|
||||
for (IrisRegion region : data.getRegionLoader().loadAll(dimension.getRegionKeys())) {
|
||||
if (!region.isCompatExcluded()) {
|
||||
regionPool.add(region);
|
||||
}
|
||||
}
|
||||
return regionStyleStream.selectRarity(regionPool);
|
||||
}
|
||||
|
||||
static ProceduralStream<IrisBiome> selectBiomes(
|
||||
ProceduralStream<Double> pickNoise,
|
||||
IrisData data,
|
||||
IrisRegion region,
|
||||
InferredType type
|
||||
) {
|
||||
if (region.hasWeightedBiomes(type)) {
|
||||
return new WeightedStream<>(pickNoise, region.getWeightedBiomes(data, type));
|
||||
}
|
||||
return pickNoise.selectRarity(loadInferredBiomes(data, region.getBiomeKeys(type), type));
|
||||
}
|
||||
|
||||
private static Map<IrisRegion, Map<InferredType, ProceduralStream<IrisBiome>>> compileInferredBiomeStreams(
|
||||
IrisDimension dimension,
|
||||
IrisData data,
|
||||
@@ -535,23 +559,20 @@ public final class DimensionTerrainContext implements DataProvider {
|
||||
InferredType type
|
||||
) {
|
||||
return switch (type) {
|
||||
case LAND -> dimension.getLandBiomeStyle()
|
||||
case LAND -> selectBiomes(dimension.getLandBiomeStyle()
|
||||
.create(rng.nextParallelRNG(InferredType.LAND.ordinal()), data).stream()
|
||||
.zoom(dimension.getBiomeZoom())
|
||||
.zoom(dimension.getLandZoom())
|
||||
.zoom(region.getLandBiomeZoom())
|
||||
.selectRarity(loadInferredBiomes(data, region.getLandBiomes(), InferredType.LAND));
|
||||
case SEA -> dimension.getSeaBiomeStyle()
|
||||
.zoom(region.getLandBiomeZoom()), data, region, InferredType.LAND);
|
||||
case SEA -> selectBiomes(dimension.getSeaBiomeStyle()
|
||||
.create(rng.nextParallelRNG(InferredType.SEA.ordinal()), data).stream()
|
||||
.zoom(dimension.getBiomeZoom())
|
||||
.zoom(dimension.getSeaZoom())
|
||||
.zoom(region.getSeaBiomeZoom())
|
||||
.selectRarity(loadInferredBiomes(data, region.getSeaBiomes(), InferredType.SEA));
|
||||
case SHORE -> dimension.getShoreBiomeStyle()
|
||||
.zoom(region.getSeaBiomeZoom()), data, region, InferredType.SEA);
|
||||
case SHORE -> selectBiomes(dimension.getShoreBiomeStyle()
|
||||
.create(rng.nextParallelRNG(InferredType.SHORE.ordinal()), data).stream()
|
||||
.zoom(dimension.getBiomeZoom())
|
||||
.zoom(region.getShoreBiomeZoom())
|
||||
.selectRarity(loadInferredBiomes(data, region.getShoreBiomes(), InferredType.SHORE));
|
||||
.zoom(region.getShoreBiomeZoom()), data, region, InferredType.SHORE);
|
||||
default -> throw new IllegalArgumentException("Unsupported stacked terrain biome type: " + type);
|
||||
};
|
||||
}
|
||||
@@ -607,14 +628,7 @@ public final class DimensionTerrainContext implements DataProvider {
|
||||
synchronized (childSelectionPlans) {
|
||||
selectionPlan = childSelectionPlans.get(biome);
|
||||
if (selectionPlan == null) {
|
||||
KList<IrisBiome> options = new KList<>();
|
||||
for (IrisBiome child : biome.getRealChildren(dataProvider)) {
|
||||
if (child != null) {
|
||||
options.add(child);
|
||||
}
|
||||
}
|
||||
options.add(biome);
|
||||
selectionPlan = IrisComplex.ChildSelectionPlan.create(options);
|
||||
selectionPlan = IrisComplex.ChildSelectionPlan.of(biome, dataProvider);
|
||||
childSelectionPlans.put(biome, selectionPlan);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ import art.arcane.iris.generation.stream.GenerationStreams;
|
||||
import art.arcane.iris.generation.stream.RarityStream;
|
||||
import art.arcane.iris.generation.stream.CachedStream2D;
|
||||
import art.arcane.iris.generation.stream.ProvisionalSampling;
|
||||
import art.arcane.iris.generation.stream.WeightedStream;
|
||||
import art.arcane.iris.generation.subterrain.SubterrainPlanner;
|
||||
import art.arcane.iris.generation.subterrain.SubterrainRasterizer;
|
||||
|
||||
@@ -63,6 +64,7 @@ import art.arcane.iris.generation.terrain.InferredType;
|
||||
import art.arcane.iris.generation.biome.IrisBiome;
|
||||
import art.arcane.iris.generation.biome.IrisBiomeGeneratorLink;
|
||||
import art.arcane.iris.pack.value.IrisRaritySelection;
|
||||
import art.arcane.iris.pack.value.Weighted;
|
||||
import art.arcane.iris.generation.noise.IrisGenerator;
|
||||
import art.arcane.iris.generation.noise.IrisGeneratorStyle;
|
||||
import art.arcane.iris.generation.terrain.ContinentGenerator;
|
||||
@@ -368,7 +370,7 @@ public class IrisComplex implements DataProvider {
|
||||
prepareInferredBiomes(focusRegion, preparedRegions);
|
||||
focusRegion.getNaturalBiomes(this).forEach(this::registerGenerators);
|
||||
} else {
|
||||
engine.getDimension().getRegions().forEach(regionKey -> {
|
||||
engine.getDimension().getRegionKeys().forEach(regionKey -> {
|
||||
IrisRegion region = data.getRegionLoader().load(regionKey);
|
||||
if (region == null || region.isCompatExcluded()) {
|
||||
return;
|
||||
@@ -1166,8 +1168,10 @@ public class IrisComplex implements DataProvider {
|
||||
InferredType inferredType,
|
||||
IrisBiome emptyBiome
|
||||
) {
|
||||
ProceduralStream<IrisBiome> picked = new RarityStream<>(biomePickNoiseStream(engine.getDimension(), region, inferredType),
|
||||
loadInferredBiomes(biomeKeys(region, inferredType), inferredType));
|
||||
ProceduralStream<Double> pickNoise = biomePickNoiseStream(engine.getDimension(), region, inferredType);
|
||||
ProceduralStream<IrisBiome> picked = region.hasWeightedBiomes(inferredType)
|
||||
? new WeightedStream<>(pickNoise, region.getWeightedBiomes(data, inferredType))
|
||||
: new RarityStream<>(pickNoise, loadInferredBiomes(biomeKeys(region, inferredType), inferredType));
|
||||
return inferredType == InferredType.CAVE ? picked.onNull(emptyBiome) : picked;
|
||||
}
|
||||
|
||||
@@ -1195,12 +1199,7 @@ public class IrisComplex implements DataProvider {
|
||||
}
|
||||
|
||||
private static KList<String> biomeKeys(IrisRegion region, InferredType inferredType) {
|
||||
return switch (inferredType) {
|
||||
case CAVE -> region.getCaveBiomes();
|
||||
case LAND -> region.getLandBiomes();
|
||||
case SEA -> region.getSeaBiomes();
|
||||
case SHORE -> region.getShoreBiomes();
|
||||
};
|
||||
return region.getBiomeKeys(inferredType);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1234,7 +1233,7 @@ public class IrisComplex implements DataProvider {
|
||||
*/
|
||||
public KList<IrisRegion> noisePickedRegions() {
|
||||
KList<IrisRegion> regions = new KList<>();
|
||||
for (IrisRegion region : data.getRegionLoader().loadAll(terrainEngine.getDimension().getRegions())) {
|
||||
for (IrisRegion region : data.getRegionLoader().loadAll(terrainEngine.getDimension().getRegionKeys())) {
|
||||
if (!region.isCompatExcluded()) {
|
||||
regions.add(region);
|
||||
}
|
||||
@@ -2256,10 +2255,10 @@ public class IrisComplex implements DataProvider {
|
||||
}
|
||||
|
||||
private void prepareInferredBiomes(IrisRegion region, KList<IrisRegion> preparedRegions) {
|
||||
loadInferredBiomes(region.getLandBiomes(), InferredType.LAND);
|
||||
loadInferredBiomes(region.getCaveBiomes(), InferredType.CAVE);
|
||||
loadInferredBiomes(region.getSeaBiomes(), InferredType.SEA);
|
||||
loadInferredBiomes(region.getShoreBiomes(), InferredType.SHORE);
|
||||
loadInferredBiomes(region.getLandBiomeKeys(), InferredType.LAND);
|
||||
loadInferredBiomes(region.getCaveBiomeKeys(), InferredType.CAVE);
|
||||
loadInferredBiomes(region.getSeaBiomeKeys(), InferredType.SEA);
|
||||
loadInferredBiomes(region.getShoreBiomeKeys(), InferredType.SHORE);
|
||||
preparedRegions.add(region);
|
||||
}
|
||||
|
||||
@@ -2383,8 +2382,8 @@ public class IrisComplex implements DataProvider {
|
||||
Set<IrisBiome> reached = Collections.newSetFromMap(new IdentityHashMap<>());
|
||||
ArrayDeque<IrisBiome> pending = new ArrayDeque<>();
|
||||
for (IrisRegion region : regions) {
|
||||
pending.addAll(loadInferredBiomes(region.getLandBiomes(), InferredType.LAND));
|
||||
pending.addAll(loadInferredBiomes(region.getSeaBiomes(), InferredType.SEA));
|
||||
pending.addAll(loadInferredBiomes(region.getLandBiomeKeys(), InferredType.LAND));
|
||||
pending.addAll(loadInferredBiomes(region.getSeaBiomeKeys(), InferredType.SEA));
|
||||
}
|
||||
pending.addAll(imageMapRuntime.getMappedBiomes());
|
||||
while (!pending.isEmpty()) {
|
||||
@@ -2589,16 +2588,7 @@ public class IrisComplex implements DataProvider {
|
||||
return synchronizedPlan;
|
||||
}
|
||||
|
||||
KList<IrisBiome> children = biome.getRealChildren(this);
|
||||
KList<IrisBiome> options = new KList<>();
|
||||
for (IrisBiome child : children) {
|
||||
if (child != null) {
|
||||
options.add(child);
|
||||
}
|
||||
}
|
||||
options.add(biome);
|
||||
|
||||
ChildSelectionPlan createdPlan = ChildSelectionPlan.create(options);
|
||||
ChildSelectionPlan createdPlan = ChildSelectionPlan.of(biome, this);
|
||||
IdentityHashMap<IrisBiome, ChildSelectionPlan> next = new IdentityHashMap<>(childSelectionPlans);
|
||||
next.put(biome, createdPlan);
|
||||
childSelectionPlans = next;
|
||||
@@ -2960,16 +2950,43 @@ public class IrisComplex implements DataProvider {
|
||||
|
||||
static final class ChildSelectionPlan {
|
||||
private final IrisRaritySelection<IrisBiome> selection;
|
||||
private final List<Weighted<IrisBiome>> weightedOptions;
|
||||
|
||||
private ChildSelectionPlan(IrisRaritySelection<IrisBiome> selection) {
|
||||
private ChildSelectionPlan(IrisRaritySelection<IrisBiome> selection, List<Weighted<IrisBiome>> weightedOptions) {
|
||||
this.selection = selection;
|
||||
this.weightedOptions = weightedOptions;
|
||||
}
|
||||
|
||||
static ChildSelectionPlan create(KList<IrisBiome> options) {
|
||||
return new ChildSelectionPlan(IrisRaritySelection.create(options));
|
||||
return new ChildSelectionPlan(IrisRaritySelection.create(options), null);
|
||||
}
|
||||
|
||||
static ChildSelectionPlan createWeighted(List<Weighted<IrisBiome>> options) {
|
||||
return new ChildSelectionPlan(null, List.copyOf(options));
|
||||
}
|
||||
|
||||
static ChildSelectionPlan of(IrisBiome biome, DataProvider provider) {
|
||||
if (biome.hasWeightedChildren()) {
|
||||
KList<Weighted<IrisBiome>> weightedChildren = biome.getWeightedChildren(provider);
|
||||
if (!weightedChildren.isEmpty()) {
|
||||
return createWeighted(weightedChildren);
|
||||
}
|
||||
}
|
||||
|
||||
KList<IrisBiome> options = new KList<>();
|
||||
for (IrisBiome child : biome.getRealChildren(provider)) {
|
||||
if (child != null) {
|
||||
options.add(child);
|
||||
}
|
||||
}
|
||||
options.add(biome);
|
||||
return create(options);
|
||||
}
|
||||
|
||||
IrisBiome select(CNG childCell, double x, double z) {
|
||||
if (weightedOptions != null) {
|
||||
return Weighted.pick(weightedOptions, childCell.noiseFast2D(x, z), Weighted.Edge.LATER);
|
||||
}
|
||||
long maximumIndex = selection.size() - 1L;
|
||||
if (maximumIndex <= 0L) {
|
||||
return selection.get(0L);
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package art.arcane.iris.generation.stream;
|
||||
|
||||
import art.arcane.iris.pack.value.Weighted;
|
||||
import art.arcane.volmlib.util.stream.BasicStream;
|
||||
import art.arcane.volmlib.util.stream.ProceduralStream;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public final class WeightedStream<T> extends BasicStream<T> {
|
||||
private final ProceduralStream<?> noise;
|
||||
private final List<Weighted<T>> entries;
|
||||
|
||||
public WeightedStream(ProceduralStream<?> noise, List<Weighted<T>> entries) {
|
||||
super();
|
||||
this.noise = Objects.requireNonNull(noise, "Weighted noise");
|
||||
this.entries = List.copyOf(entries);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T get(double x, double z) {
|
||||
return Weighted.pick(entries, noise.getDouble(x, z), Weighted.Edge.EARLIER);
|
||||
}
|
||||
|
||||
@Override
|
||||
public T get(double x, double y, double z) {
|
||||
return Weighted.pick(entries, noise.getDouble(x, y, z), Weighted.Edge.EARLIER);
|
||||
}
|
||||
|
||||
@Override
|
||||
public double toDouble(T t) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@Override
|
||||
public T fromDouble(double d) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ package art.arcane.iris.generation.terrain;
|
||||
import art.arcane.iris.world.entity.IrisSpawnGroup;
|
||||
import art.arcane.iris.generation.biome.IrisBiome;
|
||||
import art.arcane.iris.generation.biome.IrisBiomeCustom;
|
||||
import art.arcane.iris.generation.biome.IrisBiomeEntry;
|
||||
import art.arcane.iris.generation.biome.IrisCustomBiomeAliasResolver;
|
||||
import art.arcane.iris.generation.biome.IrisFloatingChildBiomes;
|
||||
import art.arcane.iris.generation.biome.IrisSurfaceLayerFallback;
|
||||
@@ -42,6 +43,8 @@ import art.arcane.iris.generation.noise.NoiseStyle;
|
||||
import art.arcane.iris.generation.terrain.transform.IrisTerrainTransform;
|
||||
import art.arcane.iris.pack.validation.CompatPools;
|
||||
import art.arcane.iris.pack.value.IrisRange;
|
||||
import art.arcane.iris.pack.value.Weighted;
|
||||
import art.arcane.iris.pack.value.WeightedReference;
|
||||
import art.arcane.iris.structure.nativegen.IrisImportedFeatureControl;
|
||||
import art.arcane.iris.structure.nativegen.IrisImportedStructureControl;
|
||||
import art.arcane.iris.structure.object.IrisObjectScale;
|
||||
@@ -251,11 +254,10 @@ public class IrisDimension extends IrisRegistrant {
|
||||
private double allObjectScaleFactor = 1D;
|
||||
@Description("The world environment")
|
||||
private IrisEnvironment environment = IrisEnvironment.NORMAL;
|
||||
@RegistryListResource(IrisRegion.class)
|
||||
@Required
|
||||
@ArrayType(min = 1, type = String.class)
|
||||
@Description("Define all of the regions to include in this dimension. Dimensions -> Regions -> Biomes -> Objects etc")
|
||||
private KList<String> regions = new KList<>();
|
||||
@ArrayType(min = 1, type = IrisRegionEntry.class)
|
||||
@Description("Define all of the regions to include in this dimension, each as a region name or an object with a region and a weight. Dimensions -> Regions -> Biomes -> Objects etc")
|
||||
private KList<IrisRegionEntry> regions = new KList<>();
|
||||
@Required
|
||||
@MinNumber(0)
|
||||
@MaxNumber(1024)
|
||||
@@ -595,9 +597,9 @@ public class IrisDimension extends IrisRegistrant {
|
||||
.getBytes(StandardCharsets.UTF_8));
|
||||
IrisData data = provider.getData();
|
||||
IrisRegion region = new IrisRegion();
|
||||
region.getLandBiomes().add(biomeKey);
|
||||
region.getSeaBiomes().add(biomeKey);
|
||||
region.getShoreBiomes().add(biomeKey);
|
||||
region.getLandBiomes().add(IrisBiomeEntry.plain(biomeKey));
|
||||
region.getSeaBiomes().add(IrisBiomeEntry.plain(biomeKey));
|
||||
region.getShoreBiomes().add(IrisBiomeEntry.plain(biomeKey));
|
||||
region.setLoadKey(key);
|
||||
region.setLoader(data);
|
||||
region.setLoadFile(new File(data.getDataFolder(), data.getRegionLoader().getFolderName() + "/" + key + ".json"));
|
||||
@@ -623,8 +625,9 @@ public class IrisDimension extends IrisRegistrant {
|
||||
return regions.v();
|
||||
}
|
||||
|
||||
for (int index = 0; index < getRegions().size(); index++) {
|
||||
String key = getRegions().get(index);
|
||||
KList<String> regionKeys = getRegionKeys();
|
||||
for (int index = 0; index < regionKeys.size(); index++) {
|
||||
String key = regionKeys.get(index);
|
||||
IrisRegion region = data.getRegionLoader().load(key);
|
||||
if (region == null) {
|
||||
continue;
|
||||
@@ -664,7 +667,7 @@ public class IrisDimension extends IrisRegistrant {
|
||||
public KList<IrisRegion> getAllAnyRegions() {
|
||||
KList<IrisRegion> r = new KList<>();
|
||||
|
||||
for (String i : getRegions()) {
|
||||
for (String i : getRegionKeys()) {
|
||||
r.add(IrisData.loadAnyRegion(i, getLoader()));
|
||||
}
|
||||
|
||||
@@ -746,7 +749,7 @@ public class IrisDimension extends IrisRegistrant {
|
||||
|
||||
visited.add(loadKey);
|
||||
biomes.put(loadKey, biome);
|
||||
addReachableBiomeKeys(pending, biome.getChildren());
|
||||
addReachableBiomeKeys(pending, biome.getChildKeys());
|
||||
addReachableBiomeKey(pending, biome.getCarvingBiome());
|
||||
addListedCaveBiomeKeys(pending, data, biome.getCaves());
|
||||
|
||||
@@ -1318,10 +1321,22 @@ public class IrisDimension extends IrisRegistrant {
|
||||
|
||||
/** The declared region pool with unloadable and gate-excluded regions removed; drops are reported once. */
|
||||
private KList<IrisRegion> resolveRegionPool(IrisData data, List<CompatFinding> sink) {
|
||||
return CompatPools.load(data == null ? null : data.getRegionLoader(), getRegions(), data,
|
||||
return CompatPools.load(data == null ? null : data.getRegionLoader(), getRegionKeys(), data,
|
||||
"dimension", getLoadKey(), "regions", sink);
|
||||
}
|
||||
|
||||
public KList<String> getRegionKeys() {
|
||||
return WeightedReference.keys(regions);
|
||||
}
|
||||
|
||||
public boolean hasWeightedRegions() {
|
||||
return WeightedReference.anyWrittenAsObject(regions);
|
||||
}
|
||||
|
||||
public KList<Weighted<IrisRegion>> getWeightedRegions(IrisData data) {
|
||||
return CompatPools.loadWeighted(data.getRegionLoader(), regions, data, "dimension", getLoadKey(), "regions", null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cascade: a dimension whose every region was excluded cannot generate anything. Pack validation turns this into a
|
||||
* blocking error. Loading regions here is safe - regions never load dimensions.
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
package art.arcane.iris.generation.terrain;
|
||||
|
||||
import art.arcane.iris.generation.biome.IrisBiome;
|
||||
import art.arcane.iris.generation.biome.IrisBiomeEntry;
|
||||
import art.arcane.iris.generation.cave.IrisCave;
|
||||
import art.arcane.iris.generation.decoration.IrisDepositGenerator;
|
||||
import art.arcane.iris.generation.decoration.IrisDepositVariant;
|
||||
@@ -27,6 +28,8 @@ import art.arcane.iris.generation.decoration.IrisOreBands;
|
||||
import art.arcane.iris.generation.decoration.IrisProceduralObjects;
|
||||
import art.arcane.iris.generation.hydrology.config.IrisHydrologyPolicy;
|
||||
import art.arcane.iris.pack.validation.CompatPools;
|
||||
import art.arcane.iris.pack.value.Weighted;
|
||||
import art.arcane.iris.pack.value.WeightedReference;
|
||||
import art.arcane.iris.structure.object.IrisObjectPlacement;
|
||||
import art.arcane.iris.structure.placement.IrisStructurePlacement;
|
||||
import art.arcane.iris.world.entity.IrisEffect;
|
||||
@@ -149,23 +152,19 @@ public class IrisRegion extends IrisRegistrant implements Rarity {
|
||||
private KList<String> caves = new KList<>();
|
||||
@Description("Water settings for this region: rainfall, pond density, where streams and ponds may form, and the fluid that fills them. A value left unset comes from the dimension.")
|
||||
private IrisHydrologyPolicy hydrologyPolicy = null;
|
||||
@RegistryListResource(IrisBiome.class)
|
||||
@Required
|
||||
@ArrayType(min = 1, type = String.class)
|
||||
@Description("A list of root-level biomes in this region. Don't specify child biomes of other biomes here. Just the root parents.")
|
||||
private KList<String> landBiomes = new KList<>();
|
||||
@RegistryListResource(IrisBiome.class)
|
||||
@ArrayType(type = String.class)
|
||||
@Description("A list of root-level sea biomes in this region. Optional: leave empty for land-only dimensions (flat, island, or fully-land worlds where no ocean is generated). Don't specify child biomes of other biomes here. Just the root parents.")
|
||||
private KList<String> seaBiomes = new KList<>();
|
||||
@RegistryListResource(IrisBiome.class)
|
||||
@ArrayType(type = String.class)
|
||||
@Description("A list of root-level shore biomes in this region. Optional: leave empty for land-only dimensions (flat, island, or fully-land worlds where no shoreline is generated). Don't specify child biomes of other biomes here. Just the root parents.")
|
||||
private KList<String> shoreBiomes = new KList<>();
|
||||
@RegistryListResource(IrisBiome.class)
|
||||
@ArrayType(min = 1, type = String.class)
|
||||
@Description("A list of root-level cave biomes in this region, used for carved cave interiors. Don't specify child biomes of other biomes here. Just the root parents.")
|
||||
private KList<String> caveBiomes = new KList<>();
|
||||
@ArrayType(min = 1, type = IrisBiomeEntry.class)
|
||||
@Description("A list of root-level biomes in this region. Each entry is a biome name or an object with a biome and a weight. Don't specify child biomes of other biomes here. Just the root parents.")
|
||||
private KList<IrisBiomeEntry> landBiomes = new KList<>();
|
||||
@ArrayType(type = IrisBiomeEntry.class)
|
||||
@Description("A list of root-level sea biomes in this region. Each entry is a biome name or an object with a biome and a weight. Optional: leave empty for land-only dimensions (flat, island, or fully-land worlds where no ocean is generated). Don't specify child biomes of other biomes here. Just the root parents.")
|
||||
private KList<IrisBiomeEntry> seaBiomes = new KList<>();
|
||||
@ArrayType(type = IrisBiomeEntry.class)
|
||||
@Description("A list of root-level shore biomes in this region. Each entry is a biome name or an object with a biome and a weight. Optional: leave empty for land-only dimensions (flat, island, or fully-land worlds where no shoreline is generated). Don't specify child biomes of other biomes here. Just the root parents.")
|
||||
private KList<IrisBiomeEntry> shoreBiomes = new KList<>();
|
||||
@ArrayType(min = 1, type = IrisBiomeEntry.class)
|
||||
@Description("A list of root-level cave biomes in this region, used for carved cave interiors. Each entry is a biome name or an object with a biome and a weight. Don't specify child biomes of other biomes here. Just the root parents.")
|
||||
private KList<IrisBiomeEntry> caveBiomes = new KList<>();
|
||||
@ArrayType(min = 1, type = IrisDepositGenerator.class)
|
||||
@Description("Define regional deposit generators that add onto the global deposit generators")
|
||||
private KList<IrisDepositGenerator> deposits = new KList<>();
|
||||
@@ -307,13 +306,55 @@ public class IrisRegion extends IrisRegistrant implements Rarity {
|
||||
|
||||
public KSet<String> getNaturalBiomeIds() {
|
||||
KSet<String> names = new KSet<>();
|
||||
names.addAll(landBiomes);
|
||||
names.addAll(caveBiomes);
|
||||
names.addAll(seaBiomes);
|
||||
names.addAll(shoreBiomes);
|
||||
names.addAll(getLandBiomeKeys());
|
||||
names.addAll(getCaveBiomeKeys());
|
||||
names.addAll(getSeaBiomeKeys());
|
||||
names.addAll(getShoreBiomeKeys());
|
||||
return names;
|
||||
}
|
||||
|
||||
public KList<String> getLandBiomeKeys() {
|
||||
return WeightedReference.keys(landBiomes);
|
||||
}
|
||||
|
||||
public KList<String> getSeaBiomeKeys() {
|
||||
return WeightedReference.keys(seaBiomes);
|
||||
}
|
||||
|
||||
public KList<String> getShoreBiomeKeys() {
|
||||
return WeightedReference.keys(shoreBiomes);
|
||||
}
|
||||
|
||||
public KList<String> getCaveBiomeKeys() {
|
||||
return WeightedReference.keys(caveBiomes);
|
||||
}
|
||||
|
||||
public KList<String> getBiomeKeys(InferredType type) {
|
||||
return WeightedReference.keys(getBiomeEntries(type));
|
||||
}
|
||||
|
||||
public KList<IrisBiomeEntry> getBiomeEntries(InferredType type) {
|
||||
return switch (type) {
|
||||
case CAVE -> caveBiomes;
|
||||
case LAND -> landBiomes;
|
||||
case SEA -> seaBiomes;
|
||||
case SHORE -> shoreBiomes;
|
||||
};
|
||||
}
|
||||
|
||||
public boolean hasWeightedBiomes(InferredType type) {
|
||||
return WeightedReference.anyWrittenAsObject(getBiomeEntries(type));
|
||||
}
|
||||
|
||||
public KList<Weighted<IrisBiome>> getWeightedBiomes(IrisData data, InferredType type) {
|
||||
KList<Weighted<IrisBiome>> inferred = new KList<>();
|
||||
for (Weighted<IrisBiome> entry : CompatPools.loadWeighted(data.getBiomeLoader(), getBiomeEntries(type), data,
|
||||
"region", getLoadKey(), type.name().toLowerCase() + "Biomes", null)) {
|
||||
inferred.add(new Weighted<>(entry.value().withInferredType(type), entry.weight()));
|
||||
}
|
||||
return inferred;
|
||||
}
|
||||
|
||||
public KList<IrisBiome> getAllBiomes(IrisDimension dimension, DataProvider g) {
|
||||
return resolveBiomes(g, getAllBiomeIds(dimension, g));
|
||||
}
|
||||
@@ -347,7 +388,7 @@ public class IrisRegion extends IrisRegistrant implements Rarity {
|
||||
|
||||
names.add(biome.getCarvingBiome());
|
||||
b.put(biome.getLoadKey(), biome);
|
||||
names.addAll(biome.getChildren());
|
||||
names.addAll(biome.getChildKeys());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -369,19 +410,19 @@ public class IrisRegion extends IrisRegistrant implements Rarity {
|
||||
}
|
||||
|
||||
public KList<IrisBiome> getRealCaveBiomes(DataProvider g) {
|
||||
return realCaveBiomes.aquire(() -> resolvePool(g, getCaveBiomes(), "caveBiomes", null));
|
||||
return realCaveBiomes.aquire(() -> resolvePool(g, getCaveBiomeKeys(), "caveBiomes", null));
|
||||
}
|
||||
|
||||
public KList<IrisBiome> getRealShoreBiomes(DataProvider g) {
|
||||
return realShoreBiomes.aquire(() -> resolvePool(g, getShoreBiomes(), "shoreBiomes", null));
|
||||
return realShoreBiomes.aquire(() -> resolvePool(g, getShoreBiomeKeys(), "shoreBiomes", null));
|
||||
}
|
||||
|
||||
public KList<IrisBiome> getRealSeaBiomes(DataProvider g) {
|
||||
return realSeaBiomes.aquire(() -> resolvePool(g, getSeaBiomes(), "seaBiomes", null));
|
||||
return realSeaBiomes.aquire(() -> resolvePool(g, getSeaBiomeKeys(), "seaBiomes", null));
|
||||
}
|
||||
|
||||
public KList<IrisBiome> getRealLandBiomes(DataProvider g) {
|
||||
return realLandBiomes.aquire(() -> resolvePool(g, getLandBiomes(), "landBiomes", null));
|
||||
return realLandBiomes.aquire(() -> resolvePool(g, getLandBiomeKeys(), "landBiomes", null));
|
||||
}
|
||||
|
||||
/** A biome reference pool with unloadable and gate-excluded biomes removed; drops are reported once. */
|
||||
@@ -394,10 +435,7 @@ public class IrisRegion extends IrisRegistrant implements Rarity {
|
||||
public KList<IrisBiome> getAllAnyBiomes() {
|
||||
KMap<String, IrisBiome> b = new KMap<>();
|
||||
KSet<String> names = new KSet<>();
|
||||
names.addAll(landBiomes);
|
||||
names.addAll(caveBiomes);
|
||||
names.addAll(seaBiomes);
|
||||
names.addAll(shoreBiomes);
|
||||
names.addAll(getNaturalBiomeIds());
|
||||
|
||||
while (!names.isEmpty()) {
|
||||
for (String i : new KList<>(names)) {
|
||||
@@ -415,7 +453,7 @@ public class IrisRegion extends IrisRegistrant implements Rarity {
|
||||
|
||||
names.add(biome.getCarvingBiome());
|
||||
b.put(biome.getLoadKey(), biome);
|
||||
names.addAll(biome.getChildren());
|
||||
names.addAll(biome.getChildKeys());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -486,9 +524,9 @@ public class IrisRegion extends IrisRegistrant implements Rarity {
|
||||
"structures[" + index + "].caveBiomes");
|
||||
}
|
||||
|
||||
base = evaluateSurfacePoolCompat(data, base, getLandBiomes(), "land");
|
||||
base = evaluateSurfacePoolCompat(data, base, getSeaBiomes(), "sea");
|
||||
return evaluateSurfacePoolCompat(data, base, getShoreBiomes(), "shore");
|
||||
base = evaluateSurfacePoolCompat(data, base, getLandBiomeKeys(), "land");
|
||||
base = evaluateSurfacePoolCompat(data, base, getSeaBiomeKeys(), "sea");
|
||||
return evaluateSurfacePoolCompat(data, base, getShoreBiomeKeys(), "shore");
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
package art.arcane.iris.generation.terrain;
|
||||
|
||||
import art.arcane.iris.pack.schema.annotation.MaxNumber;
|
||||
import art.arcane.iris.pack.schema.annotation.MinNumber;
|
||||
import art.arcane.iris.pack.schema.annotation.RegistryListResource;
|
||||
import art.arcane.iris.pack.schema.annotation.Required;
|
||||
import art.arcane.iris.pack.value.Weighted;
|
||||
import art.arcane.iris.pack.value.WeightedReference;
|
||||
import art.arcane.iris.pack.value.WeightedReferenceAdapter;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.documentation.Description;
|
||||
import com.google.gson.annotations.JsonAdapter;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
import lombok.experimental.Accessors;
|
||||
|
||||
@Accessors(chain = true)
|
||||
@NoArgsConstructor
|
||||
@Description("A region in the dimension's region list")
|
||||
@Data
|
||||
@JsonAdapter(IrisRegionEntry.Adapter.class)
|
||||
public class IrisRegionEntry implements WeightedReference {
|
||||
@Required
|
||||
@RegistryListResource(IrisRegion.class)
|
||||
@Description("The region (file name without .json)")
|
||||
private String region;
|
||||
@MinNumber(Weighted.MIN_WEIGHT)
|
||||
@MaxNumber(Weighted.MAX_WEIGHT)
|
||||
@Description("A weight of two is just as if this entry were listed twice in a row, making the region more common. The noise picks along the list in the order it is written.")
|
||||
private int weight = 1;
|
||||
private transient boolean writtenAsObject;
|
||||
|
||||
public IrisRegionEntry(String region, int weight, boolean writtenAsObject) {
|
||||
this.region = region;
|
||||
this.weight = weight;
|
||||
this.writtenAsObject = writtenAsObject;
|
||||
}
|
||||
|
||||
public static IrisRegionEntry plain(String region) {
|
||||
return new IrisRegionEntry(region, Weighted.MIN_WEIGHT, false);
|
||||
}
|
||||
|
||||
public static KList<IrisRegionEntry> plainList(String... regions) {
|
||||
KList<IrisRegionEntry> entries = new KList<>();
|
||||
for (String region : regions) {
|
||||
entries.add(plain(region));
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getReferenceKey() {
|
||||
return region;
|
||||
}
|
||||
|
||||
public static final class Adapter extends WeightedReferenceAdapter<IrisRegionEntry> {
|
||||
public Adapter() {
|
||||
super("region");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected IrisRegionEntry create(String key, int weight, boolean writtenAsObject) {
|
||||
return new IrisRegionEntry(key, weight, writtenAsObject);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import art.arcane.iris.generation.biome.IrisBiome;
|
||||
import art.arcane.iris.generation.image.IrisImageMapRuntime;
|
||||
import art.arcane.iris.generation.image.IrisImageMapApplication;
|
||||
import art.arcane.iris.generation.stream.RarityStream;
|
||||
import art.arcane.iris.generation.stream.WeightedStream;
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.studio.generation.BiomeBuffetLayout;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
@@ -19,13 +20,9 @@ public final class RegionSelection {
|
||||
if (options.focused() != null) {
|
||||
return options.focused();
|
||||
}
|
||||
KList<IrisRegion> regions = new KList<>();
|
||||
for (IrisRegion region : options.data().getRegionLoader().loadAll(options.dimension().getRegions())) {
|
||||
if (!region.isCompatExcluded()) {
|
||||
regions.add(region);
|
||||
}
|
||||
}
|
||||
ProceduralStream<IrisRegion> selected = new RarityStream<>(options.style(), regions);
|
||||
ProceduralStream<IrisRegion> selected = options.dimension().hasWeightedRegions()
|
||||
? new WeightedStream<>(options.style(), options.dimension().getWeightedRegions(options.data()))
|
||||
: new RarityStream<>(options.style(), rarityRegions(options));
|
||||
if (!options.imageMaps().has(IrisImageMapApplication.REGION)) {
|
||||
return selected;
|
||||
}
|
||||
@@ -35,6 +32,16 @@ public final class RegionSelection {
|
||||
});
|
||||
}
|
||||
|
||||
private static KList<IrisRegion> rarityRegions(Options options) {
|
||||
KList<IrisRegion> regions = new KList<>();
|
||||
for (IrisRegion region : options.data().getRegionLoader().loadAll(options.dimension().getRegionKeys())) {
|
||||
if (!region.isCompatExcluded()) {
|
||||
regions.add(region);
|
||||
}
|
||||
}
|
||||
return regions;
|
||||
}
|
||||
|
||||
public static ProceduralStream<IrisRegion> restore(Snapshot snapshot) {
|
||||
IrisData data = snapshot.data();
|
||||
IrisDimension dimension = snapshot.dimension();
|
||||
|
||||
@@ -68,10 +68,10 @@ public final class ShoreBiomeLineages {
|
||||
|
||||
private static void visitRegion(IrisRegion region, IrisData data, BiConsumer<List<IrisBiome>, IrisRegion> visitor) {
|
||||
List<IrisBiome> roots = new ArrayList<>();
|
||||
for (String key : region.getLandBiomes()) {
|
||||
for (String key : region.getLandBiomeKeys()) {
|
||||
addLoaded(roots, data, key);
|
||||
}
|
||||
for (String key : region.getSeaBiomes()) {
|
||||
for (String key : region.getSeaBiomeKeys()) {
|
||||
addLoaded(roots, data, key);
|
||||
}
|
||||
ArrayDeque<IrisBiome> chain = new ArrayDeque<>();
|
||||
@@ -86,7 +86,7 @@ public final class ShoreBiomeLineages {
|
||||
visitor.accept(List.copyOf(chain), region);
|
||||
if (chain.size() <= IrisBiome.CHILD_HOPS) {
|
||||
List<IrisBiome> children = new ArrayList<>();
|
||||
for (String key : biome.getChildren()) {
|
||||
for (String key : biome.getChildKeys()) {
|
||||
addLoaded(children, data, key);
|
||||
}
|
||||
for (IrisBiome child : children) {
|
||||
|
||||
@@ -78,7 +78,7 @@ final class PackDimensionValidator {
|
||||
|
||||
int resolvedRegions = 0;
|
||||
for (int i = 0; i < regionsArray.length(); i++) {
|
||||
String regionKey = regionsArray.optString(i, null);
|
||||
String regionKey = PackValidationIo.referenceKey(regionsArray, i, "region");
|
||||
if (regionKey == null || regionKey.isBlank()) {
|
||||
warnings.add("Dimension '" + dimensionKey + "' has a blank region entry at index " + i + ".");
|
||||
continue;
|
||||
@@ -410,7 +410,7 @@ final class PackDimensionValidator {
|
||||
}
|
||||
int resolved = 0;
|
||||
for (int i = 0; i < arr.length(); i++) {
|
||||
String biomeKey = arr.optString(i, null);
|
||||
String biomeKey = PackValidationIo.referenceKey(arr, i, "biome");
|
||||
if (biomeKey == null || biomeKey.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -548,7 +548,7 @@ final class PackImageMapValidator {
|
||||
return;
|
||||
}
|
||||
for (int index = 0; index < values.length(); index++) {
|
||||
if (biomeKey.equals(values.optString(index, null))) {
|
||||
if (biomeKey.equals(PackValidationIo.referenceKey(values, index, "biome"))) {
|
||||
roles.add(role);
|
||||
return;
|
||||
}
|
||||
@@ -561,7 +561,7 @@ final class PackImageMapValidator {
|
||||
) {
|
||||
Set<String> regionKeys = new TreeSet<>();
|
||||
if (dimension.getRegions() != null) {
|
||||
for (String regionKey : dimension.getRegions()) {
|
||||
for (String regionKey : dimension.getRegionKeys()) {
|
||||
String normalized = normalized(regionKey);
|
||||
if (normalized != null) {
|
||||
regionKeys.add(normalized);
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
|
||||
package art.arcane.iris.pack;
|
||||
|
||||
import art.arcane.volmlib.util.json.JSONArray;
|
||||
import art.arcane.volmlib.util.json.JSONObject;
|
||||
|
||||
import java.io.File;
|
||||
@@ -46,6 +47,11 @@ public final class PackValidationIo {
|
||||
}
|
||||
}
|
||||
|
||||
static String referenceKey(JSONArray references, int index, String keyField) {
|
||||
JSONObject weighted = references.optJSONObject(index);
|
||||
return weighted == null ? references.optString(index, null) : weighted.optString(keyField, null);
|
||||
}
|
||||
|
||||
static boolean isScannableJsonPath(Path path) {
|
||||
String name = path.getFileName().toString();
|
||||
if (!name.endsWith(".json")) {
|
||||
|
||||
+2
-2
@@ -312,12 +312,12 @@ public final class PackCompileContext {
|
||||
}
|
||||
|
||||
private String firstLandBiome() {
|
||||
for (String regionKey : dimension.getRegions()) {
|
||||
for (String regionKey : dimension.getRegionKeys()) {
|
||||
IrisRegion region = data.getRegionLoader().load(regionKey, false);
|
||||
if (region == null || region.isCompatExcluded()) {
|
||||
continue;
|
||||
}
|
||||
for (String biomeKey : region.getLandBiomes()) {
|
||||
for (String biomeKey : region.getLandBiomeKeys()) {
|
||||
IrisBiome biome = biomeKey == null ? null : data.getBiomeLoader().load(biomeKey, false);
|
||||
if (biome != null && !biome.isCompatExcluded()) {
|
||||
return biome.getLoadKey();
|
||||
|
||||
+5
-5
@@ -40,16 +40,16 @@ final class BiomePools {
|
||||
static BiomePools load(IrisDimension dimension, IrisData data) {
|
||||
List<RegionPools> regions = new ArrayList<>();
|
||||
SortedMap<String, IrisBiome> biomes = new TreeMap<>();
|
||||
for (IrisRegion region : data.getRegionLoader().loadAll(dimension.getRegions())) {
|
||||
for (IrisRegion region : data.getRegionLoader().loadAll(dimension.getRegionKeys())) {
|
||||
if (region.isCompatExcluded()) {
|
||||
continue;
|
||||
}
|
||||
RegionPools pools = new RegionPools(
|
||||
region,
|
||||
pool(data, region.getLandBiomes(), biomes),
|
||||
pool(data, region.getSeaBiomes(), biomes),
|
||||
pool(data, region.getShoreBiomes(), biomes),
|
||||
pool(data, region.getCaveBiomes(), biomes));
|
||||
pool(data, region.getLandBiomeKeys(), biomes),
|
||||
pool(data, region.getSeaBiomeKeys(), biomes),
|
||||
pool(data, region.getShoreBiomeKeys(), biomes),
|
||||
pool(data, region.getCaveBiomeKeys(), biomes));
|
||||
if (pools.land().isEmpty() && pools.sea().isEmpty()) {
|
||||
throw new IllegalStateException("Region '" + region.getLoadKey() + "' has no land or sea biome to export");
|
||||
}
|
||||
|
||||
+6
-6
@@ -355,17 +355,17 @@ public final class ObjectStage implements CompileStage {
|
||||
|
||||
private Map<String, IrisRegion> regions(IrisDimension dimension) {
|
||||
Map<String, IrisRegion> regions = new HashMap<>();
|
||||
for (String regionKey : dimension.getRegions()) {
|
||||
for (String regionKey : dimension.getRegionKeys()) {
|
||||
IrisRegion region = data.getRegionLoader().load(regionKey, false);
|
||||
if (region == null) {
|
||||
continue;
|
||||
}
|
||||
reportSpawners(region.getEntitySpawners(), "regions/" + region.getLoadKey());
|
||||
List<String> roots = new ArrayList<>();
|
||||
roots.addAll(region.getLandBiomes());
|
||||
roots.addAll(region.getSeaBiomes());
|
||||
roots.addAll(region.getShoreBiomes());
|
||||
roots.addAll(region.getCaveBiomes());
|
||||
roots.addAll(region.getLandBiomeKeys());
|
||||
roots.addAll(region.getSeaBiomeKeys());
|
||||
roots.addAll(region.getShoreBiomeKeys());
|
||||
roots.addAll(region.getCaveBiomeKeys());
|
||||
for (String biome : members(roots)) {
|
||||
regions.putIfAbsent(biome, region);
|
||||
}
|
||||
@@ -383,7 +383,7 @@ public final class ObjectStage implements CompileStage {
|
||||
}
|
||||
IrisBiome biome = data.getBiomeLoader().load(key, false);
|
||||
if (biome != null) {
|
||||
pending.addAll(biome.getChildren());
|
||||
pending.addAll(biome.getChildKeys());
|
||||
}
|
||||
}
|
||||
return members;
|
||||
|
||||
+2
-2
@@ -36,7 +36,7 @@ final class PlacementScopes {
|
||||
placements(dimension.getStructures())));
|
||||
Map<String, IrisRegion> regions = new LinkedHashMap<>();
|
||||
Map<String, SortedSet<String>> regionIds = new LinkedHashMap<>();
|
||||
for (String regionKey : dimension.getRegions()) {
|
||||
for (String regionKey : dimension.getRegionKeys()) {
|
||||
IrisRegion region = regionKey == null ? null : data.getRegionLoader().load(regionKey, false);
|
||||
if (region != null && !region.isCompatExcluded() && !regions.containsKey(region.getLoadKey())) {
|
||||
regions.put(region.getLoadKey(), region);
|
||||
@@ -74,7 +74,7 @@ final class PlacementScopes {
|
||||
private static SortedSet<String> closure(IrisData data, IrisRegion region) {
|
||||
SortedSet<String> keys = new TreeSet<>();
|
||||
List<IrisBiome> frontier = new ArrayList<>();
|
||||
for (KList<String> pool : List.of(region.getLandBiomes(), region.getSeaBiomes(), region.getShoreBiomes(), region.getCaveBiomes())) {
|
||||
for (KList<String> pool : List.of(region.getLandBiomeKeys(), region.getSeaBiomeKeys(), region.getShoreBiomeKeys(), region.getCaveBiomeKeys())) {
|
||||
for (IrisBiome biome : data.getBiomeLoader().loadAll(pool)) {
|
||||
if (!biome.isCompatExcluded() && keys.add(biome.getLoadKey())) {
|
||||
frontier.add(biome);
|
||||
|
||||
+5
-5
@@ -36,7 +36,7 @@ public final class RiverStage implements CompileStage {
|
||||
IrisData data = context.data();
|
||||
Set<String> exported = new HashSet<>(context.baseBiomeCodes().loadKeyByBiomeId().values());
|
||||
List<IrisRegion> regions = new ArrayList<>();
|
||||
for (IrisRegion region : data.getRegionLoader().loadAll(context.dimension().getRegions())) {
|
||||
for (IrisRegion region : data.getRegionLoader().loadAll(context.dimension().getRegionKeys())) {
|
||||
if (!region.isCompatExcluded()) {
|
||||
regions.add(region);
|
||||
}
|
||||
@@ -53,9 +53,9 @@ public final class RiverStage implements CompileStage {
|
||||
|
||||
private static Collection<List<IrisBiome>> lineages(IrisRegion region, IrisData data, Set<String> exported) {
|
||||
List<String> roots = new ArrayList<>();
|
||||
roots.addAll(region.getLandBiomes());
|
||||
roots.addAll(region.getSeaBiomes());
|
||||
roots.addAll(region.getShoreBiomes());
|
||||
roots.addAll(region.getLandBiomeKeys());
|
||||
roots.addAll(region.getSeaBiomeKeys());
|
||||
roots.addAll(region.getShoreBiomeKeys());
|
||||
SortedMap<String, List<IrisBiome>> lineages = new TreeMap<>();
|
||||
for (String key : roots) {
|
||||
IrisBiome root = exportedBiome(key, data, exported);
|
||||
@@ -75,7 +75,7 @@ public final class RiverStage implements CompileStage {
|
||||
return;
|
||||
}
|
||||
IrisBiome leaf = leafFirst.getFirst();
|
||||
for (String childKey : leaf.getChildren()) {
|
||||
for (String childKey : leaf.getChildKeys()) {
|
||||
IrisBiome child = exportedBiome(childKey, data, exported);
|
||||
if (child == null || child.getLoadKey().equals(leaf.getLoadKey())) {
|
||||
continue;
|
||||
|
||||
@@ -70,6 +70,20 @@ final class IngestJson {
|
||||
return values;
|
||||
}
|
||||
|
||||
static List<String> referenceKeys(JsonElement element, String keyField) {
|
||||
List<String> keys = new ArrayList<>();
|
||||
if (element == null || !element.isJsonArray()) {
|
||||
return keys;
|
||||
}
|
||||
for (JsonElement reference : element.getAsJsonArray()) {
|
||||
JsonElement key = reference.isJsonObject() ? reference.getAsJsonObject().get(keyField) : reference;
|
||||
if (key != null && key.isJsonPrimitive() && key.getAsJsonPrimitive().isString()) {
|
||||
keys.add(key.getAsString());
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
|
||||
static JsonObject read(Path file) throws IOException {
|
||||
try {
|
||||
JsonElement element = JsonParser.parseString(Files.readString(file, StandardCharsets.UTF_8));
|
||||
|
||||
@@ -41,6 +41,8 @@ final class IngestPackModel {
|
||||
private static final int DEFAULT_MIN_Y = -64;
|
||||
private static final int DEFAULT_MAX_Y = 320;
|
||||
private static final String DEFAULT_DERIVATIVE = "minecraft:the_void";
|
||||
private static final String REGION_KEY_FIELD = "region";
|
||||
private static final String BIOME_KEY_FIELD = "biome";
|
||||
private static final Set<String> PLANTABLE_BLOCKS = Set.of("minecraft:grass_block", "minecraft:dirt", "minecraft:coarse_dirt",
|
||||
"minecraft:podzol", "minecraft:rooted_dirt", "minecraft:mycelium", "minecraft:moss_block", "minecraft:pale_moss_block",
|
||||
"minecraft:mud", "minecraft:muddy_mangrove_roots", "minecraft:farmland");
|
||||
@@ -73,7 +75,7 @@ final class IngestPackModel {
|
||||
String dimensionPath = IngestPack.dimensionPath(dimensionKey);
|
||||
JsonObject dimension = pack.require(dimensionPath);
|
||||
Map<String, String> reachable = new LinkedHashMap<>();
|
||||
List<String> regionKeys = IngestJson.strings(dimension.get("regions"));
|
||||
List<String> regionKeys = IngestJson.referenceKeys(dimension.get("regions"), REGION_KEY_FIELD);
|
||||
List<JsonObject> regionJson = new ArrayList<>(regionKeys.size());
|
||||
List<String> loadedRegionKeys = new ArrayList<>(regionKeys.size());
|
||||
for (String regionKey : regionKeys) {
|
||||
@@ -184,7 +186,7 @@ final class IngestPackModel {
|
||||
Map<BiomeRole, List<String>> pools = new EnumMap<>(BiomeRole.class);
|
||||
for (BiomeRole role : BiomeRole.values()) {
|
||||
List<String> pool = new ArrayList<>();
|
||||
for (String biome : IngestJson.strings(region.get(role.poolField()))) {
|
||||
for (String biome : IngestJson.referenceKeys(region.get(role.poolField()), BIOME_KEY_FIELD)) {
|
||||
if (reachable.containsKey(biome) && !pool.contains(biome)) {
|
||||
pool.add(biome);
|
||||
}
|
||||
@@ -203,7 +205,7 @@ final class IngestPackModel {
|
||||
ArrayDeque<String> queue = new ArrayDeque<>();
|
||||
for (JsonObject region : regions) {
|
||||
for (BiomeRole role : BiomeRole.values()) {
|
||||
queue.addAll(IngestJson.strings(region.get(role.poolField())));
|
||||
queue.addAll(IngestJson.referenceKeys(region.get(role.poolField()), BIOME_KEY_FIELD));
|
||||
}
|
||||
}
|
||||
while (!queue.isEmpty()) {
|
||||
@@ -220,7 +222,7 @@ final class IngestPackModel {
|
||||
? VanillaJson.namespaced(derivative.getAsString())
|
||||
: DEFAULT_DERIVATIVE;
|
||||
reachable.put(biomeKey, derivativeKey);
|
||||
queue.addAll(IngestJson.strings(biome.get().get("children")));
|
||||
queue.addAll(IngestJson.referenceKeys(biome.get().get("children"), BIOME_KEY_FIELD));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -25,7 +25,8 @@ import art.arcane.iris.spi.IrisLogging;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
import java.awt.Desktop;
|
||||
import art.arcane.iris.studio.workspace.FileOpener;
|
||||
|
||||
import java.io.File;
|
||||
|
||||
@Data
|
||||
@@ -64,7 +65,7 @@ public abstract class IrisRegistrant {
|
||||
|
||||
public File openInVSCode() {
|
||||
try {
|
||||
Desktop.getDesktop().open(getLoadFile());
|
||||
FileOpener.open(getLoadFile());
|
||||
} catch (Throwable e) {
|
||||
IrisLogging.reportError(e);
|
||||
}
|
||||
|
||||
@@ -24,9 +24,11 @@ import art.arcane.iris.pack.schema.annotation.ArrayType;
|
||||
import art.arcane.iris.pack.schema.annotation.MaxNumber;
|
||||
import art.arcane.iris.pack.schema.annotation.MinNumber;
|
||||
import art.arcane.iris.pack.schema.annotation.IntegerOptions;
|
||||
import art.arcane.iris.pack.schema.annotation.RegistryListResource;
|
||||
import art.arcane.iris.pack.schema.annotation.RegistryMapBlockState;
|
||||
import art.arcane.iris.pack.schema.annotation.Required;
|
||||
import art.arcane.iris.pack.schema.annotation.Snippet;
|
||||
import art.arcane.iris.pack.value.WeightedReference;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.json.JSONObject;
|
||||
import art.arcane.volmlib.util.json.JSONArray;
|
||||
@@ -185,13 +187,13 @@ final class SchemaPropertyBuilder {
|
||||
return switch (builder.getType(t.type())) {
|
||||
case "integer" -> "List of Integers";
|
||||
case "number" -> "List of Numbers";
|
||||
case "object" -> objectArrayProperty(t, prop);
|
||||
case "object" -> objectArrayProperty(t, prop, description);
|
||||
case "string" -> stringArrayProperty(k, t, prop, description);
|
||||
default -> "List of Something...?";
|
||||
};
|
||||
}
|
||||
|
||||
private String objectArrayProperty(ArrayType t, JSONObject prop) {
|
||||
private String objectArrayProperty(ArrayType t, JSONObject prop, KList<String> description) {
|
||||
String key = "obj-" + t.type().getCanonicalName().replaceAll("\\Q.\\E", "-").toLowerCase();
|
||||
if (!builder.definitions.containsKey(key)) {
|
||||
builder.definitions.put(key, new JSONObject());
|
||||
@@ -199,10 +201,30 @@ final class SchemaPropertyBuilder {
|
||||
}
|
||||
JSONObject items = new JSONObject();
|
||||
items.put("$ref", "#/definitions/" + key);
|
||||
if (WeightedReference.class.isAssignableFrom(t.type())) {
|
||||
return weightedReferenceArrayProperty(t.type(), items, prop, description);
|
||||
}
|
||||
prop.put("items", items);
|
||||
return "List of " + t.type().getSimpleName().replaceAll("\\QIris\\E", "") + "s (Objects)";
|
||||
}
|
||||
|
||||
private String weightedReferenceArrayProperty(Class<?> entryType, JSONObject objectItem, JSONObject prop, KList<String> description) {
|
||||
JSONObject keyItem = new JSONObject();
|
||||
keyItem.put("type", "string");
|
||||
for (Field field : entryType.getDeclaredFields()) {
|
||||
if (field.isAnnotationPresent(RegistryListResource.class)) {
|
||||
registryProperties.stringRegistryType(field, keyItem, description);
|
||||
}
|
||||
}
|
||||
JSONArray alternatives = new JSONArray();
|
||||
alternatives.put(keyItem);
|
||||
alternatives.put(objectItem);
|
||||
JSONObject items = new JSONObject();
|
||||
items.put("anyOf", alternatives);
|
||||
prop.put("items", items);
|
||||
return "List of " + entryType.getSimpleName().replaceAll("\\QIris\\E|\\QEntry\\E", "") + "s (names or weighted objects)";
|
||||
}
|
||||
|
||||
private String stringArrayProperty(Field k, ArrayType t, JSONObject prop, KList<String> description) {
|
||||
String registryType = registryProperties.stringArrayRegistryType(k, prop, description);
|
||||
if (registryType != null) {
|
||||
|
||||
@@ -24,7 +24,6 @@ import art.arcane.iris.spi.IrisPlatforms;
|
||||
import art.arcane.volmlib.util.json.JSONArray;
|
||||
import art.arcane.volmlib.util.json.JSONObject;
|
||||
|
||||
import java.awt.GraphicsEnvironment;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
@@ -35,6 +34,7 @@ final class SchemaRegistryCatalog {
|
||||
/** Namespaced key or family/namespace prefix: "minecraft:village_plains", "minecraft:village", "nova_structures:". */
|
||||
static final String VANILLA_STRUCTURE_PREFIX_PATTERN = "^[a-z0-9_.-]+:[a-z0-9_./-]*$";
|
||||
private static final String MINECRAFT_NAMESPACE = "minecraft:";
|
||||
private static final String[] LOGICAL_FONT_FAMILIES = {"Dialog", "DialogInput", "Monospaced", "SansSerif", "Serif"};
|
||||
private static volatile JSONArray fontTypes;
|
||||
private final SchemaBuilder builder;
|
||||
private JSONArray potionTypes;
|
||||
@@ -44,18 +44,13 @@ final class SchemaRegistryCatalog {
|
||||
this.builder = builder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Font families are only used for schema completion. Enumerating them touches AWT, which can fail outright on a
|
||||
* headless or mod-loader JVM - a failure degrades to no completion, never to a broken schema.
|
||||
*/
|
||||
/** The logical font families every Java runtime has; listing the installed ones would need AWT, which headless and mod-loader JVMs may lack. */
|
||||
static JSONArray fontTypes() {
|
||||
JSONArray cached = fontTypes;
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
JSONArray built = CapabilityProbe.attempt("java.awt font families",
|
||||
() -> new JSONArray(GraphicsEnvironment.getLocalGraphicsEnvironment().getAvailableFontFamilyNames()),
|
||||
new JSONArray());
|
||||
JSONArray built = new JSONArray(LOGICAL_FONT_FAMILIES);
|
||||
fontTypes = built;
|
||||
return built;
|
||||
}
|
||||
|
||||
@@ -21,6 +21,8 @@ package art.arcane.iris.pack.validation;
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.pack.loading.IrisRegistrant;
|
||||
import art.arcane.iris.pack.loading.ResourceLoader;
|
||||
import art.arcane.iris.pack.value.Weighted;
|
||||
import art.arcane.iris.pack.value.WeightedReference;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
|
||||
import java.util.ArrayList;
|
||||
@@ -80,6 +82,39 @@ public final class CompatPools {
|
||||
return kept;
|
||||
}
|
||||
|
||||
/** {@link #load} for weighted references: every survivor keeps the weight its entry was written with. */
|
||||
public static <T extends IrisRegistrant> KList<Weighted<T>> loadWeighted(ResourceLoader<T> loader,
|
||||
List<? extends WeightedReference> entries,
|
||||
IrisData data,
|
||||
String subjectType,
|
||||
String subjectKey,
|
||||
String field,
|
||||
List<CompatFinding> sink) {
|
||||
KList<Weighted<T>> kept = new KList<>();
|
||||
|
||||
if (loader == null || entries == null) {
|
||||
return kept;
|
||||
}
|
||||
|
||||
for (int index = 0; index < entries.size(); index++) {
|
||||
WeightedReference entry = entries.get(index);
|
||||
T loaded = entry == null ? null : loader.load(entry.getReferenceKey());
|
||||
|
||||
if (loaded == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (loaded.isCompatExcluded()) {
|
||||
drop(data, loaded, subjectType, subjectKey, field + "[" + index + "] " + entry.getReferenceKey(), sink);
|
||||
continue;
|
||||
}
|
||||
|
||||
kept.add(new Weighted<>(loaded, entry.getWeight()));
|
||||
}
|
||||
|
||||
return kept;
|
||||
}
|
||||
|
||||
/** The surviving keys of a reference pool, in declaration order. */
|
||||
public static <T extends IrisRegistrant> KList<String> surviving(ResourceLoader<T> loader,
|
||||
List<String> keys,
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package art.arcane.iris.pack.value;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
|
||||
public record Weighted<T>(T value, int weight) {
|
||||
public static final int MIN_WEIGHT = 1;
|
||||
public static final int MAX_WEIGHT = 1000;
|
||||
|
||||
public enum Edge {
|
||||
EARLIER,
|
||||
LATER
|
||||
}
|
||||
|
||||
public Weighted {
|
||||
Objects.requireNonNull(value, "value");
|
||||
if (weight < MIN_WEIGHT || weight > MAX_WEIGHT) {
|
||||
throw new IllegalArgumentException("Weight must be from " + MIN_WEIGHT + " to " + MAX_WEIGHT + ": " + weight);
|
||||
}
|
||||
}
|
||||
|
||||
public static <T> T pick(List<Weighted<T>> entries, double noise, Edge edge) {
|
||||
if (entries.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
double slotPosition = noise * totalWeight(entries);
|
||||
int slotsUpToHere = 0;
|
||||
for (Weighted<T> entry : entries) {
|
||||
slotsUpToHere += entry.weight();
|
||||
boolean inThisEntry = edge == Edge.EARLIER ? slotPosition <= slotsUpToHere : slotPosition < slotsUpToHere;
|
||||
if (inThisEntry) {
|
||||
return entry.value();
|
||||
}
|
||||
}
|
||||
|
||||
return entries.getLast().value();
|
||||
}
|
||||
|
||||
public static int totalWeight(List<? extends Weighted<?>> entries) {
|
||||
int total = 0;
|
||||
for (Weighted<?> entry : entries) {
|
||||
total += entry.weight();
|
||||
}
|
||||
return total;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package art.arcane.iris.pack.value;
|
||||
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public interface WeightedReference {
|
||||
String getReferenceKey();
|
||||
|
||||
int getWeight();
|
||||
|
||||
boolean isWrittenAsObject();
|
||||
|
||||
static boolean anyWrittenAsObject(List<? extends WeightedReference> entries) {
|
||||
for (WeightedReference entry : entries) {
|
||||
if (entry != null && entry.isWrittenAsObject()) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static KList<String> keys(List<? extends WeightedReference> entries) {
|
||||
KList<String> keys = new KList<>();
|
||||
for (WeightedReference entry : entries) {
|
||||
if (entry != null) {
|
||||
keys.add(entry.getReferenceKey());
|
||||
}
|
||||
}
|
||||
return keys;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package art.arcane.iris.pack.value;
|
||||
|
||||
import com.google.gson.JsonParseException;
|
||||
import com.google.gson.TypeAdapter;
|
||||
import com.google.gson.stream.JsonReader;
|
||||
import com.google.gson.stream.JsonToken;
|
||||
import com.google.gson.stream.JsonWriter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
public abstract class WeightedReferenceAdapter<E extends WeightedReference> extends TypeAdapter<E> {
|
||||
private static final String WEIGHT_FIELD = "weight";
|
||||
|
||||
private final String keyField;
|
||||
|
||||
protected WeightedReferenceAdapter(String keyField) {
|
||||
this.keyField = keyField;
|
||||
}
|
||||
|
||||
protected abstract E create(String key, int weight, boolean writtenAsObject);
|
||||
|
||||
@Override
|
||||
public void write(JsonWriter writer, E entry) throws IOException {
|
||||
if (entry == null) {
|
||||
writer.nullValue();
|
||||
return;
|
||||
}
|
||||
if (!entry.isWrittenAsObject()) {
|
||||
writer.value(entry.getReferenceKey());
|
||||
return;
|
||||
}
|
||||
writer.beginObject();
|
||||
writer.name(keyField).value(entry.getReferenceKey());
|
||||
writer.name(WEIGHT_FIELD).value(entry.getWeight());
|
||||
writer.endObject();
|
||||
}
|
||||
|
||||
@Override
|
||||
public E read(JsonReader reader) throws IOException {
|
||||
JsonToken token = reader.peek();
|
||||
if (token == JsonToken.NULL) {
|
||||
reader.nextNull();
|
||||
return null;
|
||||
}
|
||||
if (token == JsonToken.STRING) {
|
||||
return create(reader.nextString(), Weighted.MIN_WEIGHT, false);
|
||||
}
|
||||
if (token != JsonToken.BEGIN_OBJECT) {
|
||||
throw new JsonParseException("Expected a " + keyField + " key or an object with \"" + keyField
|
||||
+ "\" and \"" + WEIGHT_FIELD + "\" at " + reader.getPath());
|
||||
}
|
||||
return readObject(reader);
|
||||
}
|
||||
|
||||
private E readObject(JsonReader reader) throws IOException {
|
||||
String key = null;
|
||||
int weight = Weighted.MIN_WEIGHT;
|
||||
reader.beginObject();
|
||||
while (reader.hasNext()) {
|
||||
String name = reader.nextName();
|
||||
if (name.equals(keyField)) {
|
||||
key = reader.nextString();
|
||||
} else if (name.equals(WEIGHT_FIELD)) {
|
||||
weight = reader.nextInt();
|
||||
} else {
|
||||
reader.skipValue();
|
||||
}
|
||||
}
|
||||
reader.endObject();
|
||||
if (key == null) {
|
||||
throw new JsonParseException("Missing required \"" + keyField + "\" at " + reader.getPath());
|
||||
}
|
||||
if (weight < Weighted.MIN_WEIGHT || weight > Weighted.MAX_WEIGHT) {
|
||||
throw new JsonParseException("Weight must be from " + Weighted.MIN_WEIGHT + " to " + Weighted.MAX_WEIGHT
|
||||
+ ": " + weight + " at " + reader.getPath());
|
||||
}
|
||||
return create(key, weight, true);
|
||||
}
|
||||
}
|
||||
@@ -42,6 +42,7 @@ import art.arcane.iris.pack.PackValidationRegistry;
|
||||
import art.arcane.iris.pack.PackValidationCache;
|
||||
import art.arcane.iris.pack.PackValidationResult;
|
||||
import art.arcane.iris.pack.PackValidator;
|
||||
import art.arcane.iris.studio.bridge.StudioBridges;
|
||||
import art.arcane.iris.studio.workspace.IrisProject;
|
||||
import art.arcane.iris.studio.workspace.IrisPackageCompiler;
|
||||
import art.arcane.iris.studio.workspace.IrisCodeWorkspace;
|
||||
@@ -161,6 +162,7 @@ public class StudioSVC implements IrisService {
|
||||
@Override
|
||||
public void onDisable() {
|
||||
quiesceDownloadsForShutdown();
|
||||
StudioBridges.closeAll();
|
||||
IrisLogging.debug("Studio Mode Active: Closing Projects");
|
||||
boolean stopping = IrisToolbelt.isServerStopping();
|
||||
LinkedHashSet<String> worldNamesToDelete = new LinkedHashSet<>(TransientWorldCleanupSupport.collectTransientStudioWorldNames(IrisWorldStorage.levelRoot()));
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.bridge;
|
||||
|
||||
import art.arcane.iris.studio.map.PalettePatterns;
|
||||
import com.google.gson.Gson;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
/**
|
||||
* A palette's pattern as the studio reads it, little endian:
|
||||
* <pre>
|
||||
* u32 header length | header, UTF-8 JSON | padding to 4 bytes | i16 picks[columns²]
|
||||
* </pre>
|
||||
* The header holds the columns across, the blocks between columns, the block states the picks index, and the pick
|
||||
* ({@code noBlock}) of a column the palette places nothing at.
|
||||
*/
|
||||
final class PatternEncoding {
|
||||
private static final int ALIGNMENT_BYTES = 4;
|
||||
|
||||
private PatternEncoding() {
|
||||
}
|
||||
|
||||
static byte[] encode(PalettePatterns.Pattern pattern, int blocksPerColumn, Gson gson) {
|
||||
byte[] header = gson.toJson(new Header(pattern.columns(), blocksPerColumn, pattern.blocks(), pattern.blocks(), PalettePatterns.NO_BLOCK))
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
ByteBuffer buffer = ByteBuffer.allocate(aligned(Integer.BYTES + header.length) + pattern.picks().length * Short.BYTES)
|
||||
.order(ByteOrder.LITTLE_ENDIAN);
|
||||
buffer.putInt(header.length).put(header);
|
||||
buffer.position(aligned(buffer.position()));
|
||||
buffer.asShortBuffer().put(pattern.picks());
|
||||
return buffer.array();
|
||||
}
|
||||
|
||||
private static int aligned(int bytes) {
|
||||
return (bytes + ALIGNMENT_BYTES - 1) / ALIGNMENT_BYTES * ALIGNMENT_BYTES;
|
||||
}
|
||||
|
||||
private record Header(int columns, int blocksPerColumn, java.util.List<String> blocks, java.util.List<String> drawnAs, int noBlock) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.bridge;
|
||||
|
||||
import art.arcane.iris.pack.schema.annotation.MaxNumber;
|
||||
import art.arcane.iris.pack.schema.annotation.MinNumber;
|
||||
import art.arcane.volmlib.util.documentation.Description;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* The settings of a profile object as a form: each plain number, switch and choice it has, with the value it holds, what
|
||||
* the pack says about it and its limits. A value typed into the form is carried by a request and applied to a copy, so
|
||||
* the pack's files stay as they are.
|
||||
*/
|
||||
final class ProfileForm {
|
||||
private ProfileForm() {
|
||||
}
|
||||
|
||||
/** @param kind boolean, integer, decimal or enum; {@code choices} lists an enum's names */
|
||||
record Field(String name, String description, String kind, Object value, Object defaultValue, Double minimum, Double maximum,
|
||||
List<String> choices, boolean changed) {
|
||||
}
|
||||
|
||||
record Form(String title, List<Field> fields, List<String> notes) {
|
||||
}
|
||||
|
||||
static Form of(String title, Object bean, Set<String> hidden, Map<String, String> overrides, List<String> notes) {
|
||||
Object fresh = newInstance(bean.getClass());
|
||||
List<Field> fields = new ArrayList<>();
|
||||
for (java.lang.reflect.Field field : bean.getClass().getDeclaredFields()) {
|
||||
String kind = kindOf(field);
|
||||
if (kind == null || hidden.contains(field.getName())) {
|
||||
continue;
|
||||
}
|
||||
fields.add(fieldOf(field, kind, bean, fresh, overrides.containsKey(field.getName())));
|
||||
}
|
||||
return new Form(title, fields, notes);
|
||||
}
|
||||
|
||||
/** A copy of the bean with the typed values set; a value that does not read as its field's type is ignored. */
|
||||
@SuppressWarnings("unchecked")
|
||||
static <T> T withOverrides(T bean, Map<String, String> overrides) {
|
||||
T copy = (T) newInstance(bean.getClass());
|
||||
for (java.lang.reflect.Field field : bean.getClass().getDeclaredFields()) {
|
||||
if (Modifier.isStatic(field.getModifiers()) || Modifier.isFinal(field.getModifiers())) {
|
||||
continue;
|
||||
}
|
||||
field.setAccessible(true);
|
||||
try {
|
||||
field.set(copy, field.get(bean));
|
||||
String typed = overrides.get(field.getName());
|
||||
if (typed != null && kindOf(field) != null) {
|
||||
field.set(copy, parse(field.getType(), typed));
|
||||
}
|
||||
} catch (IllegalAccessException | IllegalArgumentException unreadable) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
return copy;
|
||||
}
|
||||
|
||||
private static Field fieldOf(java.lang.reflect.Field field, String kind, Object bean, Object fresh, boolean changed) {
|
||||
field.setAccessible(true);
|
||||
try {
|
||||
Description description = field.getAnnotation(Description.class);
|
||||
MinNumber minimum = field.getAnnotation(MinNumber.class);
|
||||
MaxNumber maximum = field.getAnnotation(MaxNumber.class);
|
||||
List<String> choices = field.getType().isEnum()
|
||||
? Arrays.stream(field.getType().getEnumConstants()).map(constant -> ((Enum<?>) constant).name()).toList()
|
||||
: List.of();
|
||||
return new Field(field.getName(), description == null ? "" : description.value(), kind, plain(field.get(bean)),
|
||||
plain(field.get(fresh)), minimum == null ? null : minimum.value(), maximum == null ? null : maximum.value(), choices, changed);
|
||||
} catch (IllegalAccessException unreadable) {
|
||||
throw new IllegalStateException(unreadable);
|
||||
}
|
||||
}
|
||||
|
||||
private static Object plain(Object value) {
|
||||
return value instanceof Enum<?> constant ? constant.name() : value;
|
||||
}
|
||||
|
||||
private static String kindOf(java.lang.reflect.Field field) {
|
||||
if (Modifier.isStatic(field.getModifiers()) || Modifier.isTransient(field.getModifiers())) {
|
||||
return null;
|
||||
}
|
||||
Class<?> type = field.getType();
|
||||
if (type == boolean.class) {
|
||||
return "boolean";
|
||||
}
|
||||
if (type == int.class || type == long.class) {
|
||||
return "integer";
|
||||
}
|
||||
if (type == double.class || type == float.class) {
|
||||
return "decimal";
|
||||
}
|
||||
return type.isEnum() ? "enum" : null;
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked", "rawtypes"})
|
||||
private static Object parse(Class<?> type, String text) {
|
||||
if (type == boolean.class) {
|
||||
return Boolean.parseBoolean(text);
|
||||
}
|
||||
if (type == int.class) {
|
||||
return (int) Math.round(Double.parseDouble(text));
|
||||
}
|
||||
if (type == long.class) {
|
||||
return Math.round(Double.parseDouble(text));
|
||||
}
|
||||
if (type == double.class) {
|
||||
return Double.parseDouble(text);
|
||||
}
|
||||
if (type == float.class) {
|
||||
return (float) Double.parseDouble(text);
|
||||
}
|
||||
return Enum.valueOf((Class<? extends Enum>) type, text);
|
||||
}
|
||||
|
||||
private static Object newInstance(Class<?> type) {
|
||||
try {
|
||||
var constructor = type.getDeclaredConstructor();
|
||||
constructor.setAccessible(true);
|
||||
return constructor.newInstance();
|
||||
} catch (ReflectiveOperationException noPlainConstructor) {
|
||||
throw new IllegalStateException(type.getSimpleName() + " has no plain constructor", noPlainConstructor);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.bridge;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* Blocks collected for the studio's 3D scene, which it reads little endian:
|
||||
* <pre>
|
||||
* u32 header length | header, UTF-8 JSON | padding to 4 bytes
|
||||
* i32 blocks[blockCount * 4]: x, y, z, then the index of the block's state in the palette
|
||||
* </pre>
|
||||
* The header holds the block states used once each and the scene's bounds. Air is left out: the studio draws nothing
|
||||
* there either. Positions are from the scene's lowest corner.
|
||||
*/
|
||||
final class SceneBlocks {
|
||||
private static final int ALIGNMENT_BYTES = 4;
|
||||
private static final int INTS_PER_BLOCK = 4;
|
||||
private static final Set<String> AIR = Set.of("minecraft:air", "minecraft:cave_air", "minecraft:void_air");
|
||||
|
||||
private final Map<String, Integer> palette = new LinkedHashMap<>();
|
||||
private final List<int[]> blocks = new ArrayList<>();
|
||||
private final int[] min = {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE};
|
||||
private final int[] max = {Integer.MIN_VALUE, Integer.MIN_VALUE, Integer.MIN_VALUE};
|
||||
|
||||
void add(int x, int y, int z, String state) {
|
||||
if (AIR.contains(state)) {
|
||||
return;
|
||||
}
|
||||
int paletteIndex = palette.computeIfAbsent(state, ignored -> palette.size());
|
||||
blocks.add(new int[]{x, y, z, paletteIndex});
|
||||
int[] at = {x, y, z};
|
||||
for (int axis = 0; axis < 3; axis++) {
|
||||
min[axis] = Math.min(min[axis], at[axis]);
|
||||
max[axis] = Math.max(max[axis], at[axis] + 1);
|
||||
}
|
||||
}
|
||||
|
||||
int count() {
|
||||
return blocks.size();
|
||||
}
|
||||
|
||||
/** The scene with its lowest corner at the origin; an empty scene is one block across. */
|
||||
byte[] encode(Gson gson) {
|
||||
boolean empty = blocks.isEmpty();
|
||||
int[] origin = empty ? new int[]{0, 0, 0} : min;
|
||||
int[] top = empty ? new int[]{1, 1, 1} : max;
|
||||
byte[] header = gson.toJson(new Header(List.copyOf(palette.keySet()), blocks.size(),
|
||||
new int[]{0, 0, 0}, new int[]{top[0] - origin[0], top[1] - origin[1], top[2] - origin[2]})).getBytes(StandardCharsets.UTF_8);
|
||||
int blocksAt = aligned(Integer.BYTES + header.length);
|
||||
ByteBuffer buffer = ByteBuffer.allocate(blocksAt + blocks.size() * INTS_PER_BLOCK * Integer.BYTES).order(ByteOrder.LITTLE_ENDIAN);
|
||||
buffer.putInt(header.length).put(header).position(blocksAt);
|
||||
for (int[] block : blocks) {
|
||||
buffer.putInt(block[0] - origin[0]).putInt(block[1] - origin[1]).putInt(block[2] - origin[2]).putInt(block[3]);
|
||||
}
|
||||
return buffer.array();
|
||||
}
|
||||
|
||||
private static int aligned(int bytes) {
|
||||
return (bytes + ALIGNMENT_BYTES - 1) / ALIGNMENT_BYTES * ALIGNMENT_BYTES;
|
||||
}
|
||||
|
||||
private record Header(List<String> palette, int blockCount, int[] min, int[] max) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.bridge;
|
||||
|
||||
import java.lang.management.ManagementFactory;
|
||||
import java.lang.management.OperatingSystemMXBean;
|
||||
|
||||
/**
|
||||
* What the server asks of its machine: CPU counted like {@code top}, where 100 is one thread kept busy, and the Java
|
||||
* heap in use.
|
||||
*
|
||||
* @param cpuPercent the process's CPU use with 100 per busy thread, or null when the JVM cannot tell
|
||||
* @param threads the threads the server's CPU has, so the studio can show the most {@code cpuPercent} can reach
|
||||
* @param heapUsedBytes the Java heap in use
|
||||
* @param heapMaxBytes the most the Java heap can grow to
|
||||
*/
|
||||
record ServerUsage(Double cpuPercent, int threads, long heapUsedBytes, long heapMaxBytes) {
|
||||
private static final double PERCENT_PER_THREAD = 100D;
|
||||
|
||||
static ServerUsage sample() {
|
||||
Runtime runtime = Runtime.getRuntime();
|
||||
OperatingSystemMXBean system = ManagementFactory.getOperatingSystemMXBean();
|
||||
return of(processCpuLoad(system), runtime.availableProcessors(), runtime.totalMemory() - runtime.freeMemory(), runtime.maxMemory());
|
||||
}
|
||||
|
||||
/** @param processCpuLoad the share of every core the process uses, or below zero when unknown */
|
||||
static ServerUsage of(double processCpuLoad, int threads, long heapUsedBytes, long heapMaxBytes) {
|
||||
Double cpuPercent = processCpuLoad < 0D ? null : processCpuLoad * threads * PERCENT_PER_THREAD;
|
||||
return new ServerUsage(cpuPercent, threads, heapUsedBytes, heapMaxBytes);
|
||||
}
|
||||
|
||||
private static double processCpuLoad(OperatingSystemMXBean system) {
|
||||
return system instanceof com.sun.management.OperatingSystemMXBean hotspot ? hotspot.getProcessCpuLoad() : -1D;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,727 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.bridge;
|
||||
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import art.arcane.iris.studio.map.StudioAssets;
|
||||
import art.arcane.iris.studio.map.StudioHover;
|
||||
import art.arcane.iris.studio.imagemap.ImageMapPreviews;
|
||||
import art.arcane.iris.studio.map.PalettePatterns;
|
||||
import art.arcane.iris.studio.noise.NoiseSources;
|
||||
import art.arcane.iris.studio.noise.NoiseTile;
|
||||
import art.arcane.iris.studio.view.GuiHost;
|
||||
import art.arcane.iris.studio.view.GuiMarker;
|
||||
import art.arcane.iris.studio.view.PregenRenderSnapshot;
|
||||
import art.arcane.iris.studio.view.PregeneratorJob;
|
||||
import art.arcane.volmlib.util.function.NoiseProvider;
|
||||
import com.github.benmanes.caffeine.cache.Cache;
|
||||
import com.github.benmanes.caffeine.cache.Caffeine;
|
||||
import com.google.gson.Gson;
|
||||
import com.google.gson.GsonBuilder;
|
||||
import com.sun.net.httpserver.Headers;
|
||||
import com.sun.net.httpserver.HttpExchange;
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.InetAddress;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.net.URI;
|
||||
import java.net.URLDecoder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.HashMap;
|
||||
import java.util.HexFormat;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.concurrent.CompletableFuture;
|
||||
import java.util.concurrent.ExecutionException;
|
||||
import java.util.concurrent.ExecutorService;
|
||||
import java.util.concurrent.Executors;
|
||||
import java.util.concurrent.ScheduledExecutorService;
|
||||
import java.util.concurrent.ThreadFactory;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeoutException;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.function.BooleanSupplier;
|
||||
|
||||
/**
|
||||
* An Iris Studio app's connection to one world: HTTP on the loopback interface, on a free port, each request carrying
|
||||
* the bridge's token as {@code Authorization: Bearer <token>}. JSON for the world, hovers and players; tiles in
|
||||
* {@link StudioTile}; {@code /v1/events} streams {@link StudioEvents}. Requests run on a small pool of daemon threads,
|
||||
* so a busy studio cannot hold up the server.
|
||||
*/
|
||||
public final class StudioBridge implements AutoCloseable {
|
||||
private static final String API = "/v1/";
|
||||
private static final int TOKEN_BYTES = 24;
|
||||
private static final int DEFAULT_TILE_SIZE = 128;
|
||||
private static final int LARGEST_TILE_SIZE = 512;
|
||||
private static final double SMALLEST_BLOCKS_PER_PIXEL = 1D / 16D;
|
||||
private static final double LARGEST_BLOCKS_PER_PIXEL = 4_096D;
|
||||
private static final double SMALLEST_NOISE_BLOCKS_PER_PIXEL = 1D / 64D;
|
||||
private static final int LARGEST_PATTERN_BLOCKS_PER_COLUMN = 64;
|
||||
private static final int DEFAULT_IMAGE_MAP_PREVIEW_PIXELS = 768;
|
||||
private static final ModuleViewInfo PALETTES_VIEW = new ModuleViewInfo("iris:terrain/palettes", "Palettes",
|
||||
"The blocks each biome's palette layers place");
|
||||
private static final long DROPPED_TILE_KEPT_MINUTES = 10;
|
||||
private static final long ENTITY_WAIT_MILLIS = 3_000L;
|
||||
private static final String ASSETS_ENDPOINT = "assets/";
|
||||
private static final String ASSET_RETRY_SECONDS = "2";
|
||||
private static final long ASSET_CACHE_SECONDS = 86_400L;
|
||||
private static final String OVERRIDE_PREFIX = "set.";
|
||||
private static final String VIEW_BIOMES = "biomes";
|
||||
private static final String VIEW_REGIONS = "regions";
|
||||
private static final String VIEW_RIVERS = "rivers";
|
||||
static final int STATUS_OK = 200;
|
||||
static final int STATUS_NO_CONTENT = 204;
|
||||
static final int STATUS_BAD_REQUEST = 400;
|
||||
static final int STATUS_UNAUTHORIZED = 401;
|
||||
static final int STATUS_NOT_FOUND = 404;
|
||||
static final int STATUS_METHOD_NOT_ALLOWED = 405;
|
||||
static final int STATUS_UNPROCESSABLE = 422;
|
||||
static final int STATUS_SERVER_ERROR = 500;
|
||||
static final int STATUS_UNAVAILABLE = 503;
|
||||
|
||||
private static final String VIEW_HEIGHT = "height";
|
||||
private static final String GROUP_WORLD = "WORLD";
|
||||
private static final String GROUP_BIOME_LAYERS = "BIOME_LAYERS";
|
||||
private static final String GROUP_DIAGNOSTICS = "DIAGNOSTICS";
|
||||
|
||||
private static final List<ViewInfo> VIEWS = List.of(
|
||||
new ViewInfo(VIEW_BIOMES, "Biomes", "The biome at each spot, in the biome's colour", GROUP_WORLD, "World"),
|
||||
new ViewInfo(VIEW_REGIONS, "Regions", "The region each spot belongs to", GROUP_WORLD, "World"),
|
||||
new ViewInfo(VIEW_HEIGHT, "Height", "Terrain height, from deep water to snowy peaks", GROUP_WORLD, "World"),
|
||||
new ViewInfo(VIEW_RIVERS, "Rivers", "Streams, rivers, falls, ponds, lakes, sea inlets, grottos and cave pools from the hydrology",
|
||||
GROUP_WORLD, "World"),
|
||||
new ViewInfo("land-biomes", "Land biomes", "The land biome each spot would get, also where the sea is", GROUP_BIOME_LAYERS, "Biome layers"),
|
||||
new ViewInfo("sea-biomes", "Sea biomes", "The sea biome each spot would get, also where the land is", GROUP_BIOME_LAYERS, "Biome layers"),
|
||||
new ViewInfo("cave-biomes", "Cave biomes", "The cave biome under each spot", GROUP_BIOME_LAYERS, "Biome layers"),
|
||||
new ViewInfo("object-load", "Object load", "Configuration estimate of object density and chance, not measured performance",
|
||||
GROUP_DIAGNOSTICS, "Diagnostics"),
|
||||
new ViewInfo("decorator-load", "Decorator load", "Configuration estimate of decorator chance and stacks, not measured performance",
|
||||
GROUP_DIAGNOSTICS, "Diagnostics"),
|
||||
new ViewInfo("layer-load", "Layer load", "Configuration estimate of biome layer count, not measured performance",
|
||||
GROUP_DIAGNOSTICS, "Diagnostics"),
|
||||
new ViewInfo("noise", "Noise", "The pack's generators and the built-in noise styles, from above or as terrain",
|
||||
"GENERATORS", "Generators"),
|
||||
new ViewInfo("pregen", "Pregeneration", "The chunks of the running pregeneration as they are generated, with its progress", GROUP_WORLD, "World"),
|
||||
new ViewInfo("imageMaps","Image maps", "Terrain height, biomes or masks painted from a PNG, previewed over the world area they cover",
|
||||
"GENERATORS", "Generators"));
|
||||
|
||||
private final StudioWorld world;
|
||||
private final String token;
|
||||
private final Gson gson = new GsonBuilder().serializeNulls().create();
|
||||
private final HttpServer server;
|
||||
private final int port;
|
||||
private final ExecutorService workers;
|
||||
private final ScheduledExecutorService ticker;
|
||||
private final StudioEvents events;
|
||||
private final Runnable hotloadHook;
|
||||
private final Cache<String, AtomicBoolean> droppedTiles = Caffeine.newBuilder().expireAfterWrite(DROPPED_TILE_KEPT_MINUTES, TimeUnit.MINUTES).build();
|
||||
private volatile boolean closed;
|
||||
|
||||
private StudioBridge(StudioWorld world) throws IOException {
|
||||
this.world = world;
|
||||
this.token = newToken();
|
||||
this.events = new StudioEvents(world, gson);
|
||||
this.server = HttpServer.create(new InetSocketAddress(InetAddress.getLoopbackAddress(), 0), 0);
|
||||
this.port = server.getAddress().getPort();
|
||||
this.workers = Executors.newFixedThreadPool(workerCount(), daemonThreads("Iris Studio Bridge"));
|
||||
this.ticker = Executors.newSingleThreadScheduledExecutor(daemonThreads("Iris Studio Events"));
|
||||
this.hotloadHook = events::hotloaded;
|
||||
server.setExecutor(workers);
|
||||
server.createContext(API, this::handle);
|
||||
}
|
||||
|
||||
static StudioBridge start(StudioWorld world) throws IOException {
|
||||
StudioBridge bridge = new StudioBridge(world);
|
||||
bridge.server.start();
|
||||
bridge.ticker.scheduleWithFixedDelay(bridge::pollEvents, 0L, StudioEvents.POLL_INTERVAL_MILLIS, TimeUnit.MILLISECONDS);
|
||||
GuiHost.get().registerHotloadHook(bridge.hotloadHook);
|
||||
return bridge;
|
||||
}
|
||||
|
||||
public String worldName() {
|
||||
return world.name();
|
||||
}
|
||||
|
||||
public int port() {
|
||||
return port;
|
||||
}
|
||||
|
||||
public String token() {
|
||||
return token;
|
||||
}
|
||||
|
||||
/** What the studio app opens to connect. */
|
||||
public String link() {
|
||||
return "iris-studio://127.0.0.1:" + port() + "/?token=" + token;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
if (closed) {
|
||||
return;
|
||||
}
|
||||
closed = true;
|
||||
GuiHost.get().unregisterHotloadHook(hotloadHook);
|
||||
ticker.shutdownNow();
|
||||
events.closeAll();
|
||||
server.stop(0);
|
||||
workers.shutdownNow();
|
||||
}
|
||||
|
||||
private void pollEvents() {
|
||||
try {
|
||||
events.poll();
|
||||
} catch (Throwable error) {
|
||||
IrisLogging.debug("Studio events failed: " + error);
|
||||
}
|
||||
}
|
||||
|
||||
private void handle(HttpExchange exchange) throws IOException {
|
||||
try {
|
||||
allowAnyOrigin(exchange.getResponseHeaders());
|
||||
if ("OPTIONS".equals(exchange.getRequestMethod())) {
|
||||
exchange.sendResponseHeaders(STATUS_NO_CONTENT, -1);
|
||||
exchange.close();
|
||||
return;
|
||||
}
|
||||
if (!isAuthorized(exchange)) {
|
||||
throw new RequestError(STATUS_UNAUTHORIZED, "Missing or wrong token");
|
||||
}
|
||||
route(exchange);
|
||||
} catch (RequestError error) {
|
||||
sendJson(exchange, error.status, new ErrorBody(error.getMessage()));
|
||||
} catch (CancellationException stopped) {
|
||||
sendJson(exchange, STATUS_UNAVAILABLE, new ErrorBody("The world stopped"));
|
||||
} catch (IOException clientHungUp) {
|
||||
exchange.close();
|
||||
} catch (Throwable error) {
|
||||
IrisLogging.reportError("Studio bridge request " + exchange.getRequestURI().getPath(), error);
|
||||
sendJson(exchange, STATUS_SERVER_ERROR, new ErrorBody(String.valueOf(error.getMessage())));
|
||||
}
|
||||
}
|
||||
|
||||
private void route(HttpExchange exchange) throws IOException {
|
||||
String endpoint = exchange.getRequestURI().getPath().substring(API.length());
|
||||
Query query = Query.of(exchange.getRequestURI());
|
||||
if (endpoint.startsWith(ASSETS_ENDPOINT)) {
|
||||
sendAsset(exchange, endpoint);
|
||||
return;
|
||||
}
|
||||
switch (endpoint) {
|
||||
case "world" -> sendJson(exchange, STATUS_OK, worldInfo(get(exchange)));
|
||||
case "tile" -> sendBytes(exchange, "application/octet-stream", tile(get(exchange), query));
|
||||
case "tile-cancel" -> cancelTile(exchange, query);
|
||||
case "hover" -> sendJson(exchange, STATUS_OK, hover(get(exchange).engine(), query));
|
||||
case "picks" -> sendJson(exchange, STATUS_OK, new PickInspection("", List.of()));
|
||||
case "regions" -> sendJson(exchange, STATUS_OK, StudioHover.previewableRegions(get(exchange).engine()));
|
||||
case "entities" -> sendJson(exchange, STATUS_OK, entities(get(exchange)));
|
||||
case "scenes" -> sendJson(exchange, STATUS_OK, profileViews());
|
||||
case "scene-entries" -> sendJson(exchange, STATUS_OK, profileEntries(get(exchange).engine(), query));
|
||||
case "scene" -> sendBytes(exchange, "application/octet-stream", profileScene(get(exchange).engine(), query));
|
||||
case "scene-bake" -> sendJson(exchange, STATUS_OK, sceneBake(get(exchange).engine(), query));
|
||||
case "profile-form" -> sendJson(exchange, STATUS_OK, profileForm(get(exchange).engine(), query));
|
||||
case "noise-sources" -> sendJson(exchange, STATUS_OK, NoiseSources.of(get(exchange).engine()).list());
|
||||
case "noise-tile" -> sendBytes(exchange, "application/octet-stream", noiseTile(get(exchange).engine(), query));
|
||||
case "patterns" -> sendJson(exchange, STATUS_OK, List.of(PALETTES_VIEW));
|
||||
case "pattern-entries" -> sendJson(exchange, STATUS_OK, patternEntries(get(exchange).engine(), query));
|
||||
case "pattern" -> sendBytes(exchange, "application/octet-stream", pattern(get(exchange).engine(), query));
|
||||
case "pregen" -> sendJson(exchange, STATUS_OK, pregenStatus(exchange));
|
||||
case "pregen-map" -> sendBytes(exchange, "image/png", pregenMap(exchange));
|
||||
case "pregen-pause" -> sendJson(exchange, STATUS_OK, pregenPause(exchange));
|
||||
case "image-maps" -> sendJson(exchange, STATUS_OK, ImageMapPreviews.entries(get(exchange).engine()));
|
||||
case "image-map" -> sendJson(exchange, STATUS_OK, profiling(() -> ImageMapPreviews.details(get(exchange).engine(), query.text("key"))));
|
||||
case "image-map-preview" -> sendBytes(exchange, "image/png", imageMapPreview(get(exchange).engine(), query));
|
||||
case "saved-worlds" -> sendJson(exchange, STATUS_OK, List.of());
|
||||
case "events" -> streamEvents(exchange);
|
||||
case "teleport" -> teleport(exchange, query);
|
||||
case "open" -> throw new RequestError(STATUS_NOT_FOUND, "Opening a pack file from the studio is not available in Iris v4");
|
||||
default -> throw new RequestError(STATUS_NOT_FOUND, "No such endpoint: " + endpoint);
|
||||
}
|
||||
}
|
||||
|
||||
private StudioWorld.Session get(HttpExchange exchange) {
|
||||
requireMethod(exchange, "GET");
|
||||
return runningSession();
|
||||
}
|
||||
|
||||
private StudioWorld.Session post(HttpExchange exchange) {
|
||||
requireMethod(exchange, "POST");
|
||||
return runningSession();
|
||||
}
|
||||
|
||||
private StudioWorld.Session runningSession() {
|
||||
StudioWorld.Session session = world.session();
|
||||
if (session == null) {
|
||||
throw new RequestError(STATUS_UNAVAILABLE, "The world " + world.name() + " has no running engine");
|
||||
}
|
||||
return session;
|
||||
}
|
||||
|
||||
private static void requireMethod(HttpExchange exchange, String method) {
|
||||
if (!method.equals(exchange.getRequestMethod())) {
|
||||
throw new RequestError(STATUS_METHOD_NOT_ALLOWED, "Use " + method);
|
||||
}
|
||||
}
|
||||
|
||||
private WorldInfo worldInfo(StudioWorld.Session session) {
|
||||
Engine engine = session.engine();
|
||||
return new WorldInfo(
|
||||
world.name(),
|
||||
engine.getDimension().getLoadKey(),
|
||||
engine.getDimension().getName(),
|
||||
Long.toString(engine.getWorld().getRawWorldSeed()),
|
||||
engine.getMinHeight(),
|
||||
engine.getHeight(),
|
||||
engine.getDimension().getFluidHeight(),
|
||||
DEFAULT_TILE_SIZE,
|
||||
session.overlay() != null,
|
||||
session.tiles().hydrologyEnabled(),
|
||||
VIEWS
|
||||
);
|
||||
}
|
||||
|
||||
private static String viewOf(Query query) {
|
||||
String view = query.text("view");
|
||||
if (VIEWS.stream().noneMatch(known -> known.id().equals(view))) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, "Unknown view: " + view);
|
||||
}
|
||||
return view;
|
||||
}
|
||||
|
||||
private static String previewOf(Query query) {
|
||||
if (!query.has("preview")) {
|
||||
return null;
|
||||
}
|
||||
if (!VIEW_REGIONS.equals(viewOf(query))) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, "Only the region view previews a region");
|
||||
}
|
||||
return query.text("preview");
|
||||
}
|
||||
|
||||
private static StudioHover.Hover hover(Engine engine, Query query) {
|
||||
String view = viewOf(query);
|
||||
String preview = previewOf(query);
|
||||
if (preview != null && engine.getData().getRegionLoader().load(preview) == null) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, "This world has no region " + preview);
|
||||
}
|
||||
return StudioHover.sample(engine, query.number("x"), query.number("z"), preview, !VIEW_REGIONS.equals(view) || preview != null);
|
||||
}
|
||||
|
||||
private byte[] tile(StudioWorld.Session session, Query query) {
|
||||
Engine engine = session.engine();
|
||||
String view = viewOf(query);
|
||||
String preview = previewOf(query);
|
||||
int size = query.whole("size", DEFAULT_TILE_SIZE);
|
||||
double blocksPerPixel = query.number("scale");
|
||||
if (size < 1 || size > LARGEST_TILE_SIZE) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, "A tile is 1 to " + LARGEST_TILE_SIZE + " pixels");
|
||||
}
|
||||
if (!(blocksPerPixel >= SMALLEST_BLOCKS_PER_PIXEL && blocksPerPixel <= LARGEST_BLOCKS_PER_PIXEL)) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, "The scale is " + SMALLEST_BLOCKS_PER_PIXEL + " to " + LARGEST_BLOCKS_PER_PIXEL + " blocks per pixel");
|
||||
}
|
||||
double tileBlocks = size * blocksPerPixel;
|
||||
double startX = query.whole("x", 0) * tileBlocks;
|
||||
double startZ = query.whole("z", 0) * tileBlocks;
|
||||
AtomicBoolean dropped = query.has("request") ? droppedFlagOf(query.text("request")) : new AtomicBoolean();
|
||||
BooleanSupplier cancelled = () -> dropped.get() || closed || engine.isClosing() || engine.isClosed();
|
||||
StudioTile tile = VIEW_RIVERS.equals(view)
|
||||
? session.tiles().rivers(startX, startZ, blocksPerPixel, size, cancelled)
|
||||
: session.tiles().biomesOrRegions(view, preview, startX, startZ, blocksPerPixel, size, query.flag("heights"), cancelled);
|
||||
return tile.encode(gson);
|
||||
}
|
||||
|
||||
private static PregenStatus pregenStatus(HttpExchange exchange) {
|
||||
requireMethod(exchange, "GET");
|
||||
PregeneratorJob job = PregeneratorJob.getInstance();
|
||||
if (job == null) {
|
||||
return new PregenStatus(false, null);
|
||||
}
|
||||
return new PregenStatus(true, job.renderSnapshot());
|
||||
}
|
||||
|
||||
private static byte[] pregenMap(HttpExchange exchange) {
|
||||
requireMethod(exchange, "GET");
|
||||
PregeneratorJob job = PregeneratorJob.getInstance();
|
||||
if (job == null) {
|
||||
throw new RequestError(STATUS_NOT_FOUND, "No pregeneration is running");
|
||||
}
|
||||
return job.renderMapState().png();
|
||||
}
|
||||
|
||||
private static MessageBody pregenPause(HttpExchange exchange) {
|
||||
requireMethod(exchange, "POST");
|
||||
if (!PregeneratorJob.pauseResume()) {
|
||||
throw new RequestError(STATUS_NOT_FOUND, "No pregeneration to pause or resume");
|
||||
}
|
||||
return new MessageBody(PregeneratorJob.isPaused() ? "Paused" : "Running");
|
||||
}
|
||||
|
||||
private static byte[] imageMapPreview(Engine engine, Query query) {
|
||||
try {
|
||||
return profiling(() -> ImageMapPreviews.preview(engine, query.text("key"), query.whole("size", DEFAULT_IMAGE_MAP_PREVIEW_PIXELS)));
|
||||
} catch (IllegalArgumentException refused) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, refused.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static List<PalettePatterns.Entry> patternEntries(Engine engine, Query query) {
|
||||
requirePalettesView(query);
|
||||
return PalettePatterns.entries(engine);
|
||||
}
|
||||
|
||||
private byte[] pattern(Engine engine, Query query) {
|
||||
requirePalettesView(query);
|
||||
int columns = query.whole("size", DEFAULT_TILE_SIZE);
|
||||
int blocksPerColumn = query.whole("scale", 1);
|
||||
if (columns < 1 || columns > LARGEST_TILE_SIZE) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, "A pattern is 1 to " + LARGEST_TILE_SIZE + " columns across");
|
||||
}
|
||||
if (blocksPerColumn < 1 || blocksPerColumn > LARGEST_PATTERN_BLOCKS_PER_COLUMN) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, "The scale is 1 to " + LARGEST_PATTERN_BLOCKS_PER_COLUMN + " whole blocks per column");
|
||||
}
|
||||
String key = query.text("key");
|
||||
int tileBlocks = columns * blocksPerColumn;
|
||||
PalettePatterns.Pattern pattern = PalettePatterns.pattern(engine, key, query.whole("depth", 0),
|
||||
query.whole("x", 0) * tileBlocks, query.whole("z", 0) * tileBlocks, columns, blocksPerColumn)
|
||||
.orElseThrow(() -> new RequestError(STATUS_NOT_FOUND, "No palette " + key));
|
||||
return PatternEncoding.encode(pattern, blocksPerColumn, gson);
|
||||
}
|
||||
|
||||
private static void requirePalettesView(Query query) {
|
||||
if (!PALETTES_VIEW.id().equals(query.text("view"))) {
|
||||
throw new RequestError(STATUS_NOT_FOUND, "No pattern view " + query.text("view"));
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] noiseTile(Engine engine, Query query) {
|
||||
int size = query.whole("size", DEFAULT_TILE_SIZE);
|
||||
double blocksPerPixel = query.number("scale");
|
||||
if (size < 1 || size > LARGEST_TILE_SIZE) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, "A tile is 1 to " + LARGEST_TILE_SIZE + " pixels");
|
||||
}
|
||||
if (!(blocksPerPixel >= SMALLEST_NOISE_BLOCKS_PER_PIXEL && blocksPerPixel <= LARGEST_BLOCKS_PER_PIXEL)) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, "The scale is " + SMALLEST_NOISE_BLOCKS_PER_PIXEL + " to " + LARGEST_BLOCKS_PER_PIXEL + " blocks per pixel");
|
||||
}
|
||||
NoiseSources sources = NoiseSources.of(engine);
|
||||
String source = query.text("source");
|
||||
NoiseProvider noise = noiseSampler(sources, source, query.longNumber("seed"));
|
||||
return NoiseTile.sample(noise, query.whole("x", 0), query.whole("z", 0), blocksPerPixel, size, sources.isSmooth(source),
|
||||
() -> closed || engine.isClosing() || engine.isClosed()).encode();
|
||||
}
|
||||
|
||||
// A source that cannot be sampled fails every tile alike, so it is told once to the studio rather than logged per tile.
|
||||
private static NoiseProvider noiseSampler(NoiseSources sources, String source, long seed) {
|
||||
try {
|
||||
return sources.sampler(source, seed);
|
||||
} catch (NoSuchElementException unknown) {
|
||||
throw new RequestError(STATUS_NOT_FOUND, unknown.getMessage());
|
||||
} catch (IllegalStateException unsampleable) {
|
||||
throw new RequestError(STATUS_UNPROCESSABLE, unsampleable.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// Asset paths name one file of one Minecraft version, so a studio may keep what it fetched for as long as it runs.
|
||||
private static void sendAsset(HttpExchange exchange, String endpoint) throws IOException {
|
||||
requireMethod(exchange, "GET");
|
||||
byte[] asset;
|
||||
try {
|
||||
asset = StudioAssets.read(endpoint).orElseThrow(() -> new RequestError(STATUS_NOT_FOUND, "No asset " + endpoint));
|
||||
} catch (StudioAssets.NotReadyException notReady) {
|
||||
exchange.getResponseHeaders().set("Retry-After", ASSET_RETRY_SECONDS);
|
||||
throw new RequestError(STATUS_UNAVAILABLE, notReady.getMessage());
|
||||
}
|
||||
exchange.getResponseHeaders().set("Cache-Control", "max-age=" + ASSET_CACHE_SECONDS + ", immutable");
|
||||
sendBytes(exchange, endpoint.endsWith(".png") ? "image/png" : "application/json", asset);
|
||||
}
|
||||
|
||||
private static List<SceneViewInfo> profileViews() {
|
||||
return StudioProfiles.views().stream()
|
||||
.map(view -> new SceneViewInfo(view.id(), view.label(), view.description(), false, false, view.isBaked(), false, view.sizes(), view.hasForm()))
|
||||
.toList();
|
||||
}
|
||||
|
||||
private static List<StudioProfiles.Entry> profileEntries(Engine engine, Query query) {
|
||||
return profileView(query).entries(engine);
|
||||
}
|
||||
|
||||
private static StudioObjects.BakeTiming sceneBake(Engine engine, Query query) {
|
||||
StudioProfiles.ProfileView view = profileView(query);
|
||||
if (!view.isBaked()) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, "View " + view.id() + " is not baked");
|
||||
}
|
||||
return profiling(() -> view.timeBake(engine, query.text("key")));
|
||||
}
|
||||
|
||||
private static ProfileForm.Form profileForm(Engine engine, Query query) {
|
||||
return profiling(() -> profileView(query).form(engine, query.text("key"), query.prefixed(OVERRIDE_PREFIX)));
|
||||
}
|
||||
|
||||
private byte[] profileScene(Engine engine, Query query) {
|
||||
StudioProfiles.ProfileView view = profileView(query);
|
||||
int size = query.whole("size", view.sizes() == null ? 0 : view.sizes().opening());
|
||||
if (view.sizes() != null && !view.sizes().blocksAcross().contains(size)) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, "View " + view.id() + " builds scenes " + view.sizes().blocksAcross() + " blocks across, not " + size);
|
||||
}
|
||||
return profiling(() -> view.scene(engine, query.text("key"), query.whole("variant", 0), size, query.prefixed(OVERRIDE_PREFIX)).encode(gson));
|
||||
}
|
||||
|
||||
private static StudioProfiles.ProfileView profileView(Query query) {
|
||||
return profiling(() -> StudioProfiles.view(query.text("view")));
|
||||
}
|
||||
|
||||
// A profile the pack does not have is the studio's to be told about, not a failure of the bridge.
|
||||
private static <T> T profiling(ProfileTask<T> task) {
|
||||
try {
|
||||
return task.run();
|
||||
} catch (NoSuchElementException unknown) {
|
||||
throw new RequestError(STATUS_NOT_FOUND, unknown.getMessage());
|
||||
} catch (IOException failed) {
|
||||
throw new IllegalStateException(failed);
|
||||
}
|
||||
}
|
||||
|
||||
@FunctionalInterface
|
||||
private interface ProfileTask<T> {
|
||||
T run() throws IOException;
|
||||
}
|
||||
|
||||
private void cancelTile(HttpExchange exchange, Query query) throws IOException {
|
||||
requireMethod(exchange, "POST");
|
||||
droppedFlagOf(query.text("request")).set(true);
|
||||
sendJson(exchange, STATUS_OK, new MessageBody(null));
|
||||
}
|
||||
|
||||
private AtomicBoolean droppedFlagOf(String requestId) {
|
||||
return droppedTiles.get(requestId, id -> new AtomicBoolean());
|
||||
}
|
||||
|
||||
private List<GuiMarker> entities(StudioWorld.Session session) {
|
||||
if (session.overlay() == null) {
|
||||
return List.of();
|
||||
}
|
||||
CompletableFuture<List<GuiMarker>> found = new CompletableFuture<>();
|
||||
session.overlay().requestEntities(found::complete);
|
||||
try {
|
||||
return found.get(ENTITY_WAIT_MILLIS, TimeUnit.MILLISECONDS);
|
||||
} catch (TimeoutException slow) {
|
||||
throw new RequestError(STATUS_UNAVAILABLE, "The server did not list its entities in time");
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new CancellationException("Bridge closing");
|
||||
} catch (ExecutionException failed) {
|
||||
throw new IllegalStateException(failed.getCause());
|
||||
}
|
||||
}
|
||||
|
||||
private void teleport(HttpExchange exchange, Query query) throws IOException {
|
||||
StudioWorld.Session session = post(exchange);
|
||||
if (session.overlay() == null) {
|
||||
throw new RequestError(STATUS_NOT_FOUND, "This server cannot do that from the studio");
|
||||
}
|
||||
session.overlay().teleport(query.number("x"), query.number("z"));
|
||||
sendJson(exchange, STATUS_OK, new MessageBody(null));
|
||||
}
|
||||
|
||||
private void streamEvents(HttpExchange exchange) throws IOException {
|
||||
requireMethod(exchange, "GET");
|
||||
Headers headers = exchange.getResponseHeaders();
|
||||
headers.set("Content-Type", "text/event-stream; charset=utf-8");
|
||||
headers.set("Cache-Control", "no-cache");
|
||||
exchange.sendResponseHeaders(STATUS_OK, 0);
|
||||
OutputStream body = exchange.getResponseBody();
|
||||
body.flush();
|
||||
events.listen(body);
|
||||
}
|
||||
|
||||
private boolean isAuthorized(HttpExchange exchange) {
|
||||
String header = exchange.getRequestHeaders().getFirst("Authorization");
|
||||
String expected = "Bearer " + token;
|
||||
return header != null && MessageDigest.isEqual(
|
||||
header.getBytes(StandardCharsets.UTF_8), expected.getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static void allowAnyOrigin(Headers headers) {
|
||||
headers.set("Access-Control-Allow-Origin", "*");
|
||||
headers.set("Access-Control-Allow-Headers", "Authorization");
|
||||
headers.set("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
||||
}
|
||||
|
||||
private void sendJson(HttpExchange exchange, int status, Object body) throws IOException {
|
||||
exchange.getResponseHeaders().set("Content-Type", "application/json; charset=utf-8");
|
||||
send(exchange, status, gson.toJson(body).getBytes(StandardCharsets.UTF_8));
|
||||
}
|
||||
|
||||
private static void sendBytes(HttpExchange exchange, String contentType, byte[] body) throws IOException {
|
||||
exchange.getResponseHeaders().set("Content-Type", contentType);
|
||||
send(exchange, STATUS_OK, body);
|
||||
}
|
||||
|
||||
private static void send(HttpExchange exchange, int status, byte[] body) throws IOException {
|
||||
try (exchange) {
|
||||
exchange.sendResponseHeaders(status, body.length);
|
||||
exchange.getResponseBody().write(body);
|
||||
}
|
||||
}
|
||||
|
||||
private static String newToken() {
|
||||
byte[] bytes = new byte[TOKEN_BYTES];
|
||||
new SecureRandom().nextBytes(bytes);
|
||||
return HexFormat.of().formatHex(bytes);
|
||||
}
|
||||
|
||||
private static int workerCount() {
|
||||
return Math.max(2, Runtime.getRuntime().availableProcessors() / 2);
|
||||
}
|
||||
|
||||
private static ThreadFactory daemonThreads(String name) {
|
||||
AtomicInteger count = new AtomicInteger();
|
||||
return task -> {
|
||||
Thread thread = new Thread(task, name + " " + count.incrementAndGet());
|
||||
thread.setDaemon(true);
|
||||
return thread;
|
||||
};
|
||||
}
|
||||
|
||||
static final class RequestError extends RuntimeException {
|
||||
final int status;
|
||||
|
||||
RequestError(int status, String message) {
|
||||
super(message);
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
/** A request's query parameters; a missing or malformed one is a bad request. */
|
||||
record Query(Map<String, String> values) {
|
||||
static Query of(URI uri) {
|
||||
Map<String, String> values = new HashMap<>();
|
||||
String raw = uri.getRawQuery();
|
||||
if (raw != null) {
|
||||
for (String pair : raw.split("&")) {
|
||||
int equals = pair.indexOf('=');
|
||||
String name = equals < 0 ? pair : pair.substring(0, equals);
|
||||
String value = equals < 0 ? "" : pair.substring(equals + 1);
|
||||
values.put(decode(name), decode(value));
|
||||
}
|
||||
}
|
||||
return new Query(values);
|
||||
}
|
||||
|
||||
private static String decode(String text) {
|
||||
return URLDecoder.decode(text, StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
String text(String name) {
|
||||
String value = values.get(name);
|
||||
if (value == null) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, "Missing " + name);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
double number(String name) {
|
||||
try {
|
||||
double value = Double.parseDouble(text(name));
|
||||
if (!Double.isFinite(value)) {
|
||||
throw new NumberFormatException();
|
||||
}
|
||||
return value;
|
||||
} catch (NumberFormatException malformed) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, name + " must be a number");
|
||||
}
|
||||
}
|
||||
|
||||
int whole(String name, int fallback) {
|
||||
if (!values.containsKey(name)) {
|
||||
return fallback;
|
||||
}
|
||||
try {
|
||||
return Integer.parseInt(values.get(name));
|
||||
} catch (NumberFormatException malformed) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, name + " must be a whole number");
|
||||
}
|
||||
}
|
||||
|
||||
/** The parameters that start with {@code prefix}, by the rest of their names. */
|
||||
Map<String, String> prefixed(String prefix) {
|
||||
Map<String, String> found = new HashMap<>();
|
||||
values.forEach((name, value) -> {
|
||||
if (name.startsWith(prefix)) {
|
||||
found.put(name.substring(prefix.length()), value);
|
||||
}
|
||||
});
|
||||
return found;
|
||||
}
|
||||
|
||||
long longNumber(String name) {
|
||||
try {
|
||||
return Long.parseLong(text(name));
|
||||
} catch (NumberFormatException malformed) {
|
||||
throw new RequestError(STATUS_BAD_REQUEST, name + " must be a whole number");
|
||||
}
|
||||
}
|
||||
|
||||
boolean has(String name) {
|
||||
return values.containsKey(name);
|
||||
}
|
||||
|
||||
boolean flag(String name) {
|
||||
String value = values.get(name);
|
||||
return "1".equals(value) || "true".equals(value);
|
||||
}
|
||||
}
|
||||
|
||||
private record ErrorBody(String error) {
|
||||
}
|
||||
|
||||
private record MessageBody(String message) {
|
||||
}
|
||||
|
||||
/** A profile view as the studio lists its scene views; {@code form} when its entries have a settings form. */
|
||||
private record SceneViewInfo(String id, String label, String description, boolean editable, boolean creatable, boolean baked,
|
||||
boolean parts, StudioProfiles.Sizes sizes, boolean form) {
|
||||
}
|
||||
|
||||
/** @param snapshot null while no pregeneration runs */
|
||||
private record PregenStatus(boolean active, PregenRenderSnapshot snapshot) {
|
||||
}
|
||||
|
||||
/** A view the studio lists beside the scene and pattern views. */
|
||||
private record ModuleViewInfo(String id, String label, String description) {
|
||||
}
|
||||
|
||||
private record PickInspection(String detail, List<Object> sections) {
|
||||
}
|
||||
|
||||
/** @param seed as text, as JavaScript numbers cannot hold every long */
|
||||
private record WorldInfo(String world, String dimension, String dimensionName, String seed, int minY, int height,
|
||||
int fluidHeight, int tileSize, boolean hasPlayers, boolean hydrology, List<ViewInfo> views) {
|
||||
}
|
||||
|
||||
private record ViewInfo(String id, String label, String description, String group, String groupLabel) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.bridge;
|
||||
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
import com.google.gson.Gson;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.attribute.PosixFilePermissions;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* The open bridges, one per world. Each is announced in a connection file under {@code ~/.iris/studio/bridges}, which
|
||||
* a studio app on the same machine lists to connect without a pasted link; the file goes when the bridge closes.
|
||||
*/
|
||||
public final class StudioBridges {
|
||||
private static final Path CONNECTION_FOLDER = Path.of(System.getProperty("user.home"), ".iris", "studio", "bridges");
|
||||
private static final String OWNER_ONLY = "rw-------";
|
||||
private static final Map<String, StudioBridge> OPEN = new ConcurrentHashMap<>();
|
||||
|
||||
private StudioBridges() {
|
||||
}
|
||||
|
||||
/**
|
||||
* The bridge to {@code worldName}, started when it has none yet.
|
||||
*
|
||||
* @param engines the world's engine now, or null while it has none
|
||||
* @param openerId the player the studio's teleports move, or null for the console
|
||||
*/
|
||||
public static synchronized StudioBridge open(String worldName, Supplier<Engine> engines, UUID openerId) throws IOException {
|
||||
StudioBridge open = OPEN.get(worldName);
|
||||
if (open != null) {
|
||||
return open;
|
||||
}
|
||||
StudioBridge bridge = StudioBridge.start(new StudioWorld(worldName, engines, openerId));
|
||||
OPEN.put(worldName, bridge);
|
||||
announce(bridge);
|
||||
return bridge;
|
||||
}
|
||||
|
||||
public static synchronized void closeAll() {
|
||||
StudioWindow.closeAll();
|
||||
for (StudioBridge bridge : OPEN.values()) {
|
||||
bridge.close();
|
||||
withdraw(bridge);
|
||||
}
|
||||
OPEN.clear();
|
||||
}
|
||||
|
||||
private static void announce(StudioBridge bridge) {
|
||||
try {
|
||||
Files.createDirectories(CONNECTION_FOLDER);
|
||||
Path file = connectionFile(bridge);
|
||||
Connection connection = new Connection(bridge.worldName(), bridge.port(), bridge.token(), bridge.link(),
|
||||
ProcessHandle.current().pid(), System.currentTimeMillis());
|
||||
Files.deleteIfExists(file);
|
||||
createReadableByOwnerOnly(file);
|
||||
Files.writeString(file, new Gson().toJson(connection), StandardCharsets.UTF_8);
|
||||
} catch (IOException error) {
|
||||
IrisLogging.warn("Could not write the studio connection file: %s", error.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// The file holds the token, so other users of the machine must not read it, not even before it is written.
|
||||
private static void createReadableByOwnerOnly(Path file) throws IOException {
|
||||
if (file.getFileSystem().supportedFileAttributeViews().contains("posix")) {
|
||||
Files.createFile(file, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString(OWNER_ONLY)));
|
||||
return;
|
||||
}
|
||||
Files.createFile(file);
|
||||
}
|
||||
|
||||
private static void withdraw(StudioBridge bridge) {
|
||||
try {
|
||||
Files.deleteIfExists(connectionFile(bridge));
|
||||
} catch (IOException error) {
|
||||
IrisLogging.debug("Could not remove the studio connection file: " + error.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private static Path connectionFile(StudioBridge bridge) {
|
||||
return CONNECTION_FOLDER.resolve(bridge.port() + ".json");
|
||||
}
|
||||
|
||||
/** @param pid the server's process, so the studio can skip files a crashed server left */
|
||||
private record Connection(String world, int port, String token, String link, long pid, long startedMillis) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,163 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.bridge;
|
||||
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.studio.view.GuiMarker;
|
||||
import com.google.gson.Gson;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/**
|
||||
* Server-sent events to every connected studio: {@code players} when a player moves, {@code world} when the world's
|
||||
* engine changes (a hotload), {@code usage} with the server's CPU and heap every second, and a comment now and then so
|
||||
* a dead connection is noticed. A studio that stops
|
||||
* reading is dropped.
|
||||
*/
|
||||
final class StudioEvents {
|
||||
private static final byte[] KEEP_ALIVE = ": alive\n\n".getBytes(StandardCharsets.UTF_8);
|
||||
static final long POLL_INTERVAL_MILLIS = 250L;
|
||||
private static final long KEEP_ALIVE_INTERVAL_MILLIS = 10_000L;
|
||||
private static final long USAGE_INTERVAL_MILLIS = 1_000L;
|
||||
|
||||
private final StudioWorld world;
|
||||
private final Gson gson;
|
||||
private final List<OutputStream> listeners = new CopyOnWriteArrayList<>();
|
||||
/** Listeners not yet told the world's state. */
|
||||
private final List<OutputStream> joining = new CopyOnWriteArrayList<>();
|
||||
private final AtomicBoolean listenerJoined = new AtomicBoolean();
|
||||
private final AtomicBoolean usageWanted = new AtomicBoolean();
|
||||
private final AtomicBoolean hotloaded = new AtomicBoolean();
|
||||
private List<GuiMarker> lastPlayers;
|
||||
private Engine lastEngine;
|
||||
private long lastSentMillis;
|
||||
private long lastUsageMillis;
|
||||
|
||||
StudioEvents(StudioWorld world, Gson gson) {
|
||||
this.world = world;
|
||||
this.gson = gson;
|
||||
}
|
||||
|
||||
void listen(OutputStream stream) {
|
||||
listeners.add(stream);
|
||||
joining.add(stream);
|
||||
listenerJoined.set(true);
|
||||
usageWanted.set(true);
|
||||
}
|
||||
|
||||
/** The pack was hotloaded; the engine may be the same, its streams are not. */
|
||||
void hotloaded() {
|
||||
hotloaded.set(true);
|
||||
}
|
||||
|
||||
/** Sends what changed since the last poll; called every {@link #POLL_INTERVAL_MILLIS} from one thread. */
|
||||
void poll() {
|
||||
if (listeners.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
StudioWorld.Session session = world.session();
|
||||
Engine engine = session == null ? null : session.engine();
|
||||
List<OutputStream> joined = List.copyOf(joining);
|
||||
if (engine != lastEngine || hotloaded.getAndSet(false)) {
|
||||
lastEngine = engine;
|
||||
send("world", new WorldChange(engine != null));
|
||||
} else {
|
||||
greet(joined, engine != null);
|
||||
}
|
||||
joining.removeAll(joined);
|
||||
List<GuiMarker> players = session == null || session.overlay() == null ? List.of() : session.overlay().players();
|
||||
if (listenerJoined.getAndSet(false) || !Objects.equals(players, lastPlayers)) {
|
||||
lastPlayers = players;
|
||||
send("players", players);
|
||||
}
|
||||
long now = System.currentTimeMillis();
|
||||
if (usageWanted.getAndSet(false) || now - lastUsageMillis >= USAGE_INTERVAL_MILLIS) {
|
||||
lastUsageMillis = now;
|
||||
send("usage", ServerUsage.sample());
|
||||
}
|
||||
if (now - lastSentMillis > KEEP_ALIVE_INTERVAL_MILLIS) {
|
||||
sendToAll(KEEP_ALIVE);
|
||||
}
|
||||
}
|
||||
|
||||
void closeAll() {
|
||||
for (OutputStream listener : listeners) {
|
||||
closeQuietly(listener);
|
||||
}
|
||||
listeners.clear();
|
||||
joining.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Tells studios that just connected what state the world is in, them alone. A studio takes its first world event as
|
||||
* the state it connected to, so without one of its own it would take the next hotload for it and not redraw.
|
||||
*/
|
||||
private void greet(List<OutputStream> joined, boolean running) {
|
||||
if (joined.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
byte[] message = eventOf("world", new WorldChange(running));
|
||||
for (OutputStream listener : joined) {
|
||||
sendTo(listener, message);
|
||||
}
|
||||
}
|
||||
|
||||
private void send(String event, Object data) {
|
||||
sendToAll(eventOf(event, data));
|
||||
}
|
||||
|
||||
private byte[] eventOf(String event, Object data) {
|
||||
return ("event: " + event + "\ndata: " + gson.toJson(data) + "\n\n").getBytes(StandardCharsets.UTF_8);
|
||||
}
|
||||
|
||||
private void sendToAll(byte[] message) {
|
||||
lastSentMillis = System.currentTimeMillis();
|
||||
for (OutputStream listener : listeners) {
|
||||
sendTo(listener, message);
|
||||
}
|
||||
}
|
||||
|
||||
private void sendTo(OutputStream listener, byte[] message) {
|
||||
try {
|
||||
listener.write(message);
|
||||
listener.flush();
|
||||
} catch (IOException gone) {
|
||||
listeners.remove(listener);
|
||||
joining.remove(listener);
|
||||
closeQuietly(listener);
|
||||
}
|
||||
}
|
||||
|
||||
private static void closeQuietly(OutputStream stream) {
|
||||
try {
|
||||
stream.close();
|
||||
} catch (IOException ignored) {
|
||||
}
|
||||
}
|
||||
|
||||
/** @param running whether the world has an engine again; the studio redraws either way */
|
||||
private record WorldChange(boolean running) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.bridge;
|
||||
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.structure.object.IrisObject;
|
||||
import art.arcane.iris.studio.map.BakeRun;
|
||||
import art.arcane.iris.studio.map.ObjectSource;
|
||||
import art.arcane.iris.studio.map.PackObjectSource;
|
||||
import art.arcane.iris.studio.map.ProceduralObjectSource;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.OptionalLong;
|
||||
|
||||
/** The studio's views of the pack's object files and of the procedural objects its biomes and regions bake, as block scenes. */
|
||||
final class StudioObjects implements StudioProfiles.ProfileView {
|
||||
static final String OBJECTS = "iris:objects";
|
||||
static final String PROCEDURAL = "iris:objects/procedural";
|
||||
private static final String BAKE_STAGE = "Bake";
|
||||
|
||||
private final String id;
|
||||
private final String label;
|
||||
private final String description;
|
||||
private final ObjectSource source;
|
||||
|
||||
private StudioObjects(String id, String label, String description, ObjectSource source) {
|
||||
this.id = id;
|
||||
this.label = label;
|
||||
this.description = description;
|
||||
this.source = source;
|
||||
}
|
||||
|
||||
static StudioObjects packObjects() {
|
||||
return new StudioObjects(OBJECTS, "Objects", "Every object in the pack in 3D, with the blocks it is made of", new PackObjectSource());
|
||||
}
|
||||
|
||||
static StudioObjects proceduralObjects() {
|
||||
return new StudioObjects(PROCEDURAL, "Procedural",
|
||||
"Trees, rock formations and more that Iris generates from settings, every variant in 3D", new ProceduralObjectSource());
|
||||
}
|
||||
|
||||
/** One timed bake of a procedural entry, as the studio's bake meter reads it. */
|
||||
record BakeTiming(int variantCount, List<Stage> stages) {
|
||||
record Stage(String label, long nanos) {
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String id() {
|
||||
return id;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String label() {
|
||||
return label;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String description() {
|
||||
return description;
|
||||
}
|
||||
|
||||
@Override
|
||||
public StudioProfiles.Sizes sizes() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasForm() {
|
||||
return false;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isBaked() {
|
||||
return source.isBaked();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<StudioProfiles.Entry> entries(Engine engine) {
|
||||
IrisData data = engine.getData();
|
||||
return source.keys(data).stream()
|
||||
.sorted(Comparator.naturalOrder())
|
||||
.map(key -> new StudioProfiles.Entry(key, nameOf(key), folderOf(key), Math.max(1, source.variants(data, key).size())))
|
||||
.toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProfileForm.Form form(Engine engine, String key, Map<String, String> overrides) {
|
||||
throw new NoSuchElementException(id + " has no settings form");
|
||||
}
|
||||
|
||||
@Override
|
||||
public SceneBlocks scene(Engine engine, String key, int variant, int size, Map<String, String> overrides) {
|
||||
IrisData data = engine.getData();
|
||||
source.keys(data);
|
||||
List<IrisObject> variants = source.variants(data, key);
|
||||
if (variants.isEmpty()) {
|
||||
throw new NoSuchElementException("No object " + key);
|
||||
}
|
||||
return StudioProfiles.sceneOf(variants.get(Math.floorMod(variant, variants.size())));
|
||||
}
|
||||
|
||||
@Override
|
||||
public BakeTiming timeBake(Engine engine, String key) {
|
||||
IrisData data = engine.getData();
|
||||
source.keys(data);
|
||||
OptionalLong seed = source.seed(key);
|
||||
if (seed.isEmpty()) {
|
||||
throw new NoSuchElementException("No baked entry " + key);
|
||||
}
|
||||
BakeRun run = source.timeBake(data, key, seed.getAsLong());
|
||||
if (run == null) {
|
||||
throw new NoSuchElementException("No baked entry " + key);
|
||||
}
|
||||
return new BakeTiming(run.variantCount(), List.of(new BakeTiming.Stage(BAKE_STAGE, run.totalNanos())));
|
||||
}
|
||||
|
||||
private static String nameOf(String key) {
|
||||
return key.substring(key.lastIndexOf('/') + 1);
|
||||
}
|
||||
|
||||
private static String folderOf(String key) {
|
||||
int slash = key.lastIndexOf('/');
|
||||
return slash < 0 ? "" : key.substring(0, slash);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,461 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.bridge;
|
||||
|
||||
import art.arcane.iris.generation.biome.IrisBiome;
|
||||
import art.arcane.iris.generation.cave.IrisCaveProfile;
|
||||
import art.arcane.iris.generation.decoration.formation.IrisFormation;
|
||||
import art.arcane.iris.generation.decoration.formation.IrisFormationProfile;
|
||||
import art.arcane.iris.generation.decoration.tree.IrisProceduralTree;
|
||||
import art.arcane.iris.generation.decoration.tree.IrisTreeProfile;
|
||||
import art.arcane.iris.generation.hydrology.config.IrisFluidProfile;
|
||||
import art.arcane.iris.generation.mantle.CaveProfilePreview;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.generation.terrain.IrisDimension;
|
||||
import art.arcane.iris.generation.terrain.IrisRegion;
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.structure.object.IrisObject;
|
||||
import art.arcane.volmlib.util.collection.KList;
|
||||
import art.arcane.volmlib.util.documentation.Description;
|
||||
import art.arcane.volmlib.util.math.RNG;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.NoSuchElementException;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* The views of the config profiles Iris v4 has: cave profiles, tree profiles, formation profiles and fluid profiles.
|
||||
* Each lists what the pack has of its kind, shows its settings as a form and draws it as blocks, so the studio's scene
|
||||
* viewer can show them. Values typed into a form only change the preview.
|
||||
*/
|
||||
final class StudioProfiles {
|
||||
static final String CAVES = "caveProfiles";
|
||||
static final String TREES = "treeProfiles";
|
||||
static final String FORMATIONS = "formationProfiles";
|
||||
static final String FLUIDS = "fluidProfiles";
|
||||
|
||||
private static final List<ProfileView> VIEWS = List.of(new CaveView(), new TreeView(), new FormationView(), new FluidView(),
|
||||
StudioObjects.packObjects(), StudioObjects.proceduralObjects());
|
||||
|
||||
private StudioProfiles() {
|
||||
}
|
||||
|
||||
static List<ProfileView> views() {
|
||||
return VIEWS;
|
||||
}
|
||||
|
||||
static ProfileView view(String id) {
|
||||
return VIEWS.stream().filter(view -> view.id().equals(id)).findFirst()
|
||||
.orElseThrow(() -> new NoSuchElementException("No profile view " + id));
|
||||
}
|
||||
|
||||
record Entry(String key, String name, String group, int variants) {
|
||||
}
|
||||
|
||||
/** @param blocksAcross the sizes the scene can be built at, smallest first */
|
||||
record Sizes(List<Integer> blocksAcross, int opening) {
|
||||
}
|
||||
|
||||
interface ProfileView {
|
||||
String id();
|
||||
|
||||
String label();
|
||||
|
||||
String description();
|
||||
|
||||
/** Null when each entry draws one size. */
|
||||
Sizes sizes();
|
||||
|
||||
List<Entry> entries(Engine engine);
|
||||
|
||||
ProfileForm.Form form(Engine engine, String key, Map<String, String> overrides);
|
||||
|
||||
/** Whether each entry has a settings form; the object views have none. */
|
||||
default boolean hasForm() {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Whether the entries are baked from settings, so their bake can be timed. */
|
||||
default boolean isBaked() {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** One timed bake of the entry; only asked of baked views. */
|
||||
default StudioObjects.BakeTiming timeBake(Engine engine, String key) {
|
||||
throw new UnsupportedOperationException(id() + " is not baked");
|
||||
}
|
||||
|
||||
SceneBlocks scene(Engine engine, String key, int variant, int size, Map<String, String> overrides) throws IOException;
|
||||
}
|
||||
|
||||
private static String readable(String constantName) {
|
||||
String lower = constantName.toLowerCase(Locale.ROOT).replace('_', ' ');
|
||||
return Character.toUpperCase(lower.charAt(0)) + lower.substring(1);
|
||||
}
|
||||
|
||||
/** What the pack says about an enum constant, or its readable name when it says nothing. */
|
||||
private static String describe(Enum<?> constant) {
|
||||
try {
|
||||
Description description = constant.getDeclaringClass().getField(constant.name()).getAnnotation(Description.class);
|
||||
return description == null ? readable(constant.name()) : description.value();
|
||||
} catch (NoSuchFieldException undocumented) {
|
||||
return readable(constant.name());
|
||||
}
|
||||
}
|
||||
|
||||
private static Entry presetEntry(String key, int variants) {
|
||||
return new Entry(key, readable(key), "Presets", variants);
|
||||
}
|
||||
|
||||
static SceneBlocks sceneOf(IrisObject object) {
|
||||
SceneBlocks scene = new SceneBlocks();
|
||||
object.getBlocks().forEach((position, state) -> scene.add(position.getBlockX(), position.getBlockY(), position.getBlockZ(), state.key()));
|
||||
return scene;
|
||||
}
|
||||
|
||||
private static IrisObject variantOf(List<IrisObject> variants, int variant, String what) {
|
||||
if (variants.isEmpty()) {
|
||||
throw new NoSuchElementException("This " + what + " bakes nothing");
|
||||
}
|
||||
return variants.get(Math.floorMod(variant, variants.size()));
|
||||
}
|
||||
|
||||
// Caves ------------------------------------------------------------------------------------------------------
|
||||
|
||||
private static final class CaveView implements ProfileView {
|
||||
private static final Sizes SIZES = new Sizes(List.of(64, 128, 256), 128);
|
||||
private static final int VARIANTS = 4;
|
||||
private static final int VARIANT_SPACING_BLOCKS = 4096;
|
||||
private static final int SURFACE_ABOVE_SEA_BLOCKS = 48;
|
||||
private static final int MAX_DEPTH_BLOCKS = 160;
|
||||
private static final String DIMENSION_KEY = "dimension";
|
||||
private static final String REGION_PREFIX = "region/";
|
||||
private static final String BIOME_PREFIX = "biome/";
|
||||
private static final String[] DEPTH_BANDS = {"minecraft:yellow_concrete", "minecraft:lime_concrete", "minecraft:light_blue_concrete",
|
||||
"minecraft:purple_concrete"};
|
||||
private static final int[][] NEIGHBOURS = {{1, 0, 0}, {-1, 0, 0}, {0, 1, 0}, {0, -1, 0}, {0, 0, 1}, {0, 0, -1}};
|
||||
|
||||
@Override
|
||||
public String id() {
|
||||
return CAVES;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String label() {
|
||||
return "Cave profiles";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String description() {
|
||||
return "The carved space of each enabled cave profile of the dimension, its regions and its biomes";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Sizes sizes() {
|
||||
return SIZES;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Entry> entries(Engine engine) {
|
||||
IrisData data = engine.getData();
|
||||
IrisDimension dimension = engine.getDimension();
|
||||
List<Entry> entries = new ArrayList<>();
|
||||
if (dimension.getCaveProfile().isEnabled()) {
|
||||
entries.add(new Entry(DIMENSION_KEY, dimension.getName(), "Dimension", VARIANTS));
|
||||
}
|
||||
for (IrisRegion region : data.getRegionLoader().loadAll(data.getRegionLoader().getPossibleKeys())) {
|
||||
if (region != null && region.getCaveProfile().isEnabled()) {
|
||||
entries.add(new Entry(REGION_PREFIX + region.getLoadKey(), region.getName(), "Regions", VARIANTS));
|
||||
}
|
||||
}
|
||||
for (IrisBiome biome : data.getBiomeLoader().loadAll(data.getBiomeLoader().getPossibleKeys())) {
|
||||
if (biome != null && biome.getCaveProfile().isEnabled()) {
|
||||
entries.add(new Entry(BIOME_PREFIX + biome.getLoadKey(), biome.getName(), "Biomes", VARIANTS));
|
||||
}
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProfileForm.Form form(Engine engine, String key, Map<String, String> overrides) {
|
||||
IrisCaveProfile profile = ProfileForm.withOverrides(profileOf(engine, key), overrides);
|
||||
return ProfileForm.of("Cave profile", profile, Set.of(), overrides, List.of("Values typed here change the preview only"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public SceneBlocks scene(Engine engine, String key, int variant, int size, Map<String, String> overrides) throws IOException {
|
||||
IrisCaveProfile profile = ProfileForm.withOverrides(profileOf(engine, key), overrides);
|
||||
int surfaceY = Math.min(engine.getHeight() - 1, engine.getDimension().getFluidHeight() + SURFACE_ABOVE_SEA_BLOCKS);
|
||||
int bottomY = Math.max(0, Math.max((int) Math.floor(profile.getVerticalRange().getMin()), surfaceY - MAX_DEPTH_BLOCKS));
|
||||
boolean[] carved = CaveProfilePreview.carve(engine, profile, Math.floorMod(variant, VARIANTS) * VARIANT_SPACING_BLOCKS, size, bottomY, surfaceY);
|
||||
return outsideOf(carved, size, surfaceY - bottomY + 1);
|
||||
}
|
||||
|
||||
private static IrisCaveProfile profileOf(Engine engine, String key) {
|
||||
IrisData data = engine.getData();
|
||||
IrisCaveProfile profile = null;
|
||||
if (DIMENSION_KEY.equals(key)) {
|
||||
profile = engine.getDimension().getCaveProfile();
|
||||
} else if (key.startsWith(REGION_PREFIX)) {
|
||||
IrisRegion region = data.getRegionLoader().load(key.substring(REGION_PREFIX.length()));
|
||||
profile = region == null ? null : region.getCaveProfile();
|
||||
} else if (key.startsWith(BIOME_PREFIX)) {
|
||||
IrisBiome biome = data.getBiomeLoader().load(key.substring(BIOME_PREFIX.length()));
|
||||
profile = biome == null ? null : biome.getCaveProfile();
|
||||
}
|
||||
if (profile == null) {
|
||||
throw new NoSuchElementException("No cave profile " + key);
|
||||
}
|
||||
return profile;
|
||||
}
|
||||
|
||||
// Only the carved blocks on the outside of the space are kept, as the inside could not be seen.
|
||||
private static SceneBlocks outsideOf(boolean[] carved, int size, int height) {
|
||||
SceneBlocks scene = new SceneBlocks();
|
||||
for (int y = 0; y < height; y++) {
|
||||
String band = DEPTH_BANDS[Math.min(DEPTH_BANDS.length - 1, (height - 1 - y) * DEPTH_BANDS.length / height)];
|
||||
for (int z = 0; z < size; z++) {
|
||||
for (int x = 0; x < size; x++) {
|
||||
if (carved[cellOf(x, y, z, size)] && touchesRock(carved, x, y, z, size, height)) {
|
||||
scene.add(x, y, z, band);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return scene;
|
||||
}
|
||||
|
||||
private static boolean touchesRock(boolean[] carved, int x, int y, int z, int size, int height) {
|
||||
for (int[] step : NEIGHBOURS) {
|
||||
int nx = x + step[0];
|
||||
int ny = y + step[1];
|
||||
int nz = z + step[2];
|
||||
boolean inside = nx >= 0 && ny >= 0 && nz >= 0 && nx < size && ny < height && nz < size;
|
||||
if (!inside || !carved[cellOf(nx, ny, nz, size)]) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static int cellOf(int x, int y, int z, int size) {
|
||||
return (y * size + z) * size + x;
|
||||
}
|
||||
}
|
||||
|
||||
// Trees ------------------------------------------------------------------------------------------------------
|
||||
|
||||
private static final class TreeView implements ProfileView {
|
||||
private static final Set<String> HIDDEN = Set.of("name", "chance", "density", "variants", "seed", "plausible", "mode",
|
||||
"carvingSupport", "underwater", "profile");
|
||||
|
||||
@Override
|
||||
public String id() {
|
||||
return TREES;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String label() {
|
||||
return "Tree profiles";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String description() {
|
||||
return "The canopy shape each tree profile gives a procedural tree";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Sizes sizes() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Entry> entries(Engine engine) {
|
||||
int variants = new IrisProceduralTree().getVariants();
|
||||
return Arrays.stream(IrisTreeProfile.values()).map(profile -> presetEntry(profile.name(), variants)).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProfileForm.Form form(Engine engine, String key, Map<String, String> overrides) {
|
||||
return ProfileForm.of("Tree", treeOf(key, overrides), HIDDEN, overrides,
|
||||
List.of(describe(profileOf(key)), "Values typed here change the preview only"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public SceneBlocks scene(Engine engine, String key, int variant, int size, Map<String, String> overrides) {
|
||||
return sceneOf(variantOf(treeOf(key, overrides).getVariantObjects(engine.getData()), variant, "tree"));
|
||||
}
|
||||
|
||||
private static IrisProceduralTree treeOf(String key, Map<String, String> overrides) {
|
||||
IrisProceduralTree tree = ProfileForm.withOverrides(new IrisProceduralTree(), overrides);
|
||||
tree.setProfile(profileOf(key));
|
||||
return tree;
|
||||
}
|
||||
|
||||
private static IrisTreeProfile profileOf(String key) {
|
||||
try {
|
||||
return IrisTreeProfile.valueOf(key);
|
||||
} catch (IllegalArgumentException unknown) {
|
||||
throw new NoSuchElementException("No tree profile " + key);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Formations -------------------------------------------------------------------------------------------------
|
||||
|
||||
private static final class FormationView implements ProfileView {
|
||||
private static final Set<String> HIDDEN = Set.of("name", "chance", "density", "variants", "seed", "mode", "carvingSupport",
|
||||
"surfaceSupportBuffer", "underwater", "profile");
|
||||
|
||||
@Override
|
||||
public String id() {
|
||||
return FORMATIONS;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String label() {
|
||||
return "Formation profiles";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String description() {
|
||||
return "How each formation profile shapes a formation's width from base to top";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Sizes sizes() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Entry> entries(Engine engine) {
|
||||
int variants = new IrisFormation().getVariants();
|
||||
return Arrays.stream(IrisFormationProfile.values()).map(profile -> presetEntry(profile.name(), variants)).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProfileForm.Form form(Engine engine, String key, Map<String, String> overrides) {
|
||||
return ProfileForm.of("Formation", formationOf(key, overrides), HIDDEN, overrides,
|
||||
List.of(describe(profileOf(key)), "Values typed here change the preview only"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public SceneBlocks scene(Engine engine, String key, int variant, int size, Map<String, String> overrides) {
|
||||
return sceneOf(variantOf(formationOf(key, overrides).getVariantObjects(engine.getData()), variant, "formation"));
|
||||
}
|
||||
|
||||
private static IrisFormation formationOf(String key, Map<String, String> overrides) {
|
||||
IrisFormation formation = ProfileForm.withOverrides(new IrisFormation(), overrides);
|
||||
formation.setProfile(profileOf(key));
|
||||
return formation;
|
||||
}
|
||||
|
||||
private static IrisFormationProfile profileOf(String key) {
|
||||
try {
|
||||
return IrisFormationProfile.valueOf(key);
|
||||
} catch (IllegalArgumentException unknown) {
|
||||
throw new NoSuchElementException("No formation profile " + key);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Fluids -----------------------------------------------------------------------------------------------------
|
||||
|
||||
private static final class FluidView implements ProfileView {
|
||||
private static final Sizes SIZES = new Sizes(List.of(16, 32, 64), 32);
|
||||
private static final int VARIANTS = 4;
|
||||
private static final int VARIANT_SPACING_BLOCKS = 1024;
|
||||
private static final int DEPTH_BLOCKS = 3;
|
||||
private static final String BASIN_BLOCK = "minecraft:stone";
|
||||
|
||||
@Override
|
||||
public String id() {
|
||||
return FLUIDS;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String label() {
|
||||
return "Fluid profiles";
|
||||
}
|
||||
|
||||
@Override
|
||||
public String description() {
|
||||
return "The blocks of each named fluid of the dimension's hydrology, in a pool lined with its seam";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Sizes sizes() {
|
||||
return SIZES;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Entry> entries(Engine engine) {
|
||||
return fluids(engine).stream().map(fluid -> new Entry(fluid.getName(), fluid.getName(), "Fluids", VARIANTS)).toList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public ProfileForm.Form form(Engine engine, String key, Map<String, String> overrides) {
|
||||
IrisFluidProfile fluid = fluidOf(engine, key);
|
||||
IrisData data = engine.getData();
|
||||
List<String> notes = new ArrayList<>();
|
||||
notes.add("Blocks: " + String.join(", ", fluid.getPalette().getBlockData(data).stream().map(state -> state.key()).toList()));
|
||||
notes.add("Seam: " + (fluid.getSeam() == null ? "none" : fluid.getSeam()));
|
||||
return new ProfileForm.Form("Fluid", List.of(), notes);
|
||||
}
|
||||
|
||||
@Override
|
||||
public SceneBlocks scene(Engine engine, String key, int variant, int size, Map<String, String> overrides) {
|
||||
IrisData data = engine.getData();
|
||||
IrisFluidProfile fluid = fluidOf(engine, key);
|
||||
IrisFluidProfile seam = fluid.getSeam() == null ? null : fluidOf(engine, fluid.getSeam());
|
||||
int offset = Math.floorMod(variant, VARIANTS) * VARIANT_SPACING_BLOCKS;
|
||||
RNG rng = new RNG(offset + 1L);
|
||||
SceneBlocks scene = new SceneBlocks();
|
||||
for (int z = 0; z < size; z++) {
|
||||
for (int x = 0; x < size; x++) {
|
||||
scene.add(x, 0, z, BASIN_BLOCK);
|
||||
boolean wall = x == 0 || z == 0 || x == size - 1 || z == size - 1;
|
||||
boolean seamRing = seam != null && (x == 1 || z == 1 || x == size - 2 || z == size - 2);
|
||||
for (int y = 1; y <= DEPTH_BLOCKS; y++) {
|
||||
IrisFluidProfile filling = seamRing ? seam : fluid;
|
||||
scene.add(x, y, z, wall ? BASIN_BLOCK : filling.getPalette().get(rng, x + offset, y, z, data).key());
|
||||
}
|
||||
}
|
||||
}
|
||||
return scene;
|
||||
}
|
||||
|
||||
private static KList<IrisFluidProfile> fluids(Engine engine) {
|
||||
return engine.getDimension().getHydrology().getFluids();
|
||||
}
|
||||
|
||||
private static IrisFluidProfile fluidOf(Engine engine, String key) {
|
||||
Optional<IrisFluidProfile> found = fluids(engine).stream().filter(fluid -> key.equals(fluid.getName())).findFirst();
|
||||
return found.orElseThrow(() -> new NoSuchElementException("No fluid profile " + key));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.bridge;
|
||||
|
||||
import com.google.gson.Gson;
|
||||
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.ByteOrder;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* A square of the map as the Iris Studio app reads it, little endian:
|
||||
* <pre>
|
||||
* u32 header length | header, UTF-8 JSON | padding to 4 bytes
|
||||
* i16 subjects[grid²] | padding to 4 | i16 regions[grid²] | padding to 4 | f32 heights[grid²], when the header says so
|
||||
* </pre>
|
||||
* The grids hold {@code (size + 2)²} cells row by row: the tile's pixels inside a ring of the neighbouring tiles' edge
|
||||
* pixels, so edges and slopes continue across tiles. Subjects and regions index the header's labels.
|
||||
*
|
||||
* @param subjectKind BIOME, REGION or WATER: what the subjects are
|
||||
* @param heights null when the tile carries none
|
||||
*/
|
||||
record StudioTile(int size, double blocksPerPixel, String subjectKind, List<Label> labels, short[] subjects, short[] regions,
|
||||
float[] heights) {
|
||||
static final short NO_LABEL = -1;
|
||||
private static final int ALIGNMENT_BYTES = 4;
|
||||
|
||||
/** @param color 0xRRGGBB */
|
||||
record Label(String kind, String key, String name, int color) {
|
||||
}
|
||||
|
||||
byte[] encode(Gson gson) {
|
||||
byte[] header = gson.toJson(new Header(size, blocksPerPixel, subjectKind, labels, heights != null, false))
|
||||
.getBytes(StandardCharsets.UTF_8);
|
||||
int cells = (size + 2) * (size + 2);
|
||||
int length = aligned(Integer.BYTES + header.length) + aligned(cells * Short.BYTES) * 2
|
||||
+ (heights == null ? 0 : cells * Float.BYTES);
|
||||
ByteBuffer buffer = ByteBuffer.allocate(length).order(ByteOrder.LITTLE_ENDIAN);
|
||||
buffer.putInt(header.length).put(header);
|
||||
buffer.position(aligned(buffer.position()));
|
||||
putShorts(buffer, subjects);
|
||||
putShorts(buffer, regions);
|
||||
if (heights != null) {
|
||||
buffer.asFloatBuffer().put(heights);
|
||||
}
|
||||
return buffer.array();
|
||||
}
|
||||
|
||||
private static void putShorts(ByteBuffer buffer, short[] grid) {
|
||||
buffer.asShortBuffer().put(grid);
|
||||
buffer.position(aligned(buffer.position() + grid.length * Short.BYTES));
|
||||
}
|
||||
|
||||
private static int aligned(int bytes) {
|
||||
return (bytes + ALIGNMENT_BYTES - 1) / ALIGNMENT_BYTES * ALIGNMENT_BYTES;
|
||||
}
|
||||
|
||||
private record Header(int size, double blocksPerPixel, String subjectKind, List<Label> labels, boolean heights,
|
||||
boolean pickNoise) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.bridge;
|
||||
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.studio.map.RiverKey;
|
||||
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 art.arcane.iris.studio.map.components.MapTileRenderer;
|
||||
import art.arcane.iris.studio.map.components.PickDisplay;
|
||||
import art.arcane.iris.studio.map.components.TileType;
|
||||
import art.arcane.iris.studio.render.IrisRenderer;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.CancellationException;
|
||||
import java.util.function.BooleanSupplier;
|
||||
|
||||
/** Draws the studio app's map views with the renderer the Swing map uses, one tile at a time. */
|
||||
final class StudioTiles {
|
||||
private static final int RGB = 0xFFFFFF;
|
||||
private static final short DRY = 0;
|
||||
private static final String DRY_KEY = "dry";
|
||||
private static final int DRY_COLOR = 0x1C1F26;
|
||||
private static final int MAX_FINISH_ATTEMPTS = 200;
|
||||
private static final long FINISH_WAIT_MILLIS = 50L;
|
||||
|
||||
private final Engine engine;
|
||||
private final MapTileRenderer renderer;
|
||||
private final IrisRenderer waterRenderer;
|
||||
private final List<StudioTile.Label> waterLabels;
|
||||
private final Map<Integer, Short> waterLabelByColor;
|
||||
|
||||
StudioTiles(Engine engine, MapTileRenderer renderer) {
|
||||
this.engine = engine;
|
||||
this.renderer = renderer;
|
||||
this.waterRenderer = new IrisRenderer(engine);
|
||||
List<StudioTile.Label> labels = new ArrayList<>();
|
||||
labels.add(new StudioTile.Label("WATER", DRY_KEY, "No water", DRY_COLOR));
|
||||
Map<Integer, Short> byColor = new HashMap<>();
|
||||
for (RiverKey.Row row : RiverKey.rows()) {
|
||||
byColor.put(row.color() & RGB, (short) labels.size());
|
||||
labels.add(new StudioTile.Label("WATER", row.label(), row.label(), row.color() & RGB));
|
||||
}
|
||||
this.waterLabels = List.copyOf(labels);
|
||||
this.waterLabelByColor = Map.copyOf(byColor);
|
||||
}
|
||||
|
||||
boolean hydrologyEnabled() {
|
||||
var runtime = engine.getComplex().getHydrologyRuntime();
|
||||
return runtime != null && runtime.enabled();
|
||||
}
|
||||
|
||||
StudioTile biomesOrRegions(String view, String previewRegion, double startX, double startZ, double blocksPerPixel, int size,
|
||||
boolean withHeights, BooleanSupplier cancelled) {
|
||||
MapLayer layer = layerOf(view, previewRegion);
|
||||
boolean heightsWanted = withHeights || layer.type() == TileType.HEIGHT;
|
||||
MapTileRenderer.TileRender render = renderer.prepareTile(startX, startZ, blocksPerPixel, size, layer, heightsWanted);
|
||||
MapTile tile = render.render(cancelled);
|
||||
for (int attempt = 0; !render.complete() && attempt < MAX_FINISH_ATTEMPTS; attempt++) {
|
||||
pause(cancelled);
|
||||
tile = render.render(cancelled);
|
||||
}
|
||||
return wire(tile, blocksPerPixel, heightsWanted && tile.hasHeights(), layer.type());
|
||||
}
|
||||
|
||||
StudioTile rivers(double startX, double startZ, double blocksPerPixel, int size, BooleanSupplier cancelled) {
|
||||
int grid = size + 2;
|
||||
short[] subjects = new short[grid * grid];
|
||||
Arrays.fill(subjects, DRY);
|
||||
if (hydrologyEnabled()) {
|
||||
IrisRenderer.WaterTile water = waterRenderer.prepareStudioWater(startX - blocksPerPixel, startZ - blocksPerPixel, blocksPerPixel, grid);
|
||||
int[] colors = water.render(null, false, cancelled);
|
||||
for (int attempt = 0; !water.complete() && attempt < MAX_FINISH_ATTEMPTS; attempt++) {
|
||||
pause(cancelled);
|
||||
colors = water.render(null, false, cancelled);
|
||||
}
|
||||
for (int cell = 0; cell < colors.length; cell++) {
|
||||
subjects[cell] = waterLabelByColor.getOrDefault(colors[cell] & RGB, DRY);
|
||||
}
|
||||
}
|
||||
return new StudioTile(size, blocksPerPixel, "WATER", waterLabels, subjects, subjects, null);
|
||||
}
|
||||
|
||||
private static MapLayer layerOf(String view, String previewRegion) {
|
||||
return switch (view) {
|
||||
case "regions" -> previewRegion == null ? MapLayer.regions(PickDisplay.PICKS) : MapLayer.regionPreview(previewRegion, PickDisplay.PICKS);
|
||||
case "height" -> MapLayer.of(TileType.HEIGHT);
|
||||
case "land-biomes" -> MapLayer.of(TileType.BIOME_LAND);
|
||||
case "sea-biomes" -> MapLayer.of(TileType.BIOME_SEA);
|
||||
case "cave-biomes" -> MapLayer.of(TileType.CAVE_LAND);
|
||||
case "object-load" -> MapLayer.of(TileType.OBJECT_LOAD);
|
||||
case "decorator-load" -> MapLayer.of(TileType.DECORATOR_LOAD);
|
||||
case "layer-load" -> MapLayer.of(TileType.LAYER_LOAD);
|
||||
default -> MapLayer.biomes(PickDisplay.PICKS, false);
|
||||
};
|
||||
}
|
||||
|
||||
private StudioTile wire(MapTile tile, double blocksPerPixel, boolean withHeights, TileType legendType) {
|
||||
int size = tile.size();
|
||||
int grid = size + 2;
|
||||
Labelling labelling = new Labelling();
|
||||
short[] subjects = new short[grid * grid];
|
||||
short[] regions = new short[grid * grid];
|
||||
float[] heights = withHeights ? new float[grid * grid] : null;
|
||||
for (int z = -1; z <= size; z++) {
|
||||
for (int x = -1; x <= size; x++) {
|
||||
int cell = (z + 1) * grid + x + 1;
|
||||
subjects[cell] = labelling.indexOf(tile.labels(), tile.subjectAt(x, z));
|
||||
regions[cell] = labelling.indexOf(tile.labels(), tile.regionAt(x, z));
|
||||
if (heights != null) {
|
||||
heights[cell] = (float) tile.heightAt(x, z);
|
||||
}
|
||||
}
|
||||
}
|
||||
List<StudioTile.Label> labels = labelling.labels(renderer, legendType);
|
||||
return new StudioTile(size, blocksPerPixel, tile.subjectKind().name(), labels, subjects, regions, heights);
|
||||
}
|
||||
|
||||
private static void pause(BooleanSupplier cancelled) {
|
||||
if (cancelled.getAsBoolean()) {
|
||||
throw new CancellationException("Tile dropped");
|
||||
}
|
||||
try {
|
||||
Thread.sleep(FINISH_WAIT_MILLIS);
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new CancellationException("Tile interrupted");
|
||||
}
|
||||
}
|
||||
|
||||
/** Renumbers the labels a tile uses from 0, so its header lists only those. */
|
||||
private static final class Labelling {
|
||||
private final Map<Short, Short> indexByLabelId = new HashMap<>();
|
||||
private final List<Short> usedLabelIds = new ArrayList<>();
|
||||
|
||||
short indexOf(MapLabels labels, short labelId) {
|
||||
if (labelId == MapLabels.NONE || labels.label(labelId) == null) {
|
||||
return StudioTile.NO_LABEL;
|
||||
}
|
||||
return indexByLabelId.computeIfAbsent(labelId, id -> {
|
||||
usedLabelIds.add(id);
|
||||
return (short) (usedLabelIds.size() - 1);
|
||||
});
|
||||
}
|
||||
|
||||
List<StudioTile.Label> labels(MapTileRenderer renderer, TileType legendType) {
|
||||
List<StudioTile.Label> labels = new ArrayList<>();
|
||||
for (short id : usedLabelIds) {
|
||||
MapLabels.Label label = renderer.labels().label(id);
|
||||
labels.add(new StudioTile.Label(label.kind().name(), label.key(), label.name(),
|
||||
renderer.legendColor(label, legendType) & RGB));
|
||||
}
|
||||
return labels;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.bridge;
|
||||
|
||||
import art.arcane.iris.configuration.IrisSettings;
|
||||
import art.arcane.iris.spi.IrisLogging;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Opens the Iris Studio window on a bridge, from the app folder the studio settings name. The app keeps one window:
|
||||
* a second start hands its link to the open window and exits. Windows the server started close when it stops, as
|
||||
* their bridges go with it.
|
||||
*/
|
||||
public final class StudioWindow {
|
||||
private static final Path LOG_FILE = Path.of(System.getProperty("user.home"), ".iris", "studio", "window.log");
|
||||
private static final String DEFAULT_ELECTRON = "electron";
|
||||
private static final String BUILT_MAIN = "out/main/index.js";
|
||||
/** Set by terminals that are Electron apps themselves; left in, Electron would start as plain Node with no window. */
|
||||
private static final String RUN_AS_PLAIN_NODE = "ELECTRON_RUN_AS_NODE";
|
||||
private static final List<Process> STARTED = new ArrayList<>();
|
||||
|
||||
private StudioWindow() {
|
||||
}
|
||||
|
||||
/** False when no app is set or it could not start, so the caller's printed link is the only way in. */
|
||||
public static synchronized boolean show(StudioBridge bridge) {
|
||||
IrisSettings.IrisSettingsStudio settings = IrisSettings.get().getStudio();
|
||||
String appFolder = settings.getStudioApp();
|
||||
if (appFolder == null || appFolder.isBlank()) {
|
||||
return false;
|
||||
}
|
||||
Path app = Path.of(appFolder);
|
||||
if (!Files.isRegularFile(app.resolve(BUILT_MAIN))) {
|
||||
IrisLogging.warn("Iris Studio is not built in %s; run npm run build there.", app);
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
STARTED.removeIf(process -> !process.isAlive());
|
||||
STARTED.add(start(electronBinary(settings), app, bridge.link()));
|
||||
return true;
|
||||
} catch (IOException error) {
|
||||
IrisLogging.warn("Could not open Iris Studio: %s", error.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static synchronized void closeAll() {
|
||||
STARTED.forEach(Process::destroy);
|
||||
STARTED.clear();
|
||||
}
|
||||
|
||||
private static Process start(String electron, Path app, String link) throws IOException {
|
||||
Files.createDirectories(LOG_FILE.getParent());
|
||||
ProcessBuilder builder = new ProcessBuilder(electron, app.toString(), link)
|
||||
.redirectErrorStream(true)
|
||||
.redirectOutput(ProcessBuilder.Redirect.to(LOG_FILE.toFile()));
|
||||
builder.environment().remove(RUN_AS_PLAIN_NODE);
|
||||
return builder.start();
|
||||
}
|
||||
|
||||
private static String electronBinary(IrisSettings.IrisSettingsStudio settings) {
|
||||
String electron = settings.getElectron();
|
||||
return electron == null || electron.isBlank() ? DEFAULT_ELECTRON : electron;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Servers
|
||||
* Copyright (c) 2026 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.bridge;
|
||||
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.studio.map.components.MapTileRenderer;
|
||||
import art.arcane.iris.studio.view.GuiHost;
|
||||
import art.arcane.iris.studio.view.GuiOverlay;
|
||||
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
import java.util.function.Supplier;
|
||||
|
||||
/**
|
||||
* The world a bridge shows. Its engine is asked for again whenever the one in use closes, as a hotload or a restart of
|
||||
* the world does, so a bridge outlives them.
|
||||
*/
|
||||
final class StudioWorld {
|
||||
private final String name;
|
||||
private final Supplier<Engine> engines;
|
||||
private final UUID openerId;
|
||||
private Session session;
|
||||
|
||||
/**
|
||||
* @param engines the world's engine now; null while it has none
|
||||
* @param openerId the player the studio teleports, or null when the console opened it
|
||||
*/
|
||||
StudioWorld(String name, Supplier<Engine> engines, UUID openerId) {
|
||||
this.name = Objects.requireNonNull(name, "name");
|
||||
this.engines = Objects.requireNonNull(engines, "engines");
|
||||
this.openerId = openerId;
|
||||
}
|
||||
|
||||
String name() {
|
||||
return name;
|
||||
}
|
||||
|
||||
/** The world's engine and what the bridge draws it with; null while the world has no running engine. */
|
||||
synchronized Session session() {
|
||||
if (session != null && isRunning(session.engine())) {
|
||||
return session;
|
||||
}
|
||||
Engine engine = engines.get();
|
||||
session = isRunning(engine)
|
||||
? new Session(engine, new StudioTiles(engine, new MapTileRenderer(engine)), GuiHost.get().overlayFor(engine, openerId))
|
||||
: null;
|
||||
return session;
|
||||
}
|
||||
|
||||
private static boolean isRunning(Engine engine) {
|
||||
return engine != null && !engine.isClosed() && !engine.isClosing() && engine.getComplex() != null;
|
||||
}
|
||||
|
||||
/** @param overlay the server's players and teleports; null on a platform without one */
|
||||
record Session(Engine engine, StudioTiles tiles, GuiOverlay overlay) {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
/*
|
||||
* Iris is a World Generator for Minecraft Bukkit Servers
|
||||
* Copyright (c) 2022 Arcane Arts (Volmit Software)
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, either version 3 of the License, or
|
||||
* (at your option) any later version.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful,
|
||||
* but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
* GNU General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
package art.arcane.iris.studio.imagemap;
|
||||
|
||||
import art.arcane.iris.generation.image.CompiledIrisImageMap;
|
||||
import art.arcane.iris.generation.image.IrisImageMap;
|
||||
import art.arcane.iris.generation.image.IrisImageMapOrigin;
|
||||
import art.arcane.iris.generation.image.IrisImageMapRotation;
|
||||
import art.arcane.iris.generation.runtime.Engine;
|
||||
import art.arcane.iris.pack.loading.IrisData;
|
||||
import art.arcane.iris.studio.workspace.ImageMapStudioExporter;
|
||||
|
||||
import javax.imageio.ImageIO;
|
||||
import java.awt.image.BufferedImage;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.NoSuchElementException;
|
||||
|
||||
/** The pack's image-map presets as the studio lists, describes and previews them over the world area they cover. */
|
||||
public final class ImageMapPreviews {
|
||||
private static final int BACKGROUND_COLOR = 0x252936;
|
||||
private static final int MAP_ERROR_COLOR = 0xFF3DA8;
|
||||
private static final int SMALLEST_PREVIEW_PIXELS = 64;
|
||||
private static final int LARGEST_PREVIEW_PIXELS = 2048;
|
||||
|
||||
private ImageMapPreviews() {
|
||||
}
|
||||
|
||||
public record Entry(String key, String name, String group, int variants) {
|
||||
}
|
||||
|
||||
/** @param bounds the world area the map covers: minimum X, minimum Z, maximum X, maximum Z */
|
||||
public record Details(String key, String type, String source, int width, int height, double blocksPerPixel, double[] bounds,
|
||||
List<String> facts) {
|
||||
}
|
||||
|
||||
public static List<Entry> entries(Engine engine) {
|
||||
String[] keys = engine.getData().getImageMapLoader().getPossibleKeys();
|
||||
if (keys == null) {
|
||||
return List.of();
|
||||
}
|
||||
return Arrays.stream(keys).sorted().map(key -> new Entry(key, key.substring(key.lastIndexOf('/') + 1), folderOf(key), 1)).toList();
|
||||
}
|
||||
|
||||
public static Details details(Engine engine, String key) throws IOException {
|
||||
Loaded loaded = load(engine, key);
|
||||
IrisImageMap definition = loaded.definition();
|
||||
List<String> facts = new ArrayList<>();
|
||||
facts.add("Source " + definition.getSource() + ".png, " + loaded.compiled().getSourceWidth() + " × " + loaded.compiled().getSourceHeight() + " pixels");
|
||||
facts.add(definition.getBlocksPerPixel() + " blocks per pixel");
|
||||
if (definition.getType().name().endsWith("HEIGHT")) {
|
||||
facts.add("Heights " + definition.getMinimumHeight() + " to " + definition.getMaximumHeight());
|
||||
}
|
||||
if (loaded.compiled().getClippedPixelCount() > 0) {
|
||||
facts.add(loaded.compiled().getClippedPixelCount() + " pixels clipped to the height range");
|
||||
}
|
||||
if (loaded.compiled().getUnknownColorPixelCount() > 0) {
|
||||
facts.add(loaded.compiled().getUnknownColorPixelCount() + " pixels of a colour the legend does not name");
|
||||
}
|
||||
return new Details(key, readable(definition.getType().name()), definition.getSource(), loaded.compiled().getSourceWidth(),
|
||||
loaded.compiled().getSourceHeight(), definition.getBlocksPerPixel(), worldBounds(loaded), List.copyOf(facts));
|
||||
}
|
||||
|
||||
/** A PNG of the world area the map covers, {@code pixels} across its longer side. */
|
||||
public static byte[] preview(Engine engine, String key, int pixels) throws IOException {
|
||||
if (pixels < SMALLEST_PREVIEW_PIXELS || pixels > LARGEST_PREVIEW_PIXELS) {
|
||||
throw new IllegalArgumentException("A preview is " + SMALLEST_PREVIEW_PIXELS + " to " + LARGEST_PREVIEW_PIXELS + " pixels");
|
||||
}
|
||||
Loaded loaded = load(engine, key);
|
||||
double[] bounds = worldBounds(loaded);
|
||||
double spanX = bounds[2] - bounds[0];
|
||||
double spanZ = bounds[3] - bounds[1];
|
||||
double blocksPerPixel = Math.max(spanX, spanZ) / pixels;
|
||||
int width = Math.max(1, (int) Math.round(spanX / blocksPerPixel));
|
||||
int height = Math.max(1, (int) Math.round(spanZ / blocksPerPixel));
|
||||
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
|
||||
for (int row = 0; row < height; row++) {
|
||||
for (int column = 0; column < width; column++) {
|
||||
image.setRGB(column, row, colorAt(loaded, bounds[0] + column * blocksPerPixel, bounds[1] + row * blocksPerPixel));
|
||||
}
|
||||
}
|
||||
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
|
||||
ImageIO.write(image, "png", bytes);
|
||||
return bytes.toByteArray();
|
||||
}
|
||||
|
||||
private static int colorAt(Loaded loaded, double worldX, double worldZ) {
|
||||
CompiledIrisImageMap compiled = loaded.compiled();
|
||||
if (!compiled.containsWorld(worldX, worldZ)) {
|
||||
return BACKGROUND_COLOR;
|
||||
}
|
||||
try {
|
||||
return switch (loaded.definition().getType()) {
|
||||
case GRAYSCALE_HEIGHT, RGB_HEIGHT -> heightColor(compiled.sampleHeight(worldX, worldZ),
|
||||
loaded.definition().getMinimumHeight(), loaded.definition().getMaximumHeight());
|
||||
case COLOR_MAP -> targetColor(compiled.sampleTarget(worldX, worldZ));
|
||||
case BINARY_MASK, GRAYSCALE_MASK, ALPHA_MASK -> grayscale(compiled.sampleNormalized(worldX, worldZ));
|
||||
};
|
||||
} catch (RuntimeException unsampleable) {
|
||||
return MAP_ERROR_COLOR;
|
||||
}
|
||||
}
|
||||
|
||||
private static Loaded load(Engine engine, String key) throws IOException {
|
||||
IrisData data = engine.getData();
|
||||
IrisImageMap loaded = data.getImageMapLoader().load(key);
|
||||
if (loaded == null) {
|
||||
throw new NoSuchElementException("No image map " + key);
|
||||
}
|
||||
IrisImageMap definition = data.getGson().fromJson(data.getGson().toJson(loaded), IrisImageMap.class);
|
||||
File source = data.getImageLoader().findFile(definition.getSource());
|
||||
if (source == null || !source.isFile()) {
|
||||
throw new NoSuchElementException("The source PNG " + definition.getSource() + " is missing");
|
||||
}
|
||||
CompiledIrisImageMap compiled = ImageMapStudioExporter.preview(source.toPath(), definition).compiled();
|
||||
return new Loaded(definition, compiled);
|
||||
}
|
||||
|
||||
private static double[] worldBounds(Loaded loaded) {
|
||||
double[][] corners = {
|
||||
sourceToWorld(loaded.definition(), 0, 0),
|
||||
sourceToWorld(loaded.definition(), loaded.compiled().getSourceWidth(), 0),
|
||||
sourceToWorld(loaded.definition(), loaded.compiled().getSourceWidth(), loaded.compiled().getSourceHeight()),
|
||||
sourceToWorld(loaded.definition(), 0, loaded.compiled().getSourceHeight())
|
||||
};
|
||||
double[] bounds = {Double.MAX_VALUE, Double.MAX_VALUE, -Double.MAX_VALUE, -Double.MAX_VALUE};
|
||||
for (double[] corner : corners) {
|
||||
bounds[0] = Math.min(bounds[0], corner[0]);
|
||||
bounds[1] = Math.min(bounds[1], corner[1]);
|
||||
bounds[2] = Math.max(bounds[2], corner[0]);
|
||||
bounds[3] = Math.max(bounds[3], corner[1]);
|
||||
}
|
||||
return bounds;
|
||||
}
|
||||
|
||||
private static 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;
|
||||
}
|
||||
double[] rotated = rotated(x, z, definition.getRotation());
|
||||
return new double[]{origin.getX() + rotated[0] * definition.getBlocksPerPixel(), origin.getZ() + rotated[1] * definition.getBlocksPerPixel()};
|
||||
}
|
||||
|
||||
private static double[] rotated(double x, double z, IrisImageMapRotation rotation) {
|
||||
return switch (rotation) {
|
||||
case DEG_0 -> new double[]{x, z};
|
||||
case DEG_90 -> new double[]{-z, x};
|
||||
case DEG_180 -> new double[]{-x, -z};
|
||||
case DEG_270 -> new double[]{z, -x};
|
||||
};
|
||||
}
|
||||
|
||||
private static int targetColor(String target) {
|
||||
if (target == null) {
|
||||
return BACKGROUND_COLOR;
|
||||
}
|
||||
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 (red << 16) | (green << 8) | blue;
|
||||
}
|
||||
|
||||
private 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 ((int) red << 16) | ((int) green << 8) | (int) blue;
|
||||
}
|
||||
|
||||
private static int grayscale(double normalized) {
|
||||
int level = (int) Math.round(Math.max(0D, Math.min(1D, normalized)) * 255D);
|
||||
return (level << 16) | (level << 8) | level;
|
||||
}
|
||||
|
||||
private static String folderOf(String key) {
|
||||
int slash = key.lastIndexOf('/');
|
||||
return slash < 0 ? "" : key.substring(0, slash);
|
||||
}
|
||||
|
||||
private static String readable(String constantName) {
|
||||
String lower = constantName.toLowerCase(Locale.ROOT).replace('_', ' ');
|
||||
return Character.toUpperCase(lower.charAt(0)) + lower.substring(1);
|
||||
}
|
||||
|
||||
private record Loaded(IrisImageMap definition, CompiledIrisImageMap compiled) {
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -21,5 +21,5 @@ package art.arcane.iris.studio.map;
|
||||
/**
|
||||
* How long one bake of a procedural object's variants took.
|
||||
*/
|
||||
record BakeRun(long totalNanos, int variantCount) {
|
||||
public record BakeRun(long totalNanos, int variantCount) {
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<BakeRun> bake, BooleanSupplier stillWanted) {
|
||||
List<BakeRun> 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 "<html>" + variants + " in " + formatMillis(totalMillis()) + " · median of " + RUN_COUNT + " runs<br>"
|
||||
+ "Paid once per pack load, by the first chunk placing it<br>"
|
||||
+ BakeWeight.scale() + "</html>";
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<Engine> engineSource;
|
||||
private final PickInspectorPanel inspector;
|
||||
private final LatestMeasurement<Measurement> 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<Engine> engineSource, Consumer<PickDisplay> 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<PickInspectorPanel.Section> sections = new ArrayList<>();
|
||||
for (RegionPicks region : measurement.regions()) {
|
||||
List<JComponent> 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<IrisRegion, RegionSamples> 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<RegionPicks> 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<TypedSpread> spreads;
|
||||
private final Map<InferredType, ProceduralStream<Double>> 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<TypedSpread> 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<NoisePickSpread> spreads) {
|
||||
}
|
||||
|
||||
private record Measurement(List<RegionPicks> regions) {
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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.
|
||||
* <p>
|
||||
* 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.
|
||||
* <p>
|
||||
* 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
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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";
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
|
||||
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<Face> faces, Set<CubeFace> 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<Face> faces) {
|
||||
Set<CubeFace> 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<Face> 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<BlockTexture> change) {
|
||||
Map<BlockTexture, BlockTexture> changed = new IdentityHashMap<>();
|
||||
List<Face> 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<Face> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
|
||||
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<BlockModel> build(String blockState) {
|
||||
try {
|
||||
BlockStateId state = BlockStateId.parse(blockState);
|
||||
List<JsonObject> placements = placementsOf(state);
|
||||
if (placements == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
List<Face> 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<Face> box(Vec3 fromPixels, Vec3 toPixels, BlockTexture texture, boolean culledBySides) {
|
||||
List<Face> 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<JsonObject> placementsOf(BlockStateId state) throws IOException {
|
||||
JsonObject definition = textures.readJson(BlockTextures.assetPath(state.namespace() + ":" + state.name(), "blockstates", ".json"));
|
||||
if (definition == null) {
|
||||
return null;
|
||||
}
|
||||
List<JsonObject> placements = new ArrayList<>();
|
||||
if (definition.has("variants")) {
|
||||
for (Map.Entry<String, JsonElement> 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<JsonObject> placements, JsonElement models) {
|
||||
JsonObject first = BlockTextures.firstModel(models);
|
||||
if (first != null && first.has("model")) {
|
||||
placements.add(first);
|
||||
}
|
||||
}
|
||||
|
||||
private List<Face> 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<Face> faces = new ArrayList<>();
|
||||
for (JsonElement element : model.elements()) {
|
||||
addElementFaces(faces, state, model, element.getAsJsonObject(), rotation);
|
||||
}
|
||||
return faces;
|
||||
}
|
||||
|
||||
private void addElementFaces(List<Face> 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<String, JsonElement> 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<BlockTexture> 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);
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -49,10 +49,8 @@ final class BlockTextures {
|
||||
private final ZipFile clientJar;
|
||||
private final MinecraftBiomeColors biomeColors;
|
||||
private final Map<String, Optional<ResolvedTexture>> resolvedTextures = new ConcurrentHashMap<>();
|
||||
private final Map<String, Optional<BlockModel>> resolvedModels = new ConcurrentHashMap<>();
|
||||
private final Map<String, Optional<BlockTexture>> faceTextures = new ConcurrentHashMap<>();
|
||||
private final Map<String, Optional<BlockTexture>> icons = new ConcurrentHashMap<>();
|
||||
private final BlockModelBuilder modelBuilder = new BlockModelBuilder(this);
|
||||
|
||||
private BlockTextures(ZipFile clientJar, MinecraftBiomeColors biomeColors) {
|
||||
this.clientJar = clientJar;
|
||||
@@ -134,13 +132,6 @@ final class BlockTextures {
|
||||
.filter(ResolvedTexture::isSideOnSprite).map(ResolvedTexture::texture);
|
||||
}
|
||||
|
||||
/**
|
||||
* What the block looks like from every side, for drawing it in 3D.
|
||||
*/
|
||||
Optional<BlockModel> model(NativeBlockState block) {
|
||||
return resolvedModels.computeIfAbsent(block.key(), modelBuilder::build);
|
||||
}
|
||||
|
||||
private static Optional<NativeBlockState> withHalf(NativeBlockState block, BlockHalf half) {
|
||||
String current = IrisProceduralBlocks.propertyValue(block, BlockHalf.PROPERTY);
|
||||
if (current == 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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) {
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
|
||||
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<String> 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<String, Integer> 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<Face> 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<Face> facesAddedTo(BlockStateId state) {
|
||||
if (!state.name().equals("bell")) {
|
||||
return List.of();
|
||||
}
|
||||
Optional<BlockTexture> texture = textures.entityTexture("entity/bell/bell_body", MinecraftBlockTints.NO_TINT);
|
||||
if (texture.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
List<Face> 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<Face> 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<Face> decoratedPot(BlockStateId state, ModelDefinition model) {
|
||||
List<Face> 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<Face> chest(BlockStateId state) {
|
||||
String type = state.properties().getOrDefault("type", "single");
|
||||
String suffix = type.equals("single") ? "" : "_" + type;
|
||||
Optional<BlockTexture> 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<Face> 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<Face> head(BlockStateId state, ModelDefinition model) {
|
||||
boolean onWall = state.name().contains("_wall_");
|
||||
String kind = state.name().replace("_wall_", "_");
|
||||
Optional<HeadLook> look = HeadLook.of(kind);
|
||||
Optional<BlockTexture> 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<Face> 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<BlockTexture> frame = textures.entityTexture("entity/banner/banner_base", MinecraftBlockTints.NO_TINT);
|
||||
Optional<BlockTexture> 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<Face> 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<Face> 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<Face> 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<HeadLook> 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;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<Rectangle> seeThroughParts();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return where what the window shows has to show through the panels over it, in the window's coordinates
|
||||
*/
|
||||
static List<Rectangle> seeThroughOver(Component window) {
|
||||
List<Rectangle> 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<Rectangle> parts) {
|
||||
List<Rectangle> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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());
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<String> 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<Long> 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<Long> watchedDisplays = ConcurrentHashMap.newKeySet();
|
||||
private static final Set<Long> 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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<U extends GpuCache.Upload> {
|
||||
private final LinkedHashMap<Source, U> leastRecentlyUsedFirst = new LinkedHashMap<>(16, 0.75F, true);
|
||||
private final ReferenceQueue<Object> 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<Object> kept) {
|
||||
long bytes = 0L;
|
||||
for (U upload : leastRecentlyUsedFirst.values()) {
|
||||
bytes += upload.bytes();
|
||||
}
|
||||
Iterator<Map.Entry<Source, U>> oldestFirst = leastRecentlyUsedFirst.entrySet().iterator();
|
||||
while (bytes > mostBytes && oldestFirst.hasNext()) {
|
||||
Map.Entry<Source, U> 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<Object> {
|
||||
private final int identityHash;
|
||||
|
||||
private Source(Object source, ReferenceQueue<Object> 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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<String> 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<GlxDisplay> 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<GpuContext> 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> T call(Callable<T> 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;
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<OrbitPicture> drawInto(GpuFrameTarget target);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return the picture, or nothing when the caller should draw it without a card
|
||||
*/
|
||||
static Optional<OrbitPicture> 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<OrbitPicture> drawOnScreen(ScreenTarget screen, Drawing drawing) {
|
||||
return onCard(gpu -> {
|
||||
Optional<GlxDisplay> 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<GlxDisplay> windows = gpu.windows();
|
||||
long window = screen.canvas().window();
|
||||
if (windows.isEmpty() || window == 0L) {
|
||||
return Optional.<Boolean>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.<Boolean>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 <T> Optional<T> onCard(CardWork<T> work) {
|
||||
if (failed) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Optional<GpuContext> 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<T> {
|
||||
Optional<T> drawOn(GpuContext gpu);
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<String> 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<BlockTexture, Integer> 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<BlockTexture, Integer> offsets) {
|
||||
int texelCount = 0;
|
||||
for (List<ObjectMesh.Quad> 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<ObjectMesh.Quad> 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<BlockTexture, Integer> textureOffsets) {
|
||||
FloatBuffer packed = MemoryUtil.memAllocFloat(Math.max(1, quadCount()) * FLOATS_PER_QUAD);
|
||||
try {
|
||||
for (List<ObjectMesh.Quad> 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<BlockTexture, Integer> 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});
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<GpuObjectMesh> 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<OrbitPicture> 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<OrbitPicture> 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<OrbitPicture> 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);
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<String, Integer> 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));
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<OrbitPicture> 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<OrbitPicture> 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<OrbitPicture> 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<UploadedLayer> 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<UploadedLayer> layers = layersOnCard(scene.layers());
|
||||
Set<GpuTileCache.Place> 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<HoledLayer> layers) {
|
||||
long deadline = System.nanoTime() + UPLOAD_NANOS_PER_FRAME;
|
||||
List<HoledLayer> 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<UploadedLayer> layersOnCard(List<HoledLayer> layers) {
|
||||
List<UploadedLayer> 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<UploadedLayer> layers, boolean complete) {
|
||||
}
|
||||
|
||||
private enum UploadProgress {
|
||||
COMPLETE,
|
||||
CATCHING_UP,
|
||||
TOO_LARGE
|
||||
}
|
||||
|
||||
private record UploadedLayer(NoiseTerrain terrain, GpuFaces faces, GpuColors colors, TerrainHole hole) {
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<TerrainLayer> 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();
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<Place, GpuTile> 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<Place> shown) {
|
||||
long bytes = 0L;
|
||||
Iterator<Map.Entry<Place, GpuTile>> oldestFirst = leastRecentlyUsedFirst.entrySet().iterator();
|
||||
while (oldestFirst.hasNext()) {
|
||||
Map.Entry<Place, GpuTile> 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<Place, GpuTile> 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<Rectangle> 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<Rectangle> 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<PicturePatch> readPatches() {
|
||||
Rectangle frame = new Rectangle(0, 0, width, height);
|
||||
List<PicturePatch> 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);
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<Vec3> 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<Vec3> groundInView(int most, DoubleBinaryOperator surfaceY) {
|
||||
Reach reach = reach();
|
||||
double spacing = gridSpacing(reach, most);
|
||||
List<Vec3> 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) {
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<TerrainTile> fillers) {
|
||||
TerrainHole holeAmong(Predicate<TerrainTile> drawable) {
|
||||
return TerrainHole.of(tile, fillers.stream().filter(drawable).toList());
|
||||
}
|
||||
|
||||
TerrainHole holeOfAllFillers() {
|
||||
return TerrainHole.of(tile, fillers);
|
||||
}
|
||||
|
||||
NoiseTerrain terrain() {
|
||||
return layer.terrain();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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<String, String> legend(List<LegendRow> rows) {
|
||||
KMap<String, String> 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<LegendRow> legendRows(IrisImageMap definition) {
|
||||
List<LegendRow> rows = new ArrayList<>();
|
||||
if (definition.getColors() == null) {
|
||||
return rows;
|
||||
}
|
||||
for (Map.Entry<String, String> 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<IrisImageMapMask> masks(List<MaskRow> rows) {
|
||||
KList<IrisImageMapMask> 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<MaskRow> maskRows(List<IrisImageMapMask> masks) {
|
||||
List<MaskRow> 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<String> warnings(
|
||||
IrisImageMap definition,
|
||||
int sourceWidth,
|
||||
int sourceHeight,
|
||||
IrisWorldBoundary boundary
|
||||
) {
|
||||
List<String> 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
|
||||
) {
|
||||
}
|
||||
}
|
||||
@@ -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<String> 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<RenderResult, Void> worker;
|
||||
private Consumer<String> diagnosticConsumer = ignored -> {
|
||||
};
|
||||
private Consumer<String> 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<String> diagnosticConsumer) {
|
||||
this.diagnosticConsumer = diagnosticConsumer == null ? ignored -> {
|
||||
} : diagnosticConsumer;
|
||||
}
|
||||
|
||||
private void setHoverConsumer(Consumer<String> 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) {
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
|
||||
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<Rectangle> 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);
|
||||
}
|
||||
}
|
||||
@@ -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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
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<T> {
|
||||
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<T> measurement, Consumer<T> 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<BooleanSupplier, T> measurement, Consumer<T> 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> T measureSafely(Supplier<T> measurement) {
|
||||
try {
|
||||
return measurement.get();
|
||||
} catch (Throwable error) {
|
||||
IrisLogging.reportError(error);
|
||||
return 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 <https://www.gnu.org/licenses/>.
|
||||
*/
|
||||
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));
|
||||
}
|
||||
}
|
||||
Loaded 100 of 518 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user