Display hydration droplets above hunger with pack-aware fallback
Some checks failed
Hydration HUD Overlay / hydration-hud (push) Successful in 2m4s
DuneRealms Plugin CI / plugins (push) Successful in 10m8s
DuneRealms Resourcepack CI / resourcepack (push) Failing after 18s

This commit is contained in:
unimatrixgit 2026-12-06 16:34:05 +01:00
commit 330721d0d7
8 changed files with 366 additions and 4 deletions

View file

@ -0,0 +1,47 @@
name: Hydration HUD Overlay
on:
workflow_dispatch:
push:
branches: ['feat/hydration-hud-*']
jobs:
hydration-hud:
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
test "$(git rev-parse HEAD)" = "$GITHUB_SHA"
- 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 tested hydration presentation and client assets
shell: bash
run: |
set -euo pipefail
gradle --no-daemon -p DuneRealms-minecraft-only test jar
python3 -m unittest discover -s tools -p test_hydration_hud.py
python3 tools/build_hydration_hud.py hydration-hud
PYTHONPATH=tools python3 - <<'PY'
from pathlib import Path
from plugin_hydration_hud import entries,NAMES
from build_hydration_hud import archive
core=entries('DuneRealms-minecraft-only/build/libs/DuneRealms-Core.jar')
Path('hydration-hud/hydration-hud-classes.zip').write_bytes(archive({n:core[n]for n in NAMES}))
PY
cp tools/{build_hydration_hud.py,plugin_hydration_hud.py,test_hydration_hud.py} hydration-hud/
echo "$GITHUB_SHA" > hydration-hud/SOURCE_COMMIT
(cd hydration-hud && sha256sum -- *.zip *.mcpack *.json *.py SOURCE_COMMIT > SHA256SUMS)
- uses: actions/upload-artifact@v3
with:
name: DuneRealms-Hydration-HUD
path: hydration-hud

View file

