Files
src
build.gradle
gradle.properties
manifest.kod
settings.gradle
Code
16 631
src/client/java/dev/kodari/worldreset/WorldResetClient.java
package dev.kodari.worldreset;
import com.mojang.blaze3d.platform.InputConstants;
import io.wispforest.owo.ui.base.BaseOwoScreen;
import io.wispforest.owo.ui.component.UIComponents;
import io.wispforest.owo.ui.container.FlowLayout;
import io.wispforest.owo.ui.container.StackLayout;
import io.wispforest.owo.ui.container.UIContainers;
import io.wispforest.owo.ui.core.HorizontalAlignment;
import io.wispforest.owo.ui.core.Insets;
import io.wispforest.owo.ui.core.OwoUIAdapter;
import io.wispforest.owo.ui.core.Positioning;
import io.wispforest.owo.ui.core.Sizing;
import io.wispforest.owo.ui.core.Surface;
import io.wispforest.owo.ui.core.VerticalAlignment;
import io.wispforest.owo.ui.layers.Layer;
import io.wispforest.owo.ui.layers.Layers;
import net.fabricmc.api.ClientModInitializer;
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
import net.fabricmc.fabric.api.client.keymapping.v1.KeyMappingHelper;
import net.fabricmc.fabric.api.client.screen.v1.ScreenEvents;
import net.fabricmc.fabric.api.client.screen.v1.Screens;
import net.minecraft.client.KeyMapping;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.screens.PauseScreen;
import net.minecraft.client.gui.screens.TitleScreen;
import net.minecraft.client.gui.screens.worldselection.CreateWorldScreen;
import net.minecraft.client.gui.screens.worldselection.SelectWorldScreen;
import net.minecraft.client.server.IntegratedServer;
import net.minecraft.network.chat.Component;
import net.minecraft.network.chat.contents.TranslatableContents;
import net.minecraft.resources.Identifier;
import dev.kodari.worldreset.mixin.CreateWorldScreenInvoker;
import net.minecraft.world.level.storage.LevelResource;
import net.minecraft.world.level.storage.LevelStorageSource;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Comparator;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;
public class WorldResetClient implements ClientModInitializer {
private static final Logger LOGGER = LoggerFactory.getLogger("quick_world_reset");
private static boolean resetting;
@Override
public void onInitializeClient() {
KeyMapping.Category category = KeyMapping.Category.register(Identifier.fromNamespaceAndPath("quick_world_reset", "main"));
KeyMapping randomKey = KeyMappingHelper.registerKeyMapping(new KeyMapping("key.quick_world_reset.random", InputConstants.UNKNOWN.getValue(), category));
KeyMapping sameSeedKey = KeyMappingHelper.registerKeyMapping(new KeyMapping("key.quick_world_reset.same_seed", InputConstants.UNKNOWN.getValue(), category));
ClientTickEvents.END_CLIENT_TICK.register(client -> {
boolean random = randomKey.consumeClick();
boolean sameSeed = sameSeedKey.consumeClick();
if (client.gui.screen() == null && (random || sameSeed)) reset(client, !random && sameSeed);
});
ScreenEvents.AFTER_INIT.register((client, screen, width, height) -> {
if (!(screen instanceof PauseScreen) || !client.hasSingleplayerServer()) return;
Screens.getWidgets(screen).stream().filter(widget -> widget.getMessage().getContents() instanceof TranslatableContents text
&& text.getKey().equals("menu.returnToMenu")).findFirst().ifPresent(exit -> {
exit.setX(exit.getX() + 22);
exit.setWidth(exit.getWidth() - 44);
});
});
Layers.add(UIContainers::verticalFlow, instance -> {
Minecraft client = Minecraft.getInstance();
if (!client.hasSingleplayerServer() || instance.queryWidget(widget ->
widget.getMessage().getContents() instanceof TranslatableContents text
&& text.getKey().equals("menu.returnToMenu")) == null) {
return;
}
instance.aggressivePositioning = true;
FlowLayout row = UIContainers.horizontalFlow(Sizing.content(), Sizing.content());
row.margins(Insets.left(2));
StackLayout icon = UIContainers.stack(Sizing.fixed(20), Sizing.fixed(20));
icon.alignment(HorizontalAlignment.CENTER, VerticalAlignment.CENTER);
icon.child(UIComponents.button(Component.literal(""), button -> reset(client, false))
.sizing(Sizing.fixed(20), Sizing.fixed(20))
.tooltip(Component.translatable("quick_world_reset.tooltip")));
icon.child(UIComponents.texture(Identifier.fromNamespaceAndPath("quick_world_reset", "textures/gui/reset.png"),
0, 0, 16, 16, 16, 16).blend(true).sizing(Sizing.fixed(16), Sizing.fixed(16)));
row.child(icon);
instance.adapter.rootComponent.child(row);
instance.alignComponentToWidget(widget ->
widget.getMessage().getContents() instanceof TranslatableContents text
&& text.getKey().equals("menu.returnToMenu"),
Layer.Instance.AnchorSide.RIGHT, 0.5f, row);
StackLayout sameSeedIcon = UIContainers.stack(Sizing.fixed(20), Sizing.fixed(20));
sameSeedIcon.alignment(HorizontalAlignment.CENTER, VerticalAlignment.CENTER);
sameSeedIcon.margins(Insets.right(2));
sameSeedIcon.child(UIComponents.button(Component.literal(""), button -> reset(client, true))
.sizing(Sizing.fixed(20), Sizing.fixed(20))
.tooltip(Component.translatable("quick_world_reset.same_seed")));
sameSeedIcon.child(UIComponents.texture(Identifier.fromNamespaceAndPath("quick_world_reset", "textures/gui/same_seed.png"),
0, 0, 16, 16, 16, 16).blend(true).sizing(Sizing.fixed(16), Sizing.fixed(16)));
instance.adapter.rootComponent.child(sameSeedIcon);
instance.alignComponentToWidget(widget ->
widget.getMessage().getContents() instanceof TranslatableContents text
&& text.getKey().equals("menu.returnToMenu"),
Layer.Instance.AnchorSide.LEFT, 0.5f, sameSeedIcon);
}, PauseScreen.class);
Layers.add(UIContainers::verticalFlow, instance -> {
StackLayout icon = UIContainers.stack(Sizing.fixed(20), Sizing.fixed(20));
icon.alignment(HorizontalAlignment.CENTER, VerticalAlignment.CENTER);
icon.positioning(Positioning.relative(100, 100));
icon.margins(Insets.of(4));
icon.child(UIComponents.button(Component.literal(""), button ->
Minecraft.getInstance().gui.setScreen(new ArchiveScreen(instance.screen)))
.sizing(Sizing.fixed(20), Sizing.fixed(20))
.tooltip(Component.translatable("quick_world_reset.archive.button")));
icon.child(UIComponents.texture(Identifier.fromNamespaceAndPath("quick_world_reset", "textures/gui/archive.png"),
0, 0, 16, 16, 16, 16).blend(true).sizing(Sizing.fixed(16), Sizing.fixed(16)));
instance.adapter.rootComponent.child(icon);
}, SelectWorldScreen.class);
}
private static void reset(Minecraft client, boolean sameSeed) {
IntegratedServer server = client.getSingleplayerServer();
if (!client.hasSingleplayerServer() || server == null || resetting) return;
String levelId = server.getWorldPath(LevelResource.ROOT).normalize().getFileName().toString();
resetting = true;
client.disconnectWithSavingScreen();
CompletableFuture.supplyAsync(() -> {
try {
while (!server.isShutdown()) Thread.sleep(50);
Path archive = archivePath(client);
Files.createDirectories(archive);
Path source = client.getLevelSource().getBaseDir().resolve(levelId);
String archiveId = String.format("%013d-%s", System.currentTimeMillis(), UUID.randomUUID());
Files.move(source, archive.resolve(archiveId));
pruneArchives(archive);
return archiveId;
} catch (IOException | InterruptedException e) {
if (e instanceof InterruptedException) Thread.currentThread().interrupt();
throw new RuntimeException(e);
}
}).whenComplete((archiveId, error) -> client.execute(() -> {
resetting = false;
if (error != null) {
LOGGER.error("Could not archive world {}", levelId, error);
client.gui.setScreen(new ResetErrorScreen());
return;
}
try (var access = LevelStorageSource.createDefault(archivePath(client)).validateAndCreateAccess(archiveId)) {
var settings = client.createWorldOpenFlows().recreateWorldData(access);
var context = settings.getSecond();
context.validate();
Path packs = access.getLevelPath(LevelResource.DATAPACK_DIR);
Path copiedPacks = null;
if (Files.isDirectory(packs)) {
try (var entries = Files.list(packs)) {
if (entries.findAny().isPresent()) {
copiedPacks = CreateWorldScreen.createTempDataPackDirFromExistingWorld(packs, client);
if (copiedPacks == null) throw new IOException("Could not copy world datapacks");
}
}
}
CreateWorldScreen createScreen = CreateWorldScreen.createFromExisting(
client, () -> client.gui.setScreen(new TitleScreen()), settings.getFirst(), context, copiedPacks);
if (!sameSeed) createScreen.getUiState().setSeed("");
client.gui.setScreen(createScreen);
((CreateWorldScreenInvoker) createScreen).quickWorldReset$create();
} catch (Exception e) {
LOGGER.error("Could not recreate archived world {}", archiveId, e);
client.gui.setScreen(new ResetErrorScreen());
}
}));
}
static Path archivePath(Minecraft client) {
return client.getLevelSource().getBaseDir().resolveSibling("quick_world_reset_archive");
}
private static void pruneArchives(Path archive) {
try (var entries = Files.list(archive)) {
var worlds = entries.filter(Files::isDirectory)
.filter(path -> path.getFileName().toString().matches("\\d{13}-[0-9a-f-]{36}"))
.sorted(Comparator.comparing((Path path) -> path.getFileName().toString()).reversed())
.toList();
LevelStorageSource source = LevelStorageSource.createDefault(archive);
for (int i = 3; i < worlds.size(); i++) {
try (var access = source.createAccess(worlds.get(i).getFileName().toString())) {
access.deleteLevel();
} catch (IOException e) {
LOGGER.error("Could not remove old archived world {}", worlds.get(i), e);
}
}
} catch (IOException | RuntimeException e) {
LOGGER.error("Could not prune archived worlds", e);
}
}













