Build and roll out DuneChest on planet servers only
This commit is contained in:
parent
0726dbaf6a
commit
56346a273d
47 changed files with 1098 additions and 9 deletions
48
.forgejo/workflows/dunechest.yml
Normal file
48
.forgejo/workflows/dunechest.yml
Normal file
|
|
@ -0,0 +1,48 @@
|
|||
name: Planet DuneChest Build
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches: ['feat/dunechest-planets-*']
|
||||
|
||||
jobs:
|
||||
dunechest:
|
||||
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: Build DuneChest and verify the planet pack
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
gradle --no-daemon -p DuneChest test jar
|
||||
python3 tools/test_plugin_fleet_install.py -v
|
||||
python3 tools/test_plugin_pack_properties.py -v
|
||||
mkdir chest-artifacts
|
||||
cp DuneChest/build/libs/DuneChest.jar chest-artifacts/
|
||||
printf '%s\n' "$(git rev-parse HEAD)" > chest-artifacts/SOURCE_COMMIT
|
||||
pack="chest-artifacts/DuneRealms-Resources-${GITHUB_SHA}.zip"
|
||||
python3 tools/build-unified-resourcepack.py --source "$GITHUB_SHA" --output "$pack"
|
||||
curl --fail --location --retry 2 https://www.dunerealms.com/downloads/DuneRealms-Resources-0726dbaf6a057a15c5d1753b3208cff010ae6239.zip -o navigator-baseline.zip
|
||||
python3 tools/plugin_dunechest_pack.py navigator-baseline.zip "$pack"
|
||||
python3 tools/write-plugin-manifest.py chest-artifacts "$GITHUB_SHA"
|
||||
cp tools/install-plugin-fleet.py tools/plugin_menu_pack.py tools/plugin_backend_abi.py tools/plugin_pillager_abi.py tools/plugin_fleet_rollback.py tools/plugin_pack_properties.py tools/publish-plugin-menu.py chest-artifacts/
|
||||
(cd chest-artifacts && sha256sum -- *.jar *.zip *.json *.py SOURCE_COMMIT > SHA256SUMS)
|
||||
- uses: actions/upload-artifact@v3
|
||||
with:
|
||||
name: DuneRealms-Planet-DuneChest
|
||||
path: chest-artifacts/
|
||||
if-no-files-found: error
|
||||
20
DuneChest/build.gradle.kts
Normal file
20
DuneChest/build.gradle.kts
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
plugins { java }
|
||||
group = "com.example"
|
||||
version = "1.0.0"
|
||||
repositories {
|
||||
mavenCentral()
|
||||
maven("https://repo.papermc.io/repository/maven-public/")
|
||||
maven("https://repo.opencollab.dev/main/")
|
||||
}
|
||||
dependencies {
|
||||
compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT")
|
||||
compileOnly("org.geysermc.floodgate:api:2.2.5-SNAPSHOT")
|
||||
testImplementation("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT")
|
||||
testImplementation("org.junit.jupiter:junit-jupiter:5.11.4")
|
||||
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
|
||||
}
|
||||
sourceSets.main { java.srcDir("../gui-common/src/main/java") }
|
||||
tasks.jar { archiveFileName.set("DuneChest.jar") }
|
||||
java { toolchain.languageVersion.set(JavaLanguageVersion.of(21)) }
|
||||
tasks.withType<JavaCompile> { options.encoding = "UTF-8" }
|
||||
tasks.test { useJUnitPlatform() }
|
||||
1
DuneChest/settings.gradle.kts
Normal file
1
DuneChest/settings.gradle.kts
Normal file
|
|
@ -0,0 +1 @@
|
|||
rootProject.name = "DuneChest"
|
||||
18
DuneChest/src/main/java/com/example/dunechest/DuneChest.java
Normal file
18
DuneChest/src/main/java/com/example/dunechest/DuneChest.java
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
package com.example.dunechest;
|
||||
|
||||
import java.util.Objects;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
|
||||
/** DuneChest: colour-linked Ender Chests, Speed Hoppers and Auto Crafters, per planet. */
|
||||
public final class DuneChest extends JavaPlugin {
|
||||
private StorageModule storage;
|
||||
public StorageModule storage() { return storage; }
|
||||
|
||||
@Override public void onEnable() {
|
||||
storage = new StorageModule(this);
|
||||
storage.start();
|
||||
Objects.requireNonNull(getCommand("dunechest")).setExecutor(storage);
|
||||
}
|
||||
|
||||
@Override public void onDisable() { if (storage != null) storage.stop(); storage = null; }
|
||||
}
|
||||
|
|
@ -0,0 +1,93 @@
|
|||
package com.example.dunechest;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.util.*;
|
||||
import org.bukkit.*;
|
||||
import org.bukkit.configuration.ConfigurationSection;
|
||||
import org.bukkit.configuration.file.YamlConfiguration;
|
||||
import org.bukkit.inventory.Inventory;
|
||||
import org.bukkit.inventory.InventoryHolder;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
/** Persistent state of the custom storage blocks on this planet: placed blocks and colour-frequency inventories. */
|
||||
final class StorageData {
|
||||
enum Kind { ENDER_CHEST, SPEED_HOPPER, AUTO_CRAFTER }
|
||||
|
||||
static final class Placed {
|
||||
Kind kind; int[] colors = new int[3]; UUID owner; boolean priv; int tier = 1; boolean whitelist = false;
|
||||
List<Material> filter = new ArrayList<>(); ItemStack[] recipe = new ItemStack[9]; int cooldown; Location loc;
|
||||
}
|
||||
|
||||
/** Holder of a frequency inventory so listeners recognise it. */
|
||||
static final class FreqHolder implements InventoryHolder {
|
||||
final String key; Inventory inventory;
|
||||
FreqHolder(String key) { this.key = key; }
|
||||
@Override public Inventory getInventory() { return inventory; }
|
||||
}
|
||||
|
||||
private final Plugin plugin; private final File blocksFile, invFile;
|
||||
final Map<String, Placed> blocks = new LinkedHashMap<>();
|
||||
final Map<String, FreqHolder> inventories = new HashMap<>();
|
||||
boolean dirty;
|
||||
|
||||
StorageData(Plugin plugin) { this.plugin = plugin; blocksFile = new File(plugin.getDataFolder(), "storage-blocks.yml"); invFile = new File(plugin.getDataFolder(), "storage-inventories.yml"); }
|
||||
|
||||
static String key(Location l) { return l.getWorld().getName() + ";" + l.getBlockX() + ";" + l.getBlockY() + ";" + l.getBlockZ(); }
|
||||
static String key(org.bukkit.block.Block b) { return key(b.getLocation()); }
|
||||
|
||||
Placed at(org.bukkit.block.Block b) { return blocks.get(key(b)); }
|
||||
Placed at(Location l) { return l == null || l.getWorld() == null ? null : blocks.get(key(l)); }
|
||||
|
||||
Inventory inventory(String frequency) {
|
||||
var holder = inventories.computeIfAbsent(frequency, k -> new FreqHolder(k));
|
||||
if (holder.inventory == null) holder.inventory = Bukkit.createInventory(holder, 27, net.kyori.adventure.text.Component.text("Ender Chest"));
|
||||
return holder.inventory;
|
||||
}
|
||||
|
||||
// ---------- persistence ----------
|
||||
void load() {
|
||||
blocks.clear(); inventories.clear();
|
||||
if (blocksFile.exists()) {
|
||||
var y = YamlConfiguration.loadConfiguration(blocksFile); var sec = y.getConfigurationSection("blocks");
|
||||
if (sec != null) for (String k : sec.getKeys(false)) {
|
||||
ConfigurationSection s = sec.getConfigurationSection(k); if (s == null) continue;
|
||||
try {
|
||||
Placed p = new Placed(); p.kind = Kind.valueOf(s.getString("kind", "ENDER_CHEST"));
|
||||
p.colors = StorageRules.parseColors(s.getString("colors")); String o = s.getString("owner"); p.owner = o == null ? null : UUID.fromString(o);
|
||||
p.priv = s.getBoolean("private"); p.tier = s.getInt("tier", 1); p.whitelist = s.getBoolean("whitelist");
|
||||
for (String m : s.getStringList("filter")) { Material mat = Material.matchMaterial(m); if (mat != null) p.filter.add(mat); }
|
||||
List<?> rec = s.getList("recipe");
|
||||
if (rec != null) for (int i = 0; i < 9 && i < rec.size(); i++) p.recipe[i] = rec.get(i) instanceof ItemStack st ? st : null;
|
||||
blocks.put(k, p);
|
||||
} catch (RuntimeException ex) { plugin.getLogger().warning("Skipped bad storage block " + k + ": " + ex.getMessage()); }
|
||||
}
|
||||
}
|
||||
if (invFile.exists()) {
|
||||
var y = YamlConfiguration.loadConfiguration(invFile); var sec = y.getConfigurationSection("inventories");
|
||||
if (sec != null) for (String k : sec.getKeys(false)) {
|
||||
String freq = k.replace('/', ':'); var inv = inventory(freq); List<?> items = sec.getList(k);
|
||||
if (items != null) for (int i = 0; i < items.size() && i < inv.getSize(); i++) inv.setItem(i, items.get(i) instanceof ItemStack st ? st : null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void save() {
|
||||
var yb = new YamlConfiguration();
|
||||
for (var e : blocks.entrySet()) {
|
||||
String b = "blocks." + e.getKey().replace('.', '_'); Placed p = e.getValue();
|
||||
yb.set(b + ".kind", p.kind.name()); yb.set(b + ".colors", StorageRules.colorsToString(p.colors)); yb.set(b + ".owner", p.owner == null ? null : p.owner.toString());
|
||||
yb.set(b + ".private", p.priv); yb.set(b + ".tier", p.tier); yb.set(b + ".whitelist", p.whitelist);
|
||||
yb.set(b + ".filter", p.filter.stream().map(Enum::name).toList()); yb.set(b + ".recipe", Arrays.asList(p.recipe));
|
||||
}
|
||||
var yi = new YamlConfiguration();
|
||||
for (var e : inventories.entrySet()) {
|
||||
if (e.getValue().inventory == null) continue;
|
||||
boolean any = false; for (ItemStack s : e.getValue().inventory.getContents()) if (s != null && !s.getType().isAir()) { any = true; break; }
|
||||
if (any) yi.set("inventories." + e.getKey().replace(':', '/'), Arrays.asList(e.getValue().inventory.getContents()));
|
||||
}
|
||||
try { plugin.getDataFolder().mkdirs(); yb.save(blocksFile); yi.save(invFile); dirty = false; }
|
||||
catch (IOException ex) { plugin.getLogger().warning("Could not save storage data: " + ex.getMessage()); }
|
||||
}
|
||||
}
|
||||
103
DuneChest/src/main/java/com/example/dunechest/StorageItems.java
Normal file
103
DuneChest/src/main/java/com/example/dunechest/StorageItems.java
Normal file
|
|
@ -0,0 +1,103 @@
|
|||
package com.example.dunechest;
|
||||
|
||||
import java.util.*;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
import net.kyori.adventure.text.format.TextDecoration;
|
||||
import org.bukkit.*;
|
||||
import org.bukkit.inventory.*;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.persistence.PersistentDataType;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
|
||||
/** The three custom items, their recipes, and how to recognise them. */
|
||||
public final class StorageItems {
|
||||
public static final String ENDER = "ender_chest", HOPPER = "speed_hopper", CRAFTER = "auto_crafter", WRENCH = "wrench";
|
||||
private final Plugin plugin; final NamespacedKey type, tier, colors, owner, priv, filter, whitelist;
|
||||
|
||||
StorageItems(Plugin plugin) {
|
||||
this.plugin = plugin;
|
||||
type = new NamespacedKey(plugin, "storage_type"); tier = new NamespacedKey(plugin, "storage_tier"); colors = new NamespacedKey(plugin, "storage_colors");
|
||||
owner = new NamespacedKey(plugin, "storage_owner"); priv = new NamespacedKey(plugin, "storage_private");
|
||||
filter = new NamespacedKey(plugin, "storage_filter"); whitelist = new NamespacedKey(plugin, "storage_whitelist");
|
||||
}
|
||||
|
||||
public ItemStack create(String id, int tierNumber) {
|
||||
Material base = switch (id) { case ENDER -> Material.BARREL; case HOPPER -> Material.HOPPER; case WRENCH -> Material.KNOWLEDGE_BOOK; default -> Material.CRAFTING_TABLE; };
|
||||
ItemStack item = new ItemStack(base); ItemMeta m = item.getItemMeta();
|
||||
var pdc = m.getPersistentDataContainer(); pdc.set(type, PersistentDataType.STRING, id);
|
||||
List<Component> lore = new ArrayList<>();
|
||||
switch (id) {
|
||||
case ENDER -> { m.displayName(name("Ender Chest", NamedTextColor.LIGHT_PURPLE)); pdc.set(colors, PersistentDataType.STRING, "0,0,0");
|
||||
lore.add(gray("Chests with the same three colours share one inventory."));
|
||||
lore.add(gray("Right-click a dye on a pad, or use the colour menu.")); lore.add(gray("Right-click a diamond to make it private.")); lore.add(gray("Sneak + empty hand: colour menu.")); m.setItemModel(new NamespacedKey("dunerealms", "ender_chest")); }
|
||||
case HOPPER -> { int t = Math.max(1, Math.min(3, tierNumber)); var tr = StorageRules.Tier.of(t); pdc.set(tier, PersistentDataType.INTEGER, t);
|
||||
m.displayName(name("Speed Hopper Mk " + "I".repeat(t), t == 1 ? NamedTextColor.GOLD : t == 2 ? NamedTextColor.AQUA : NamedTextColor.LIGHT_PURPLE));
|
||||
lore.add(gray(String.format(Locale.ROOT, "%.0f items/s (vanilla 2.5)", tr.itemsPerSecond()))); lore.add(gray("Sneak + empty hand: item filter.")); lore.add(gray("Or left-click with a Wrench.")); m.setItemModel(new NamespacedKey("dunerealms", "speed_hopper_" + t)); }
|
||||
case WRENCH -> { m.displayName(name("Wrench", NamedTextColor.GOLD)); lore.add(gray("Left-click an Ender Chest, Speed Hopper or Auto Crafter")); lore.add(gray("to open its panel. Works on Bedrock too.")); m.setItemModel(new NamespacedKey("dunerealms", "wrench")); m.setMaxStackSize(1); }
|
||||
default -> { m.displayName(name("Auto Crafter", NamedTextColor.GREEN)); lore.add(gray("Crafts from the container above into the container below.")); lore.add(gray("Right-click to set the recipe.")); }
|
||||
}
|
||||
m.lore(lore); m.setEnchantmentGlintOverride(true);
|
||||
item.setItemMeta(m); return item;
|
||||
}
|
||||
|
||||
/** Item used by the overlay display on a placed Speed Hopper: custom model, spout down or sideways. */
|
||||
ItemStack hopperDisplayItem(int tierNumber, boolean side) {
|
||||
ItemStack it = new ItemStack(Material.HOPPER); ItemMeta m = it.getItemMeta();
|
||||
m.setItemModel(new NamespacedKey("dunerealms", "speed_hopper_" + Math.max(1, Math.min(3, tierNumber)) + (side ? "_side" : "")));
|
||||
it.setItemMeta(m); return it;
|
||||
}
|
||||
|
||||
private static Component name(String s, NamedTextColor c) { return Component.text(s, c).decoration(TextDecoration.ITALIC, false); }
|
||||
private static Component gray(String s) { return Component.text(s, NamedTextColor.GRAY).decoration(TextDecoration.ITALIC, false); }
|
||||
|
||||
public String typeOf(ItemStack item) { return item == null || !item.hasItemMeta() ? null : item.getItemMeta().getPersistentDataContainer().get(type, PersistentDataType.STRING); }
|
||||
int tierOf(ItemStack item) { Integer t = item.getItemMeta().getPersistentDataContainer().get(tier, PersistentDataType.INTEGER); return t == null ? 1 : t; }
|
||||
|
||||
/** Item for a picked-up placed block, carrying its settings. */
|
||||
ItemStack fromPlaced(StorageData.Placed p) {
|
||||
String id = switch (p.kind) { case ENDER_CHEST -> ENDER; case SPEED_HOPPER -> HOPPER; case AUTO_CRAFTER -> CRAFTER; };
|
||||
ItemStack item = create(id, p.tier); ItemMeta m = item.getItemMeta(); var pdc = m.getPersistentDataContainer();
|
||||
if (p.kind == StorageData.Kind.ENDER_CHEST) {
|
||||
pdc.set(colors, PersistentDataType.STRING, StorageRules.colorsToString(p.colors));
|
||||
if (p.priv && p.owner != null) { pdc.set(priv, PersistentDataType.BYTE, (byte) 1); pdc.set(owner, PersistentDataType.STRING, p.owner.toString()); }
|
||||
} else if (p.kind == StorageData.Kind.SPEED_HOPPER && !p.filter.isEmpty()) {
|
||||
pdc.set(filter, PersistentDataType.STRING, String.join(",", p.filter.stream().map(Enum::name).toList())); pdc.set(whitelist, PersistentDataType.BYTE, (byte) (p.whitelist ? 1 : 0));
|
||||
}
|
||||
item.setItemMeta(m); return item;
|
||||
}
|
||||
|
||||
/** Settings stored on the item being placed. */
|
||||
StorageData.Placed toPlaced(ItemStack item, UUID placer) {
|
||||
String id = typeOf(item); var pdc = item.getItemMeta().getPersistentDataContainer(); var p = new StorageData.Placed();
|
||||
switch (id == null ? "" : id) {
|
||||
case ENDER -> { p.kind = StorageData.Kind.ENDER_CHEST; p.colors = StorageRules.parseColors(pdc.get(colors, PersistentDataType.STRING));
|
||||
p.priv = pdc.has(priv, PersistentDataType.BYTE); String o = pdc.get(owner, PersistentDataType.STRING); p.owner = o == null ? null : UUID.fromString(o); if (p.priv && p.owner == null) p.owner = placer; }
|
||||
case HOPPER -> { p.kind = StorageData.Kind.SPEED_HOPPER; p.tier = tierOf(item); String f = pdc.get(filter, PersistentDataType.STRING);
|
||||
if (f != null && !f.isEmpty()) for (String s : f.split(",")) { Material m = Material.matchMaterial(s); if (m != null) p.filter.add(m); }
|
||||
Byte w = pdc.get(whitelist, PersistentDataType.BYTE); p.whitelist = w != null && w == 1; }
|
||||
default -> p.kind = StorageData.Kind.AUTO_CRAFTER;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
void registerRecipes() {
|
||||
ItemStack ender = create(ENDER, 1), mk1 = create(HOPPER, 1), mk2 = create(HOPPER, 2), mk3 = create(HOPPER, 3), crafter = create(CRAFTER, 1);
|
||||
shaped("ender_chest", ender, new String[]{"OEO", "OBO", "OOO"}, 'O', Material.OBSIDIAN, 'E', Material.ENDER_EYE, 'B', Material.BARREL);
|
||||
shaped("speed_hopper_1", mk1, new String[]{"GRG", "RHR", "GRG"}, 'G', Material.GOLD_INGOT, 'R', Material.REDSTONE, 'H', Material.HOPPER);
|
||||
shaped("speed_hopper_2", mk2, new String[]{"DRD", "RIR", "DRD"}, 'D', Material.DIAMOND, 'R', Material.REDSTONE_BLOCK, 'I', new RecipeChoice.ExactChoice(mk1));
|
||||
shaped("speed_hopper_3", mk3, new String[]{"NRN", "RIR", "NRN"}, 'N', Material.NETHERITE_INGOT, 'R', Material.REDSTONE_BLOCK, 'I', new RecipeChoice.ExactChoice(mk2));
|
||||
shaped("wrench", create(WRENCH, 1), new String[]{"I I", " I ", " S "}, 'I', Material.IRON_INGOT, 'S', Material.STICK);
|
||||
shaped("auto_crafter", crafter, new String[]{"IRI", "RTR", "IDI"}, 'I', Material.IRON_INGOT, 'R', Material.REDSTONE, 'T', Material.CRAFTING_TABLE, 'D', Material.DROPPER);
|
||||
}
|
||||
|
||||
private void shaped(String key, ItemStack result, String[] shape, Object... ingredients) {
|
||||
var nk = new NamespacedKey(plugin, key); Bukkit.removeRecipe(nk);
|
||||
var r = new ShapedRecipe(nk, result); r.shape(shape);
|
||||
for (int i = 0; i < ingredients.length; i += 2) {
|
||||
char c = (Character) ingredients[i];
|
||||
if (ingredients[i + 1] instanceof Material mat) r.setIngredient(c, mat); else r.setIngredient(c, (RecipeChoice) ingredients[i + 1]);
|
||||
}
|
||||
Bukkit.addRecipe(r);
|
||||
}
|
||||
}
|
||||
418
DuneChest/src/main/java/com/example/dunechest/StorageModule.java
Normal file
418
DuneChest/src/main/java/com/example/dunechest/StorageModule.java
Normal file
|
|
@ -0,0 +1,418 @@
|
|||
package com.example.dunechest;
|
||||
|
||||
import java.util.*;
|
||||
import java.util.function.Predicate;
|
||||
import net.kyori.adventure.text.Component;
|
||||
import net.kyori.adventure.text.format.NamedTextColor;
|
||||
import net.kyori.adventure.text.format.TextDecoration;
|
||||
import org.bukkit.*;
|
||||
import org.bukkit.block.*;
|
||||
import org.bukkit.block.data.type.Barrel;
|
||||
import org.bukkit.command.*;
|
||||
import org.bukkit.entity.*;
|
||||
import org.bukkit.event.*;
|
||||
import org.bukkit.event.block.*;
|
||||
import org.bukkit.event.entity.EntityExplodeEvent;
|
||||
import org.bukkit.event.inventory.*;
|
||||
import org.bukkit.event.player.PlayerInteractEvent;
|
||||
import org.bukkit.inventory.*;
|
||||
import org.bukkit.inventory.meta.ItemMeta;
|
||||
import org.bukkit.plugin.Plugin;
|
||||
import org.bukkit.plugin.java.JavaPlugin;
|
||||
import org.bukkit.scheduler.BukkitTask;
|
||||
import org.bukkit.util.Transformation;
|
||||
import org.joml.AxisAngle4f;
|
||||
import org.joml.Vector3f;
|
||||
|
||||
/**
|
||||
* Custom storage blocks for DuneChest, per planet and without client mods: colour-coded Ender Chests (a tagged barrel, vanilla
|
||||
* chests untouched), faster Speed Hoppers with item filters, and Auto Crafters. Vanilla barrels, hoppers and crafting tables
|
||||
* behave normally; only blocks placed from the custom items are tracked.
|
||||
*/
|
||||
public final class StorageModule implements Listener, CommandExecutor {
|
||||
private final JavaPlugin plugin; private final StorageData data; final StorageItems items;
|
||||
private final List<BukkitTask> tasks = new ArrayList<>();
|
||||
private final Map<String, List<UUID>> displays = new HashMap<>(); private final Map<String, String> signatures = new HashMap<>();
|
||||
private int counter;
|
||||
|
||||
/** Menu holder: kind is tune, filter or recipe; blockKey names the tracked block. */
|
||||
private static final class Menu implements InventoryHolder {
|
||||
final String kind, blockKey; Inventory inventory;
|
||||
Menu(String kind, String blockKey) { this.kind = kind; this.blockKey = blockKey; }
|
||||
@Override public Inventory getInventory() { return inventory; }
|
||||
}
|
||||
|
||||
public StorageModule(JavaPlugin plugin) { this.plugin = plugin; this.data = new StorageData(plugin); this.items = new StorageItems(plugin); }
|
||||
|
||||
public void start() {
|
||||
data.load(); items.registerRecipes();
|
||||
Bukkit.getPluginManager().registerEvents(this, plugin);
|
||||
tasks.add(Bukkit.getScheduler().runTaskTimer(plugin, this::tick, 40L, 2L));
|
||||
}
|
||||
public void stop() { tasks.forEach(BukkitTask::cancel); displays.values().forEach(l -> l.forEach(this::kill)); displays.clear(); data.save(); }
|
||||
|
||||
/** For the JARVIS Exchange: build a custom item by id (ender_chest, speed_hopper with tier, auto_crafter). */
|
||||
public ItemStack issue(String id, int tier) { return items.create(id, tier); }
|
||||
|
||||
// ---------- helpers ----------
|
||||
private static boolean isDye(Material m) { return m.name().endsWith("_DYE") && dyeIndex(m) >= 0; }
|
||||
private static int dyeIndex(Material m) { try { return DyeColor.valueOf(m.name().substring(0, m.name().length() - 4)).ordinal(); } catch (IllegalArgumentException e) { return -1; } }
|
||||
private static Material wool(int c) { return Material.valueOf(DyeColor.values()[StorageRules.wrap(c)].name() + "_WOOL"); }
|
||||
private static Material dye(int c) { return Material.valueOf(DyeColor.values()[StorageRules.wrap(c)].name() + "_DYE"); }
|
||||
private static Component text(String s, NamedTextColor c) { return Component.text(s, c).decoration(TextDecoration.ITALIC, false); }
|
||||
private void say(Player p, String s) { p.sendMessage(Component.text(s, NamedTextColor.GRAY)); }
|
||||
|
||||
private Location locate(String key, StorageData.Placed p) {
|
||||
if (p.loc != null) return p.loc;
|
||||
String[] a = key.split(";"); World w = Bukkit.getWorld(a[0]); if (w == null) return null;
|
||||
return p.loc = new Location(w, Integer.parseInt(a[1]), Integer.parseInt(a[2]), Integer.parseInt(a[3]));
|
||||
}
|
||||
private BlockFace front(Block b) { return b.getBlockData() instanceof Barrel bar ? bar.getFacing() : BlockFace.SOUTH; }
|
||||
private String freq(StorageData.Placed p) { return StorageRules.frequency(p.colors, p.priv ? p.owner : null); }
|
||||
private boolean canUse(Player pl, StorageData.Placed p) { return !p.priv || p.owner == null || p.owner.equals(pl.getUniqueId()) || pl.hasPermission("dune.admin"); }
|
||||
|
||||
// ---------- placing / breaking ----------
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void place(BlockPlaceEvent e) {
|
||||
String id = items.typeOf(e.getItemInHand()); if (id == null) return;
|
||||
var p = items.toPlaced(e.getItemInHand(), e.getPlayer().getUniqueId());
|
||||
Block b = e.getBlockPlaced();
|
||||
if (p.kind == StorageData.Kind.ENDER_CHEST && b.getBlockData() instanceof Barrel bar) {
|
||||
bar.setFacing(e.getPlayer().getFacing().getOppositeFace()); bar.setOpen(false); b.setBlockData(bar);
|
||||
}
|
||||
data.blocks.put(StorageData.key(b), p); data.dirty = true;
|
||||
}
|
||||
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void breakBlock(BlockBreakEvent e) {
|
||||
var p = data.at(e.getBlock()); if (p == null) return;
|
||||
boolean drops = e.isDropItems();
|
||||
e.setDropItems(false); String key = StorageData.key(e.getBlock());
|
||||
if (drops && e.getPlayer().getGameMode() != GameMode.CREATIVE) e.getBlock().getWorld().dropItemNaturally(e.getBlock().getLocation().add(0.5, 0.5, 0.5), items.fromPlaced(p));
|
||||
remove(key);
|
||||
}
|
||||
private void remove(String key) {
|
||||
data.blocks.remove(key); data.dirty = true; signatures.remove(key);
|
||||
var l = displays.remove(key); if (l != null) l.forEach(this::kill);
|
||||
}
|
||||
private void kill(UUID id) { Entity en = Bukkit.getEntity(id); if (en != null) en.remove(); }
|
||||
|
||||
@EventHandler(ignoreCancelled = true) public void piston(BlockPistonExtendEvent e) { for (Block b : e.getBlocks()) if (data.at(b) != null) { e.setCancelled(true); return; } }
|
||||
@EventHandler(ignoreCancelled = true) public void piston(BlockPistonRetractEvent e) { for (Block b : e.getBlocks()) if (data.at(b) != null) { e.setCancelled(true); return; } }
|
||||
@EventHandler(ignoreCancelled = true) public void explode(EntityExplodeEvent e) { e.blockList().removeIf(b -> data.at(b) != null); }
|
||||
@EventHandler(ignoreCancelled = true) public void explode(BlockExplodeEvent e) { e.blockList().removeIf(b -> data.at(b) != null); }
|
||||
|
||||
// ---------- interaction ----------
|
||||
/** Wrench: left-click a storage block to open its panel (works on Bedrock, and picks the exact block when several are adjacent). */
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void wrench(PlayerInteractEvent e) {
|
||||
if (e.getAction() != org.bukkit.event.block.Action.LEFT_CLICK_BLOCK || e.getClickedBlock() == null) return;
|
||||
if (!StorageItems.WRENCH.equals(items.typeOf(e.getPlayer().getInventory().getItemInMainHand()))) return;
|
||||
var p = data.at(e.getClickedBlock()); if (p == null) return;
|
||||
e.setCancelled(true); panel(e.getPlayer(), e.getClickedBlock(), p);
|
||||
}
|
||||
@EventHandler(priority = EventPriority.LOWEST) public void wrenchNoBreak(BlockBreakEvent e) {
|
||||
if (StorageItems.WRENCH.equals(items.typeOf(e.getPlayer().getInventory().getItemInMainHand())) && data.at(e.getBlock()) != null) e.setCancelled(true);
|
||||
}
|
||||
private void panel(Player pl, Block b, StorageData.Placed p) {
|
||||
String key = StorageData.key(b);
|
||||
switch (p.kind) {
|
||||
case ENDER_CHEST -> { if (!canUse(pl, p)) say(pl, "This Ender Chest is private."); else tuneMenu(pl, key); }
|
||||
case SPEED_HOPPER -> openFilter(pl, key, p);
|
||||
case AUTO_CRAFTER -> openRecipe(pl, key, p);
|
||||
}
|
||||
}
|
||||
@EventHandler(priority = EventPriority.HIGHEST, ignoreCancelled = true) public void interact(PlayerInteractEvent e) {
|
||||
if (e.getAction() != org.bukkit.event.block.Action.RIGHT_CLICK_BLOCK || e.getHand() != EquipmentSlot.HAND || e.getClickedBlock() == null) return;
|
||||
Block b = e.getClickedBlock(); var p = data.at(b); if (p == null) return;
|
||||
Player pl = e.getPlayer(); ItemStack hand = pl.getInventory().getItemInMainHand(); boolean empty = hand.getType().isAir(), sneak = pl.isSneaking();
|
||||
String key = StorageData.key(b);
|
||||
switch (p.kind) {
|
||||
case ENDER_CHEST -> {
|
||||
if (sneak && !empty) return;
|
||||
e.setCancelled(true);
|
||||
if (!canUse(pl, p)) { say(pl, "This Ender Chest is private."); return; }
|
||||
if (isDye(hand.getType()) && e.getBlockFace() == BlockFace.UP && e.getInteractionPoint() != null) {
|
||||
int pad = StorageRules.padAt(front(b), e.getInteractionPoint().getX() - b.getX(), e.getInteractionPoint().getZ() - b.getZ());
|
||||
p.colors[pad] = dyeIndex(hand.getType()); changed(key, p); say(pl, "Frequency: " + describe(p.colors)); return;
|
||||
}
|
||||
if (hand.getType() == Material.DIAMOND) {
|
||||
p.priv = !p.priv; p.owner = p.priv ? pl.getUniqueId() : null; changed(key, p);
|
||||
say(pl, p.priv ? "Ender Chest is now private to you." : "Ender Chest is now shared."); return;
|
||||
}
|
||||
if (sneak) { tuneMenu(pl, key); return; }
|
||||
pl.openInventory(data.inventory(freq(p)));
|
||||
}
|
||||
case SPEED_HOPPER -> { if (sneak && empty) { e.setCancelled(true); openFilter(pl, key, p); } }
|
||||
case AUTO_CRAFTER -> { if (sneak && !empty) return; e.setCancelled(true); openRecipe(pl, key, p); }
|
||||
}
|
||||
}
|
||||
private String describe(int[] c) { return DyeColor.values()[c[0]].name() + " / " + DyeColor.values()[c[1]].name() + " / " + DyeColor.values()[c[2]].name(); }
|
||||
private void changed(String key, StorageData.Placed p) { data.dirty = true; signatures.remove(key); }
|
||||
|
||||
// ---------- menus ----------
|
||||
private Inventory menu(String kind, String key, int size, String title) {
|
||||
var h = new Menu(kind, key); h.inventory = Bukkit.createInventory(h, size, Component.text(title)); return h.inventory;
|
||||
}
|
||||
private ItemStack icon(Material m, String name, String... lore) {
|
||||
ItemStack i = new ItemStack(m); ItemMeta meta = i.getItemMeta(); meta.displayName(text(name, NamedTextColor.WHITE));
|
||||
meta.lore(Arrays.stream(lore).map(s -> text(s, NamedTextColor.GRAY)).toList()); i.setItemMeta(meta); return i;
|
||||
}
|
||||
// ---------- colour menu: the shared DuneMenus screen model (Java canvas, Bedrock form, dialog fallback) ----------
|
||||
@SuppressWarnings("deprecation")
|
||||
private ItemStack legacyIcon(Material m, String name, String... lore) {
|
||||
ItemStack i = new ItemStack(m); ItemMeta meta = i.getItemMeta(); meta.setDisplayName(ChatColor.WHITE + name);
|
||||
meta.setLore(Arrays.stream(lore).map(l -> ChatColor.GRAY + l).toList()); i.setItemMeta(meta); return i;
|
||||
}
|
||||
private static String colourName(int c) { String n = DyeColor.values()[StorageRules.wrap(c)].name().toLowerCase(Locale.ROOT).replace('_', ' '); return Character.toUpperCase(n.charAt(0)) + n.substring(1); }
|
||||
|
||||
private void tuneMenu(Player pl, String key) {
|
||||
var p = data.blocks.get(key); if (p == null || p.kind != StorageData.Kind.ENDER_CHEST) return;
|
||||
if (!canUse(pl, p)) { say(pl, "This Ender Chest is private."); return; }
|
||||
Inventory model = Bukkit.createInventory(null, 27); Map<Integer, Runnable> actions = new HashMap<>();
|
||||
int[] slots = {11, 13, 15};
|
||||
for (int i = 0; i < 3; i++) { final int pad = i;
|
||||
model.setItem(slots[i], legacyIcon(wool(p.colors[i]), "Pad " + (i + 1) + ": " + colourName(p.colors[i]), "Click to choose a colour"));
|
||||
actions.put(slots[i], () -> pickerMenu(pl, key, pad)); }
|
||||
model.setItem(4, legacyIcon(Material.ENDER_EYE, "Frequency", describe(p.colors), p.priv ? "Private" : "Shared by everyone with this frequency"));
|
||||
model.setItem(22, legacyIcon(Material.DIAMOND, p.priv ? "Private - click to share" : "Shared - click to make private", "Private chests only open for their owner"));
|
||||
actions.put(22, () -> { var q = data.blocks.get(key); if (q == null) return; q.priv = !q.priv; q.owner = q.priv ? pl.getUniqueId() : null; changed(key, q); tuneMenu(pl, key); });
|
||||
model.setItem(26, legacyIcon(Material.BARREL, "Open storage", "27 slots shared by this frequency"));
|
||||
actions.put(26, () -> { var q = data.blocks.get(key); if (q != null && canUse(pl, q)) pl.openInventory(data.inventory(freq(q))); });
|
||||
com.example.dunegui.NativeMenus.inventory(plugin, pl, "Ender Chest", model, actions);
|
||||
}
|
||||
|
||||
private void pickerMenu(Player pl, String key, int pad) {
|
||||
var p = data.blocks.get(key); if (p == null || !canUse(pl, p)) return;
|
||||
Inventory model = Bukkit.createInventory(null, 27); Map<Integer, Runnable> actions = new HashMap<>();
|
||||
for (int c = 0; c < 16; c++) { final int colour = c; int slot = (c / 8) * 9 + (c % 8) + 1 + 0;
|
||||
ItemStack icon = legacyIcon(dye(c), colourName(c) + (p.colors[pad] == c ? " (current)" : ""), "Set pad " + (pad + 1) + " to " + colourName(c).toLowerCase(Locale.ROOT));
|
||||
if (p.colors[pad] == c) { ItemMeta m = icon.getItemMeta(); m.setEnchantmentGlintOverride(true); icon.setItemMeta(m); }
|
||||
model.setItem(slot, icon);
|
||||
actions.put(slot, () -> { var q = data.blocks.get(key); if (q == null) return; q.colors[pad] = colour; changed(key, q); tuneMenu(pl, key); });
|
||||
}
|
||||
model.setItem(22, legacyIcon(Material.ARROW, "Back"));
|
||||
actions.put(22, () -> tuneMenu(pl, key));
|
||||
com.example.dunegui.NativeMenus.inventory(plugin, pl, "Ender Chest - Pad " + (pad + 1), model, actions);
|
||||
}
|
||||
|
||||
private void openFilter(Player pl, String key, StorageData.Placed p) {
|
||||
Inventory inv = menu("filter", key, 9, "Hopper Filter");
|
||||
for (int i = 0; i < 5 && i < p.filter.size(); i++) inv.setItem(i, new ItemStack(p.filter.get(i)));
|
||||
inv.setItem(6, icon(p.whitelist ? Material.LIME_DYE : Material.RED_DYE, p.whitelist ? "Whitelist" : "Blacklist", "Click to switch", "Empty filter accepts everything."));
|
||||
inv.setItem(8, icon(Material.PAPER, "Click a slot with an item to set it", "Click with an empty cursor to clear"));
|
||||
pl.openInventory(inv);
|
||||
}
|
||||
private static int gridSlot(int g) { return (g / 3) * 9 + (g % 3) + 1; }
|
||||
private void openRecipe(Player pl, String key, StorageData.Placed p) {
|
||||
Inventory inv = menu("recipe", key, 27, "Auto Crafter Recipe");
|
||||
for (int g = 0; g < 9; g++) inv.setItem(gridSlot(g), p.recipe[g] == null ? null : p.recipe[g].clone());
|
||||
previewRecipe(inv, pl.getWorld()); pl.openInventory(inv);
|
||||
}
|
||||
private void previewRecipe(Inventory inv, World w) {
|
||||
ItemStack[] m = new ItemStack[9]; for (int g = 0; g < 9; g++) m[g] = inv.getItem(gridSlot(g));
|
||||
Recipe r = Bukkit.getCraftingRecipe(m, w); inv.setItem(14, r == null ? icon(Material.BARRIER, "No recipe") : r.getResult());
|
||||
}
|
||||
|
||||
@EventHandler public void click(InventoryClickEvent e) {
|
||||
var top = e.getView().getTopInventory();
|
||||
if (top.getHolder() instanceof StorageData.FreqHolder) { data.dirty = true; return; }
|
||||
if (!(top.getHolder() instanceof Menu m)) return;
|
||||
e.setCancelled(true);
|
||||
var p = data.blocks.get(m.blockKey); if (p == null || !(e.getWhoClicked() instanceof Player pl)) return;
|
||||
if (e.getClickedInventory() != top) return;
|
||||
int slot = e.getRawSlot(); ItemStack cursor = e.getCursor();
|
||||
switch (m.kind) {
|
||||
case "filter" -> {
|
||||
if (slot >= 0 && slot < 5) { top.setItem(slot, cursor == null || cursor.getType().isAir() ? null : new ItemStack(cursor.getType())); }
|
||||
if (slot == 6) { p.whitelist = !p.whitelist; top.setItem(6, icon(p.whitelist ? Material.LIME_DYE : Material.RED_DYE, p.whitelist ? "Whitelist" : "Blacklist", "Click to switch", "Empty filter accepts everything.")); data.dirty = true; }
|
||||
}
|
||||
case "recipe" -> {
|
||||
for (int g = 0; g < 9; g++) if (slot == gridSlot(g)) { top.setItem(slot, cursor == null || cursor.getType().isAir() ? null : cursor.asOne()); previewRecipe(top, pl.getWorld()); }
|
||||
}
|
||||
default -> { }
|
||||
}
|
||||
}
|
||||
@EventHandler public void drag(InventoryDragEvent e) { if (e.getView().getTopInventory().getHolder() instanceof Menu) e.setCancelled(true); }
|
||||
@EventHandler public void close(InventoryCloseEvent e) {
|
||||
var inv = e.getInventory();
|
||||
if (inv.getHolder() instanceof StorageData.FreqHolder) { data.dirty = true; signatures.clear(); return; }
|
||||
if (!(inv.getHolder() instanceof Menu m)) return;
|
||||
var p = data.blocks.get(m.blockKey); if (p == null) return;
|
||||
if (m.kind.equals("filter")) {
|
||||
p.filter = new ArrayList<>(); for (int i = 0; i < 5; i++) { var s = inv.getItem(i); if (s != null && !s.getType().isAir() && !p.filter.contains(s.getType())) p.filter.add(s.getType()); }
|
||||
data.dirty = true;
|
||||
} else if (m.kind.equals("recipe")) {
|
||||
for (int g = 0; g < 9; g++) { var s = inv.getItem(gridSlot(g)); p.recipe[g] = s == null || s.getType().isAir() ? null : s.asOne(); }
|
||||
data.dirty = true;
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- vanilla hopper interplay ----------
|
||||
@EventHandler(ignoreCancelled = true) public void move(InventoryMoveItemEvent e) {
|
||||
var init = data.at(e.getInitiator().getLocation()); if (init != null && init.kind == StorageData.Kind.SPEED_HOPPER) { e.setCancelled(true); return; }
|
||||
var src = data.at(e.getSource().getLocation()); var dst = data.at(e.getDestination().getLocation());
|
||||
if (src != null && src.kind != StorageData.Kind.SPEED_HOPPER) e.setCancelled(true);
|
||||
if (dst != null && (dst.kind != StorageData.Kind.SPEED_HOPPER || !StorageRules.accepts(dst.whitelist, dst.filter, e.getItem().getType()))) e.setCancelled(true);
|
||||
}
|
||||
@EventHandler(ignoreCancelled = true) public void pickup(InventoryPickupItemEvent e) {
|
||||
var p = data.at(e.getInventory().getLocation()); if (p != null && p.kind == StorageData.Kind.SPEED_HOPPER) e.setCancelled(true);
|
||||
}
|
||||
|
||||
// ---------- engine ----------
|
||||
private void tick() {
|
||||
counter++;
|
||||
for (var en : new ArrayList<>(data.blocks.entrySet())) {
|
||||
var p = en.getValue(); Location loc = locate(en.getKey(), p); if (loc == null || !loc.getWorld().isChunkLoaded(loc.getBlockX() >> 4, loc.getBlockZ() >> 4)) continue;
|
||||
Block b = loc.getBlock();
|
||||
switch (p.kind) {
|
||||
case SPEED_HOPPER -> { if (b.getType() != Material.HOPPER) { remove(en.getKey()); continue; } hopper(b, p); if (counter % 25 == 0) hopperDisplay(en.getKey(), b, p); }
|
||||
case AUTO_CRAFTER -> { if (b.getType() != Material.CRAFTING_TABLE) { remove(en.getKey()); continue; } if (counter % 10 == 0) crafter(b, p); }
|
||||
case ENDER_CHEST -> { if (b.getType() != Material.BARREL) { remove(en.getKey()); continue; } if (counter % 25 == 0) displays(en.getKey(), b, p); }
|
||||
}
|
||||
}
|
||||
if (counter % 300 == 0 && data.dirty) data.save();
|
||||
}
|
||||
|
||||
private Inventory containerAt(Block b) {
|
||||
var p = data.at(b);
|
||||
if (p != null && p.kind == StorageData.Kind.ENDER_CHEST) return data.inventory(freq(p));
|
||||
if (p != null && p.kind == StorageData.Kind.AUTO_CRAFTER) return null;
|
||||
return b.getState(false) instanceof Container c ? c.getInventory() : null;
|
||||
}
|
||||
|
||||
private void hopper(Block b, StorageData.Placed p) {
|
||||
p.cooldown -= 2; if (p.cooldown > 0) return;
|
||||
if (!(b.getBlockData() instanceof org.bukkit.block.data.type.Hopper hd) || !hd.isEnabled()) return;
|
||||
if (!(b.getState(false) instanceof org.bukkit.block.Hopper hs)) return;
|
||||
var tier = StorageRules.Tier.of(p.tier); Inventory own = hs.getInventory(); boolean moved = false;
|
||||
Block out = b.getRelative(hd.getFacing()); Inventory target = containerAt(out);
|
||||
if (target != null && StorageRules.transferable(target.getType().name()) && move(own, target, tier.amount, s -> true, hd.getFacing() == BlockFace.DOWN, false) > 0) moved = true;
|
||||
Block above = b.getRelative(BlockFace.UP); Inventory source = containerAt(above);
|
||||
Predicate<ItemStack> ok = s -> StorageRules.accepts(p.whitelist, p.filter, s.getType());
|
||||
if (source != null && StorageRules.transferable(source.getType().name())) { if (move(source, own, tier.amount, ok, true, true) > 0) moved = true; }
|
||||
else if (source == null && !above.getType().isSolid()) { if (suck(above, own, tier.amount, ok) > 0) moved = true; }
|
||||
if (moved && (data.at(out) != null || data.at(above) != null)) data.dirty = true;
|
||||
p.cooldown = tier.interval;
|
||||
}
|
||||
|
||||
private int suck(Block above, Inventory own, int max, Predicate<ItemStack> ok) {
|
||||
int moved = 0;
|
||||
for (Entity en : above.getWorld().getNearbyEntities(above.getBoundingBox(), x -> x instanceof Item)) {
|
||||
Item item = (Item) en; ItemStack s = item.getItemStack(); if (!ok.test(s)) continue;
|
||||
int take = Math.min(max - moved, s.getAmount()); ItemStack part = s.clone(); part.setAmount(take);
|
||||
var left = own.addItem(part); int done = take - (left.isEmpty() ? 0 : left.values().iterator().next().getAmount());
|
||||
if (done > 0) { s.setAmount(s.getAmount() - done); if (s.getAmount() <= 0) item.remove(); else item.setItemStack(s); moved += done; }
|
||||
if (moved >= max) break;
|
||||
}
|
||||
return moved;
|
||||
}
|
||||
|
||||
/** Moves up to max items; returns how many moved. Furnaces are handled slot-correctly. */
|
||||
private int move(Inventory src, Inventory dst, int max, Predicate<ItemStack> ok, boolean down, boolean pulling) {
|
||||
int moved = 0;
|
||||
for (int i = 0; i < src.getSize() && moved < max; i++) {
|
||||
ItemStack s = src.getItem(i); if (s == null || s.getType().isAir() || !ok.test(s)) continue;
|
||||
if (src instanceof FurnaceInventory && i != 2) continue;
|
||||
int take = Math.min(max - moved, s.getAmount()); ItemStack part = s.clone(); part.setAmount(take);
|
||||
int left = insert(dst, part, down);
|
||||
int done = take - left; if (done <= 0) continue;
|
||||
s.setAmount(s.getAmount() - done); src.setItem(i, s.getAmount() <= 0 ? null : s); moved += done;
|
||||
}
|
||||
return moved;
|
||||
}
|
||||
|
||||
private int insert(Inventory dst, ItemStack part, boolean down) {
|
||||
if (dst instanceof FurnaceInventory f) {
|
||||
int slot = down ? 0 : 1; ItemStack cur = f.getItem(slot);
|
||||
if (cur == null || cur.getType().isAir()) { f.setItem(slot, part); return 0; }
|
||||
if (!cur.isSimilar(part)) return part.getAmount();
|
||||
int room = cur.getMaxStackSize() - cur.getAmount(), add = Math.min(room, part.getAmount()); cur.setAmount(cur.getAmount() + add); f.setItem(slot, cur); return part.getAmount() - add;
|
||||
}
|
||||
var left = dst.addItem(part); return left.isEmpty() ? 0 : left.values().iterator().next().getAmount();
|
||||
}
|
||||
|
||||
private void crafter(Block b, StorageData.Placed p) {
|
||||
boolean any = false; for (ItemStack s : p.recipe) if (s != null) { any = true; break; } if (!any) return;
|
||||
Inventory src = containerAt(b.getRelative(BlockFace.UP)), dst = containerAt(b.getRelative(BlockFace.DOWN));
|
||||
if (src == null || dst == null || !StorageRules.transferable(src.getType().name()) || !StorageRules.transferable(dst.getType().name())) return;
|
||||
Recipe r = Bukkit.getCraftingRecipe(p.recipe.clone(), b.getWorld()); if (r == null) return;
|
||||
Map<Material, Integer> need = new EnumMap<>(Material.class);
|
||||
for (ItemStack s : p.recipe) if (s != null) need.merge(s.getType(), 1, Integer::sum);
|
||||
for (var n : need.entrySet()) if (!src.containsAtLeast(new ItemStack(n.getKey()), n.getValue())) return;
|
||||
ItemStack result = r.getResult().clone();
|
||||
Inventory probe = Bukkit.createInventory(null, Math.min(54, Math.max(9, (dst.getSize() + 8) / 9 * 9)));
|
||||
for (int i = 0; i < dst.getSize() && i < probe.getSize(); i++) probe.setItem(i, dst.getItem(i));
|
||||
if (!probe.addItem(result.clone()).isEmpty()) return;
|
||||
for (var n : need.entrySet()) src.removeItem(new ItemStack(n.getKey(), n.getValue()));
|
||||
dst.addItem(result); data.dirty = true;
|
||||
}
|
||||
|
||||
// ---------- display entities (pads on top, most common item on the front) ----------
|
||||
/** Custom-model overlay (scaled 1.01) over the vanilla hopper so Speed Hoppers look distinct; spout follows the hopper's facing. */
|
||||
private void hopperDisplay(String key, Block b, StorageData.Placed p) {
|
||||
BlockFace face = b.getBlockData() instanceof org.bukkit.block.data.type.Hopper h ? h.getFacing() : BlockFace.DOWN;
|
||||
String sig = face + "|" + p.tier;
|
||||
var ids = displays.get(key);
|
||||
if (sig.equals(signatures.get(key)) && ids != null && ids.stream().allMatch(id -> { Entity en = Bukkit.getEntity(id); return en != null && en.isValid(); })) return;
|
||||
if (ids != null) ids.forEach(this::kill);
|
||||
boolean side = face != BlockFace.DOWN;
|
||||
Location centre = b.getLocation().add(0.5, 0.5, 0.5);
|
||||
centre.setYaw(switch (face) { case WEST -> 90f; case NORTH -> 180f; case EAST -> -90f; default -> 0f; });
|
||||
var body = b.getWorld().spawn(centre, ItemDisplay.class, id -> {
|
||||
id.setItemStack(items.hopperDisplayItem(p.tier, side)); id.setPersistent(false); id.setItemDisplayTransform(ItemDisplay.ItemDisplayTransform.NONE);
|
||||
id.setTransformation(new Transformation(new Vector3f(), new AxisAngle4f(), new Vector3f(1.01f, 1.01f, 1.01f), new AxisAngle4f()));
|
||||
});
|
||||
displays.put(key, new ArrayList<>(List.of(body.getUniqueId()))); signatures.put(key, sig);
|
||||
}
|
||||
|
||||
private void displays(String key, Block b, StorageData.Placed p) {
|
||||
BlockFace f = front(b); Material common = StorageRules.mostCommon(Arrays.asList(data.inventory(freq(p)).getContents()));
|
||||
String sig = f + "|" + StorageRules.colorsToString(p.colors) + "|" + common;
|
||||
var ids = displays.get(key);
|
||||
if (sig.equals(signatures.get(key)) && ids != null && ids.stream().allMatch(id -> { Entity en = Bukkit.getEntity(id); return en != null && en.isValid(); })) return;
|
||||
if (ids != null) ids.forEach(this::kill);
|
||||
List<UUID> made = new ArrayList<>(); World w = b.getWorld();
|
||||
Location centre = b.getLocation().add(0.5, 0.5, 0.5);
|
||||
centre.setYaw(switch (f) { case WEST -> 90f; case NORTH -> 180f; case EAST -> -90f; default -> 0f; });
|
||||
var body = w.spawn(centre, ItemDisplay.class, id -> {
|
||||
id.setItemStack(items.create(StorageItems.ENDER, 1)); id.setPersistent(false); id.setItemDisplayTransform(ItemDisplay.ItemDisplayTransform.NONE);
|
||||
id.setTransformation(new Transformation(new Vector3f(), new AxisAngle4f(), new Vector3f(1.01f, 1.01f, 1.01f), new AxisAngle4f()));
|
||||
});
|
||||
made.add(body.getUniqueId());
|
||||
for (int i = 0; i < 3; i++) {
|
||||
double[] c = StorageRules.padCentre(f, i); final int idx = i;
|
||||
var d = w.spawn(b.getLocation(), BlockDisplay.class, bd -> {
|
||||
bd.setBlock(wool(p.colors[idx]).createBlockData()); bd.setPersistent(false);
|
||||
bd.setTransformation(new Transformation(new Vector3f((float) (c[0] - 0.135), 1.012f, (float) (c[1] - 0.135)), new AxisAngle4f(), new Vector3f(0.27f, 0.05f, 0.27f), new AxisAngle4f()));
|
||||
});
|
||||
made.add(d.getUniqueId());
|
||||
}
|
||||
if (common != null) {
|
||||
Location at = b.getLocation().add(0.5 + f.getModX() * 0.52, 0.55, 0.5 + f.getModZ() * 0.52);
|
||||
at.setYaw(switch (f) { case WEST -> 90f; case NORTH -> 180f; case EAST -> -90f; default -> 0f; });
|
||||
var d = w.spawn(at, ItemDisplay.class, id -> {
|
||||
id.setItemStack(new ItemStack(common)); id.setPersistent(false); id.setItemDisplayTransform(ItemDisplay.ItemDisplayTransform.FIXED);
|
||||
id.setTransformation(new Transformation(new Vector3f(), new AxisAngle4f(), new Vector3f(0.45f, 0.45f, 0.45f), new AxisAngle4f()));
|
||||
});
|
||||
made.add(d.getUniqueId());
|
||||
}
|
||||
displays.put(key, made); signatures.put(key, sig);
|
||||
}
|
||||
|
||||
/** Click-free way in for clients that cannot sneak-click: opens the settings of the storage block being looked at (within 5 blocks). */
|
||||
private void settingsAtCrosshair(Player pl) {
|
||||
Block b = pl.getTargetBlockExact(5); var p = b == null ? null : data.at(b);
|
||||
if (p == null) { say(pl, "Look at an Ender Chest or Speed Hopper (within 5 blocks), or left-click it with a Wrench."); return; }
|
||||
panel(pl, b, p);
|
||||
}
|
||||
// ---------- /dunechest give ----------
|
||||
@Override public boolean onCommand(CommandSender s, Command c, String l, String[] a) {
|
||||
if (a.length >= 1 && a[0].equalsIgnoreCase("panel") && s instanceof Player pl) { settingsAtCrosshair(pl); return true; }
|
||||
if (!s.hasPermission("dune.admin")) { s.sendMessage("Look at an Ender Chest or Speed Hopper and use a Wrench or /dunechest panel."); return true; }
|
||||
if (a.length < 2 || !a[0].equalsIgnoreCase("give")) { s.sendMessage("/dunechest give <player> <ender|hopper1|hopper2|hopper3|crafter|wrench> [amount]"); return true; }
|
||||
Player t = Bukkit.getPlayerExact(a[1]); if (t == null || a.length < 3) { s.sendMessage("Player offline or missing item."); return true; }
|
||||
ItemStack item = switch (a[2].toLowerCase(Locale.ROOT)) { case "ender" -> items.create(StorageItems.ENDER, 1); case "hopper1" -> items.create(StorageItems.HOPPER, 1);
|
||||
case "hopper2" -> items.create(StorageItems.HOPPER, 2); case "hopper3" -> items.create(StorageItems.HOPPER, 3); case "crafter" -> items.create(StorageItems.CRAFTER, 1); case "wrench" -> items.create(StorageItems.WRENCH, 1); default -> null; };
|
||||
if (item == null) { s.sendMessage("Unknown item."); return true; }
|
||||
int n = 1; try { if (a.length > 3) n = Math.max(1, Math.min(64, Integer.parseInt(a[3]))); } catch (NumberFormatException ignored) { }
|
||||
item.setAmount(n); t.getInventory().addItem(item).values().forEach(r -> t.getWorld().dropItemNaturally(t.getLocation(), r)); s.sendMessage("Gave " + n + " " + a[2] + " to " + t.getName()); return true;
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,76 @@
|
|||
package com.example.dunechest;
|
||||
|
||||
import java.util.*;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.BlockFace;
|
||||
|
||||
/** Pure rules for the custom storage blocks: hopper tiers, filters, ender-chest colour frequencies and pad geometry. */
|
||||
public final class StorageRules {
|
||||
private StorageRules() {}
|
||||
|
||||
/** Speed hopper tier: moves {@code amount} items every {@code interval} ticks (vanilla: 1 item every 8 ticks). */
|
||||
public enum Tier {
|
||||
MK1(4, 1), MK2(4, 2), MK3(2, 4);
|
||||
public final int interval, amount;
|
||||
Tier(int interval, int amount) { this.interval = interval; this.amount = amount; }
|
||||
public static Tier of(int n) { return values()[Math.max(1, Math.min(3, n)) - 1]; }
|
||||
public double itemsPerSecond() { return 20.0 * amount / interval; }
|
||||
}
|
||||
|
||||
public static final int COLORS = 16;
|
||||
public static int wrap(int color) { return Math.floorMod(color, COLORS); }
|
||||
public static int cycle(int color, boolean forward) { return wrap(color + (forward ? 1 : -1)); }
|
||||
|
||||
/** Frequency key: shared "a-b-c", or private "p:<owner>:a-b-c". */
|
||||
public static String frequency(int[] c, UUID privateOwner) {
|
||||
String f = wrap(c[0]) + "-" + wrap(c[1]) + "-" + wrap(c[2]);
|
||||
return privateOwner == null ? f : "p:" + privateOwner + ":" + f;
|
||||
}
|
||||
public static int[] parseColors(String s) {
|
||||
String[] p = s == null ? new String[0] : s.split(",");
|
||||
int[] c = new int[3];
|
||||
for (int i = 0; i < 3; i++) try { c[i] = wrap(Integer.parseInt(p[i].trim())); } catch (RuntimeException e) { c[i] = 0; }
|
||||
return c;
|
||||
}
|
||||
public static String colorsToString(int[] c) { return wrap(c[0]) + "," + wrap(c[1]) + "," + wrap(c[2]); }
|
||||
|
||||
/** Empty filter accepts everything; otherwise whitelist accepts listed types, blacklist rejects them. */
|
||||
public static boolean accepts(boolean whitelist, Collection<Material> filter, Material m) {
|
||||
if (filter.isEmpty()) return true;
|
||||
return whitelist == filter.contains(m);
|
||||
}
|
||||
|
||||
/** Direction the viewer's right hand points when standing in front of a block whose front faces {@code front}. */
|
||||
public static int[] rightVector(BlockFace front) {
|
||||
return switch (front) { case SOUTH -> new int[]{1, 0}; case NORTH -> new int[]{-1, 0}; case EAST -> new int[]{0, -1}; case WEST -> new int[]{0, 1}; default -> new int[]{1, 0}; };
|
||||
}
|
||||
/** Local (0..1) x/z centre of pad i (0 = viewer's left) on the top of a block fronting {@code front}. */
|
||||
public static double[] padCentre(BlockFace front, int i) {
|
||||
double u = (i + 0.5) / 3.0; int[] r = rightVector(front);
|
||||
double x = r[0] == 0 ? 0.5 : (r[0] > 0 ? u : 1 - u), z = r[1] == 0 ? 0.5 : (r[1] > 0 ? u : 1 - u);
|
||||
return new double[]{x, z};
|
||||
}
|
||||
/** Which pad (0..2) a click at local x/z hit on the top face. */
|
||||
public static int padAt(BlockFace front, double lx, double lz) {
|
||||
int[] r = rightVector(front);
|
||||
double u = r[0] != 0 ? (r[0] > 0 ? lx : 1 - lx) : (r[1] > 0 ? lz : 1 - lz);
|
||||
return Math.max(0, Math.min(2, (int) Math.floor(u * 3)));
|
||||
}
|
||||
|
||||
/** Most common material among stacks (ties by first seen), or null when empty. */
|
||||
public static Material mostCommon(Iterable<org.bukkit.inventory.ItemStack> stacks) {
|
||||
Map<Material, Integer> counts = new LinkedHashMap<>();
|
||||
for (var s : stacks) if (s != null && !s.getType().isAir()) counts.merge(s.getType(), s.getAmount(), Integer::sum);
|
||||
return pick(counts);
|
||||
}
|
||||
|
||||
/** Material with the largest total (first seen wins ties), or null when empty. */
|
||||
public static Material pick(Map<Material, Integer> counts) {
|
||||
Material best = null; int max = 0;
|
||||
for (var e : counts.entrySet()) if (e.getValue() > max) { max = e.getValue(); best = e.getKey(); }
|
||||
return best;
|
||||
}
|
||||
|
||||
static final Set<String> BLOCKED_TARGETS = Set.of("BREWING", "CRAFTER", "JUKEBOX", "LECTERN", "COMPOSTER", "DECORATED_POT", "CHISELED_BOOKSHELF", "BEACON", "ENCHANTING", "ANVIL", "SMITHING");
|
||||
public static boolean transferable(String inventoryType) { return !BLOCKED_TARGETS.contains(inventoryType); }
|
||||
}
|
||||
11
DuneChest/src/main/resources/plugin.yml
Normal file
11
DuneChest/src/main/resources/plugin.yml
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
name: DuneChest
|
||||
version: 1.0.0
|
||||
main: com.example.dunechest.DuneChest
|
||||
api-version: '1.21.8'
|
||||
softdepend: [floodgate, DuneMenus, DuneEss]
|
||||
prefix: DuneChest
|
||||
description: DuneChest - colour-linked Ender Chests, Speed Hoppers and Auto Crafters
|
||||
commands:
|
||||
dunechest:
|
||||
description: DuneChest storage panel and admin give
|
||||
usage: /dunechest panel | /dunechest give <player> <ender|hopper1|hopper2|hopper3|crafter|wrench> [amount]
|
||||
|
|
@ -0,0 +1,63 @@
|
|||
package com.example.dunechest;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import java.util.*;
|
||||
import org.bukkit.Material;
|
||||
import org.bukkit.block.BlockFace;
|
||||
import org.bukkit.inventory.ItemStack;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class StorageRulesTest {
|
||||
@Test void tiersAreFasterThanVanilla() {
|
||||
double vanilla = 20.0 / 8;
|
||||
assertEquals(2.5, vanilla);
|
||||
double prev = vanilla;
|
||||
for (var t : StorageRules.Tier.values()) { assertTrue(t.itemsPerSecond() > prev, t.name()); prev = t.itemsPerSecond(); }
|
||||
assertEquals(5.0, StorageRules.Tier.MK1.itemsPerSecond()); assertEquals(10.0, StorageRules.Tier.MK2.itemsPerSecond()); assertEquals(40.0, StorageRules.Tier.MK3.itemsPerSecond());
|
||||
assertEquals(StorageRules.Tier.MK3, StorageRules.Tier.of(9)); assertEquals(StorageRules.Tier.MK1, StorageRules.Tier.of(0));
|
||||
}
|
||||
|
||||
@Test void filtersWhitelistAndBlacklist() {
|
||||
List<Material> f = List.of(Material.STONE, Material.BONE);
|
||||
assertTrue(StorageRules.accepts(true, f, Material.BONE)); assertFalse(StorageRules.accepts(true, f, Material.DIRT));
|
||||
assertFalse(StorageRules.accepts(false, f, Material.BONE)); assertTrue(StorageRules.accepts(false, f, Material.DIRT));
|
||||
assertTrue(StorageRules.accepts(true, List.of(), Material.DIRT) && StorageRules.accepts(false, List.of(), Material.DIRT));
|
||||
}
|
||||
|
||||
@Test void colourFrequenciesGive4096SharedAndPrivateKeys() {
|
||||
Set<String> keys = new HashSet<>();
|
||||
for (int a = 0; a < 16; a++) for (int b = 0; b < 16; b++) for (int c = 0; c < 16; c++) keys.add(StorageRules.frequency(new int[]{a, b, c}, null));
|
||||
assertEquals(4096, keys.size());
|
||||
UUID u = UUID.fromString("00000000-0000-0000-0000-000000000001");
|
||||
assertNotEquals(StorageRules.frequency(new int[]{1, 2, 3}, null), StorageRules.frequency(new int[]{1, 2, 3}, u));
|
||||
assertEquals("p:" + u + ":1-2-3", StorageRules.frequency(new int[]{1, 2, 3}, u));
|
||||
assertEquals(StorageRules.frequency(new int[]{17, -1, 3}, null), "1-15-3");
|
||||
assertArrayEquals(new int[]{4, 5, 6}, StorageRules.parseColors("4,5,6"));
|
||||
assertArrayEquals(new int[]{0, 0, 0}, StorageRules.parseColors("junk"));
|
||||
assertEquals("4,5,6", StorageRules.colorsToString(new int[]{4, 5, 6}));
|
||||
assertEquals(0, StorageRules.cycle(15, true)); assertEquals(15, StorageRules.cycle(0, false));
|
||||
}
|
||||
|
||||
@Test void padGeometryIsViewerRelativeAndInvertible() {
|
||||
for (BlockFace f : new BlockFace[]{BlockFace.NORTH, BlockFace.SOUTH, BlockFace.EAST, BlockFace.WEST}) {
|
||||
Set<Double> positions = new HashSet<>();
|
||||
for (int i = 0; i < 3; i++) {
|
||||
double[] c = StorageRules.padCentre(f, i);
|
||||
assertEquals(i, StorageRules.padAt(f, c[0], c[1]), f + " pad " + i);
|
||||
positions.add(c[0] * 10 + c[1]);
|
||||
}
|
||||
assertEquals(3, positions.size());
|
||||
}
|
||||
// facing south, viewer looks north and their right is east (+x): pad 0 is the smallest x
|
||||
assertTrue(StorageRules.padCentre(BlockFace.SOUTH, 0)[0] < StorageRules.padCentre(BlockFace.SOUTH, 2)[0]);
|
||||
assertTrue(StorageRules.padCentre(BlockFace.NORTH, 0)[0] > StorageRules.padCentre(BlockFace.NORTH, 2)[0]);
|
||||
}
|
||||
|
||||
@Test void mostCommonItemPicksBiggestTotal() {
|
||||
var counts = new java.util.LinkedHashMap<Material, Integer>();
|
||||
counts.put(Material.DIRT, 50); counts.put(Material.STONE, 40);
|
||||
assertEquals(Material.DIRT, StorageRules.pick(counts));
|
||||
assertNull(StorageRules.pick(new java.util.LinkedHashMap<>()));
|
||||
assertFalse(StorageRules.transferable("BREWING")); assertTrue(StorageRules.transferable("CHEST"));
|
||||
}
|
||||
}
|
||||
75
DuneChest/tools/dunechest_art.py
Normal file
75
DuneChest/tools/dunechest_art.py
Normal file
|
|
@ -0,0 +1,75 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Generates DuneChest wrench + Speed Hopper (MK1-3) textures/models/item definitions into a resource-pack overlay dir.
|
||||
usage: dunechest_art.py <overlay assets/dunerealms dir>"""
|
||||
import json, os, random, sys
|
||||
from PIL import Image, ImageDraw
|
||||
root = sys.argv[1]; rng = random.Random(2049); S = 32
|
||||
|
||||
def w(rel, obj):
|
||||
p = os.path.join(root, rel); os.makedirs(os.path.dirname(p), exist_ok=True); open(p, "w").write(json.dumps(obj, separators=(",", ":")))
|
||||
def save(rel, im):
|
||||
p = os.path.join(root, rel); os.makedirs(os.path.dirname(p), exist_ok=True); im.save(p)
|
||||
|
||||
# ---- Speed Hopper textures: dark steel with a tier-coloured accent stripe ----
|
||||
STEEL = [(54, 56, 64), (60, 62, 72), (48, 50, 58), (66, 68, 78)]
|
||||
ACCENT = {1: ((214, 168, 70), (246, 214, 120), (150, 108, 40)), # gold
|
||||
2: ((70, 200, 220), (150, 235, 245), (36, 120, 140)), # diamond
|
||||
3: ((150, 90, 220), (200, 150, 255), (88, 50, 140))} # netherite/violet
|
||||
for t in (1, 2, 3):
|
||||
a, hi, lo = ACCENT[t]
|
||||
im = Image.new("RGBA", (S, S)); px = im.load()
|
||||
for y in range(S):
|
||||
for x in range(S): px[x, y] = rng.choice(STEEL) + (255,)
|
||||
d = ImageDraw.Draw(im)
|
||||
d.rectangle([0, 0, S - 1, S - 1], outline=(20, 20, 26, 255))
|
||||
d.line([(1, 1), (S - 2, 1)], fill=(96, 98, 112, 255)); d.line([(1, 1), (1, S - 2)], fill=(80, 82, 96, 255))
|
||||
for y0 in (6, 24): # accent bands
|
||||
d.rectangle([0, y0, S - 1, y0 + 3], fill=a + (255,)); d.line([(0, y0), (S - 1, y0)], fill=hi + (255,)); d.line([(0, y0 + 3), (S - 1, y0 + 3)], fill=lo + (255,))
|
||||
for x in (4, S - 5): d.ellipse([x - 1, 14, x + 1, 16], fill=hi + (255,), outline=lo + (255,))
|
||||
for i in range(t): # one pip per tier
|
||||
d.rectangle([13 + i * 4, 13, 15 + i * 4, 17], fill=a + (255,), outline=lo + (255,))
|
||||
save(f"textures/block/speed_hopper_{t}.png", im)
|
||||
|
||||
WALLS = [([0,10,0],[16,16,2]), ([0,10,14],[16,16,16]), ([0,10,2],[2,16,14]), ([14,10,2],[16,16,14])]
|
||||
def hopper_elements(side):
|
||||
els = [{"from": f, "to": t, "faces": {k: {"texture": "#t"} for k in ("down","up","north","south","west","east")}} for f, t in WALLS]
|
||||
els.append({"from": [2,10,2], "to": [14,11,14], "faces": {k: {"texture": "#t"} for k in ("down","up")}})
|
||||
els.append({"from": [4,4,4], "to": [12,10,12], "faces": {k: {"texture": "#t"} for k in ("down","up","north","south","west","east")}})
|
||||
spout = ([6,4,10],[10,8,16]) if side else ([6,0,6],[10,4,10])
|
||||
els.append({"from": spout[0], "to": spout[1], "faces": {k: {"texture": "#t"} for k in ("down","up","north","south","west","east")}})
|
||||
return els
|
||||
for t in (1, 2, 3):
|
||||
for side in (False, True):
|
||||
n = f"speed_hopper_{t}" + ("_side" if side else "")
|
||||
w(f"models/block/{n}.json", {"parent": "minecraft:block/block", "textures": {"particle": f"dunerealms:block/speed_hopper_{t}", "t": f"dunerealms:block/speed_hopper_{t}"}, "elements": hopper_elements(side)})
|
||||
w(f"models/item/{n}.json", {"parent": f"dunerealms:block/{n}"})
|
||||
w(f"items/{n}.json", {"model": {"type": "minecraft:model", "model": f"dunerealms:item/{n}"}})
|
||||
|
||||
# ---- Wrench: 32px handheld sprite, diagonal brass-and-iron spanner ----
|
||||
im = Image.new("RGBA", (S, S), (0, 0, 0, 0)); d = ImageDraw.Draw(im)
|
||||
IRON = (150, 154, 164, 255); IRON_HI = (200, 204, 214, 255); IRON_LO = (88, 92, 102, 255); BR = (214, 168, 70, 255); BR_HI = (246, 214, 120, 255); BR_LO = (150, 108, 40, 255); OUT = (24, 24, 30, 255)
|
||||
for i in range(7, 24): # handle, bottom-left to upper-right
|
||||
x, y = i, S - 1 - i
|
||||
for dx in (-1, 0, 1):
|
||||
d.point((x + dx, y), fill=IRON); d.point((x, y + dx), fill=IRON)
|
||||
d.point((x - 1, y - 1), fill=IRON_HI); d.point((x + 1, y + 1), fill=IRON_LO)
|
||||
for i in range(3, 9): # brass grip
|
||||
x, y = i, S - 1 - i
|
||||
for dx in (-1, 0, 1):
|
||||
d.point((x + dx, y), fill=BR); d.point((x, y + dx), fill=BR)
|
||||
d.point((x - 1, y - 1), fill=BR_HI); d.point((x + 1, y + 1), fill=BR_LO)
|
||||
d.ellipse([19, 2, 29, 12], fill=IRON, outline=OUT) # open-ended head
|
||||
d.ellipse([22, 5, 27, 10], fill=(0, 0, 0, 0)); d.rectangle([25, 2, 30, 7], fill=(0, 0, 0, 0))
|
||||
d.arc([19, 2, 29, 12], 110, 330, fill=IRON_HI)
|
||||
# outline pass
|
||||
src = im.copy(); sp = src.load(); op = im.load()
|
||||
for y in range(S):
|
||||
for x in range(S):
|
||||
if sp[x, y][3] == 0:
|
||||
for dx, dy in ((1,0),(-1,0),(0,1),(0,-1)):
|
||||
nx, ny = x + dx, y + dy
|
||||
if 0 <= nx < S and 0 <= ny < S and sp[nx, ny][3] and sp[nx, ny][:3] != OUT[:3]: op[x, y] = OUT; break
|
||||
save("textures/item/wrench.png", im)
|
||||
w("models/item/wrench.json", {"parent": "minecraft:item/handheld", "textures": {"layer0": "dunerealms:item/wrench"}})
|
||||
w("items/wrench.json", {"model": {"type": "minecraft:model", "model": "dunerealms:item/wrench"}})
|
||||
print("wrote DuneChest art to", root)
|
||||
79
DuneChest/tools/ender_chest_art.py
Normal file
79
DuneChest/tools/ender_chest_art.py
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
#!/usr/bin/env python3
|
||||
"""Generates the DuneRealms Ender Chest block textures, model and item definition into a resource-pack overlay dir.
|
||||
usage: ender_chest_art.py <overlay assets/dunerealms dir>"""
|
||||
import json, os, random, sys
|
||||
from PIL import Image, ImageDraw
|
||||
|
||||
S = 32
|
||||
root = sys.argv[1]
|
||||
rng = random.Random(1701)
|
||||
|
||||
BODY = [(38, 24, 58), (44, 28, 66), (33, 20, 50), (50, 32, 74)] # dark violet stone
|
||||
BRASS = [(196, 150, 70), (222, 178, 92), (160, 118, 52)]
|
||||
EDGE = (20, 12, 32)
|
||||
|
||||
def body():
|
||||
im = Image.new("RGBA", (S, S))
|
||||
px = im.load()
|
||||
for y in range(S):
|
||||
for x in range(S):
|
||||
px[x, y] = rng.choice(BODY) + (255,)
|
||||
return im
|
||||
|
||||
def bevel(im):
|
||||
d = ImageDraw.Draw(im)
|
||||
d.rectangle([0, 0, S - 1, S - 1], outline=EDGE + (255,))
|
||||
d.line([(1, 1), (S - 2, 1)], fill=(88, 60, 124, 255)); d.line([(1, 1), (1, S - 2)], fill=(72, 48, 104, 255))
|
||||
return im
|
||||
|
||||
def band(im, y0, y1):
|
||||
d = ImageDraw.Draw(im)
|
||||
for y in range(y0, y1 + 1):
|
||||
c = BRASS[0] if y not in (y0, y1) else BRASS[2]
|
||||
d.line([(0, y), (S - 1, y)], fill=c + (255,))
|
||||
d.line([(0, y0), (S - 1, y0)], fill=BRASS[1] + (255,))
|
||||
|
||||
def rivets(im, y):
|
||||
d = ImageDraw.Draw(im)
|
||||
for x in (3, S - 4):
|
||||
d.ellipse([x - 1, y - 1, x + 1, y + 1], fill=BRASS[1] + (255,), outline=BRASS[2] + (255,))
|
||||
|
||||
def eye(im):
|
||||
d = ImageDraw.Draw(im)
|
||||
cx, cy = S // 2, 19
|
||||
d.rectangle([cx - 7, cy - 6, cx + 6, cy + 6], fill=(18, 10, 28, 255), outline=BRASS[0] + (255,))
|
||||
d.ellipse([cx - 5, cy - 3, cx + 4, cy + 3], fill=(63, 208, 176, 255), outline=(30, 120, 104, 255))
|
||||
d.ellipse([cx - 2, cy - 2, cx + 1, cy + 1], fill=(8, 20, 24, 255))
|
||||
d.point((cx + 1, cy - 2), fill=(220, 255, 245, 255))
|
||||
|
||||
side = bevel(body()); band(side, 1, 5); band(side, S - 6, S - 2); rivets(side, 3); rivets(side, S - 4)
|
||||
front = bevel(body()); band(front, 1, 7); band(front, S - 6, S - 2); eye(front); rivets(front, 4)
|
||||
d = ImageDraw.Draw(front); d.rectangle([S // 2 - 2, 6, S // 2 + 1, 10], fill=BRASS[1] + (255,), outline=BRASS[2] + (255,)) # latch
|
||||
|
||||
top = bevel(body())
|
||||
d = ImageDraw.Draw(top)
|
||||
for i in range(3): # three recessed pad slots, matching the wool pads placed on top
|
||||
cx = int(round((i + 0.5) / 3 * S))
|
||||
d.rectangle([cx - 5, S // 2 - 5, cx + 5, S // 2 + 5], fill=(14, 8, 22, 255), outline=BRASS[0] + (255,))
|
||||
d.rectangle([cx - 4, S // 2 - 4, cx + 4, S // 2 + 4], outline=(60, 40, 90, 255))
|
||||
bottom = bevel(body())
|
||||
|
||||
os.makedirs(os.path.join(root, "textures/block"), exist_ok=True)
|
||||
for name, im in (("ender_chest_side", side), ("ender_chest_front", front), ("ender_chest_top", top), ("ender_chest_bottom", bottom)):
|
||||
im.save(os.path.join(root, "textures/block", name + ".png"))
|
||||
|
||||
def w(rel, obj):
|
||||
p = os.path.join(root, rel); os.makedirs(os.path.dirname(p), exist_ok=True)
|
||||
open(p, "w").write(json.dumps(obj, separators=(",", ":")))
|
||||
|
||||
w("models/block/ender_chest.json", {
|
||||
"parent": "minecraft:block/block",
|
||||
"textures": {"particle": "dunerealms:block/ender_chest_side", "side": "dunerealms:block/ender_chest_side", "front": "dunerealms:block/ender_chest_front",
|
||||
"top": "dunerealms:block/ender_chest_top", "bottom": "dunerealms:block/ender_chest_bottom"},
|
||||
"elements": [{"from": [0, 0, 0], "to": [16, 16, 16], "faces": {
|
||||
"down": {"texture": "#bottom", "cullface": "down"}, "up": {"texture": "#top", "cullface": "up"},
|
||||
"north": {"texture": "#side", "cullface": "north"}, "south": {"texture": "#front", "cullface": "south"},
|
||||
"west": {"texture": "#side", "cullface": "west"}, "east": {"texture": "#side", "cullface": "east"}}}]})
|
||||
w("models/item/ender_chest.json", {"parent": "dunerealms:block/ender_chest"})
|
||||
w("items/ender_chest.json", {"model": {"type": "minecraft:model", "model": "dunerealms:item/ender_chest"}})
|
||||
print("wrote ender chest art to", root)
|
||||
|
|
@ -58,9 +58,18 @@ tasks.processResources {
|
|||
into("menu-art/pack")
|
||||
include("assets/dunerealms/items/**", "assets/dunerealms/models/**", "assets/dunerealms/textures/**")
|
||||
// These Arrakis gameplay models are delivered by the server pack.
|
||||
for (item in listOf("crysknife", "maker_tooth")) {
|
||||
for (item in listOf("crysknife", "maker_tooth", "wrench")) {
|
||||
exclude("assets/dunerealms/items/$item.json", "assets/dunerealms/models/item/$item.json",
|
||||
"assets/dunerealms/textures/item/$item.png")
|
||||
}
|
||||
exclude("assets/dunerealms/items/ender_chest.json", "assets/dunerealms/models/item/ender_chest.json",
|
||||
"assets/dunerealms/models/block/ender_chest.json", "assets/dunerealms/textures/block/ender_chest_*.png")
|
||||
for (tier in 1..3) {
|
||||
for (model in listOf("speed_hopper_$tier", "speed_hopper_${tier}_side")) {
|
||||
exclude("assets/dunerealms/items/$model.json", "assets/dunerealms/models/item/$model.json",
|
||||
"assets/dunerealms/models/block/$model.json")
|
||||
}
|
||||
exclude("assets/dunerealms/textures/block/speed_hopper_$tier.png")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1 @@
|
|||
{"model":{"type":"minecraft:model","model":"dunerealms:item/ender_chest"}}
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"model":{"type":"minecraft:model","model":"dunerealms:item/speed_hopper_1"}}
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"model":{"type":"minecraft:model","model":"dunerealms:item/speed_hopper_1_side"}}
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"model":{"type":"minecraft:model","model":"dunerealms:item/speed_hopper_2"}}
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"model":{"type":"minecraft:model","model":"dunerealms:item/speed_hopper_2_side"}}
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"model":{"type":"minecraft:model","model":"dunerealms:item/speed_hopper_3"}}
|
||||
|
|
@ -0,0 +1 @@
|
|||
{"model":{"type":"minecraft:model","model":"dunerealms:item/speed_hopper_3_side"}}
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue

Staff