Implement Dunium alpha Fabric client and Paper editor with 46 engine checks
This commit is contained in:
parent
bca69b3463
commit
48c6e74cba
29 changed files with 1619 additions and 27 deletions
3
.gitattributes
vendored
Normal file
3
.gitattributes
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
||||||
|
* text=auto eol=lf
|
||||||
|
*.jar binary
|
||||||
|
*.bat text eol=crlf
|
||||||
15
.gitea/workflows/build.yml
Normal file
15
.gitea/workflows/build.yml
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
name: Build Dunium
|
||||||
|
on: [push, pull_request, workflow_dispatch]
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
- uses: actions/setup-java@v4
|
||||||
|
with:
|
||||||
|
distribution: temurin
|
||||||
|
java-version: '21'
|
||||||
|
- name: Build and run engine regression checks
|
||||||
|
run: sh gradlew --no-daemon clean build
|
||||||
|
- name: List distributable artifacts
|
||||||
|
run: find dunium-server/build/libs dunium-client/build/libs -name '*.jar' -type f
|
||||||
6
.gitignore
vendored
Normal file
6
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
.gradle/
|
||||||
|
**/build/
|
||||||
|
run/
|
||||||
|
*.log
|
||||||
|
.idea/
|
||||||
|
*.iml
|
||||||
100
README.md
100
README.md
|
|
@ -1,44 +1,90 @@
|
||||||
# Dunium
|
# Dunium
|
||||||
|
|
||||||
An original Minecraft building and terrain editor with a visual client mod and a Paper server plugin.
|
Original Minecraft building tools: **Fabric visual client mod + Paper server plugin**.
|
||||||
|
|
||||||
|
Version **0.1.0-alpha.1** targets **Minecraft Java 1.21.8 / Java 21**.
|
||||||
|
|
||||||
## Status
|
## Status
|
||||||
|
|
||||||
Project initialized. This repository currently contains the design and roadmap; there are no working mod/plugin releases yet.
|
Server source compiles against Paper 1.21.8, and the editing engine passes **46 regression checks**. A server JAR is packaged for testing. The Fabric client source is implemented, but **its build and in-game behavior are not verified**: this environment cannot download Fabric dependencies or connect to Gradle's local daemon. Full Gradle build and live integration remain release gates. This is an experimental alpha, not Axiom feature parity.
|
||||||
|
|
||||||
## Planned components
|
## Features in the source
|
||||||
|
|
||||||
| Module | Responsibility |
|
| Component | Features |
|
||||||
| --- | --- |
|
| --- | --- |
|
||||||
| dunium-client | Java Edition client mod: visual selections, tool palette, previews and brushes |
|
| Visual client | K palette, [ / ] corner selection, server-confirmed cyan outlines, building and terrain tool pages |
|
||||||
| dunium-server | Paper plugin: authoritative edits, permissions, scheduling and history |
|
| Editing | Cuboid fill, exact-state replace, copy/paste including air, 90/180/270 degree rotation, X/Z mirroring, solid sphere brush, flatten to Y |
|
||||||
| dunium-common | Versioned protocol, selection geometry and operation definitions |
|
| Recovery | Undo/redo with expected-state conflict checks; cancel retains completed edits in current-session history |
|
||||||
|
| Multiplayer | Global per-tick work budget, limited concurrent jobs, overlapping Dunium operations refused, permission/location rechecks |
|
||||||
|
| Protection | Explicit world allowlist, creative-only default, loaded chunks only, border/height/distance checks, block entity exclusion, optional WorldGuard 7 bridge and cancellable protection event |
|
||||||
|
|
||||||
The client loader and exact Minecraft/Java versions must be pinned before implementation. Bedrock players cannot install the Java client mod; server commands can be designed separately for them.
|
Clipboard transforms also rotate/mirror directional block states through Paper's API. Preview means bounds and an upper-bound position count; it does not show an exact ghost copy or guarantee every position changes.
|
||||||
|
|
||||||
## Planned features
|
## Build
|
||||||
|
|
||||||
- Cuboid selections and visible selection outlines.
|
Set JAVA_HOME to a JDK 21 installation. Initial builds require internet. The Gradle 8.14 wrapper includes a distribution SHA-256 check.
|
||||||
- Fill, replace, copy, paste, rotate and mirror.
|
|
||||||
- Terrain brushes: sphere, flatten, smooth and paint.
|
|
||||||
- Preview and explicit confirmation before large edits.
|
|
||||||
- Undo/redo with bounded history and conflict handling.
|
|
||||||
- Multiplayer edit coordination and operation progress/cancellation.
|
|
||||||
- Administrator-configured edit sizes, brush sizes, history budgets and blocks per tick. No artificial paid feature gates are planned; operational limits protect server performance.
|
|
||||||
|
|
||||||
## Server authority
|
```sh
|
||||||
|
sh gradlew clean build
|
||||||
|
# Server and engine checks only:
|
||||||
|
sh gradlew -PserverOnly :dunium-server:build :dunium-common:check
|
||||||
|
```
|
||||||
|
|
||||||
Treat every client message as untrusted. Validate protocol version, permission, world, bounds, block states, payload size and rate limits before accepting an operation. Integrate region protection before editing protected land. Run world mutations on the server thread in bounded batches. Record original block state for recovery, and avoid overwriting newer edits during undo. Never load arbitrary chunks or accept unlimited work from a client request.
|
```powershell
|
||||||
|
.\gradlew.bat clean build
|
||||||
|
.\gradlew.bat -PserverOnly :dunium-server:build :dunium-common:check
|
||||||
|
```
|
||||||
|
|
||||||
## Development roadmap
|
Artifacts: `dunium-server/build/libs/Dunium-Server-0.1.0-alpha.1.jar` and `dunium-client/build/libs/Dunium-Client-0.1.0-alpha.1.jar`. Use the remapped client JAR, not a sources/dev JAR. The server embeds the shared engine; no common JAR needs installing. Minecraft and Fabric API are not bundled.
|
||||||
|
|
||||||
1. Establish a reproducible multi-module build, pin dependencies and add CI.
|
A Gitea Actions workflow is included; it needs an enabled runner and network access. No successful CI run is claimed. Windows machines with cached Paper dependencies can run `scripts/build-cached-server.ps1 -DependencyCache <Gradle modules-2/files-2.1> -JavaHome <JDK>` to compile, check and package only the server without Gradle/network.
|
||||||
2. Implement selections, permission checks, bounded fill/replace and undo on Paper.
|
|
||||||
3. Add the client handshake, visual outline and preview workflow.
|
|
||||||
4. Add clipboard transforms and terrain brushes.
|
|
||||||
5. Verify protection integration, cancellation, history persistence and multiplayer conflict behavior.
|
|
||||||
6. Package separate client and server JARs with installation documentation.
|
|
||||||
|
|
||||||
## Project boundaries
|
## Test installation
|
||||||
|
|
||||||
Dunium uses original code and assets. It does not include Axiom code, assets, license bypasses or proprietary protocol implementations. This is a standalone project; no DuneRealms server deployment is performed by initializing this repository.
|
1. Back up a disposable Paper 1.21.8 build world. Put the server JAR in that stopped test server's `plugins/` directory.
|
||||||
|
2. Start once to generate `plugins/Dunium/config.yml`. Stop, explicitly add the test world's name to `allowed-worlds`, and restart. An empty allowlist denies all edits.
|
||||||
|
3. Grant `dunium.use` and `dunium.edit` (both default to operators) and use creative mode.
|
||||||
|
4. After the client builds successfully, install Fabric Loader 0.17.2+ for Minecraft 1.21.8, Fabric API 0.133.4+1.21.8 and the client JAR in that client profile's `mods/` folder.
|
||||||
|
5. Join, wait for the handshake, set corners using [ and ] while looking at blocks, and press K. Full preview/error messages appear in chat. Minecraft controls allow rebinding keys.
|
||||||
|
|
||||||
|
Paper commands also work without the mod, including for Bedrock players through an existing Geyser installation. Bedrock cannot run the Fabric UI. Singleplayer integrated-server editing, Folia, other Minecraft versions and live DuneRealms deployment are not included.
|
||||||
|
|
||||||
|
## Commands
|
||||||
|
|
||||||
|
Use `/dunium` or `/du`.
|
||||||
|
|
||||||
|
| Command | Action |
|
||||||
|
| --- | --- |
|
||||||
|
| `pos1 [x y z]`, `pos2 [x y z]` | Set corners; omitted coordinates use your current block position |
|
||||||
|
| `clear`, `status`, `help` | Manage selection or inspect work |
|
||||||
|
| `fill <state>` | Prepare cuboid fill |
|
||||||
|
| `replace <exact-state> <state>` | Match the complete canonical block state, including properties |
|
||||||
|
| `copy` | Batched snapshot; refused if any position is unsupported/protected |
|
||||||
|
| `rotate <90\|180\|270>`, `mirror <x\|z>` | Transform clipboard |
|
||||||
|
| `paste [x y z]` | Prepare paste; origin is minimum corner; includes air |
|
||||||
|
| `sphere <radius> <state> [x y z]` | Prepare solid sphere centered on coordinate |
|
||||||
|
| `flatten <y> <state>` | Within selection, fill through Y and clear above |
|
||||||
|
| `confirm` | Start the prepared edit before its timeout |
|
||||||
|
| `cancel` | Discard preview or stop remaining work; completed changes remain undoable |
|
||||||
|
| `undo`, `redo` | Run history immediately in batches |
|
||||||
|
|
||||||
|
Example: `/du pos1`, move, `/du pos2`, `/du fill minecraft:sandstone`, inspect bounds, `/du confirm`, then `/du undo`.
|
||||||
|
|
||||||
|
## Limits and data behavior
|
||||||
|
|
||||||
|
- No paid feature gates. Administrators configure block counts, brush radius, global tick budget, sessions/jobs, distance, confirmation timeout and history budgets. Hard validation ceilings prevent overflow/unbounded allocation.
|
||||||
|
- History and clipboards are memory-only. Logout, plugin disable or restart discards them; completed world changes persist. No crash recovery journal exists. Back up test worlds.
|
||||||
|
- Block entities (containers, signs, spawners and other NBT blocks) are excluded from source and destination. Entities/inventories are not copied. Denied materials are refused or skipped.
|
||||||
|
- Direct writes suppress physics. Later neighbor updates may still affect fluids, gravity, multiblock structures and redstone. Undo tracks direct block-data writes, not external effects.
|
||||||
|
- Conflict checks compare block data, and cannot identify a later edit that restored the same state. Conflicting/protected history positions are skipped and not automatically retried.
|
||||||
|
- Dunium jobs cannot overlap each other. Other plugins and players can still edit; a copy across multiple ticks is not an atomic snapshot.
|
||||||
|
- WorldGuard 7 integration fails closed when installed but incompatible/unavailable; runtime compatibility still needs testing. Other protection systems must listen to `DuniumEditCheckEvent` or restrict the build-world allowlist. Generic protection compatibility is not claimed.
|
||||||
|
- Protocol v1 uses bounded UTF-8 plugin messages on `dunium:command` and `dunium:state`. The server trusts no client-supplied identity or permissions and revalidates operations.
|
||||||
|
|
||||||
|
## Remaining work
|
||||||
|
|
||||||
|
Full Fabric build and live test matrix, persisted recovery, smooth/noise brushes, gradients/hollow shapes, schematic import/export, exact ghost previews, preferences and more protection adapters. See [validation](docs/VALIDATION.md).
|
||||||
|
|
||||||
|
## Provenance
|
||||||
|
|
||||||
|
Original implementation and visuals; no Axiom code, assets, license bypasses or proprietary protocols. No distribution license for Dunium's own code has been selected. The Gradle wrapper is third-party Apache-2.0 code; see `gradle/wrapper/LICENSE-Gradle.txt`.
|
||||||
|
|
|
||||||
10
build.gradle
Normal file
10
build.gradle
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
allprojects {
|
||||||
|
group = 'com.dunerealms.dunium'
|
||||||
|
version = '0.1.0-alpha.1'
|
||||||
|
repositories { mavenCentral() }
|
||||||
|
}
|
||||||
|
subprojects {
|
||||||
|
apply plugin: 'java'
|
||||||
|
java { toolchain { languageVersion = JavaLanguageVersion.of(21) }; withSourcesJar() }
|
||||||
|
tasks.withType(JavaCompile).configureEach { options.encoding = 'UTF-8'; options.release = 21 }
|
||||||
|
}
|
||||||
23
docs/GIEDERMARK-DEPLOYMENT.md
Normal file
23
docs/GIEDERMARK-DEPLOYMENT.md
Normal file
|
|
@ -0,0 +1,23 @@
|
||||||
|
# Requested Giedermark replacement
|
||||||
|
|
||||||
|
User requested replacing AxiomPaper on Giedi Prime, displayed as Giedermark in the control panel, and supplying the matching Dunium client mod.
|
||||||
|
|
||||||
|
## Observed 7 November 2026
|
||||||
|
|
||||||
|
- Control panel target: Giedermark, zero players when inspected.
|
||||||
|
- Paper 1.21.8 build 60; loaded world `giedi_prime`.
|
||||||
|
- AxiomPaper 6.0.1+1.21.8, WorldGuard 7.0.13 and CoreProtect 24.1 are currently installed.
|
||||||
|
- The panel offers start/stop/restart and console commands, but no file upload/manager was present.
|
||||||
|
- No server files or plugins have been changed yet.
|
||||||
|
|
||||||
|
## Deployment steps when authenticated file access is available
|
||||||
|
|
||||||
|
1. Complete the Fabric build and verify the client JAR. Preserve the existing Axiom client mod/profile for rollback.
|
||||||
|
2. Recheck Giedermark player count. Save the world, stop only Giedermark and confirm it stopped.
|
||||||
|
3. Back up its AxiomPaper JAR/configuration outside the plugins scan path; preserve world data. Do not delete the old plugin or touch other planets.
|
||||||
|
4. Upload the verified Dunium server JAR. Configure only `giedi_prime` in `allowed-worlds`. Retain creative-only, permission checks and bounded defaults.
|
||||||
|
5. Start Giedermark. Verify Dunium startup, no AxiomPaper startup, Paper health and protection integration. Restore Axiom backup if Dunium fails.
|
||||||
|
6. On a small backed-up test patch, check fill/undo, WorldGuard denial, clipboard orientation, cancellation and client handshake/outline.
|
||||||
|
7. Supply the matching Fabric 1.21.8 client JAR and required Fabric API. The Java client needs its own version-matched profile; server ViaVersion does not make the client mod work on a different Minecraft version.
|
||||||
|
|
||||||
|
CoreProtect integration is not implemented in this alpha: Dunium direct edits are not guaranteed to appear in CoreProtect's database. Do not assume CoreProtect can roll them back. Current-session Dunium undo and backups remain separate mechanisms.
|
||||||
20
docs/VALIDATION.md
Normal file
20
docs/VALIDATION.md
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
# Dunium 0.1.0-alpha.1 validation
|
||||||
|
|
||||||
|
## Verified locally
|
||||||
|
|
||||||
|
- Java 21 compilation of the common engine and Paper server source against cached Paper 1.21.8 API dependencies.
|
||||||
|
- 46 engine checks: inclusive/reversed/negative bounds, iteration, overflow, overlap, batch budget, denied reads, permission changes between slices, exact-state replace, no-op history, cancellation, partial undo, later-edit conflict, redo, immutable clipboard, translated paste including air, recovery after post-write failure, rotated coordinates/states, mirrored coordinates, transform round trips, sphere shape/budget and flatten bounds/behavior.
|
||||||
|
- Server plugin JAR packaging with expanded version, plugin.yml, config.yml and embedded common engine.
|
||||||
|
|
||||||
|
## Not verified / release gates
|
||||||
|
|
||||||
|
1. Run the full Gradle build with Fabric dependency downloads enabled. Verify both distributable JARs, not only source compilation of the server.
|
||||||
|
2. Start a separate Paper 1.21.8 test server; verify plugin startup and default-deny allowlist. Do not deploy to the live network for this validation.
|
||||||
|
3. Connect a Fabric 1.21.8 client. Verify plugin-channel registration, handshake, tool palette, key bindings, selection synchronization and outlines, disconnect/reconnect and dimension changes.
|
||||||
|
4. Exercise fill, exact replace, copy/paste with air, oriented stairs/logs rotation/mirror, sphere and flatten. Verify confirmation expiry, cancellation, progress and history trimming.
|
||||||
|
5. Revoke permissions/change game mode mid-operation; unload chunks, move the border and walk out of range. Verify no denied mutation or forced chunk loading.
|
||||||
|
6. Use two builders. Verify combined per-tick budget and overlap rejection. Manually change a block between edit and undo; verify conflict is preserved.
|
||||||
|
7. Test WorldGuard 7 allowed/denied regions and incompatible API failure. Test custom protection cancellation. Verify chests/signs/NBT blocks are refused/skipped with their data intact.
|
||||||
|
8. Verify logout/restart history loss is understood, and world backups can restore test changes. Verify post-write failures retain sufficient current-session undo information.
|
||||||
|
|
||||||
|
The environment blocks command-line DNS/network access and Gradle's local daemon connection. A direct Java compiler path was used for server validation. No client JAR, successful full Gradle/CI build, live server validation, crash-safe rollback or Axiom feature parity is claimed.
|
||||||
10
dunium-client/build.gradle
Normal file
10
dunium-client/build.gradle
Normal file
|
|
@ -0,0 +1,10 @@
|
||||||
|
plugins { id 'fabric-loom' version '1.11.8' }
|
||||||
|
repositories { maven { url = 'https://maven.fabricmc.net/' } }
|
||||||
|
dependencies {
|
||||||
|
minecraft 'com.mojang:minecraft:1.21.8'
|
||||||
|
mappings 'net.fabricmc:yarn:1.21.8+build.1:v2'
|
||||||
|
modImplementation 'net.fabricmc:fabric-loader:0.17.2'
|
||||||
|
modImplementation 'net.fabricmc.fabric-api:fabric-api:0.133.4+1.21.8'
|
||||||
|
}
|
||||||
|
base { archivesName = 'Dunium-Client' }
|
||||||
|
processResources { inputs.property 'version', project.version; filesMatching('fabric.mod.json') { expand version: project.version } }
|
||||||
127
dunium-client/src/main/java/dunium/DuniumClient.java
Normal file
127
dunium-client/src/main/java/dunium/DuniumClient.java
Normal file
|
|
@ -0,0 +1,127 @@
|
||||||
|
package dunium;
|
||||||
|
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import net.fabricmc.api.ClientModInitializer;
|
||||||
|
import net.fabricmc.fabric.api.client.event.lifecycle.v1.ClientTickEvents;
|
||||||
|
import net.fabricmc.fabric.api.client.keybinding.v1.KeyBindingHelper;
|
||||||
|
import net.fabricmc.fabric.api.client.networking.v1.*;
|
||||||
|
import net.fabricmc.fabric.api.client.rendering.v1.WorldRenderEvents;
|
||||||
|
import net.fabricmc.fabric.api.networking.v1.PayloadTypeRegistry;
|
||||||
|
import net.minecraft.client.MinecraftClient;
|
||||||
|
import net.minecraft.client.option.KeyBinding;
|
||||||
|
import net.minecraft.client.render.*;
|
||||||
|
import net.minecraft.client.util.InputUtil;
|
||||||
|
import net.minecraft.network.RegistryByteBuf;
|
||||||
|
import net.minecraft.network.codec.PacketCodec;
|
||||||
|
import net.minecraft.network.packet.CustomPayload;
|
||||||
|
import net.minecraft.text.Text;
|
||||||
|
import net.minecraft.util.Identifier;
|
||||||
|
import net.minecraft.util.hit.*;
|
||||||
|
import net.minecraft.util.math.*;
|
||||||
|
import org.lwjgl.glfw.GLFW;
|
||||||
|
|
||||||
|
public final class DuniumClient implements ClientModInitializer {
|
||||||
|
public static String feedback="Waiting for a Dunium-enabled server. Creative mode and builder permissions are required.";
|
||||||
|
public static boolean connected;
|
||||||
|
private static String dimension="";
|
||||||
|
private static BlockPos a,b;
|
||||||
|
private int ticks;
|
||||||
|
|
||||||
|
public record CommandPayload(String message) implements CustomPayload {
|
||||||
|
public static final Id<CommandPayload> ID=new Id<>(Identifier.of("dunium","command"));
|
||||||
|
public static final PacketCodec<RegistryByteBuf,CommandPayload> CODEC=PacketCodec.of(
|
||||||
|
(value,buf)->write(buf,value.message,1024),buf->new CommandPayload(read(buf,1024)));
|
||||||
|
public Id<? extends CustomPayload> getId() { return ID; }
|
||||||
|
}
|
||||||
|
public record StatePayload(String message) implements CustomPayload {
|
||||||
|
public static final Id<StatePayload> ID=new Id<>(Identifier.of("dunium","state"));
|
||||||
|
public static final PacketCodec<RegistryByteBuf,StatePayload> CODEC=PacketCodec.of(
|
||||||
|
(value,buf)->write(buf,value.message,4096),buf->new StatePayload(read(buf,4096)));
|
||||||
|
public Id<? extends CustomPayload> getId() { return ID; }
|
||||||
|
}
|
||||||
|
private static String read(RegistryByteBuf buffer,int limit) {
|
||||||
|
int size=buffer.readableBytes();
|
||||||
|
if (size>limit) throw new IllegalArgumentException("Dunium payload is too large");
|
||||||
|
return buffer.readCharSequence(size,StandardCharsets.UTF_8).toString();
|
||||||
|
}
|
||||||
|
private static void write(RegistryByteBuf buffer,String value,int limit) {
|
||||||
|
byte[] bytes=value.getBytes(StandardCharsets.UTF_8);
|
||||||
|
if (bytes.length>limit) throw new IllegalArgumentException("Dunium payload is too large");
|
||||||
|
buffer.writeBytes(bytes);
|
||||||
|
}
|
||||||
|
@Override public void onInitializeClient() {
|
||||||
|
PayloadTypeRegistry.playC2S().register(CommandPayload.ID,CommandPayload.CODEC);
|
||||||
|
PayloadTypeRegistry.playS2C().register(StatePayload.ID,StatePayload.CODEC);
|
||||||
|
ClientPlayNetworking.registerGlobalReceiver(StatePayload.ID,(payload,context)->context.client().execute(()->receive(payload.message)));
|
||||||
|
ClientPlayConnectionEvents.JOIN.register((handler,sender,client)->reset());
|
||||||
|
ClientPlayConnectionEvents.DISCONNECT.register((handler,client)->reset());
|
||||||
|
KeyBinding menu=key("key.dunium.menu",GLFW.GLFW_KEY_K);
|
||||||
|
KeyBinding first=key("key.dunium.pos1",GLFW.GLFW_KEY_LEFT_BRACKET);
|
||||||
|
KeyBinding second=key("key.dunium.pos2",GLFW.GLFW_KEY_RIGHT_BRACKET);
|
||||||
|
ClientTickEvents.END_CLIENT_TICK.register(client->{
|
||||||
|
if (client.player==null || client.world==null) return;
|
||||||
|
ticks++;
|
||||||
|
if (!connected && ticks%100==40 && ClientPlayNetworking.canSend(CommandPayload.ID)) send("hello");
|
||||||
|
while (menu.wasPressed()) if (client.currentScreen==null) client.setScreen(new ToolScreen(target(client)));
|
||||||
|
while (first.wasPressed()) if (client.currentScreen==null) select(1,target(client));
|
||||||
|
while (second.wasPressed()) if (client.currentScreen==null) select(2,target(client));
|
||||||
|
});
|
||||||
|
WorldRenderEvents.AFTER_ENTITIES.register(context->{
|
||||||
|
MinecraftClient client=MinecraftClient.getInstance();
|
||||||
|
if (client.world==null || a==null || b==null || !client.world.getRegistryKey().getValue().toString().equals(dimension)) return;
|
||||||
|
var matrices=context.matrixStack(); var consumers=context.consumers();
|
||||||
|
if (matrices==null || consumers==null) return;
|
||||||
|
Vec3d camera=context.camera().getPos();
|
||||||
|
Box box=new Box(Math.min(a.getX(),b.getX()),Math.min(a.getY(),b.getY()),Math.min(a.getZ(),b.getZ()),
|
||||||
|
Math.max(a.getX(),b.getX())+1,Math.max(a.getY(),b.getY())+1,Math.max(a.getZ(),b.getZ())+1);
|
||||||
|
matrices.push();
|
||||||
|
try {
|
||||||
|
matrices.translate(-camera.x,-camera.y,-camera.z);
|
||||||
|
VertexRendering.drawBox(matrices,consumers.getBuffer(RenderLayer.getLines()),box.expand(0.002),0.1f,0.85f,0.95f,1f);
|
||||||
|
} finally { matrices.pop(); }
|
||||||
|
});
|
||||||
|
}
|
||||||
|
private KeyBinding key(String name,int code) {
|
||||||
|
return KeyBindingHelper.registerKeyBinding(new KeyBinding(name,InputUtil.Type.KEYSYM,code,"category.dunium"));
|
||||||
|
}
|
||||||
|
private void reset() {
|
||||||
|
connected=false; a=null; b=null; dimension=""; ticks=0;
|
||||||
|
feedback="Waiting for a Dunium-enabled server. Creative mode and builder permissions are required.";
|
||||||
|
}
|
||||||
|
private static BlockPos parse(String value) {
|
||||||
|
if (value.equals("-")) return null;
|
||||||
|
String[] xyz=value.split(",");
|
||||||
|
if (xyz.length!=3) throw new IllegalArgumentException("Invalid point");
|
||||||
|
int x=Integer.parseInt(xyz[0]),y=Integer.parseInt(xyz[1]),z=Integer.parseInt(xyz[2]);
|
||||||
|
if (Math.abs((long)x)>30_000_000 || Math.abs((long)z)>30_000_000 || Math.abs((long)y)>4096) throw new IllegalArgumentException("Invalid bounds");
|
||||||
|
return new BlockPos(x,y,z);
|
||||||
|
}
|
||||||
|
private static void receive(String message) {
|
||||||
|
String[] fields=message.split("\t",5);
|
||||||
|
if (fields.length!=5 || !fields[0].equals("1")) return;
|
||||||
|
try {
|
||||||
|
BlockPos first=parse(fields[2]),second=parse(fields[3]);
|
||||||
|
dimension=fields[1]; a=first; b=second; feedback=fields[4]; connected=true;
|
||||||
|
} catch (IllegalArgumentException ignored) { /* Ignore incompatible or malformed state. */ }
|
||||||
|
}
|
||||||
|
public static BlockPos target(MinecraftClient client) {
|
||||||
|
if (client.player==null) return BlockPos.ORIGIN;
|
||||||
|
HitResult hit=client.player.raycast(64,1,false);
|
||||||
|
return hit instanceof BlockHitResult block && hit.getType()==HitResult.Type.BLOCK ? block.getBlockPos() : client.player.getBlockPos();
|
||||||
|
}
|
||||||
|
public static void select(int index,BlockPos point) { send("pos"+index+" "+point.getX()+" "+point.getY()+" "+point.getZ()); }
|
||||||
|
public static void send(String command) {
|
||||||
|
if (!ClientPlayNetworking.canSend(CommandPayload.ID)) {
|
||||||
|
feedback="This server does not advertise Dunium. Install Dunium-Server and grant builder permissions.";
|
||||||
|
var player=MinecraftClient.getInstance().player;
|
||||||
|
if (player!=null) player.sendMessage(Text.literal(feedback),false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
ClientPlayNetworking.send(new CommandPayload("1\t"+command));
|
||||||
|
}
|
||||||
|
public static String selectionText() {
|
||||||
|
if (a==null || b==null) return "Selection: set both corners using [ and ] while looking at blocks.";
|
||||||
|
long volume=((long)Math.abs(a.getX()-b.getX())+1)*(Math.abs(a.getY()-b.getY())+1)*(Math.abs(a.getZ()-b.getZ())+1);
|
||||||
|
return "Selection: "+volume+" blocks. Outline reflects the server's accepted corners.";
|
||||||
|
}
|
||||||
|
}
|
||||||
64
dunium-client/src/main/java/dunium/ToolScreen.java
Normal file
64
dunium-client/src/main/java/dunium/ToolScreen.java
Normal file
|
|
@ -0,0 +1,64 @@
|
||||||
|
package dunium;
|
||||||
|
|
||||||
|
import net.minecraft.client.gui.DrawContext;
|
||||||
|
import net.minecraft.client.gui.screen.Screen;
|
||||||
|
import net.minecraft.client.gui.widget.*;
|
||||||
|
import net.minecraft.text.Text;
|
||||||
|
import net.minecraft.util.math.BlockPos;
|
||||||
|
|
||||||
|
/** Original compact tool palette; actual edits always require server confirmation. */
|
||||||
|
public final class ToolScreen extends Screen {
|
||||||
|
private final BlockPos target;
|
||||||
|
private final boolean terrain;
|
||||||
|
private TextFieldWidget source,destination;
|
||||||
|
private int left,top,panelWidth;
|
||||||
|
public ToolScreen(BlockPos target) { this(target,false); }
|
||||||
|
private ToolScreen(BlockPos target,boolean terrain) { super(Text.literal("Dunium")); this.target=target; this.terrain=terrain; }
|
||||||
|
@Override protected void init() {
|
||||||
|
panelWidth=Math.min(480,width-20); left=(width-panelWidth)/2; top=Math.max(4,(height-300)/2);
|
||||||
|
int half=(panelWidth-30)/2, x=left+10, right=x+half+10;
|
||||||
|
source=new TextFieldWidget(textRenderer,x,top+62,half,20,Text.literal("Exact source block state"));
|
||||||
|
source.setMaxLength(400); source.setText(terrain?"3":"minecraft:stone"); addDrawableChild(source);
|
||||||
|
destination=new TextFieldWidget(textRenderer,right,top+62,half,20,Text.literal("Destination block state"));
|
||||||
|
destination.setMaxLength(400); destination.setText("minecraft:sandstone"); addDrawableChild(destination);
|
||||||
|
if (!terrain) {
|
||||||
|
button("Set corner 1",x,top+90,half,()->DuniumClient.select(1,target));
|
||||||
|
button("Set corner 2",right,top+90,half,()->DuniumClient.select(2,target));
|
||||||
|
button("Preview fill",x,top+114,half,()->DuniumClient.send("fill "+destination.getText().trim()));
|
||||||
|
button("Preview replace",right,top+114,half,()->DuniumClient.send("replace "+source.getText().trim()+" "+destination.getText().trim()));
|
||||||
|
button("Copy selection",x,top+138,half,()->DuniumClient.send("copy"));
|
||||||
|
button("Preview paste here",right,top+138,half,()->DuniumClient.send("paste "+target.getX()+" "+target.getY()+" "+target.getZ()));
|
||||||
|
} else {
|
||||||
|
button("Preview sphere",x,top+90,half,()->DuniumClient.send("sphere "+source.getText().trim()+" "+destination.getText().trim()+" "+target.getX()+" "+target.getY()+" "+target.getZ()));
|
||||||
|
button("Flatten to target Y",right,top+90,half,()->DuniumClient.send("flatten "+target.getY()+" "+destination.getText().trim()));
|
||||||
|
button("Rotate clipboard 90",x,top+114,half,()->DuniumClient.send("rotate 90"));
|
||||||
|
button("Rotate clipboard 180",right,top+114,half,()->DuniumClient.send("rotate 180"));
|
||||||
|
button("Mirror clipboard X",x,top+138,half,()->DuniumClient.send("mirror x"));
|
||||||
|
button("Mirror clipboard Z",right,top+138,half,()->DuniumClient.send("mirror z"));
|
||||||
|
}
|
||||||
|
button("Confirm edit",x,top+162,half,()->DuniumClient.send("confirm"));
|
||||||
|
button("Cancel work",right,top+162,half,()->DuniumClient.send("cancel"));
|
||||||
|
button("Undo",x,top+186,half,()->DuniumClient.send("undo"));
|
||||||
|
button("Redo",right,top+186,half,()->DuniumClient.send("redo"));
|
||||||
|
button(terrain?"Building tools":"Terrain / clipboard",x,top+210,half,()->{ if (client!=null) client.setScreen(new ToolScreen(target,!terrain)); });
|
||||||
|
button("Close",right,top+210,half,this::close);
|
||||||
|
}
|
||||||
|
private void button(String text,int x,int y,int width,Runnable run) {
|
||||||
|
addDrawableChild(ButtonWidget.builder(Text.literal(text),b->run.run()).dimensions(x,y,width,20).build());
|
||||||
|
}
|
||||||
|
@Override public void render(DrawContext context,int mouseX,int mouseY,float delta) {
|
||||||
|
context.fill(left,top,left+panelWidth,Math.min(height-4,top+300),0xED101C27);
|
||||||
|
context.drawTextWithShadow(textRenderer,"DUNIUM / BUILD TOOLS",left+10,top+10,0xFF63DAE8);
|
||||||
|
context.drawTextWithShadow(textRenderer,DuniumClient.connected?"Server connected | K opens tools":"Awaiting server handshake",left+10,top+26,0xFFD3DCE5);
|
||||||
|
context.drawTextWithShadow(textRenderer,terrain?"Sphere radius":"Exact source",left+10,top+50,0xFFBBC7D3);
|
||||||
|
context.drawTextWithShadow(textRenderer,"Destination",left+20+(panelWidth-30)/2,top+50,0xFFBBC7D3);
|
||||||
|
super.render(context,mouseX,mouseY,delta);
|
||||||
|
String status=DuniumClient.feedback;
|
||||||
|
// Keep status readable on smaller displays; full messages are also sent through chat.
|
||||||
|
String trimmed=textRenderer.trimToWidth(status,panelWidth-20);
|
||||||
|
context.drawTextWithShadow(textRenderer,trimmed,left+10,top+240,0xFFFFD68A);
|
||||||
|
context.drawTextWithShadow(textRenderer,textRenderer.trimToWidth(DuniumClient.selectionText(),panelWidth-20),left+10,top+255,0xFFBBC7D3);
|
||||||
|
context.drawTextWithShadow(textRenderer,"Target: "+target.getX()+", "+target.getY()+", "+target.getZ(),left+10,top+270,0xFFBBC7D3);
|
||||||
|
}
|
||||||
|
@Override public boolean shouldPause() { return false; }
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,6 @@
|
||||||
|
{
|
||||||
|
"category.dunium": "Dunium",
|
||||||
|
"key.dunium.menu": "Open building tools",
|
||||||
|
"key.dunium.pos1": "Select first corner",
|
||||||
|
"key.dunium.pos2": "Select second corner"
|
||||||
|
}
|
||||||
15
dunium-client/src/main/resources/fabric.mod.json
Normal file
15
dunium-client/src/main/resources/fabric.mod.json
Normal file
|
|
@ -0,0 +1,15 @@
|
||||||
|
{
|
||||||
|
"schemaVersion": 1,
|
||||||
|
"id": "dunium",
|
||||||
|
"version": "${version}",
|
||||||
|
"name": "Dunium",
|
||||||
|
"description": "Original visual building tools for Dunium-enabled Paper servers.",
|
||||||
|
"environment": "client",
|
||||||
|
"entrypoints": { "client": ["dunium.DuniumClient"] },
|
||||||
|
"depends": {
|
||||||
|
"fabricloader": ">=0.17.2",
|
||||||
|
"minecraft": "1.21.8",
|
||||||
|
"java": ">=21",
|
||||||
|
"fabric-api": "*"
|
||||||
|
}
|
||||||
|
}
|
||||||
6
dunium-common/build.gradle
Normal file
6
dunium-common/build.gradle
Normal file
|
|
@ -0,0 +1,6 @@
|
||||||
|
tasks.register('engineChecks', JavaExec) {
|
||||||
|
dependsOn testClasses
|
||||||
|
classpath = sourceSets.test.runtimeClasspath
|
||||||
|
mainClass = 'dunium.EngineChecks'
|
||||||
|
}
|
||||||
|
check.dependsOn engineChecks
|
||||||
132
dunium-common/src/main/java/dunium/Editor.java
Normal file
132
dunium-common/src/main/java/dunium/Editor.java
Normal file
|
|
@ -0,0 +1,132 @@
|
||||||
|
package dunium;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** Platform-independent editing rules. World access is supplied by the server. */
|
||||||
|
public final class Editor {
|
||||||
|
private Editor() {}
|
||||||
|
public record Point(int x, int y, int z) {
|
||||||
|
public Point add(Point p) { return new Point(Math.addExact(x,p.x), Math.addExact(y,p.y), Math.addExact(z,p.z)); }
|
||||||
|
}
|
||||||
|
public record Region(Point min, Point max) implements Iterable<Point> {
|
||||||
|
public Region {
|
||||||
|
if (min.x>max.x || min.y>max.y || min.z>max.z) throw new IllegalArgumentException("Inverted region");
|
||||||
|
}
|
||||||
|
public static Region between(Point a, Point b) {
|
||||||
|
return new Region(new Point(Math.min(a.x,b.x),Math.min(a.y,b.y),Math.min(a.z,b.z)),
|
||||||
|
new Point(Math.max(a.x,b.x),Math.max(a.y,b.y),Math.max(a.z,b.z)));
|
||||||
|
}
|
||||||
|
public long volume() {
|
||||||
|
return Math.multiplyExact(Math.multiplyExact((long)max.x-min.x+1,(long)max.y-min.y+1),(long)max.z-min.z+1);
|
||||||
|
}
|
||||||
|
public boolean overlaps(Region b) {
|
||||||
|
return min.x<=b.max.x && max.x>=b.min.x && min.y<=b.max.y && max.y>=b.min.y && min.z<=b.max.z && max.z>=b.min.z;
|
||||||
|
}
|
||||||
|
public Iterator<Point> iterator() {
|
||||||
|
return new Iterator<>() {
|
||||||
|
long index; final long size=volume(), sx=(long)max.x-min.x+1, sz=(long)max.z-min.z+1;
|
||||||
|
public boolean hasNext() { return index<size; }
|
||||||
|
public Point next() {
|
||||||
|
if (!hasNext()) throw new NoSuchElementException();
|
||||||
|
long i=index++;
|
||||||
|
return new Point((int)(min.x+i%sx),(int)(min.y+i/(sx*sz)),(int)(min.z+(i/sx)%sz));
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/** Null replacement means a skipped shape position, which still consumes budget. */
|
||||||
|
public record Intent(Point point, String expected, String replacement) {
|
||||||
|
public Intent { Objects.requireNonNull(point); }
|
||||||
|
}
|
||||||
|
public record Change(Point point, String before, String after) {}
|
||||||
|
public interface Access {
|
||||||
|
/** Must reject unloaded chunks, protected blocks, block entities and revoked permissions. */
|
||||||
|
boolean allowed(Point point);
|
||||||
|
String read(Point point);
|
||||||
|
void write(Point point, String state);
|
||||||
|
}
|
||||||
|
/** Advances at most budget positions, including skipped positions. No unbounded pre-scan. */
|
||||||
|
public static final class Task {
|
||||||
|
private final Iterator<Intent> intents;
|
||||||
|
private final List<Change> changes=new ArrayList<>();
|
||||||
|
private long visited, skipped;
|
||||||
|
private boolean cancelled;
|
||||||
|
public Task(Iterator<Intent> intents) { this.intents=Objects.requireNonNull(intents); }
|
||||||
|
public int advance(Access access, int budget) {
|
||||||
|
if (budget<1) throw new IllegalArgumentException("Positive budget required");
|
||||||
|
int used=0;
|
||||||
|
while (!cancelled && used<budget && intents.hasNext()) {
|
||||||
|
Intent intent=intents.next(); used++; visited++;
|
||||||
|
if (intent.replacement==null) continue;
|
||||||
|
if (!access.allowed(intent.point)) { skipped++; continue; }
|
||||||
|
String before=access.read(intent.point);
|
||||||
|
if (intent.expected!=null && !intent.expected.equals(before)) { skipped++; continue; }
|
||||||
|
if (before.equals(intent.replacement)) continue;
|
||||||
|
// Record before writing, so a failure after a partial write remains recoverable.
|
||||||
|
Change change=new Change(intent.point,before,intent.replacement);
|
||||||
|
changes.add(change);
|
||||||
|
access.write(intent.point,intent.replacement);
|
||||||
|
}
|
||||||
|
return used;
|
||||||
|
}
|
||||||
|
public boolean done() { return cancelled || !intents.hasNext(); }
|
||||||
|
public void cancel() { cancelled=true; }
|
||||||
|
public boolean cancelled() { return cancelled; }
|
||||||
|
public List<Change> changes() { return List.copyOf(changes); }
|
||||||
|
public long visited() { return visited; }
|
||||||
|
public long skipped() { return skipped; }
|
||||||
|
}
|
||||||
|
public static Iterator<Intent> fill(Region region, String state, String match) {
|
||||||
|
Iterator<Point> points=region.iterator();
|
||||||
|
return new Iterator<>() {
|
||||||
|
public boolean hasNext() { return points.hasNext(); }
|
||||||
|
public Intent next() { return new Intent(points.next(),match,state); }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
public static Iterator<Intent> reverse(List<Change> changes) {
|
||||||
|
ListIterator<Change> it=changes.listIterator(changes.size());
|
||||||
|
return new Iterator<>() {
|
||||||
|
public boolean hasNext() { return it.hasPrevious(); }
|
||||||
|
public Intent next() { Change c=it.previous(); return new Intent(c.point,c.after,c.before); }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
public static Iterator<Intent> sphere(Region region,Point center,int radius,String state) {
|
||||||
|
if (radius<1 || radius>64) throw new IllegalArgumentException("Radius must be 1..64");
|
||||||
|
Iterator<Point> points=region.iterator();
|
||||||
|
return new Iterator<>() {
|
||||||
|
public boolean hasNext() { return points.hasNext(); }
|
||||||
|
public Intent next() {
|
||||||
|
Point p=points.next();
|
||||||
|
long dx=(long)p.x-center.x,dy=(long)p.y-center.y,dz=(long)p.z-center.z;
|
||||||
|
return new Intent(p,null,dx*dx+dy*dy+dz*dz<=(long)radius*radius?state:null);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
public static Iterator<Intent> flatten(Region region,int level,String state,String air) {
|
||||||
|
if (level<region.min.y || level>region.max.y) throw new IllegalArgumentException("Level must be inside selection");
|
||||||
|
Iterator<Point> points=region.iterator();
|
||||||
|
return new Iterator<>() {
|
||||||
|
public boolean hasNext() { return points.hasNext(); }
|
||||||
|
public Intent next() { Point p=points.next(); return new Intent(p,null,p.y<=level?state:air); }
|
||||||
|
};
|
||||||
|
}
|
||||||
|
public record Cell(Point offset, String state) {}
|
||||||
|
public record Clipboard(int width, int height, int depth, List<Cell> cells) {
|
||||||
|
public Clipboard {
|
||||||
|
if (width<1 || height<1 || depth<1) throw new IllegalArgumentException("Empty clipboard");
|
||||||
|
cells=List.copyOf(cells);
|
||||||
|
}
|
||||||
|
public Region at(Point origin) { return new Region(origin,origin.add(new Point(width-1,height-1,depth-1))); }
|
||||||
|
public Iterator<Intent> paste(Point origin) {
|
||||||
|
return cells.stream().map(c->new Intent(origin.add(c.offset),null,c.state)).iterator();
|
||||||
|
}
|
||||||
|
public Clipboard rotateClockwise(java.util.function.UnaryOperator<String> rotateState) {
|
||||||
|
return new Clipboard(depth,height,width,cells.stream().map(c->new Cell(
|
||||||
|
new Point(depth-1-c.offset.z,c.offset.y,c.offset.x),rotateState.apply(c.state))).toList());
|
||||||
|
}
|
||||||
|
public Clipboard mirror(boolean xAxis,java.util.function.UnaryOperator<String> mirrorState) {
|
||||||
|
return new Clipboard(width,height,depth,cells.stream().map(c->new Cell(
|
||||||
|
new Point(xAxis?width-1-c.offset.x:c.offset.x,c.offset.y,xAxis?c.offset.z:depth-1-c.offset.z),mirrorState.apply(c.state))).toList());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
118
dunium-common/src/test/java/dunium/EngineChecks.java
Normal file
118
dunium-common/src/test/java/dunium/EngineChecks.java
Normal file
|
|
@ -0,0 +1,118 @@
|
||||||
|
package dunium;
|
||||||
|
|
||||||
|
import dunium.Editor.*;
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/** Dependency-free regression suite, also wired into Gradle check. */
|
||||||
|
public final class EngineChecks {
|
||||||
|
private static int checks;
|
||||||
|
private static final Point A=new Point(0,0,0), B=new Point(1,0,0), C=new Point(2,0,0);
|
||||||
|
private static final Region REGION=new Region(A,C);
|
||||||
|
private static final class Memory implements Access {
|
||||||
|
final Map<Point,String> blocks=new HashMap<>();
|
||||||
|
final Set<Point> denied=new HashSet<>();
|
||||||
|
int reads,writes;
|
||||||
|
public boolean allowed(Point p) { return !denied.contains(p); }
|
||||||
|
public String read(Point p) { reads++; return blocks.getOrDefault(p,"air"); }
|
||||||
|
public void write(Point p,String state) { writes++; blocks.put(p,state); }
|
||||||
|
String at(Point p) { return blocks.getOrDefault(p,"air"); }
|
||||||
|
}
|
||||||
|
private static void check(boolean condition,String reason) {
|
||||||
|
checks++; if (!condition) throw new AssertionError(reason);
|
||||||
|
}
|
||||||
|
private static void rejects(Runnable action,String reason) {
|
||||||
|
boolean rejected=false;
|
||||||
|
try { action.run(); } catch (IllegalArgumentException | ArithmeticException | NoSuchElementException expected) { rejected=true; }
|
||||||
|
check(rejected,reason);
|
||||||
|
}
|
||||||
|
public static void main(String[] args) {
|
||||||
|
Region normal=Region.between(new Point(2,1,3),new Point(-1,-2,-3));
|
||||||
|
check(normal.volume()==112,"Inclusive negative/reversed volume");
|
||||||
|
Set<Point> visited=new HashSet<>(); normal.forEach(visited::add);
|
||||||
|
check(visited.size()==normal.volume(),"Every coordinate exactly once");
|
||||||
|
check(visited.contains(normal.min())&&visited.contains(normal.max()),"Both extrema included");
|
||||||
|
var iterator=new Region(A,A).iterator(); check(iterator.next().equals(A),"Single-block region");
|
||||||
|
rejects(iterator::next,"Exhausted iterator throws");
|
||||||
|
rejects(()->new Region(B,A),"Reject inverted bounds");
|
||||||
|
rejects(()->new Region(new Point(Integer.MIN_VALUE,Integer.MIN_VALUE,Integer.MIN_VALUE),new Point(Integer.MAX_VALUE,Integer.MAX_VALUE,Integer.MAX_VALUE)).volume(),"Reject volume overflow");
|
||||||
|
rejects(()->new Point(Integer.MAX_VALUE,0,0).add(B),"Reject coordinate overflow");
|
||||||
|
check(REGION.overlaps(new Region(C,new Point(3,0,0))),"Shared edge is an overlap");
|
||||||
|
check(!REGION.overlaps(new Region(new Point(3,0,0),new Point(4,0,0))),"Adjacent independent blocks do not overlap");
|
||||||
|
Memory world=new Memory(); Editor.Task task=new Editor.Task(Editor.fill(REGION,"stone",null));
|
||||||
|
check(task.advance(world,1)==1&&world.writes==1&&!task.done(),"Budget bounds first slice");
|
||||||
|
check(task.advance(world,1)==1&&world.writes==2,"Budget bounds second slice");
|
||||||
|
task.advance(world,1); check(task.done()&&task.changes().size()==3,"Final slice completes");
|
||||||
|
rejects(()->task.advance(world,0),"Reject zero budget");
|
||||||
|
Memory protectedWorld=new Memory(); protectedWorld.denied.add(A); protectedWorld.denied.add(B);
|
||||||
|
Editor.Task protectedTask=new Editor.Task(Editor.fill(REGION,"stone",null));
|
||||||
|
check(protectedTask.advance(protectedWorld,2)==2&&protectedWorld.writes==0&&!protectedTask.done(),"Denied positions consume budget");
|
||||||
|
check(protectedWorld.reads==0,"Never read a denied block");
|
||||||
|
protectedTask.advance(protectedWorld,2); check(protectedTask.skipped()==2&&protectedTask.changes().size()==1,"Protected blocks skipped, permitted block changed");
|
||||||
|
Memory revoked=new Memory(); Editor.Task revocation=new Editor.Task(Editor.fill(REGION,"stone",null));
|
||||||
|
revocation.advance(revoked,1); revoked.denied.add(B); revocation.advance(revoked,1);
|
||||||
|
check(revoked.at(B).equals("air"),"Permission changes respected between slices");
|
||||||
|
Memory filtered=new Memory(); filtered.blocks.put(A,"stone"); filtered.blocks.put(B,"dirt");
|
||||||
|
Editor.Task replace=new Editor.Task(Editor.fill(REGION,"sand","stone")); replace.advance(filtered,3);
|
||||||
|
check(filtered.at(A).equals("sand")&&filtered.at(B).equals("dirt"),"Replace changes only exact matches");
|
||||||
|
check(replace.skipped()==2,"Exact replace skip count");
|
||||||
|
Memory same=new Memory(); same.blocks.put(A,"stone");
|
||||||
|
Editor.Task noop=new Editor.Task(Editor.fill(new Region(A,A),"stone",null)); noop.advance(same,1);
|
||||||
|
check(noop.changes().isEmpty()&&same.writes==0,"No-op creates no history");
|
||||||
|
Editor.Task cancelled=new Editor.Task(Editor.fill(REGION,"gold",null)); Memory partial=new Memory();
|
||||||
|
cancelled.advance(partial,1); cancelled.cancel(); cancelled.advance(partial,100);
|
||||||
|
check(partial.writes==1&&cancelled.done()&&cancelled.cancelled(),"Cancellation stops remaining mutations");
|
||||||
|
Editor.Task partialUndo=new Editor.Task(Editor.reverse(cancelled.changes())); partialUndo.advance(partial,10);
|
||||||
|
check(partial.at(A).equals("air"),"Completed part of cancelled edit is undoable");
|
||||||
|
world.blocks.put(B,"other-player-change");
|
||||||
|
Editor.Task undo=new Editor.Task(Editor.reverse(task.changes())); undo.advance(world,10);
|
||||||
|
check(world.at(A).equals("air")&&world.at(C).equals("air"),"Undo restores original states");
|
||||||
|
check(world.at(B).equals("other-player-change")&&undo.skipped()==1,"Undo preserves later edits");
|
||||||
|
Editor.Task redo=new Editor.Task(Editor.reverse(undo.changes())); redo.advance(world,10);
|
||||||
|
check(world.at(A).equals("stone")&&world.at(C).equals("stone"),"Redo reverses actual undo");
|
||||||
|
check(world.at(B).equals("other-player-change"),"Redo does not resurrect skipped conflict");
|
||||||
|
List<Cell> original=new ArrayList<>(); original.add(new Cell(A,"stone")); original.add(new Cell(B,"air"));
|
||||||
|
Clipboard clipboard=new Clipboard(2,1,1,original); original.clear();
|
||||||
|
check(clipboard.cells().size()==2,"Clipboard is an immutable snapshot");
|
||||||
|
Point origin=new Point(-5,10,3); check(clipboard.at(origin).max().equals(new Point(-4,10,3)),"Paste uses minimum-corner origin");
|
||||||
|
Memory pasted=new Memory(); pasted.blocks.put(origin.add(B),"dirt");
|
||||||
|
Editor.Task paste=new Editor.Task(clipboard.paste(origin)); paste.advance(pasted,10);
|
||||||
|
check(pasted.at(origin).equals("stone")&&pasted.at(origin.add(B)).equals("air"),"Paste translates positions and includes air");
|
||||||
|
Memory failed=new Memory();
|
||||||
|
Editor.Task fault=new Editor.Task(Editor.fill(new Region(A,A),"stone",null));
|
||||||
|
boolean threw=false;
|
||||||
|
try { fault.advance(new Access() {
|
||||||
|
public boolean allowed(Point p) { return true; }
|
||||||
|
public String read(Point p) { return failed.read(p); }
|
||||||
|
public void write(Point p,String state) { failed.write(p,state); throw new IllegalStateException("post-write fault"); }
|
||||||
|
},1); } catch (IllegalStateException expected) { threw=true; }
|
||||||
|
check(threw&&fault.changes().size()==1,"Post-write failure retains recovery record");
|
||||||
|
new Editor.Task(Editor.reverse(fault.changes())).advance(failed,1);
|
||||||
|
check(failed.at(A).equals("air"),"Failed write can be recovered");
|
||||||
|
Clipboard rotated=clipboard.rotateClockwise(state->state+"-rotated");
|
||||||
|
check(rotated.width()==1&&rotated.depth()==2,"Rotation swaps dimensions");
|
||||||
|
check(rotated.cells().get(1).offset().equals(new Point(0,0,1)),"Clockwise coordinates");
|
||||||
|
check(rotated.cells().get(0).state().equals("stone-rotated"),"Rotation transforms directional states");
|
||||||
|
Clipboard roundtrip=clipboard;
|
||||||
|
for (int i=0;i<4;i++) roundtrip=roundtrip.rotateClockwise(state->state);
|
||||||
|
check(roundtrip.equals(clipboard),"Four turns restore clipboard");
|
||||||
|
Clipboard mirrored=clipboard.mirror(true,state->state);
|
||||||
|
check(mirrored.cells().get(0).offset().equals(B),"X mirror flips X");
|
||||||
|
check(mirrored.mirror(true,state->state).equals(clipboard),"Double X mirror restores clipboard");
|
||||||
|
check(clipboard.mirror(false,state->state).mirror(false,state->state).equals(clipboard),"Double Z mirror restores clipboard");
|
||||||
|
Memory sphereWorld=new Memory();
|
||||||
|
Region cube=new Region(new Point(-1,-1,-1),new Point(1,1,1));
|
||||||
|
Editor.Task sphere=new Editor.Task(Editor.sphere(cube,A,1,"stone"));
|
||||||
|
sphere.advance(sphereWorld,1);
|
||||||
|
check(sphere.visited()==1&&sphereWorld.writes==0,"Outside sphere positions consume budget");
|
||||||
|
sphere.advance(sphereWorld,100);
|
||||||
|
check(sphereWorld.writes==7&&sphere.visited()==27,"Integer unit sphere includes seven blocks");
|
||||||
|
check(sphereWorld.at(new Point(1,1,1)).equals("air"),"Sphere leaves cube corners unchanged");
|
||||||
|
rejects(()->Editor.sphere(cube,A,0,"stone"),"Reject invalid brush radius");
|
||||||
|
Memory terrain=new Memory(); terrain.blocks.put(new Point(0,1,0),"dirt");
|
||||||
|
Editor.Task flat=new Editor.Task(Editor.flatten(cube,0,"sandstone","air")); flat.advance(terrain,100);
|
||||||
|
check(terrain.at(new Point(0,-1,0)).equals("sandstone")&&terrain.at(A).equals("sandstone"),"Flatten fills through target level");
|
||||||
|
check(terrain.at(new Point(0,1,0)).equals("air"),"Flatten clears above target level");
|
||||||
|
rejects(()->Editor.flatten(cube,2,"sandstone","air"),"Reject flatten outside selection");
|
||||||
|
System.out.println("Dunium engine: "+checks+" checks passed.");
|
||||||
|
}
|
||||||
|
}
|
||||||
7
dunium-server/build.gradle
Normal file
7
dunium-server/build.gradle
Normal file
|
|
@ -0,0 +1,7 @@
|
||||||
|
repositories { maven { url = 'https://repo.papermc.io/repository/maven-public/' } }
|
||||||
|
dependencies {
|
||||||
|
implementation project(':dunium-common')
|
||||||
|
compileOnly 'io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT'
|
||||||
|
}
|
||||||
|
processResources { inputs.property 'version', project.version; filesMatching('plugin.yml') { expand version: project.version } }
|
||||||
|
jar { archiveBaseName = 'Dunium-Server'; from project(':dunium-common').sourceSets.main.output }
|
||||||
20
dunium-server/src/main/java/dunium/DuniumEditCheckEvent.java
Normal file
20
dunium-server/src/main/java/dunium/DuniumEditCheckEvent.java
Normal file
|
|
@ -0,0 +1,20 @@
|
||||||
|
package dunium;
|
||||||
|
|
||||||
|
import org.bukkit.block.Block;
|
||||||
|
import org.bukkit.entity.Player;
|
||||||
|
import org.bukkit.event.*;
|
||||||
|
|
||||||
|
/** Protection plugins may cancel any attempted read or write. Fired on the server thread. */
|
||||||
|
public final class DuniumEditCheckEvent extends Event implements Cancellable {
|
||||||
|
private static final HandlerList HANDLERS=new HandlerList();
|
||||||
|
private final Player player;
|
||||||
|
private final Block block;
|
||||||
|
private boolean cancelled;
|
||||||
|
public DuniumEditCheckEvent(Player player, Block block) { this.player=player; this.block=block; }
|
||||||
|
public Player getPlayer() { return player; }
|
||||||
|
public Block getBlock() { return block; }
|
||||||
|
public boolean isCancelled() { return cancelled; }
|
||||||
|
public void setCancelled(boolean value) { cancelled=value; }
|
||||||
|
public HandlerList getHandlers() { return HANDLERS; }
|
||||||
|
public static HandlerList getHandlerList() { return HANDLERS; }
|
||||||
|
}
|
||||||
382
dunium-server/src/main/java/dunium/DuniumPlugin.java
Normal file
382
dunium-server/src/main/java/dunium/DuniumPlugin.java
Normal file
|
|
@ -0,0 +1,382 @@
|
||||||
|
package dunium;
|
||||||
|
|
||||||
|
import dunium.Editor.*;
|
||||||
|
import java.nio.charset.StandardCharsets;
|
||||||
|
import java.util.*;
|
||||||
|
import java.util.function.Supplier;
|
||||||
|
import org.bukkit.*;
|
||||||
|
import org.bukkit.block.Block;
|
||||||
|
import org.bukkit.block.TileState;
|
||||||
|
import org.bukkit.block.data.BlockData;
|
||||||
|
import org.bukkit.block.structure.Mirror;
|
||||||
|
import org.bukkit.block.structure.StructureRotation;
|
||||||
|
import org.bukkit.command.*;
|
||||||
|
import org.bukkit.entity.Player;
|
||||||
|
import org.bukkit.event.*;
|
||||||
|
import org.bukkit.event.player.*;
|
||||||
|
import org.bukkit.plugin.java.JavaPlugin;
|
||||||
|
import org.bukkit.plugin.messaging.PluginMessageListener;
|
||||||
|
import net.kyori.adventure.text.Component;
|
||||||
|
|
||||||
|
/** All mutable state and all world access stay on Paper's main thread. */
|
||||||
|
public final class DuniumPlugin extends JavaPlugin implements Listener, CommandExecutor, TabCompleter, PluginMessageListener {
|
||||||
|
private static final String COMMAND="dunium:command", STATE="dunium:state";
|
||||||
|
private final Map<UUID,Session> sessions=new LinkedHashMap<>();
|
||||||
|
private final Map<UUID,Job> jobs=new LinkedHashMap<>();
|
||||||
|
private Protection protection;
|
||||||
|
private int budget,maxBlocks,maxHistory,maxEntries,maxSessions,maxJobs,reach,maxRadius,timeout,ticks;
|
||||||
|
private boolean creativeOnly;
|
||||||
|
private Set<String> worlds,denied;
|
||||||
|
|
||||||
|
private static final class Session {
|
||||||
|
UUID world;
|
||||||
|
Point a,b;
|
||||||
|
Clipboard clipboard;
|
||||||
|
Pending pending;
|
||||||
|
boolean mod;
|
||||||
|
long lastCommand;
|
||||||
|
final Deque<History> undo=new ArrayDeque<>(),redo=new ArrayDeque<>();
|
||||||
|
}
|
||||||
|
private record History(UUID world, Region bounds, List<Change> changes) {}
|
||||||
|
private record Pending(UUID world, Region bounds, String label, Supplier<Iterator<Intent>> intents, long expires) {}
|
||||||
|
private static final class Job {
|
||||||
|
Player player;
|
||||||
|
UUID world;
|
||||||
|
Region bounds;
|
||||||
|
String label;
|
||||||
|
Editor.Task task;
|
||||||
|
Iterator<Point> copying;
|
||||||
|
List<Cell> cells;
|
||||||
|
int historyMode; // 0 normal, 1 undo, 2 redo
|
||||||
|
boolean cancel;
|
||||||
|
long visited;
|
||||||
|
}
|
||||||
|
@Override public void onEnable() {
|
||||||
|
saveDefaultConfig();
|
||||||
|
budget=setting("blocks-per-tick",500,1,5000);
|
||||||
|
maxBlocks=setting("max-blocks",10000,1,1000000);
|
||||||
|
maxHistory=setting("max-history-blocks-per-player",20000,maxBlocks,2000000);
|
||||||
|
maxEntries=setting("max-history-entries-per-player",10,1,100);
|
||||||
|
maxSessions=setting("max-sessions",16,1,100);
|
||||||
|
maxJobs=setting("max-concurrent-jobs",2,1,16);
|
||||||
|
reach=setting("max-selection-distance",128,1,1024);
|
||||||
|
maxRadius=setting("max-brush-radius",16,1,64);
|
||||||
|
timeout=setting("confirmation-timeout-seconds",30,1,300);
|
||||||
|
creativeOnly=getConfig().getBoolean("creative-only",true);
|
||||||
|
worlds=Set.copyOf(getConfig().getStringList("allowed-worlds"));
|
||||||
|
denied=new HashSet<>(getConfig().getStringList("denied-materials"));
|
||||||
|
protection=new Protection(this);
|
||||||
|
Objects.requireNonNull(getCommand("dunium")).setExecutor(this);
|
||||||
|
Objects.requireNonNull(getCommand("dunium")).setTabCompleter(this);
|
||||||
|
getServer().getPluginManager().registerEvents(this,this);
|
||||||
|
getServer().getMessenger().registerIncomingPluginChannel(this,COMMAND,this);
|
||||||
|
getServer().getMessenger().registerOutgoingPluginChannel(this,STATE);
|
||||||
|
getServer().getScheduler().runTaskTimer(this,this::tick,1,1);
|
||||||
|
getLogger().info("Dunium alpha enabled. Allowed worlds: "+worlds+". History is session-only.");
|
||||||
|
}
|
||||||
|
private int setting(String key,int fallback,int min,int max) {
|
||||||
|
int value=getConfig().getInt(key,fallback);
|
||||||
|
if (value<min || value>max) throw new IllegalArgumentException(key+" must be between "+min+" and "+max);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
@Override public void onDisable() {
|
||||||
|
jobs.clear(); sessions.clear();
|
||||||
|
getServer().getMessenger().unregisterIncomingPluginChannel(this);
|
||||||
|
getServer().getMessenger().unregisterOutgoingPluginChannel(this);
|
||||||
|
}
|
||||||
|
@EventHandler public void quit(PlayerQuitEvent event) {
|
||||||
|
jobs.remove(event.getPlayer().getUniqueId());
|
||||||
|
sessions.remove(event.getPlayer().getUniqueId());
|
||||||
|
}
|
||||||
|
@EventHandler public void changedWorld(PlayerChangedWorldEvent event) {
|
||||||
|
Player p=event.getPlayer(); Job job=jobs.get(p.getUniqueId());
|
||||||
|
if (job!=null) finish(job,true,"Stopped after changing worlds");
|
||||||
|
Session s=sessions.get(p.getUniqueId());
|
||||||
|
if (s!=null) { s.a=null; s.b=null; s.world=null; s.pending=null; reply(p,s,"Selection cleared after changing worlds."); }
|
||||||
|
}
|
||||||
|
@Override public boolean onCommand(CommandSender sender,Command command,String label,String[] args) {
|
||||||
|
if (!(sender instanceof Player player)) { sender.sendMessage("Dunium is an in-game builder tool."); return true; }
|
||||||
|
execute(player,args); return true;
|
||||||
|
}
|
||||||
|
@Override public List<String> onTabComplete(CommandSender sender,Command cmd,String label,String[] args) {
|
||||||
|
if (args.length!=1) return List.of();
|
||||||
|
return List.of("help","pos1","pos2","clear","fill","replace","sphere","flatten","copy","rotate","mirror","paste","confirm","cancel","undo","redo","status").stream()
|
||||||
|
.filter(s->s.startsWith(args[0].toLowerCase(Locale.ROOT))).toList();
|
||||||
|
}
|
||||||
|
@Override public void onPluginMessageReceived(String channel,Player p,byte[] data) {
|
||||||
|
if (!channel.equals(COMMAND) || data.length<3 || data.length>1024 || !Bukkit.isPrimaryThread()) return;
|
||||||
|
String message=new String(data,StandardCharsets.UTF_8);
|
||||||
|
if (!message.startsWith("1\t")) return;
|
||||||
|
String body=message.substring(2);
|
||||||
|
if (!body.matches("[a-zA-Z0-9_ :,=\\[\\]./+-]{1,500}")) return;
|
||||||
|
Session existing=sessions.get(p.getUniqueId());
|
||||||
|
if (existing!=null) existing.mod=true;
|
||||||
|
execute(p,body.split(" +"));
|
||||||
|
Session s=sessions.get(p.getUniqueId());
|
||||||
|
if (s!=null && !s.mod) { s.mod=true; reply(p,s,"Dunium connected."); }
|
||||||
|
}
|
||||||
|
private Session session(Player p) {
|
||||||
|
Session s=sessions.get(p.getUniqueId());
|
||||||
|
if (s==null) {
|
||||||
|
if (sessions.size()>=maxSessions) throw new IllegalArgumentException("Builder session limit reached. Try again later.");
|
||||||
|
s=new Session(); sessions.put(p.getUniqueId(),s);
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
private void execute(Player p,String[] args) {
|
||||||
|
if (!p.hasPermission("dunium.use")) { p.sendMessage("Dunium: missing dunium.use permission."); return; }
|
||||||
|
Session s=null;
|
||||||
|
try {
|
||||||
|
s=session(p);
|
||||||
|
long now=System.nanoTime();
|
||||||
|
if (now-s.lastCommand<100_000_000L) return;
|
||||||
|
s.lastCommand=now;
|
||||||
|
String action=args.length==0 ? "help" : args[0].toLowerCase(Locale.ROOT);
|
||||||
|
switch (action) {
|
||||||
|
case "hello" -> reply(p,s,"Dunium connected. Press K for tools.");
|
||||||
|
case "help" -> reply(p,s,"/du pos1|pos2 [x y z]; fill <state>; replace <exact-state> <state>; sphere <radius> <state> [x y z]; flatten <y> <state>; copy; rotate <90|180|270>; mirror <x|z>; paste [x y z]; confirm; cancel; undo; redo; clear; status. Changes require confirm. Creative/build worlds only.");
|
||||||
|
case "status" -> {
|
||||||
|
Job j=jobs.get(p.getUniqueId());
|
||||||
|
reply(p,s,j==null ? "Idle. Clipboard: "+(s.clipboard==null?0:s.clipboard.cells().size())+" blocks. Undo: "+s.undo.size()+", redo: "+s.redo.size()+". Pending: "+(s.pending==null?"none":s.pending.label()) : j.label+": "+(j.task==null?j.visited:j.task.visited())+"/"+j.bounds.volume());
|
||||||
|
}
|
||||||
|
case "cancel" -> {
|
||||||
|
s.pending=null;
|
||||||
|
Job j=jobs.get(p.getUniqueId());
|
||||||
|
if (j!=null) finish(j,true,"Cancelled; completed changes remain undoable");
|
||||||
|
else reply(p,s,"Pending edit cleared.");
|
||||||
|
}
|
||||||
|
case "clear" -> { idle(p); s.a=null; s.b=null; s.world=null; s.pending=null; reply(p,s,"Selection cleared."); }
|
||||||
|
case "pos1","pos2" -> {
|
||||||
|
editPermission(p); idle(p);
|
||||||
|
Point point=coordinate(p,args); checkPoint(p,p.getWorld(),point);
|
||||||
|
if (!p.getWorld().getUID().equals(s.world)) { s.a=null; s.b=null; s.world=p.getWorld().getUID(); }
|
||||||
|
if (action.equals("pos1")) s.a=point; else s.b=point;
|
||||||
|
s.pending=null;
|
||||||
|
reply(p,s,action+" = "+point+((s.a!=null&&s.b!=null)?"; volume "+Region.between(s.a,s.b).volume():""));
|
||||||
|
}
|
||||||
|
case "fill","replace" -> {
|
||||||
|
editPermission(p); idle(p);
|
||||||
|
int expected=action.equals("fill")?2:3;
|
||||||
|
if (args.length!=expected) throw new IllegalArgumentException("Usage: /du "+action+(expected==2?" <state>":" <exact-state> <state>"));
|
||||||
|
Region region=selection(p,s); validate(p,p.getWorld(),region);
|
||||||
|
String match=expected==3?state(args[1]):null;
|
||||||
|
String to=state(args[expected-1]);
|
||||||
|
prepare(p,s,region,action+" "+region.volume()+" positions",()->Editor.fill(region,to,match));
|
||||||
|
}
|
||||||
|
case "sphere" -> {
|
||||||
|
editPermission(p); idle(p);
|
||||||
|
if (args.length!=3 && args.length!=6) throw new IllegalArgumentException("Usage: /du sphere <radius> <state> [x y z]");
|
||||||
|
int radius=Integer.parseInt(args[1]);
|
||||||
|
if (radius<1 || radius>maxRadius) throw new IllegalArgumentException("Brush radius must be 1.."+maxRadius+" (also subject to max-blocks).");
|
||||||
|
String to=state(args[2]);
|
||||||
|
Point center=coordinate(p,args.length==3?new String[]{"sphere"}:new String[]{"sphere",args[3],args[4],args[5]});
|
||||||
|
Region region=new Region(center.add(new Point(-radius,-radius,-radius)),center.add(new Point(radius,radius,radius)));
|
||||||
|
validate(p,p.getWorld(),region);
|
||||||
|
s.world=p.getWorld().getUID(); s.a=region.min(); s.b=region.max();
|
||||||
|
prepare(p,s,region,"sphere radius "+radius+" ("+region.volume()+" bounds positions)",()->Editor.sphere(region,center,radius,to));
|
||||||
|
}
|
||||||
|
case "flatten" -> {
|
||||||
|
editPermission(p); idle(p);
|
||||||
|
if (args.length!=3) throw new IllegalArgumentException("Usage: /du flatten <y> <state>");
|
||||||
|
int level=Integer.parseInt(args[1]); String to=state(args[2]);
|
||||||
|
Region region=selection(p,s); validate(p,p.getWorld(),region);
|
||||||
|
if (level<region.min().y() || level>region.max().y()) throw new IllegalArgumentException("Flatten Y must be inside the selection.");
|
||||||
|
prepare(p,s,region,"flatten to Y="+level+" (fills below, clears above inside selection)",()->Editor.flatten(region,level,to,"minecraft:air"));
|
||||||
|
}
|
||||||
|
case "rotate","mirror" -> {
|
||||||
|
editPermission(p); idle(p);
|
||||||
|
if (s.clipboard==null) throw new IllegalArgumentException("Copy a selection first.");
|
||||||
|
if (args.length!=2) throw new IllegalArgumentException("Usage: /du "+action+(action.equals("rotate")?" <90|180|270>":" <x|z>"));
|
||||||
|
if (action.equals("rotate")) {
|
||||||
|
int degrees=Integer.parseInt(args[1]);
|
||||||
|
if (degrees!=90 && degrees!=180 && degrees!=270) throw new IllegalArgumentException("Rotation must be 90, 180 or 270.");
|
||||||
|
Clipboard rotated=s.clipboard;
|
||||||
|
for (int turn=0;turn<degrees/90;turn++) rotated=rotated.rotateClockwise(value->{ BlockData data=Bukkit.createBlockData(value); data.rotate(StructureRotation.CLOCKWISE_90); return data.getAsString(); });
|
||||||
|
s.clipboard=rotated;
|
||||||
|
} else {
|
||||||
|
if (!args[1].equals("x") && !args[1].equals("z")) throw new IllegalArgumentException("Mirror axis must be x or z.");
|
||||||
|
boolean x=args[1].equals("x");
|
||||||
|
s.clipboard=s.clipboard.mirror(x,value->{ BlockData data=Bukkit.createBlockData(value); data.mirror(x?Mirror.FRONT_BACK:Mirror.LEFT_RIGHT); return data.getAsString(); });
|
||||||
|
}
|
||||||
|
s.pending=null; reply(p,s,"Clipboard transformed, including directional block states. Prepare paste to preview.");
|
||||||
|
}
|
||||||
|
case "copy" -> {
|
||||||
|
editPermission(p); idle(p); capacity();
|
||||||
|
Region region=selection(p,s); validate(p,p.getWorld(),region); unlocked(p.getWorld().getUID(),region);
|
||||||
|
Job j=new Job(); j.player=p; j.world=p.getWorld().getUID(); j.bounds=region; j.label="Copy";
|
||||||
|
j.copying=region.iterator(); j.cells=new ArrayList<>();
|
||||||
|
jobs.put(p.getUniqueId(),j); s.pending=null; reply(p,s,"Copy started (bounded per tick).");
|
||||||
|
}
|
||||||
|
case "paste" -> {
|
||||||
|
editPermission(p); idle(p);
|
||||||
|
if (s.clipboard==null) throw new IllegalArgumentException("Copy a selection first.");
|
||||||
|
Clipboard clip=s.clipboard;
|
||||||
|
Point origin=coordinate(p,args); Region region=clip.at(origin); validate(p,p.getWorld(),region);
|
||||||
|
prepare(p,s,region,"paste "+clip.cells().size()+" blocks (includes air)",()->clip.paste(origin));
|
||||||
|
}
|
||||||
|
case "confirm" -> {
|
||||||
|
editPermission(p); idle(p); capacity();
|
||||||
|
Pending pending=s.pending; s.pending=null;
|
||||||
|
if (pending==null || System.nanoTime()>pending.expires) throw new IllegalArgumentException("No unexpired edit to confirm.");
|
||||||
|
if (!pending.world.equals(p.getWorld().getUID())) throw new IllegalArgumentException("World changed; prepare the edit again.");
|
||||||
|
validate(p,p.getWorld(),pending.bounds); unlocked(pending.world,pending.bounds);
|
||||||
|
Job j=job(p,pending.world,pending.bounds,pending.label,new Editor.Task(pending.intents.get()));
|
||||||
|
jobs.put(p.getUniqueId(),j); reply(p,s,"Started "+j.label+". /du cancel stops remaining work.");
|
||||||
|
}
|
||||||
|
case "undo","redo" -> {
|
||||||
|
editPermission(p); idle(p); capacity(); s.pending=null;
|
||||||
|
Deque<History> stack=action.equals("undo")?s.undo:s.redo;
|
||||||
|
History entry=stack.peekFirst();
|
||||||
|
if (entry==null) throw new IllegalArgumentException("Nothing to "+action+".");
|
||||||
|
World world=Bukkit.getWorld(entry.world);
|
||||||
|
if (world==null || !world.equals(p.getWorld())) throw new IllegalArgumentException("Return to the operation's world first.");
|
||||||
|
validate(p,world,entry.bounds); unlocked(entry.world,entry.bounds);
|
||||||
|
Job j=job(p,entry.world,entry.bounds,action,new Editor.Task(Editor.reverse(entry.changes)));
|
||||||
|
j.historyMode=action.equals("undo")?1:2;
|
||||||
|
stack.removeFirst(); jobs.put(p.getUniqueId(),j); reply(p,s,"Started "+action+"; changed/protected blocks will be skipped.");
|
||||||
|
}
|
||||||
|
default -> throw new IllegalArgumentException("Unknown tool. Use /du help.");
|
||||||
|
}
|
||||||
|
} catch (IllegalArgumentException | ArithmeticException error) {
|
||||||
|
if (s==null) p.sendMessage("Dunium: "+error.getMessage()); else reply(p,s,error.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private Job job(Player p,UUID world,Region bounds,String label,Editor.Task task) {
|
||||||
|
Job j=new Job(); j.player=p; j.world=world; j.bounds=bounds; j.label=label; j.task=task; return j;
|
||||||
|
}
|
||||||
|
private void prepare(Player p,Session s,Region region,String label,Supplier<Iterator<Intent>> intents) {
|
||||||
|
s.pending=new Pending(p.getWorld().getUID(),region,label,intents,System.nanoTime()+timeout*1_000_000_000L);
|
||||||
|
reply(p,s,"Preview: "+label+" in "+region+". /du confirm within "+timeout+"s. Protected, unloaded and block-entity positions are skipped. This is a bounds preview, not an exact change count.");
|
||||||
|
}
|
||||||
|
private void idle(Player p) { if (jobs.containsKey(p.getUniqueId())) throw new IllegalArgumentException("An operation is running. Use /du cancel first."); }
|
||||||
|
private void capacity() { if (jobs.size()>=maxJobs) throw new IllegalArgumentException("Global edit queue is full. Try again shortly."); }
|
||||||
|
private void unlocked(UUID world,Region bounds) {
|
||||||
|
for (Job job:jobs.values()) if (job.world.equals(world)&&job.bounds.overlaps(bounds)) throw new IllegalArgumentException("Another Dunium operation overlaps this region.");
|
||||||
|
}
|
||||||
|
private void editPermission(Player p) {
|
||||||
|
if (!p.hasPermission("dunium.use") || !p.hasPermission("dunium.edit")) throw new IllegalArgumentException("Missing dunium.edit permission.");
|
||||||
|
if (creativeOnly && p.getGameMode()!=GameMode.CREATIVE) throw new IllegalArgumentException("Creative mode is required.");
|
||||||
|
if (!worlds.contains(p.getWorld().getName())) throw new IllegalArgumentException("This world is not enabled in Dunium/config.yml allowed-worlds.");
|
||||||
|
}
|
||||||
|
private Point coordinate(Player p,String[] args) {
|
||||||
|
if (args.length==1) { var loc=p.getLocation(); return new Point(loc.getBlockX(),loc.getBlockY(),loc.getBlockZ()); }
|
||||||
|
if (args.length!=4) throw new IllegalArgumentException("Supply no coordinates or all three integer coordinates.");
|
||||||
|
try { return new Point(Integer.parseInt(args[1]),Integer.parseInt(args[2]),Integer.parseInt(args[3])); }
|
||||||
|
catch (NumberFormatException error) { throw new IllegalArgumentException("Coordinates must be integers."); }
|
||||||
|
}
|
||||||
|
private Region selection(Player p,Session s) {
|
||||||
|
if (s.a==null || s.b==null || !p.getWorld().getUID().equals(s.world)) throw new IllegalArgumentException("Set pos1 and pos2 in this world first.");
|
||||||
|
return Region.between(s.a,s.b);
|
||||||
|
}
|
||||||
|
private void validate(Player p,World world,Region region) {
|
||||||
|
editPermission(p);
|
||||||
|
if (!world.equals(p.getWorld())) throw new IllegalArgumentException("Operation belongs to a different world.");
|
||||||
|
if (region.volume()>maxBlocks) throw new IllegalArgumentException("Selection exceeds max-blocks ("+maxBlocks+").");
|
||||||
|
checkPoint(p,world,region.min()); checkPoint(p,world,region.max());
|
||||||
|
for (int x=region.min().x()>>4;x<=region.max().x()>>4;x++)
|
||||||
|
for (int z=region.min().z()>>4;z<=region.max().z()>>4;z++)
|
||||||
|
if (!world.isChunkLoaded(x,z)) throw new IllegalArgumentException("Every selected chunk must already be loaded.");
|
||||||
|
}
|
||||||
|
private void checkPoint(Player p,World world,Point point) {
|
||||||
|
if (Math.abs((long)point.x())>29_999_984 || Math.abs((long)point.z())>29_999_984 || point.y()<world.getMinHeight() || point.y()>=world.getMaxHeight()) throw new IllegalArgumentException("Position is outside world bounds.");
|
||||||
|
var loc=p.getLocation();
|
||||||
|
if (Math.abs(point.x()-loc.getBlockX())>reach || Math.abs(point.y()-loc.getBlockY())>reach || Math.abs(point.z()-loc.getBlockZ())>reach) throw new IllegalArgumentException("Position exceeds selection distance "+reach+".");
|
||||||
|
if (!world.getWorldBorder().isInside(new Location(world,point.x()+0.5,point.y()+0.5,point.z()+0.5))) throw new IllegalArgumentException("Position is outside the world border.");
|
||||||
|
}
|
||||||
|
private String state(String input) {
|
||||||
|
if (input.length()>400) throw new IllegalArgumentException("Block state is too long.");
|
||||||
|
BlockData data;
|
||||||
|
try { data=Bukkit.createBlockData(input); }
|
||||||
|
catch (IllegalArgumentException error) { throw new IllegalArgumentException("Invalid block state: "+input); }
|
||||||
|
if (!safe(data)) throw new IllegalArgumentException("Block entities or denied materials are not supported: "+data.getMaterial());
|
||||||
|
return data.getAsString();
|
||||||
|
}
|
||||||
|
private boolean safe(BlockData data) {
|
||||||
|
return !denied.contains(data.getMaterial().name()) && !(data.createBlockState() instanceof TileState);
|
||||||
|
}
|
||||||
|
private Block allowedBlock(Player p,World world,Point point) {
|
||||||
|
editPermission(p); checkPoint(p,world,point);
|
||||||
|
if (!world.isChunkLoaded(point.x()>>4,point.z()>>4)) return null;
|
||||||
|
Block block=world.getBlockAt(point.x(),point.y(),point.z());
|
||||||
|
if (block.getState(false) instanceof TileState || !safe(block.getBlockData()) || !protection.allowed(p,block)) return null;
|
||||||
|
return block;
|
||||||
|
}
|
||||||
|
private void tick() {
|
||||||
|
ticks++;
|
||||||
|
if (jobs.isEmpty()) return;
|
||||||
|
int remaining=budget, count=jobs.size();
|
||||||
|
for (Job j:List.copyOf(jobs.values())) {
|
||||||
|
if (remaining<1) break;
|
||||||
|
int slice=Math.max(1,remaining/count--);
|
||||||
|
World world=Bukkit.getWorld(j.world);
|
||||||
|
if (world==null || !j.player.isOnline() || !j.player.getWorld().equals(world)) { finish(j,true,"World/player unavailable"); continue; }
|
||||||
|
try {
|
||||||
|
editPermission(j.player);
|
||||||
|
if (j.copying!=null) {
|
||||||
|
int used=0;
|
||||||
|
while (used<slice && j.copying.hasNext()) {
|
||||||
|
Point point=j.copying.next(); used++; j.visited++;
|
||||||
|
Block block=allowedBlock(j.player,world,point);
|
||||||
|
if (block==null) throw new IllegalArgumentException("Copy refused: protected, unloaded or unsupported block. Old clipboard retained.");
|
||||||
|
j.cells.add(new Cell(new Point(point.x()-j.bounds.min().x(),point.y()-j.bounds.min().y(),point.z()-j.bounds.min().z()),block.getBlockData().getAsString()));
|
||||||
|
}
|
||||||
|
remaining-=used;
|
||||||
|
if (!j.copying.hasNext()) {
|
||||||
|
Session s=sessions.get(j.player.getUniqueId());
|
||||||
|
s.clipboard=new Clipboard(j.bounds.max().x()-j.bounds.min().x()+1,j.bounds.max().y()-j.bounds.min().y()+1,j.bounds.max().z()-j.bounds.min().z()+1,j.cells);
|
||||||
|
finish(j,false,"Copied "+j.cells.size()+" blocks. Paste origin is the minimum corner.");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
remaining-=j.task.advance(new Access() {
|
||||||
|
public boolean allowed(Point point) { return allowedBlock(j.player,world,point)!=null; }
|
||||||
|
public String read(Point point) { return world.getBlockAt(point.x(),point.y(),point.z()).getBlockData().getAsString(); }
|
||||||
|
public void write(Point point,String state) {
|
||||||
|
BlockData data=Bukkit.createBlockData(state);
|
||||||
|
if (!safe(data)) throw new IllegalArgumentException("Target material is no longer allowed.");
|
||||||
|
world.getBlockAt(point.x(),point.y(),point.z()).setBlockData(data,false);
|
||||||
|
}
|
||||||
|
},slice);
|
||||||
|
if (j.task.done()) finish(j,false,"Finished");
|
||||||
|
}
|
||||||
|
if (ticks%20==0 && jobs.containsKey(j.player.getUniqueId())) j.player.sendActionBar(Component.text("Dunium "+j.label+": "+(j.task==null?j.visited:j.task.visited())+"/"+j.bounds.volume()));
|
||||||
|
} catch (RuntimeException error) {
|
||||||
|
getLogger().warning("Stopped "+j.label+" for "+j.player.getName()+": "+error.getClass().getSimpleName()+": "+error.getMessage());
|
||||||
|
finish(j,true,"Stopped: "+(error instanceof IllegalArgumentException?error.getMessage():"server error; see console"));
|
||||||
|
// A thrown access/write may have consumed part of this slice. Do not exceed the global budget.
|
||||||
|
remaining-=slice;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private void finish(Job j,boolean cancelled,String message) {
|
||||||
|
jobs.remove(j.player.getUniqueId());
|
||||||
|
Session s=sessions.get(j.player.getUniqueId());
|
||||||
|
if (s==null) return;
|
||||||
|
if (j.task!=null) {
|
||||||
|
if (cancelled) j.task.cancel();
|
||||||
|
List<Change> changes=j.task.changes();
|
||||||
|
if (!changes.isEmpty()) {
|
||||||
|
History history=new History(j.world,j.bounds,changes);
|
||||||
|
if (j.historyMode==1) s.redo.addFirst(history);
|
||||||
|
else { s.undo.addFirst(history); if (j.historyMode==0) s.redo.clear(); }
|
||||||
|
trim(s);
|
||||||
|
}
|
||||||
|
message+=". Changed "+changes.size()+", skipped "+j.task.skipped()+", visited "+j.task.visited()+".";
|
||||||
|
getLogger().info("[audit] "+j.player.getUniqueId()+" "+j.label+" world="+j.world+" bounds="+j.bounds+" changed="+changes.size()+" cancelled="+cancelled);
|
||||||
|
}
|
||||||
|
reply(j.player,s,message);
|
||||||
|
}
|
||||||
|
private void trim(Session s) {
|
||||||
|
while (s.undo.size()+s.redo.size()>maxEntries || historySize(s)>maxHistory) {
|
||||||
|
if (s.undo.size()>1 || s.redo.isEmpty()) s.undo.removeLast(); else s.redo.removeLast();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
private int historySize(Session s) { return s.undo.stream().mapToInt(h->h.changes.size()).sum()+s.redo.stream().mapToInt(h->h.changes.size()).sum(); }
|
||||||
|
private String point(Point point) { return point==null?"-":point.x()+","+point.y()+","+point.z(); }
|
||||||
|
private void reply(Player p,Session s,String message) {
|
||||||
|
p.sendMessage(Component.text("Dunium: "+message));
|
||||||
|
if (!s.mod || !p.isOnline()) return;
|
||||||
|
String dimension=p.getWorld().getKey().toString();
|
||||||
|
String payload="1\t"+dimension+"\t"+point(s.a)+"\t"+point(s.b)+"\t"+message.replace('\t',' ').replace('\n',' ');
|
||||||
|
p.sendPluginMessage(this,STATE,payload.getBytes(StandardCharsets.UTF_8));
|
||||||
|
}
|
||||||
|
}
|
||||||
41
dunium-server/src/main/java/dunium/Protection.java
Normal file
41
dunium-server/src/main/java/dunium/Protection.java
Normal file
|
|
@ -0,0 +1,41 @@
|
||||||
|
package dunium;
|
||||||
|
|
||||||
|
import java.lang.reflect.*;
|
||||||
|
import org.bukkit.Bukkit;
|
||||||
|
import org.bukkit.block.Block;
|
||||||
|
import org.bukkit.entity.Player;
|
||||||
|
import org.bukkit.plugin.Plugin;
|
||||||
|
|
||||||
|
/** Optional WorldGuard 7 API bridge. Presence with an incompatible API fails closed. */
|
||||||
|
final class Protection {
|
||||||
|
private final DuniumPlugin plugin;
|
||||||
|
private boolean warned;
|
||||||
|
Protection(DuniumPlugin plugin) { this.plugin=plugin; }
|
||||||
|
boolean allowed(Player player, Block block) {
|
||||||
|
DuniumEditCheckEvent event=new DuniumEditCheckEvent(player,block);
|
||||||
|
Bukkit.getPluginManager().callEvent(event);
|
||||||
|
if (event.isCancelled()) return false;
|
||||||
|
Plugin wg=Bukkit.getPluginManager().getPlugin("WorldGuard");
|
||||||
|
if (wg==null) return true;
|
||||||
|
if (!wg.isEnabled()) return false;
|
||||||
|
try {
|
||||||
|
ClassLoader loader=wg.getClass().getClassLoader();
|
||||||
|
Class<?> guard=Class.forName("com.sk89q.worldguard.WorldGuard",true,loader);
|
||||||
|
Object instance=guard.getMethod("getInstance").invoke(null);
|
||||||
|
Object platform=guard.getMethod("getPlatform").invoke(instance);
|
||||||
|
Object container=platform.getClass().getMethod("getRegionContainer").invoke(platform);
|
||||||
|
Object query=container.getClass().getMethod("createQuery").invoke(container);
|
||||||
|
Class<?> adapter=Class.forName("com.sk89q.worldedit.bukkit.BukkitAdapter",true,loader);
|
||||||
|
Object location=adapter.getMethod("adapt",org.bukkit.Location.class).invoke(null,block.getLocation());
|
||||||
|
Object local=wg.getClass().getMethod("wrapPlayer",Player.class).invoke(wg,player);
|
||||||
|
Class<?> loc=Class.forName("com.sk89q.worldedit.util.Location",true,loader);
|
||||||
|
Class<?> actor=Class.forName("com.sk89q.worldguard.LocalPlayer",true,loader);
|
||||||
|
Class<?> flag=Class.forName("com.sk89q.worldguard.protection.flags.StateFlag",true,loader);
|
||||||
|
Object flags=Array.newInstance(flag,0);
|
||||||
|
return (boolean)query.getClass().getMethod("testBuild",loc,actor,flags.getClass()).invoke(query,location,local,flags);
|
||||||
|
} catch (ReflectiveOperationException | LinkageError | RuntimeException error) {
|
||||||
|
if (!warned) { plugin.getLogger().warning("WorldGuard bridge unavailable; Dunium denies edits: "+error.getClass().getSimpleName()); warned=true; }
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
30
dunium-server/src/main/resources/config.yml
Normal file
30
dunium-server/src/main/resources/config.yml
Normal file
|
|
@ -0,0 +1,30 @@
|
||||||
|
# Bounded globally per tick; skipped positions also consume the budget.
|
||||||
|
blocks-per-tick: 500
|
||||||
|
max-blocks: 10000
|
||||||
|
max-history-blocks-per-player: 20000
|
||||||
|
max-history-entries-per-player: 10
|
||||||
|
max-sessions: 16
|
||||||
|
max-concurrent-jobs: 2
|
||||||
|
max-selection-distance: 128
|
||||||
|
max-brush-radius: 16
|
||||||
|
confirmation-timeout-seconds: 30
|
||||||
|
creative-only: true
|
||||||
|
# Empty list denies every world. Explicitly opt in to build worlds before use.
|
||||||
|
allowed-worlds: []
|
||||||
|
# Includes fluids/portals/technical blocks with substantial side effects.
|
||||||
|
denied-materials:
|
||||||
|
- BEDROCK
|
||||||
|
- BARRIER
|
||||||
|
- COMMAND_BLOCK
|
||||||
|
- CHAIN_COMMAND_BLOCK
|
||||||
|
- REPEATING_COMMAND_BLOCK
|
||||||
|
- STRUCTURE_BLOCK
|
||||||
|
- JIGSAW
|
||||||
|
- NETHER_PORTAL
|
||||||
|
- END_PORTAL
|
||||||
|
- END_GATEWAY
|
||||||
|
- WATER
|
||||||
|
- LAVA
|
||||||
|
- TNT
|
||||||
|
- FIRE
|
||||||
|
- SOUL_FIRE
|
||||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue

Staff