Cooking & Baking Beta with confirmed Arrakis spice harvest #93

Merged
unimatrix merged 13 commits from feat/regional-cooking-beta-20261206 into main 2026-12-06 15:54:44 +01:00
442 changed files with 8167 additions and 38 deletions

View file

@ -0,0 +1,85 @@
name: Cooking and Baking Overlay
on:
workflow_dispatch:
push:
branches: ['feat/regional-cooking-beta-*']
jobs:
cooking-beta:
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 and package scoped regional cooking donors
shell: bash
run: |
set -euo pipefail
gradle --no-daemon -p JarvisConnector test jar
gradle --no-daemon -p DuneRealmsGUI test jar
gradle --no-daemon -p DuneTerrain test jar
gradle --no-daemon -p DuneRealms-minecraft-only test jar
PYTHONPATH=tools python3 -m unittest discover -s tools -p test_cooking_beta_artwork.py
PYTHONPATH=tools python3 -m unittest discover -s tools -p test_cooking_bedrock.py
mkdir cooking-beta
PYTHONPATH=tools python3 - <<'PY'
import json
from pathlib import Path
from plugin_regional_cooking import ROLES, slice_donor
from plugin_wild_update import read_archive, write_archive
out = Path("cooking-beta")
catalogue = Path("network/content-assets/cookbook/regional-cooking.json")
modules = {
"jarvis": "JarvisConnector/build/libs/jarvistranslator.jar",
"gui": "DuneRealmsGUI/build/libs/DunerealmsGUI.jar",
**dict.fromkeys(("arrakis", "giedi", "kaitain"), "DuneTerrain/build/libs/DuneRealms-Terrain.jar"),
"arrakis-core": "DuneRealms-minecraft-only/build/libs/DuneRealms-Core.jar",
}
for role in ROLES:
archive = read_archive(Path(modules[role]).read_bytes())
payload = slice_donor(archive, role)
if role in ("jarvis", "gui") and payload["regional-cooking.json"] != catalogue.read_bytes():
raise ValueError(f"{role} catalogue payload drift")
(out / f"{role}-donor.zip").write_bytes(write_archive(payload))
core = read_archive(Path("DuneRealms-minecraft-only/build/libs/DuneRealms-Core.jar").read_bytes())
(out / "HydrationProfiles.class").write_bytes(core["com/example/dunerealms/HydrationProfiles.class"])
ei = Path("DuneRealmsGUI/executableitems/regional-cooking")
ids = {row["id"] for row in json.loads(catalogue.read_bytes())["items"]}
if {p.stem for p in ei.glob("*.yml")} != ids:
raise ValueError("EI item IDs must exactly match catalogue")
(out / "executable-items.zip").write_bytes(write_archive({"regional-cooking/" + p.name: p.read_bytes() for p in sorted(ei.glob("*.yml"))}))
art = Path("network/resource-pack/cooking-beta")
stone = Path("network/resource-pack/realistic-stone-family/assets/minecraft/textures/block/stone.png")
paths = [catalogue, stone, art / "artwork-manifest.json", *(p for p in (art / "overlay").rglob("*") if p.is_file())]
if len(paths) != 300:
raise ValueError("Incomplete artwork payload")
(out / "artwork-source.zip").write_bytes(write_archive({p.as_posix():p.read_bytes() for p in paths}))
biomes = Path("DuneTerrain/planet-datapacks/giedi_prime/data/minecraft/worldgen/biome")
names = ("badlands", "dripstone_caves", "eroded_badlands", "pale_garden", "stony_peaks", "windswept_gravelly_hills", "wooded_badlands")
(out / "giedi-biomes-donor.zip").write_bytes(write_archive({
"data/minecraft/worldgen/biome/" + name + ".json": (biomes / (name + ".json")).read_bytes() for name in names
}))
PY
PYTHONPATH=tools python3 tools/build_cooking_bedrock.py . cooking-beta
cp tools/{RegionalCookingMerge.java,plugin_regional_cooking.py,plugin_golden_path.py,plugin_wild_update.py,HydrationMerge.java,plugin_hydration.py,cooking_beta_artwork.py,build_cooking_bedrock.py} cooking-beta/
echo "$GITHUB_SHA" > cooking-beta/SOURCE_COMMIT
(cd cooking-beta && sha256sum -- *.zip *.py *.java *.class *.mcpack *.json SOURCE_COMMIT > SHA256SUMS)
- uses: actions/upload-artifact@v3
with:
name: DuneRealms-Cooking-Beta
path: cooking-beta
if-no-files-found: error

View file

