Allow same-planet home returns from Nether and End #84

Merged
unimatrix merged 1 commit from fix/home-dimension-return-20261205 into main 2026-12-05 16:24:45 +01:00
6 changed files with 198 additions and 2 deletions

View file

@ -0,0 +1,47 @@
name: Home Dimension Return Overlay
on:
workflow_dispatch:
push:
branches: ['fix/home-dimension-return-*']
jobs:
home-dimension:
runs-on: dune-ci
steps:
- name: Check out exact revision
shell: bash
env:
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
git init .
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA"
git checkout --detach FETCH_HEAD
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '21'
- uses: gradle/actions/setup-gradle@v4
with:
gradle-version: '9.2.1'
- name: Test DuneEss and extract the dimension route class
shell: bash
run: |
set -euo pipefail
gradle --no-daemon -p DuneEss test jar
mkdir home-dimension
PYTHONPATH=tools python3 - <<'PY'
from pathlib import Path
from plugin_home_dimension import ROUTES
from plugin_wild_update import read_archive, write_archive
source = read_archive(Path("DuneEss/build/libs/DuneRealms-Essentials.jar").read_bytes())
Path("home-dimension/donor.zip").write_bytes(write_archive({ROUTES: source[ROUTES]}))
PY
cp tools/{HomeDimensionOverlay.java,plugin_home_dimension.py,plugin_wild_update.py} home-dimension/
printf '%s\n' "$GITHUB_SHA" > home-dimension/SOURCE_COMMIT
(cd home-dimension && sha256sum -- *.zip *.py *.java SOURCE_COMMIT > SHA256SUMS)
- uses: actions/upload-artifact@v3
with:
name: DuneRealms-Home-Dimension-Return
path: home-dimension
if-no-files-found: error

View file

@ -0,0 +1,21 @@
package com.example.duneess;
import java.util.Set;
import org.bukkit.World;
/** Dimension returns on one backend, preserving the Guild boundary between planets. */
final class HomeDimensionRoutes {
private static final Set<String> MAIN_WORLDS = Set.of(
"arrakis", "caladan", "giedi_prime", "kaitain", "sigma_draconis_iv", "lobby_base");
private HomeDimensionRoutes() {}
static boolean canReturn(World source, Object destination) {
if (source == null || !(destination instanceof World target)) return false;
if (source.equals(target)) return true;
String main = target.getName();
if (target.getEnvironment() != World.Environment.NORMAL || !MAIN_WORLDS.contains(main)) return false;
return source.getEnvironment() == World.Environment.NETHER && source.getName().equals(main + "_nether")
|| source.getEnvironment() == World.Environment.THE_END && source.getName().equals(main + "_the_end");
}
}

View file