@ -3,6 +3,8 @@ group = "com.example"
version = "1.0.13"
repositories { mavenCentral(); maven("https://repo.papermc.io/repository/maven-public/"); maven("https://jitpack.io") }
dependencies {
compileOnly("io.netty:netty-transport:4.2.15.Final")
testImplementation("io.netty:netty-transport:4.2.15.Final")
compileOnly("io.papermc.paper:paper-api:1.21.8-R0.1-SNAPSHOT")
compileOnly("com.github.MilkBowl:VaultAPI:1.7") {
exclude(group = "org.bukkit", module = "bukkit")

View file

@ -0,0 +1,130 @@
package com.example.dunerealms;
import io.netty.channel.*;
import java.lang.reflect.*;
import java.util.*;
import java.util.concurrent.TimeUnit;
import net.kyori.adventure.key.Key;
import net.kyori.adventure.text.Component;
import net.kyori.adventure.text.format.NamedTextColor;
import org.bukkit.Bukkit;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.entity.Player;
/** Presentation only. The lock-owned hydration value remains in HydrationProfiles. */
final class HydrationHud {
static final String BEDROCK_PREFIX="DRHYD:";
static final String HANDLER="dunerealms_hydration_hud";
static final Key FONT=Key.key("dunerealms:hydration");
private static final long MESSAGE_TIME=TimeUnit.SECONDS.toNanos(3);
private final Map<UUID,Output> outputs=new HashMap<>();
private boolean warned;
private long nextPinCheck;
private boolean javaAssets,bedrockAssets;
static int step(double hydration){
if(!Double.isFinite(hydration)||hydration<0||hydration>100)throw new IllegalArgumentException("Invalid hydration");
return hydration==0?0:(int)Math.ceil(hydration/5);
}
static Component javaBar(double hydration,boolean submerged){
// Net advance is zero: position the 81px sprite 10px right of screen centre.
// Two font rows place it above hunger, or above the native air bubbles.
char glyph=(char)((submerged?0xE820:0xE800)+step(hydration));
return Component.text("\uE7F0"+glyph+"\uE7F1",NamedTextColor.WHITE).font(FONT);
}
static String bedrockBar(double hydration,boolean submerged){return BEDROCK_PREFIX+step(hydration)+(submerged?":air":"");}
static boolean own(String text){
if(text==null)return false;
if(text.equals("\uE7F2"))return true;
if(text.matches("DRHYD:(?:[0-9]|1[0-9]|20)(?::air)?")||text.equals(BEDROCK_PREFIX+"hide"))return true;
return text.length()==3&&text.charAt(0)==0xE7F0&&text.charAt(2)==0xE7F1&&
((text.charAt(1)>=0xE800&&text.charAt(1)<=0xE814)||(text.charAt(1)>=0xE820&&text.charAt(1)<=0xE834));
}
private boolean ready(Player player,boolean bedrock){
var gui=Bukkit.getPluginManager().getPlugin("DunerealmsGUI");if(gui==null||!gui.isEnabled())return false;
// A new font/UI is never sent with the old pack. Both flags are source-bound
// release pins, installed only together with the corresponding client assets.
if(System.nanoTime()>=nextPinCheck){
var pins=YamlConfiguration.loadConfiguration(new java.io.File(gui.getDataFolder(),"menu-pack.yml"));
javaAssets=pins.getInt("hydration-hud-version",0)==1;bedrockAssets=pins.getInt("bedrock-hydration-hud-version",0)==1;
nextPinCheck=System.nanoTime()+TimeUnit.SECONDS.toNanos(5);
}
if(!(bedrock?bedrockAssets:javaAssets))return false;
if(bedrock)return true; // Operator also requires Geyser's mandatory pack handshake.
try{return Boolean.TRUE.equals(gui.getClass().getMethod("menuAssetsLoaded",Player.class).invoke(gui,player));}
catch(ReflectiveOperationException|LinkageError failure){return false;}
}
private boolean bedrock(Player player){
try{return org.geysermc.floodgate.api.FloodgateApi.getInstance().isFloodgatePlayer(player.getUniqueId());}
catch(LinkageError|IllegalStateException unavailable){return false;}
}
boolean show(Player player,double hydration){
boolean bedrock=bedrock(player);
if(player.isInsideVehicle()||!ready(player,bedrock)){hide(player);return false;}
Output output=outputs.get(player.getUniqueId());
if(output==null){
try{output=attach(player);outputs.put(player.getUniqueId(),output);}
catch(ReflectiveOperationException|RuntimeException failure){
if(!warned){warned=true;Bukkit.getLogger().warning("Hydration HUD packet observer unavailable; retaining hydration boss bar");}
return false;
}
}
if(!output.installed)return false;
// Observe, never cancel or rewrite, other plugins' action bars. Raid warnings,
// jukebox messages and similar notices get their full native display interval.
if(output.suppressed(System.nanoTime()))return true;
boolean air=player.isUnderWater()||player.getRemainingAir()<player.getMaximumAir();
player.sendActionBar(bedrock?Component.text(bedrockBar(hydration,air)):javaBar(hydration,air));
output.lastOwned=true;output.bedrock=bedrock;return true;
}
void hide(Player player){
Output output=outputs.get(player.getUniqueId());
if(output!=null&&output.lastOwned&&!output.suppressed(System.nanoTime())){
player.sendActionBar(output.bedrock?Component.text(BEDROCK_PREFIX+"hide"):Component.text("\uE7F2").font(FONT));output.lastOwned=false;
}
}
void forget(Player player){hide(player);Output old=outputs.remove(player.getUniqueId());if(old!=null)old.detach();}
void close(){for(Output output:outputs.values())output.detach();outputs.clear();}
private Output attach(Player player)throws ReflectiveOperationException{
Object handle=player.getClass().getMethod("getHandle").invoke(player);
Object listener=field(handle,"net.minecraft.server.network.ServerGamePacketListenerImpl");
Object connection=field(listener,"net.minecraft.network.Connection");
Channel channel=(Channel)field(connection,"io.netty.channel.Channel");
Output output=new Output(channel);
channel.eventLoop().execute(()->{
if(channel.isActive()&&channel.pipeline().get(HANDLER)==null){channel.pipeline().addBefore("packet_handler",HANDLER,output);output.installed=true;}
});return output;
}
private static Object field(Object owner,String type)throws ReflectiveOperationException{
for(Class<?> c=owner.getClass();c!=null;c=c.getSuperclass())for(Field f:c.getDeclaredFields())
if(f.getType().getName().equals(type)){f.setAccessible(true);Object value=f.get(owner);if(value==null)throw new IllegalStateException("Connection not ready");return value;}
throw new NoSuchFieldException(type);
}
static final class Output extends ChannelOutboundHandlerAdapter {
final Channel channel;
volatile long externalUntil;
volatile boolean installed,lastOwned,bedrock;
Output(Channel channel){this.channel=channel;}
boolean suppressed(long now){return now<externalUntil;}
void observe(String text,long now){if(!own(text)){externalUntil=now+MESSAGE_TIME;lastOwned=false;}}
@Override public void write(ChannelHandlerContext context,Object packet,ChannelPromise promise)throws Exception{
String name=packet.getClass().getName();
boolean overlay=name.equals("net.minecraft.network.protocol.game.ClientboundSetActionBarTextPacket");
if(name.equals("net.minecraft.network.protocol.game.ClientboundSystemChatPacket")){
try{overlay=Boolean.TRUE.equals(packet.getClass().getMethod("overlay").invoke(packet));}catch(ReflectiveOperationException ignored){}
}
if(overlay)try{
Object component=field(packet,"net.minecraft.network.chat.Component");
String text=(String)Class.forName("net.minecraft.network.chat.Component").getMethod("getString").invoke(component);
long now=System.nanoTime();
// Recheck on the actual network event loop as well: a notice may have been
// queued after the server tick's check but before its hydration packet.
if(own(text)&&suppressed(now)){io.netty.util.ReferenceCountUtil.release(packet);promise.setSuccess();return;}
observe(text,now);
}catch(ReflectiveOperationException failure){externalUntil=System.nanoTime()+MESSAGE_TIME;lastOwned=false;}
context.write(packet,promise);
}
void detach(){channel.eventLoop().execute(()->{if(channel.pipeline().get(HANDLER)==this)channel.pipeline().remove(this);installed=false;});}
}
}

View file

@ -21,6 +21,7 @@ public final class HydrationProfiles implements Listener {
private final JavaPlugin plugin;
private final SharedDatabase database;
private final Map<UUID,BossBar> bars=new HashMap<>();
private final HydrationHud hud=new HydrationHud();
private static HydrationProfiles active;
private HydrationProfiles(JavaPlugin plugin,SharedDatabase database){this.plugin=plugin;this.database=database;}
@ -48,7 +49,7 @@ public final class HydrationProfiles implements Listener {
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 forget(Player player){values.remove(player.getUniqueId());if(active!=null){active.hud.forget(player);active.hide(player.getUniqueId());}}
public static void start(JavaPlugin plugin){
try{
Object db=plugin.getClass().getMethod("sharedDatabase").invoke(plugin);
@ -60,7 +61,7 @@ public final class HydrationProfiles implements Listener {
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();}
public static void close(){if(active!=null){for(Player player:Bukkit.getOnlinePlayers())active.hud.hide(player);active.hud.close();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){
@ -73,8 +74,9 @@ public final class HydrationProfiles implements Listener {
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;}
UUID id=player.getUniqueId();if(!eligible(player)){hud.hide(player);hide(id);continue;}
double value=Math.max(0,values.get(id)-decay(realm(player.getWorld().getName())));values.put(id,value);
if(hud.show(player,value)){hide(id);continue;}
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);
}
@ -96,5 +98,5 @@ public final class HydrationProfiles implements Listener {
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());}
@EventHandler public void quit(PlayerQuitEvent event){hud.forget(event.getPlayer());hide(event.getPlayer().getUniqueId());}
}

View file

@ -0,0 +1,30 @@
package com.example.dunerealms;
import io.netty.channel.embedded.EmbeddedChannel;
import net.kyori.adventure.text.TextComponent;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
class HydrationHudTest {
@Test void boundedHalfDropletsNeverRoundAnEmptyProfileUp(){
assertEquals(0,HydrationHud.step(0));assertEquals(1,HydrationHud.step(.01));
assertEquals(10,HydrationHud.step(50));assertEquals(20,HydrationHud.step(100));
for(double invalid:new double[]{Double.NaN,Double.POSITIVE_INFINITY,-1,101})assertThrows(IllegalArgumentException.class,()->HydrationHud.step(invalid));
}
@Test void bothLayoutsEncodeTheSameAuthoritativeValueWithoutPlainTextFallbackGlyphs(){
for(int step=0;step<=20;step++)for(boolean air:new boolean[]{false,true}){
double value=step*5;String java=((TextComponent)HydrationHud.javaBar(value,air)).content();
assertEquals(3,java.length());assertEquals((air?0xE820:0xE800)+step,java.charAt(1));assertTrue(HydrationHud.own(java));
String bedrock=HydrationHud.bedrockBar(value,air);assertTrue(HydrationHud.own(bedrock));assertEquals("DRHYD:"+step+(air?":air":""),bedrock);
}
assertFalse(HydrationHud.own("Sardaukar raid in 10 seconds"));assertFalse(HydrationHud.own("DRHYD:999"));
}
@Test void otherActionbarsPassThroughAndHaveAnUninterruptedThreeSecondWindow(){
EmbeddedChannel channel=new EmbeddedChannel();HydrationHud.Output output=new HydrationHud.Output(channel);channel.pipeline().addLast(output);
try{
Object message=new Object();assertTrue(channel.writeOutbound(message));assertSame(message,channel.readOutbound());
output.lastOwned=true;output.observe("Raid warning",100);assertFalse(output.lastOwned);assertTrue(output.suppressed(100));assertTrue(output.suppressed(3_000_000_099L));assertFalse(output.suppressed(3_000_000_100L));
output.observe("DRHYD:20",4_000_000_000L);assertFalse(output.suppressed(4_000_000_000L));
}finally{channel.finishAndReleaseAll();}
}
}

View file

@ -0,0 +1,90 @@
"""Deterministic small hydration HUD sprites and additive Java/Bedrock packs.
Java uses its own font; it never replaces default font, food, air or health art.
Bedrock inserts an actionbar factory into the native Classic/Pocket HUD panels.
"""
import argparse,hashlib,json,struct,uuid,zlib,zipfile
from pathlib import Path
def encoded(value):return (json.dumps(value,ensure_ascii=False,indent=2)+'\n').encode()
def png(width,height,pixels):
def chunk(kind,data):return struct.pack('>I',len(data))+kind+data+struct.pack('>I',zlib.crc32(kind+data)&0xffffffff)
raw=b''.join(b'\0'+bytes(pixels[y*width*4:(y+1)*width*4])for y in range(height))
return b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',width,height,8,6,0,0,0))+chunk(b'IDAT',zlib.compress(raw,9))+chunk(b'IEND',b'')
def assets():
width,height=81,9*21;pixels=bytearray(width*height*4)
outline=(71,69,46,255);empty=(24,45,43,255);water=(75,168,174,255);light=(154,218,210,255)
shape=['...#...','..###..','.#####.','#######','#######','#######','.#####.','..###..']
for step in range(21):
def put(x,y,rgba):pixels[((step*9+y)*width+x)*4:((step*9+y)*width+x)*4+4]=bytes(rgba)
# A muted gold baseline fixes the exact bitmap advance at 82px on Java.
for x in range(width):put(x,8,(103,91,53,255))
for icon in range(10):
half=max(0,min(2,step-icon*2))
for y,line in enumerate(shape):
for x,c in enumerate(line):
if c!='#':continue
edge=y==0 or x==0 or x==6 or (y>0 and shape[y-1][x]!='#') or (y<7 and shape[y+1][x]!='#') or (x>0 and line[x-1]!='#') or (x<6 and line[x+1]!='#')
color=outline if edge else (water if half==2 or half==1 and y>=4 else empty)
if not edge and half==2 and x==2 and y in [2,3]:color=light
put(1+icon*8+x,y,color)
sprite=png(width,height,pixels)
providers=[{'type':'space','advances':{'\ue7f0':10,'\ue7f1':-92,'\ue7f2':0}}]
for base,ascent in [(0xE800,-16),(0xE820,-6)]:
providers.append({'type':'bitmap','file':'dunerealms:gui/hydration.png','height':9,'ascent':ascent,'chars':[chr(base+n)for n in range(21)]})
java={'assets/dunerealms/font/hydration.json':encoded({'providers':providers}),'assets/dunerealms/textures/gui/hydration.png':sprite}
ui={'namespace':'hud','hud_actionbar_text':{'$dr_text':"(($actionbar_text - '§r') - '§f')",'visible':"(($dr_text - 'DRHYD:') = $dr_text)"}}
controls=[]
for air in [False,True]:
for step in range(21):
token='DRHYD:'+str(step)+(':air'if air else'')
controls.append({'water_'+str(step)+('_air'if air else''):{'type':'image','texture':'textures/ui/dunerealms_hydration','size':[81,9],'uv':[0,step*9],'uv_size':[81,9],'layer':32,'offset':[0,-10 if air else 0],'$dr_text':"(($actionbar_text - '§r') - '§f')",'visible':"($dr_text = '"+token+"')"}})
ui['dunerealms_hydration']={'type':'panel','size':[81,9],'controls':controls,'alpha':'@hud.anim_actionbar_text_alpha_out'}
import copy
ui['dunerealms_hydration_pocket_display']=copy.deepcopy(ui['dunerealms_hydration'])
for control in ui['dunerealms_hydration_pocket_display']['controls']:
next(iter(control.values()))['offset']=[0,0]
for kind,parent,offset,anchor in [('classic','centered_gui_elements_at_bottom_middle',[99,-50],'bottom_left'),('classic_touch','centered_gui_elements_at_bottom_middle_touch',[119,-50],'bottom_left'),('pocket','not_centered_gui_elements',[-83,2],'top_right')]:
name='dunerealms_hydration_'+kind
template='dunerealms_hydration_pocket_display'if kind=='pocket'else'dunerealms_hydration'
ui[name]={'type':'panel','size':[81,9],'anchor_from':anchor,'anchor_to':'top_left','offset':offset,'factory':{'name':'hud_actionbar_text_factory','control_ids':{'hud_actionbar_text':'hud_actionbar_text@hud.'+template}}}
ui[parent]={'modifications':[{'array_name':'controls','operation':'insert_front','value':[{name+'@hud.'+name:{}}]}]}
# Pocket hunger starts at the top edge: reserve one row above it for hydration.
ui['not_centered_gui_elements/hunger_rend']={'offset':[-2,12]}
ui['not_centered_gui_elements/bubbles_rend_0']={'offset':[-1,22]}
ui['not_centered_gui_elements/bubbles_rend_1']={'offset':[-1,42]}
bedrock={'ui/hud_screen.json':encoded(ui),'textures/ui/dunerealms_hydration.png':sprite}
packid=str(uuid.uuid5(uuid.NAMESPACE_URL,'https://www.dunerealms.com/packs/hydration-hud/v1'))
module=str(uuid.uuid5(uuid.NAMESPACE_URL,'https://www.dunerealms.com/packs/hydration-hud/v1/resources'))
bedrock['manifest.json']=encoded({'format_version':2,'header':{'name':'DuneRealms Hydration HUD','description':'Dune water droplets above hunger. Classic and Pocket layouts.','uuid':packid,'version':[1,0,0],'min_engine_version':[1,21,0]},'modules':[{'type':'resources','uuid':module,'version':[1,0,0]}]})
return java,bedrock
def archive(entries):
import io
stream=io.BytesIO()
with zipfile.ZipFile(stream,'w',compression=zipfile.ZIP_DEFLATED,compresslevel=9)as z:
for name,data in sorted(entries.items()):
info=zipfile.ZipInfo(name,(2026,1,1,0,0,0));info.compress_type=zipfile.ZIP_DEFLATED;info.create_system=3;info.external_attr=0o100644<<16;z.writestr(info,data)
return stream.getvalue()
def build(output,baseline=None,expected_sha=None):
output=Path(output);output.mkdir(parents=True,exist_ok=True);java,bedrock=assets();proof={}
if baseline:
raw=Path(baseline).read_bytes()
if hashlib.sha256(raw).hexdigest()!=expected_sha:raise ValueError('Unverified Java baseline')
with zipfile.ZipFile(baseline)as z:
if len(z.namelist())!=len(set(z.namelist())):raise ValueError('Duplicate baseline entries')
old={i.filename:z.read(i)for i in z.infolist()if not i.is_dir()}
if set(old)&set(java):raise ValueError('HUD already present')
result=archive(old|java);(output/'network-with-hydration.zip').write_bytes(result)
with zipfile.ZipFile(output/'network-with-hydration.zip')as z:assert all(z.read(n)==b for n,b in old.items())
proof['java']={'sha256':hashlib.sha256(result).hexdigest(),'sha1':hashlib.sha1(result).hexdigest(),'added':sorted(java),'retainedEntries':len(old)}
for name,data in java.items():
p=output/'java'/name;p.parent.mkdir(parents=True,exist_ok=True);p.write_bytes(data)
pack=archive(bedrock);(output/'DuneRealms-Hydration-HUD-v1.mcpack').write_bytes(pack)
proof['bedrock']={'sha256':hashlib.sha256(pack).hexdigest(),'entries':{n:hashlib.sha256(b).hexdigest()for n,b in bedrock.items()}}
(output/'hydration-hud-proof.json').write_bytes(encoded(proof));return proof
if __name__=='__main__':
p=argparse.ArgumentParser(description=__doc__);p.add_argument('output',type=Path);p.add_argument('--baseline',type=Path);p.add_argument('--baseline-sha');a=p.parse_args();print(json.dumps(build(a.output,a.baseline,a.baseline_sha)))

View file

@ -0,0 +1,29 @@
"""Replace only the tested hydration presenter in an already hydrated Core JAR."""
import argparse,hashlib,zipfile
from pathlib import Path
from build_hydration_hud import archive
PREFIX='com/example/dunerealms/'
OLD='59dc487f44227445300e855a37269751b0ec567a60a8bf48e00bddab59b10c96'
NAMES={PREFIX+n for n in ['HydrationProfiles.class','HydrationHud.class','HydrationHud$Output.class']}
def sha(b):return hashlib.sha256(b).hexdigest()
def entries(path):
with zipfile.ZipFile(path)as z:
if len(z.namelist())!=len(set(z.namelist())):raise ValueError('Duplicate archive entry')
return {i.filename:z.read(i)for i in z.infolist()if not i.is_dir()}
def patch(baseline,expected,donor,donor_sha,output):
baseline,donor,output=map(Path,[baseline,donor,output])
if output.resolve()in[baseline.resolve(),donor.resolve()]or output.exists():raise ValueError('New output path required')
if sha(baseline.read_bytes())!=expected or sha(donor.read_bytes())!=donor_sha:raise ValueError('Unverified input')
before,delta=entries(baseline),entries(donor)
if set(delta)!=NAMES:raise ValueError('Unexpected donor scope')
if sha(before.get(PREFIX+'HydrationProfiles.class',b''))!=OLD:raise ValueError('Unexpected existing hydration presenter')
if (NAMES-{PREFIX+'HydrationProfiles.class'})&set(before):raise ValueError('HUD already present')
output.write_bytes(archive(before|delta));after=entries(output)
assert set(after)-set(before)==NAMES-{PREFIX+'HydrationProfiles.class'}
assert {n for n in before if before[n]!=after[n]}=={PREFIX+'HydrationProfiles.class'}
return sha(output.read_bytes())
if __name__=='__main__':
p=argparse.ArgumentParser(description=__doc__)
for name in ['baseline','baseline_sha','donor','donor_sha','output']:p.add_argument(name)
a=p.parse_args();print(patch(a.baseline,a.baseline_sha,a.donor,a.donor_sha,a.output))

View file

@ -0,0 +1,32 @@
import io,json,struct,tempfile,unittest,zipfile,zlib
from pathlib import Path
from build_hydration_hud import assets,build,archive
class HydrationHudTest(unittest.TestCase):
def test_java_geometry_is_exact_and_default_assets_are_not_overridden(self):
java,bedrock=assets();self.assertEqual(len(java),2)
font=json.loads(java['assets/dunerealms/font/hydration.json']);spaces=font['providers'][0]['advances']
self.assertEqual(spaces['\ue7f0']+82+spaces['\ue7f1'],0)
self.assertEqual([x['ascent']for x in font['providers'][1:]],[-16,-6])
for provider in font['providers'][1:]:self.assertEqual(len(provider['chars']),21);self.assertEqual(provider['height'],9)
raw=java['assets/dunerealms/textures/gui/hydration.png'];self.assertEqual(struct.unpack('>II',raw[16:24]),(81,189))
self.assertEqual(raw,bedrock['textures/ui/dunerealms_hydration.png'])
def test_bedrock_uses_native_factories_and_leaves_existing_actionbars_available(self):
_,bedrock=assets();ui=json.loads(bedrock['ui/hud_screen.json'])
self.assertNotIn('root_panel',ui);self.assertNotIn('hud_actionbar_text_factory',ui)
self.assertEqual(len(ui['dunerealms_hydration']['controls']),42)
for kind in ['classic','classic_touch','pocket']:
self.assertEqual(ui['dunerealms_hydration_'+kind]['factory']['name'],'hud_actionbar_text_factory')
self.assertTrue(ui['dunerealms_hydration_'+kind]['factory']['control_ids']['hud_actionbar_text'].startswith('hud_actionbar_text@hud.'))
self.assertEqual(ui['dunerealms_hydration_classic_touch']['offset'][0]-ui['dunerealms_hydration_classic']['offset'][0],20)
for control in ui['dunerealms_hydration_pocket_display']['controls']:self.assertEqual(next(iter(control.values()))['offset'],[0,0])
self.assertIn("DRHYD:",ui['hud_actionbar_text']['visible'])
self.assertEqual(ui['not_centered_gui_elements/hunger_rend']['offset'],[-2,12])
def test_additive_pack_keeps_every_old_byte_and_rejects_bad_baselines(self):
import hashlib
with tempfile.TemporaryDirectory()as tmp:
root=Path(tmp);base=root/'base.zip';base.write_bytes(archive({'pack.mcmeta':b'{"pack":{}}','old/file.bin':b'keep me'}));digest=hashlib.sha256(base.read_bytes()).hexdigest()
proof=build(root/'out',base,digest);self.assertEqual(proof['java']['retainedEntries'],2)
with zipfile.ZipFile(root/'out/network-with-hydration.zip')as z:self.assertEqual(z.read('old/file.bin'),b'keep me')
with self.assertRaises(ValueError):build(root/'bad',base,'0'*64)
if __name__=='__main__':unittest.main()