@ -170,6 +170,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
Bukkit.getScheduler().runTaskTimer(this, this::spawnSandworms, 200L, 200L);
Bukkit.getScheduler().runTaskTimer(this, this::spawnSpiceRaiders, 200L, 200L);
getLogger().info("DuneCore enabled. Gameplay, faction travel, Arrakis threats, and spice raiders ready.");
HydrationProfiles.start(this);
}
@Override public void onDisable() {
OrdosCold.close(this);
@ -182,6 +183,7 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
catch (Exception ex) { getLogger().severe("Shared shutdown save failed for " + p.getName() + ": " + ex.getMessage()); }
sharedDatabase.close();
} else if (data != null && dataFile != null) savePlayers();
HydrationProfiles.close();
}
private void savePlayers() {
if (sharedDatabase != null) {
@ -806,17 +808,72 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
World w = Bukkit.getWorld(planets[index]);
if (w != null) e.setRespawnLocation(w.getSpawnLocation().clone());
}
@EventHandler public void onSpice(BlockBreakEvent e) {
Block block = e.getBlock();
if (!block.getWorld().getName().equals("arrakis") || block.getType() != Material.SUSPICIOUS_SAND) return;
Player p = e.getPlayer();
ItemStack held = p.getInventory().getItemInMainHand();
if (held.getType() != Material.NETHERITE_SHOVEL || !is(held, "shovel")) {
e.setCancelled(true);
p.sendMessage(ChatColor.RED + "Only the Spice Harvest Shovel from /dune kit can mine a spice deposit.");
private static final Map<UUID,BlockBreakEvent> pendingSpiceHarvests = new HashMap<>();
@EventHandler(priority=org.bukkit.event.EventPriority.HIGHEST,ignoreCancelled=true)
public void onSpice(BlockBreakEvent event) {
if (event.isCancelled()) return;
Block block=event.getBlock();
if (!arrakisSpice(block) || event.getPlayer().getGameMode()==org.bukkit.GameMode.CREATIVE) return;
Player player=event.getPlayer();
ItemStack shovel=player.getInventory().getItemInMainHand();
if (!shovel.getType().name().endsWith("_SHOVEL") || !is(shovel,"shovel")) {
event.setCancelled(true);
player.sendMessage(ChatColor.RED + "Use a registered Spice Harvest Shovel to mine this deposit.");
return;
}
e.setDropItems(false); e.setExpToDrop(0);
event.setExpToDrop(0);
UUID id=player.getUniqueId();
pendingSpiceHarvests.put(id,event);
Bukkit.getScheduler().runTask(this,()->pendingSpiceHarvests.remove(id,event));
}
private static boolean arrakisSpice(Block block) {
return block.getWorld().getName().equals("arrakis") && block.getType()==Material.SUSPICIOUS_SAND;
}
@EventHandler(priority=org.bukkit.event.EventPriority.MONITOR)
public void resyncDeniedSpice(BlockBreakEvent event) {
if (!event.isCancelled() || !arrakisSpice(event.getBlock())) return;
Player player=event.getPlayer();
Block block=event.getBlock();
Bukkit.getScheduler().runTask(this,()->{
if (player.isOnline() && player.getWorld()==block.getWorld()
&& block.getWorld().isChunkLoaded(block.getX()>>4,block.getZ()>>4)) {
player.sendBlockChange(block.getLocation(),block.getBlockData());
}
});
}
@EventHandler(priority=org.bukkit.event.EventPriority.MONITOR,ignoreCancelled=true)
public void finishSpiceHarvest(org.bukkit.event.block.BlockDropItemEvent event) {
if (event.isCancelled()) return;
Player player=event.getPlayer();
BlockBreakEvent pending=pendingSpiceHarvests.get(player.getUniqueId());
Block block=event.getBlock();
Material now=block.getType();
if (pending==null || pending.isCancelled() || !pending.getBlock().equals(block)
|| event.getBlockState().getType()!=Material.SUSPICIOUS_SAND
|| (now!=Material.AIR&&now!=Material.CAVE_AIR&&now!=Material.VOID_AIR)) return;
pendingSpiceHarvests.remove(player.getUniqueId(),pending);
harvestWithEvidence(pending,()->dropConfirmedSpice(block,player));
}
private void harvestWithEvidence(BlockBreakEvent pending,Runnable reward) {
var jarvis=Bukkit.getPluginManager().getPlugin("JarvisTranslator");
if (jarvis==null || !jarvis.isEnabled()) { reward.run(); return; }
java.lang.reflect.Method observer;
try {
observer=jarvis.getClass().getMethod("withConfirmedSpiceHarvest",BlockBreakEvent.class,Runnable.class);
} catch(NoSuchMethodException absent) { reward.run(); return; }
try {
observer.invoke(jarvis,pending,reward);
} catch(ReflectiveOperationException problem) {
getLogger().warning("Confirmed spice harvest failed: "+problem.getClass().getSimpleName());
}
}
private void dropConfirmedSpice(Block block,Player p) {
int amount = selected.getOrDefault(p.getUniqueId(), "").equals("Fremen") ? 2 : 1;
serverJobs.harvest(p, amount);
UUID sponsor = activeWorkers.get(p.getUniqueId());
@ -841,19 +898,12 @@ public final class DuneCore extends JavaPlugin implements Listener, CommandExecu
p.sendMessage(ChatColor.GOLD + "Job spice: +" + workerPay + " Solaris (15% share).");
// Contract spice is sold automatically, not dropped as a second payout.
if (credited == amount) {
scheduleSpiceRespawn(block.getLocation());
return;
}
amount -= credited;
}
}
block.getWorld().dropItemNaturally(block.getLocation(), spiceDrop(p, amount));
scheduleSpiceRespawn(block.getLocation());
}
private void scheduleSpiceRespawn(Location location) {
Location loc = location.clone();
long delay = 20L * getConfig().getLong("spice-respawn-seconds", 120);
Bukkit.getScheduler().runTaskLater(this, () -> { if (loc.getChunk().isLoaded() && loc.getBlock().getType() == Material.AIR) loc.getBlock().setType(Material.SUSPICIOUS_SAND); }, delay);
}
private void migrateLegacyData() {
File legacy = new File(getDataFolder().getParentFile(), "DuneRealms");

View file

@ -0,0 +1,100 @@
package com.example.dunerealms;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.*;
import org.bukkit.*;
import org.bukkit.boss.*;
import org.bukkit.entity.Player;
import org.bukkit.event.*;
import org.bukkit.event.player.*;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.PotionMeta;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionType;
/** Hydration belongs to the existing lock-owned network profile, never local player data. */
public final class HydrationProfiles implements Listener {
private static final Map<UUID,Double> values=new HashMap<>();
private static final Set<String> PLANETS=Set.of("arrakis","caladan","kaitain","giedi_prime","sigma_draconis_iv");
private final JavaPlugin plugin;
private final SharedDatabase database;
private final Map<UUID,BossBar> bars=new HashMap<>();
private static HydrationProfiles active;
private HydrationProfiles(JavaPlugin plugin,SharedDatabase database){this.plugin=plugin;this.database=database;}
public static void initialize(SharedDatabase database)throws SQLException{
try(Connection c=database.connect()){
boolean exists;
try(PreparedStatement p=c.prepareStatement("SELECT * FROM dune_players WHERE 1=0");ResultSet r=p.executeQuery()){
exists=false;ResultSetMetaData m=r.getMetaData();for(int i=1;i<=m.getColumnCount();i++)if(m.getColumnName(i).equalsIgnoreCase("hydration"))exists=true;
}
if(!exists)try(Statement s=c.createStatement()){s.executeUpdate("ALTER TABLE dune_players ADD COLUMN hydration DOUBLE PRECISION NOT NULL DEFAULT 100");}
catch(SQLException e){if(!"42S21".equals(e.getSQLState())&&!"42701".equals(e.getSQLState()))throw e;}
try(Statement s=c.createStatement();ResultSet r=s.executeQuery("SELECT hydration FROM dune_players WHERE 1=0")){r.getMetaData();}
}
}
public static void load(Player player,ResultSet row)throws SQLException{
double amount=row.getDouble("hydration");
if(row.wasNull()||!Double.isFinite(amount)||amount<0||amount>100)throw new SQLException("Invalid shared hydration profile");
values.put(player.getUniqueId(),amount);
}
/** Called within the original single atomic profile UPDATE on its owning connection. */
public static void bind(PreparedStatement query,Player player)throws SQLException{
Double value=values.get(player.getUniqueId());
if(value==null||!Double.isFinite(value)||value<0||value>100)throw new SQLException("Hydration profile was not loaded");
query.setDouble(9,value);
if(query.getConnection().getMetaData().getDatabaseProductName().equalsIgnoreCase("PostgreSQL"))query.setObject(10,player.getUniqueId());
else query.setString(10,player.getUniqueId().toString());
}
public static void forget(Player player){values.remove(player.getUniqueId());if(active!=null)active.hide(player.getUniqueId());}
public static void start(JavaPlugin plugin){
try{
Object db=plugin.getClass().getMethod("sharedDatabase").invoke(plugin);
if(!(db instanceof SharedDatabase shared))return;
if(active!=null)throw new IllegalStateException("Hydration already started");
active=new HydrationProfiles(plugin,shared);
Bukkit.getPluginManager().registerEvents(active,plugin);
Bukkit.getScheduler().runTaskTimer(plugin,active::tick,20L,20L);
plugin.getLogger().info("Shared thirst active; Arrakis 2/min, other planets 1/min; Lobby and Builder exempt");
}catch(ReflectiveOperationException e){throw new IllegalStateException("Shared hydration API unavailable",e);}
}
public static void close(){if(active!=null){active.bars.values().forEach(BossBar::removeAll);active.bars.clear();active=null;}values.clear();}
static String realm(String name){for(String p:PLANETS)if(name.equals(p)||name.equals(p+"_nether")||name.equals(p+"_the_end"))return p;return "";}
static double decay(String realm){return realm.equals("arrakis")?2.0/60:1.0/60;}
private boolean eligible(Player player){
if(!player.isOnline()||player.isDead()||!Set.of(GameMode.SURVIVAL,GameMode.ADVENTURE).contains(player.getGameMode())||realm(player.getWorld().getName()).isEmpty()||!database.isLoaded(player.getUniqueId())||!values.containsKey(player.getUniqueId()))return false;
try{
Field field=SharedDatabase.class.getDeclaredField("builderLeases");field.setAccessible(true);
return field.get(database) instanceof Map<?,?> leases&&!leases.containsKey(player.getUniqueId());
}catch(NoSuchFieldException e){return true;}catch(ReflectiveOperationException e){return false;}
}
private void hide(UUID id){BossBar old=bars.remove(id);if(old!=null)old.removeAll();}
private void tick(){
for(Player player:Bukkit.getOnlinePlayers()){
UUID id=player.getUniqueId();if(!eligible(player)){hide(id);continue;}
double value=Math.max(0,values.get(id)-decay(realm(player.getWorld().getName())));values.put(id,value);
BossBar bar=bars.computeIfAbsent(id,key->{BossBar b=Bukkit.createBossBar("Thirst",BarColor.BLUE,BarStyle.SEGMENTED_10);b.addPlayer(player);return b;});
bar.setProgress(value/100);bar.setTitle("Hydration "+(int)Math.ceil(value)+" / 100");bar.setColor(value<20?BarColor.RED:BarColor.BLUE);
}
}
private int restoration(ItemStack item){
var jarvis=Bukkit.getPluginManager().getPlugin("JarvisTranslator");
if(jarvis!=null&&jarvis.isEnabled())try{return Math.max(0,Math.min(100,(Integer)jarvis.getClass().getMethod("hydrationRestoration",ItemStack.class).invoke(jarvis,item)));}
catch(ReflectiveOperationException e){plugin.getLogger().warning("Drink hydration API unavailable");return 0;}
return 0;
}
static boolean plainWater(ItemStack item){
if(item==null||item.getType()!=Material.POTION||!(item.getItemMeta() instanceof PotionMeta meta)||meta.getBasePotionType()!=PotionType.WATER||meta.hasCustomEffects())return false;
return !meta.getPersistentDataContainer().has(new NamespacedKey("executableitems","ei-id"),PersistentDataType.STRING)
&&!meta.getPersistentDataContainer().has(new NamespacedKey("dunerealms","item"),PersistentDataType.STRING);
}
@EventHandler(priority=EventPriority.MONITOR,ignoreCancelled=true) public void consume(PlayerItemConsumeEvent event){
Player player=event.getPlayer();if(!eligible(player))return;
ItemStack item=event.getItem();int amount=plainWater(item)?35:restoration(item);
if(amount<=0)return;
Bukkit.getScheduler().runTask(plugin,()->{if(!event.isCancelled()&&eligible(player))values.computeIfPresent(player.getUniqueId(),(id,v)->Math.min(100,v+amount));});
}
@EventHandler public void quit(PlayerQuitEvent event){hide(event.getPlayer().getUniqueId());}
}

View file

@ -49,6 +49,7 @@ public final class SharedDatabase implements AutoCloseable {
s.executeUpdate("CREATE TABLE IF NOT EXISTS dune_bounties (target UUID PRIMARY KEY, world TEXT NOT NULL, reward INTEGER NOT NULL, claimed BOOLEAN NOT NULL DEFAULT FALSE, hunter UUID)");
c.commit();
}
HydrationProfiles.initialize(this);
}
public Connection connect() throws SQLException {
@ -90,12 +91,13 @@ public final class SharedDatabase implements AutoCloseable {
Integer level, total, slot;
Float progress;
try (PreparedStatement q = c.prepareStatement(
"SELECT faction,inventory,experience_level,experience_progress,total_experience,held_slot,session_open FROM dune_players WHERE uuid=?")) {
"SELECT faction,inventory,experience_level,experience_progress,total_experience,held_slot,session_open,hydration FROM dune_players WHERE uuid=?")) {
q.setObject(1, id);
try (ResultSet r = q.executeQuery()) {
if (!r.next()) throw new SQLException("Missing network profile");
if (r.getBoolean("session_open"))
throw new SQLException("Unclean previous session; administrator recovery required");
HydrationProfiles.load(p,r);
faction = r.getString("faction");
String blob = r.getString("inventory");
if (blob != null && !blob.isBlank()) inventory = decode(blob);
@ -225,6 +227,7 @@ public final class SharedDatabase implements AutoCloseable {
writePlayer(p, factions, true);
} finally {
forgetBuilderProfile(p);
HydrationProfiles.forget(p);
Connection c = sessions.remove(p.getUniqueId());
if (c != null) c.close();
}
@ -236,7 +239,7 @@ public final class SharedDatabase implements AutoCloseable {
// Never reconnect here: a replacement connection would not own the session lock.
String inventory = encode(p.getInventory().getContents());
try (PreparedStatement q = c.prepareStatement(
"UPDATE dune_players SET faction=?,inventory=?,experience_level=?,experience_progress=?,total_experience=?,held_slot=?,session_open=?,inventory_view=?::jsonb,inventory_updated_at=CURRENT_TIMESTAMP WHERE uuid=?")) {
"UPDATE dune_players SET faction=?,inventory=?,experience_level=?,experience_progress=?,total_experience=?,held_slot=?,session_open=?,inventory_view=?::jsonb,inventory_updated_at=CURRENT_TIMESTAMP,hydration=? WHERE uuid=?")) {
q.setString(1, factions.getOrDefault(p.getUniqueId(), ""));
q.setString(2, inventory);
q.setInt(3, p.getLevel());
@ -246,6 +249,7 @@ public final class SharedDatabase implements AutoCloseable {
q.setBoolean(7, !release);
q.setString(8, InventoryWebSnapshot.capture(p));
q.setObject(9, p.getUniqueId());
HydrationProfiles.bind(q,p);
if (q.executeUpdate() != 1) throw new SQLException("Network profile disappeared during save");
} catch (SQLException ex) {
try {

View file

@ -0,0 +1,89 @@
package com.example.dunerealms;
import java.util.UUID;
import org.bukkit.*;
import org.bukkit.block.Block;
import org.bukkit.block.BlockState;
import org.bukkit.entity.Player;
import org.bukkit.event.block.BlockBreakEvent;
import org.bukkit.event.block.BlockDropItemEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.ItemMeta;
import org.bukkit.persistence.PersistentDataContainer;
import org.bukkit.persistence.PersistentDataType;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.scheduler.BukkitScheduler;
import org.junit.jupiter.api.Test;
import static org.mockito.ArgumentMatchers.*;
import static org.mockito.Mockito.*;
class ArrakisSpiceHarvestTest {
public interface Evidence extends Plugin {
void withConfirmedSpiceHarvest(BlockBreakEvent original,Runnable reward);
}
@Test void onlyOneConfirmedRemovalEntersRewardAndQuestScope() throws Exception {
var core=mock(DuneCore.class,CALLS_REAL_METHODS);
var key=new NamespacedKey("dunerealms","item");
var field=DuneCore.class.getDeclaredField("itemKey");
field.setAccessible(true);
field.set(core,key);
var world=mock(World.class);
when(world.getName()).thenReturn("arrakis");
var block=mock(Block.class);
when(block.getWorld()).thenReturn(world);
when(block.getType()).thenReturn(Material.SUSPICIOUS_SAND);
var oldState=mock(BlockState.class);
when(oldState.getType()).thenReturn(Material.SUSPICIOUS_SAND);
var player=mock(Player.class);
when(player.getUniqueId()).thenReturn(UUID.randomUUID());
when(player.getGameMode()).thenReturn(GameMode.SURVIVAL);
var inventory=mock(PlayerInventory.class);
when(player.getInventory()).thenReturn(inventory);
var shovel=mock(ItemStack.class);
when(inventory.getItemInMainHand()).thenReturn(shovel);
when(shovel.getType()).thenReturn(Material.IRON_SHOVEL);
when(shovel.hasItemMeta()).thenReturn(true);
var meta=mock(ItemMeta.class);
when(shovel.getItemMeta()).thenReturn(meta);
var data=mock(PersistentDataContainer.class);
when(meta.getPersistentDataContainer()).thenReturn(data);
when(data.get(key,PersistentDataType.STRING)).thenReturn("shovel");
var scheduler=mock(BukkitScheduler.class);
var pluginManager=mock(PluginManager.class);
var evidence=mock(Evidence.class);
when(evidence.isEnabled()).thenReturn(true);
when(pluginManager.getPlugin("JarvisTranslator")).thenReturn(evidence);
try(var bukkit=mockStatic(Bukkit.class)){
bukkit.when(Bukkit::getScheduler).thenReturn(scheduler);
bukkit.when(Bukkit::getPluginManager).thenReturn(pluginManager);
var original=new BlockBreakEvent(block,player);
var dropped=new BlockDropItemEvent(block,oldState,player,new java.util.ArrayList<>());
original.setCancelled(true);
core.onSpice(original);
when(block.getType()).thenReturn(Material.AIR);
core.finishSpiceHarvest(dropped);
verifyNoInteractions(evidence);
original.setCancelled(false);
when(block.getType()).thenReturn(Material.SUSPICIOUS_SAND);
core.onSpice(original);
core.finishSpiceHarvest(dropped);
when(block.getType()).thenReturn(Material.AIR);
dropped.setCancelled(true);
core.finishSpiceHarvest(dropped);
verifyNoInteractions(evidence);
dropped.setCancelled(false);
core.finishSpiceHarvest(dropped);
core.finishSpiceHarvest(dropped);
verify(evidence,times(1)).withConfirmedSpiceHarvest(eq(original),any());
verify(scheduler,never()).runTaskLater(any(Plugin.class),any(Runnable.class),anyLong());
}
}
}

View file

@ -31,10 +31,23 @@ class SharedDatabaseTest {
@BeforeEach void prepare() throws Exception {
Connection schema = mock(Connection.class);
when(schema.createStatement()).thenReturn(mock(Statement.class));
PreparedStatement hydrationSchema=mock(PreparedStatement.class);
ResultSet hydrationColumns=mock(ResultSet.class);
ResultSetMetaData hydrationMeta=mock(ResultSetMetaData.class);
when(schema.prepareStatement(anyString())).thenReturn(hydrationSchema);
when(hydrationSchema.executeQuery()).thenReturn(hydrationColumns);
when(hydrationColumns.getMetaData()).thenReturn(hydrationMeta);
when(hydrationMeta.getColumnCount()).thenReturn(1);
when(hydrationMeta.getColumnName(1)).thenReturn("hydration");
when(schema.createStatement().executeQuery(anyString())).thenReturn(hydrationColumns);
owner = mock(Connection.class);
DatabaseMetaData ownerMeta=mock(DatabaseMetaData.class);
when(ownerMeta.getDatabaseProductName()).thenReturn("PostgreSQL");
when(owner.getMetaData()).thenReturn(ownerMeta);
lock = mock(PreparedStatement.class);
row = mock(PreparedStatement.class);
update = mock(PreparedStatement.class);
when(update.getConnection()).thenReturn(owner);
lockResult = mock(ResultSet.class);
profile = mock(ResultSet.class);
when(owner.prepareStatement(anyString())).thenAnswer(call -> {
@ -49,10 +62,11 @@ class SharedDatabaseTest {
when(row.executeQuery()).thenReturn(profile);
when(profile.next()).thenReturn(true);
when(profile.getString("faction")).thenReturn("fremen");
when(profile.getDouble("hydration")).thenReturn(100.0);
when(update.executeUpdate()).thenReturn(1);
driver = mock(Driver.class);
when(driver.acceptsURL("jdbc:dune-test:profiles")).thenReturn(true);
when(driver.connect(eq("jdbc:dune-test:profiles"), any())).thenReturn(schema, owner);
when(driver.connect(eq("jdbc:dune-test:profiles"), any())).thenReturn(schema, schema, owner);
DriverManager.registerDriver(driver);
JavaPlugin plugin = mock(JavaPlugin.class);
YamlConfiguration config = new YamlConfiguration();
@ -76,9 +90,27 @@ class SharedDatabaseTest {
@AfterEach void cleanup() throws Exception {
db.close();
HydrationProfiles.close();
DriverManager.deregisterDriver(driver);
}
@Test void hydrationIsLoadedAndSavedInsideTheOriginalOwnedAtomicCheckpoint() throws Exception {
when(profile.getDouble("hydration")).thenReturn(37.25);
db.loadPlayer(player,factions);
db.savePlayer(player,factions);
verify(update).setDouble(9,37.25);
verify(update).setObject(10,id);
verify(owner).prepareStatement(contains("hydration=? WHERE uuid=?"));
verify(driver,times(3)).connect(eq("jdbc:dune-test:profiles"),any());
}
@Test void invalidHydrationRefusesProfileBeforeOpeningOrApplyingInventory() throws Exception {
when(profile.getDouble("hydration")).thenReturn(Double.NaN);
assertThrows(SQLException.class,()->db.loadPlayer(player,factions));
verify(owner,never()).prepareStatement("UPDATE dune_players SET session_open=TRUE WHERE uuid=?");
verify(inventory,never()).setContents(any());
}
@Test void builderCheckpointRejectsCreativeWritesAndRestoresCommittedInventory() throws Exception {
db.loadPlayer(player, factions);
when(owner.getAutoCommit()).thenReturn(true);
@ -160,13 +192,13 @@ class SharedDatabaseTest {
verify(update).setBoolean(7, false);
verify(owner).close();
assertFalse(db.isLoaded(id));
verify(driver, times(2)).connect(anyString(), any()); // Schema + one owned connection only.
verify(driver, times(3)).connect(anyString(), any()); // Schema + hydration schema + one owned connection only.
}
@Test void duplicateLoadOnSameBackendCannotOverwriteSession() throws Exception {
db.loadPlayer(player, factions);
assertThrows(SQLException.class, () -> db.loadPlayer(player, factions));
verify(driver, times(2)).connect(anyString(), any());
verify(driver, times(3)).connect(anyString(), any());
verify(owner, never()).close();
}

View file

@ -18,6 +18,7 @@ tasks.jar { archiveFileName.set("DunerealmsGUI.jar") }
sourceSets.main { java.srcDirs("../citizens-common/src/main/java", "../pack-session-common/src/main/java") }
tasks.processResources {
from(rootProject.file("../network/content-assets/cookbook/spice-crafting.json"))
from(rootProject.file("../network/content-assets/cookbook/regional-cooking.json"))
}
val mcguiRuntime = providers.gradleProperty("mcguiRuntime")

View file

@ -0,0 +1,27 @@
{
"name": "&fBacon",
"material": "COOKED_PORKCHOP",
"lore": [],
"glow": false,
"disableStack": false,
"keepItemOnDeath": false,
"storeItemInfo": false,
"canBeUsedOnlyByTheOwner": false,
"cancelEventIfNoPermission": false,
"config_5": true,
"config_update": false,
"usageFeatures": {
"usage": -1,
"isRefreshableClean": false,
"usageLimit": -1
},
"hiders": {
"hideUsage": true
},
"giveFirstJoinFeatures": {
"giveFirstJoin": false
},
"activators": {},
"variables": {},
"itemModel": "dunerealms:cooking/bacon"
}

View file

@ -0,0 +1,27 @@
{
"name": "&fBaguette",
"material": "BREAD",
"lore": [],
"glow": false,
"disableStack": false,
"keepItemOnDeath": false,
"storeItemInfo": false,
"canBeUsedOnlyByTheOwner": false,
"cancelEventIfNoPermission": false,
"config_5": true,
"config_update": false,
"usageFeatures": {
"usage": -1,
"isRefreshableClean": false,
"usageLimit": -1
},
"hiders": {
"hideUsage": true
},
"giveFirstJoinFeatures": {
"giveFirstJoin": false
},
"activators": {},
"variables": {},
"itemModel": "dunerealms:cooking/baguette"
}

View file

@ -0,0 +1,27 @@
{
"name": "&fBaking Dough",
"material": "CLAY_BALL",
"lore": [],
"glow": false,
"disableStack": false,
"keepItemOnDeath": false,
"storeItemInfo": false,
"canBeUsedOnlyByTheOwner": false,
"cancelEventIfNoPermission": false,
"config_5": true,
"config_update": false,
"usageFeatures": {
"usage": -1,
"isRefreshableClean": false,
"usageLimit": -1
},
"hiders": {
"hideUsage": true
},
"giveFirstJoinFeatures": {
"giveFirstJoin": false
},
"activators": {},
"variables": {},
"itemModel": "dunerealms:cooking/baking_dough"
}

View file

@ -0,0 +1,27 @@
{
"name": "&fBeef Burger",
"material": "COOKED_BEEF",
"lore": [],
"glow": false,
"disableStack": false,
"keepItemOnDeath": false,
"storeItemInfo": false,
"canBeUsedOnlyByTheOwner": false,
"cancelEventIfNoPermission": false,
"config_5": true,
"config_update": false,
"usageFeatures": {
"usage": -1,
"isRefreshableClean": false,
"usageLimit": -1
},
"hiders": {
"hideUsage": true
},
"giveFirstJoinFeatures": {
"giveFirstJoin": false
},
"activators": {},
"variables": {},
"itemModel": "dunerealms:cooking/beef_burger"
}

View file

@ -0,0 +1,27 @@
{
"name": "&fBeef Mince",
"material": "BEEF",
"lore": [],
"glow": false,
"disableStack": false,
"keepItemOnDeath": false,
"storeItemInfo": false,
"canBeUsedOnlyByTheOwner": false,
"cancelEventIfNoPermission": false,
"config_5": true,
"config_update": false,
"usageFeatures": {
"usage": -1,
"isRefreshableClean": false,
"usageLimit": -1
},
"hiders": {
"hideUsage": true
},
"giveFirstJoinFeatures": {
"giveFirstJoin": false
},
"activators": {},
"variables": {},
"itemModel": "dunerealms:cooking/beef_mince"
}

View file

@ -0,0 +1,27 @@
{
"name": "&fBeef Stock",
"material": "MUSHROOM_STEW",
"lore": [],
"glow": false,
"disableStack": false,
"keepItemOnDeath": false,
"storeItemInfo": false,
"canBeUsedOnlyByTheOwner": false,
"cancelEventIfNoPermission": false,
"config_5": true,
"config_update": false,
"usageFeatures": {
"usage": -1,
"isRefreshableClean": false,
"usageLimit": -1
},
"hiders": {
"hideUsage": true
},
"giveFirstJoinFeatures": {
"giveFirstJoin": false
},
"activators": {},
"variables": {},
"itemModel": "dunerealms:cooking/beef_stock"
}

View file

@ -0,0 +1,27 @@
{
"name": "&fBerry Cordial",
"material": "POTION",
"lore": [],
"glow": false,
"disableStack": false,
"keepItemOnDeath": false,
"storeItemInfo": false,
"canBeUsedOnlyByTheOwner": false,
"cancelEventIfNoPermission": false,
"config_5": true,
"config_update": false,
"usageFeatures": {
"usage": -1,
"isRefreshableClean": false,
"usageLimit": -1
},
"hiders": {
"hideUsage": true
},
"giveFirstJoinFeatures": {
"giveFirstJoin": false
},
"activators": {},
"variables": {},
"itemModel": "dunerealms:cooking/berry_cordial"
}

View file

@ -0,0 +1,27 @@
{
"name": "&fBerry Tart",
"material": "PUMPKIN_PIE",
"lore": [],
"glow": false,
"disableStack": false,
"keepItemOnDeath": false,
"storeItemInfo": false,
"canBeUsedOnlyByTheOwner": false,
"cancelEventIfNoPermission": false,
"config_5": true,
"config_update": false,
"usageFeatures": {
"usage": -1,
"isRefreshableClean": false,
"usageLimit": -1
},
"hiders": {
"hideUsage": true
},
"giveFirstJoinFeatures": {
"giveFirstJoin": false
},
"activators": {},
"variables": {},
"itemModel": "dunerealms:cooking/berry_tart"
}

View file

@ -0,0 +1,27 @@
{
"name": "&fBerry Tart Mix",
"material": "CLAY_BALL",
"lore": [],
"glow": false,
"disableStack": false,
"keepItemOnDeath": false,
"storeItemInfo": false,
"canBeUsedOnlyByTheOwner": false,
"cancelEventIfNoPermission": false,
"config_5": true,
"config_update": false,
"usageFeatures": {
"usage": -1,
"isRefreshableClean": false,
"usageLimit": -1
},
"hiders": {
"hideUsage": true
},
"giveFirstJoinFeatures": {
"giveFirstJoin": false
},
"activators": {},
"variables": {},
"itemModel": "dunerealms:cooking/berry_tart_mix"
}

View file

@ -0,0 +1,27 @@
{
"name": "&fBerry Tea",
"material": "POTION",
"lore": [],
"glow": false,
"disableStack": false,
"keepItemOnDeath": false,
"storeItemInfo": false,
"canBeUsedOnlyByTheOwner": false,
"cancelEventIfNoPermission": false,
"config_5": true,
"config_update": false,
"usageFeatures": {
"usage": -1,
"isRefreshableClean": false,
"usageLimit": -1
},
"hiders": {
"hideUsage": true
},
"giveFirstJoinFeatures": {
"giveFirstJoin": false
},
"activators": {},
"variables": {},
"itemModel": "dunerealms:cooking/berry_tea"
}

View file

@ -0,0 +1,27 @@
{
"name": "&fBrown Mushroom Broth",
"material": "MUSHROOM_STEW",
"lore": [],
"glow": false,
"disableStack": false,
"keepItemOnDeath": false,
"storeItemInfo": false,
"canBeUsedOnlyByTheOwner": false,
"cancelEventIfNoPermission": false,
"config_5": true,
"config_update": false,
"usageFeatures": {
"usage": -1,
"isRefreshableClean": false,
"usageLimit": -1
},
"hiders": {
"hideUsage": true
},
"giveFirstJoinFeatures": {
"giveFirstJoin": false
},
"activators": {},
"variables": {},
"itemModel": "dunerealms:cooking/brown_mushroom_broth"
}

View file

@ -0,0 +1,27 @@
{
"name": "&fBurger Bun",
"material": "BREAD",
"lore": [],
"glow": false,
"disableStack": false,
"keepItemOnDeath": false,
"storeItemInfo": false,
"canBeUsedOnlyByTheOwner": false,
"cancelEventIfNoPermission": false,
"config_5": true,
"config_update": false,
"usageFeatures": {
"usage": -1,
"isRefreshableClean": false,
"usageLimit": -1
},
"hiders": {
"hideUsage": true
},
"giveFirstJoinFeatures": {
"giveFirstJoin": false
},
"activators": {},
"variables": {},
"itemModel": "dunerealms:cooking/burger_bun"
}

View file

@ -0,0 +1,27 @@
{
"name": "&fButter",
"material": "HONEYCOMB",
"lore": [],
"glow": false,
"disableStack": false,
"keepItemOnDeath": false,
"storeItemInfo": false,
"canBeUsedOnlyByTheOwner": false,
"cancelEventIfNoPermission": false,
"config_5": true,
"config_update": false,
"usageFeatures": {
"usage": -1,
"isRefreshableClean": false,
"usageLimit": -1
},
"hiders": {
"hideUsage": true
},
"giveFirstJoinFeatures": {
"giveFirstJoin": false
},
"activators": {},
"variables": {},
"itemModel": "dunerealms:cooking/butter"
}

Some files were not shown because too many files have changed in this diff Show more