@ -50,7 +50,7 @@ final class PersonalHomeTravel implements Listener {
private void begin(Player p,Location destination,String mode){
boolean rescue=mode.equals("rescue");
if(!valid(destination)){p.sendMessage("That saved home is unavailable or outside the world's playable bounds.");return;}
if(!p.getWorld().equals(destination.getWorld())){p.sendMessage("Travel to that world through the Guild first, then use /home.");return;}
if(rescue?!p.getWorld().equals(destination.getWorld()):!HomeDimensionRoutes.canReturn(p.getWorld(),destination.getWorld())){p.sendMessage("Travel to that world through the Guild first, then use /home.");return;}
String id=p.getUniqueId().toString();if(waiting.containsKey(p.getUniqueId())||journal.contains(id)){p.sendMessage("Your home journey is already being completed.");return;}
var connector=Bukkit.getPluginManager().getPlugin("JarvisTranslator");if(connector==null||!connector.isEnabled()){p.sendMessage("Central home travel is unavailable. No payment was made.");return;}
UUID token=UUID.randomUUID(),world=p.getWorld().getUID();waiting.put(p.getUniqueId(),token);Location target=destination.clone();
@ -91,7 +91,7 @@ final class PersonalHomeTravel implements Listener {
if(!state.equals("pending")){journal.set(id,null);persist();return;}
if(!stage.equals("reserve"))return;
Player current=Bukkit.getPlayer(UUID.fromString(id));Location target=journal.getLocation(id+".destination");
if(current==null||!current.isOnline()||current.isDead()||!valid(target)||rescue&&!safe(target)||!current.getWorld().equals(target.getWorld())){stage(id,"cancel");return;}
if(current==null||!current.isOnline()||current.isDead()||!valid(target)||(rescue?!safe(target)||!current.getWorld().equals(target.getWorld()):!HomeDimensionRoutes.canReturn(current.getWorld(),target.getWorld()))){stage(id,"cancel");return;}
// Keep the busy latch until the actual native result. Crash recovery re-delivers the same destination.
current.teleportAsync(target).whenComplete((success,failure)->Bukkit.getScheduler().runTask(plugin,()->{
boolean arrived=Boolean.TRUE.equals(success)&&failure==null;

View file

@ -0,0 +1,34 @@
package com.example.duneess;
import org.bukkit.World;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class HomeDimensionRoutesTest {
@Test void onlyReturnsToTheOwningMainWorld() {
var sigma = world("sigma_draconis_iv", World.Environment.NORMAL);
var end = world("sigma_draconis_iv_the_end", World.Environment.THE_END);
var giedi = world("giedi_prime", World.Environment.NORMAL);
var nether = world("giedi_prime_nether", World.Environment.NETHER);
var build = world("lobby_arrakis", World.Environment.NORMAL);
assertTrue(HomeDimensionRoutes.canReturn(end, sigma));
assertTrue(HomeDimensionRoutes.canReturn(nether, giedi));
assertTrue(HomeDimensionRoutes.canReturn(giedi, giedi));
assertFalse(HomeDimensionRoutes.canReturn(end, giedi));
assertFalse(HomeDimensionRoutes.canReturn(nether, sigma));
assertFalse(HomeDimensionRoutes.canReturn(sigma, end));
assertFalse(HomeDimensionRoutes.canReturn(end, nether));
assertFalse(HomeDimensionRoutes.canReturn(build, sigma));
assertFalse(HomeDimensionRoutes.canReturn(end, null));
assertFalse(HomeDimensionRoutes.canReturn(world("sigma_draconis_iv_the_end", World.Environment.CUSTOM), sigma));
}
private static World world(String name, World.Environment environment) {
var world = mock(World.class);
when(world.getName()).thenReturn(name);
when(world.getEnvironment()).thenReturn(environment);
return world;
}
}

View file

@ -0,0 +1,44 @@
import java.nio.file.Files;
import java.nio.file.Path;
import org.objectweb.asm.ClassReader;
import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodInsnNode;
final class HomeDimensionOverlay implements Opcodes {
private static final String TRAVEL = "com/example/duneess/PersonalHomeTravel";
private static final String ROUTES = "com/example/duneess/HomeDimensionRoutes";
public static void main(String[] args) throws Exception {
if (args.length != 2) throw new IllegalArgumentException("Expected retained and output class");
var old = new ClassReader(Files.readAllBytes(Path.of(args[0])));
var retained = new ClassNode();
old.accept(retained, 0);
if (!retained.name.equals(TRAVEL)) throw new IllegalArgumentException("Unexpected retained travel class");
replace(retained, "begin", "(Lorg/bukkit/entity/Player;Lorg/bukkit/Location;)V");
replace(retained, "lambda$attempt$3",
"(Lcom/google/gson/JsonObject;Ljava/lang/String;Lorg/bukkit/entity/Player;Ljava/lang/String;)V");
var writer = new ClassWriter(old, 0);
retained.accept(writer);
Files.write(Path.of(args[1]), writer.toByteArray());
}
private static void replace(ClassNode retained, String name, String descriptor) {
var method = retained.methods.stream().filter(m -> m.name.equals(name) && m.desc.equals(descriptor))
.findFirst().orElseThrow();
int patched = 0;
for (var instruction : method.instructions.toArray()) {
if (instruction instanceof MethodInsnNode call && call.getOpcode() == INVOKEINTERFACE
&& call.owner.equals("org/bukkit/World") && call.name.equals("equals")
&& call.desc.equals("(Ljava/lang/Object;)Z")) {
method.instructions.set(call, new MethodInsnNode(INVOKESTATIC, ROUTES, "canReturn",
"(Lorg/bukkit/World;Ljava/lang/Object;)Z", false));
patched++;
}
}
if (patched != 1) throw new IllegalArgumentException("Expected one retained world predicate: " + name);
}
}

View file

@ -0,0 +1,50 @@
"""Permit a local return from a native dimension without replacing the home payment journal."""
import argparse
import os
from pathlib import Path
import subprocess
from tempfile import TemporaryDirectory
from plugin_wild_update import digest, read_archive, write_archive
TRAVEL = "com/example/duneess/PersonalHomeTravel.class"
ROUTES = "com/example/duneess/HomeDimensionRoutes.class"
TRAVEL_BASELINES = {
"7fde0b6b5aba9e6755292a88b8157780e212708aadc5fe62de084f599234587d",
"dee4b89e17c254e28254c5dfe88fbcf9f5c284a6a21332f0e7ab121d8c882afc",
}
def assemble(baseline, baseline_sha, donor, donor_sha, output, classpath):
existing = baseline.read_bytes()
compiled = donor.read_bytes()
if digest(existing) != baseline_sha or digest(compiled) != donor_sha:
raise ValueError("Unexpected baseline or donor checksum")
retained = read_archive(existing)
source = read_archive(compiled)
if set(source) != {ROUTES} or ROUTES in retained or digest(retained[TRAVEL]) not in TRAVEL_BASELINES:
raise ValueError("Unexpected home travel class scope")
java_home = os.environ.get("JAVA_HOME")
executable = "java.exe" if os.name == "nt" else "java"
java = str(Path(java_home) / "bin" / executable) if java_home else executable
helper = Path(__file__).with_name("HomeDimensionOverlay.java")
with TemporaryDirectory() as temporary:
root = Path(temporary)
old, merged = root / "retained.class", root / "merged.class"
old.write_bytes(retained[TRAVEL])
subprocess.run([java, "--class-path", classpath, str(helper), str(old), str(merged)], check=True)
retained[TRAVEL] = merged.read_bytes()
retained[ROUTES] = source[ROUTES]
with output.open("xb") as candidate:
candidate.write(write_archive(retained))
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("baseline", type=Path)
parser.add_argument("baseline_sha")
parser.add_argument("donor", type=Path)
parser.add_argument("donor_sha")
parser.add_argument("output", type=Path)
parser.add_argument("classpath", help="ASM core and tree JARs")
assemble(**vars(parser.parse_args()))