from __future__ import annotations import argparse, json, math, shutil, struct, subprocess, sys, tempfile, zipfile from pathlib import Path APP_NAME = "DD Beekeeper Class Vita Patcher" VERSION = "1.0.0" TITLE_ID = "PCSE00919" TRANSLATIONS_FILE = Path(__file__).with_name("translations.json") def load_translations(): if not TRANSLATIONS_FILE.exists(): return {} return json.loads(TRANSLATIONS_FILE.read_text(encoding="utf-8")) def log(msg): print(msg, flush=True) def run(cmd, cwd=None): log("> " + " ".join(f'"{x}"' if " " in str(x) else str(x) for x in cmd)) cp = subprocess.run([str(x) for x in cmd], cwd=cwd, text=True, capture_output=True) if cp.stdout.strip(): print(cp.stdout.rstrip()) if cp.returncode != 0: if cp.stderr.strip(): print(cp.stderr.rstrip(), file=sys.stderr) raise RuntimeError(f"Command failed ({cp.returncode}): {cmd[0]}") return cp def build_extract_command(tool:Path, archive:Path, destination:Path): return [tool, "extract", "-y", archive, f"--to={destination}"] def build_create_command(tool:Path, output:Path, filelist:Path): return [tool, "create", "-y", "-C", "-R", "--level=9", f"-I{filelist}", f"-o{output}"] def nearest_pow2_half(v:int)->int: x=max(1.0,v/2.0) return max(4,min(1024,int(2 ** round(math.log(x,2))))) def compression_for(rel:Path)->str: s=rel.as_posix().lower() if ".ability." in s or "portrait_roster" in s or "/icons_equip/" in "/"+s or "/raid/camping/skill_icons/" in "/"+s: return "DXT1" return "DXT5" def parse_gxt(path:Path): b=path.read_bytes() if len(b)<64 or b[:4]!=b"GXT\x00": raise RuntimeError(f"Invalid GXT: {path}") _,_,_,_,_,fmt,wh,_=struct.unpack_from(">16)&0xffff} def resolve_mod(source:Path, tmp:Path)->Path: if source.is_dir(): candidates=[source, source/"beekeeper_class", source/"_class"] for c in candidates: if (c/"heroes"/"beekeeper").exists(): return c raise RuntimeError("Could not find heroes/beekeeper inside the selected mod folder.") if source.suffix.lower()==".zip": dst=tmp/"mod" with zipfile.ZipFile(source) as z: z.extractall(dst) hits=list(dst.rglob("heroes/beekeeper")) if not hits: raise RuntimeError("ZIP does not contain heroes/beekeeper.") return hits[0].parents[1] raise RuntimeError("Mod input must be a folder or ZIP.") def loc2_to_loc(src:Path,dst:Path,text_map:dict[str,str]|None=None): b=src.read_bytes() if len(b)<4200: raise RuntimeError(f"LOC2 too small: {src.name}") h1,h2,h3=struct.unpack_from("=n or idx+cnt>n): raise RuntimeError(f"Invalid LOC2 index: {src.name}") # Descriptors point to NUL-terminated UTF-8 strings. Rebuild the blob so # translations can change byte length without touching the hash/index table. old_blob=b[h3:] new_blob=bytearray() new_desc=bytearray() text_map=text_map or {} for i in range(n): old_off,old_len,flags=struct.unpack_from(" {tw}x{th} {comp}") finally: shutil.rmtree(temp,ignore_errors=True) def overlay_mod(stage:Path,mod:Path): # Vita loads a custom class from the content root, not dlc/. # The PC FMOD payload is intentionally excluded: hero_beekeeper.bank is # Vorbis/FSB5 and is not compatible with the Vita FADPCM bank format. for item in mod.iterdir(): name=item.name.lower() if name.startswith("preview_icon.") or name in {"project.xml","modfiles.txt","audio"}: continue dst=stage/item.name if item.is_dir(): shutil.copytree(item,dst,dirs_exist_ok=True) else: shutil.copy2(item,dst) # known typo in original distribution bad=stage/"upgrades"/"heores"/"beekeeper.upgrades.json" good=stage/"upgrades"/"heroes"/"beekeeper.upgrades.json" if bad.exists(): good.parent.mkdir(parents=True,exist_ok=True); shutil.move(str(bad),str(good)) try: bad.parent.rmdir() except OSError: pass def prepare_localization(stage:Path,mod:Path): loc=stage/"localization"; loc.mkdir(exist_ok=True) # remove Beekeeper loc2 from active Vita content, replace with legacy .loc for p in loc.glob("*beekeeper*.loc2"): p.unlink() for p in loc.glob("2634437056_*.loc2"): p.unlink() srcdir=mod/"localization" translations=load_translations() for p in sorted(srcdir.glob("2634437056_*.loc2")): lang=p.stem.split("_",1)[1] text_map=translations.get(lang,{}) loc2_to_loc(p,loc/f"beekeeper_{lang}.loc",text_map) if text_map: log(f"Localization [{lang}]: applied {len(text_map)} translated strings.") log(f"Localization: generated {len(list(loc.glob('beekeeper_*.loc')))} Vita .loc files.") def prepare_audio_output(mod:Path,outroot:Path): # Disabled until a native Vita-compatible Beekeeper bank exists. Exporting # the original PC bank causes the Vita build to consume an incompatible # FSB5/Vorbis bank. Keep this explicit so the stable no-audio behavior is testable. bank=mod/"audio"/"secondary_banks"/"hero_beekeeper.bank" if bank.exists(): log("Skipping incompatible PC hero_beekeeper.bank; custom audio is disabled for this build.") else: log("No Beekeeper audio bank found; custom audio remains disabled.") def build_arg_parser(): ap=argparse.ArgumentParser(description=APP_NAME) ap.add_argument("--psarc",required=True,type=Path,help="Original Vita content_patch_13.psarc") ap.add_argument("--mod",required=True,type=Path,help="Original Beekeeper mod ZIP or folder") ap.add_argument("--output",type=Path,default=Path("output"),help="Output directory") ap.add_argument("--tools",type=Path,default=Path("tools"),help="Folder containing psp2psarc.exe and psp2gxt.exe") ap.add_argument("--force-stagecoach",action="store_true",help="DEBUG: force Beekeeper as the Stage Coach class pool (OFF by default)") ap.add_argument("--keep-work",action="store_true") return ap def main(argv=None): args=build_arg_parser().parse_args(argv) psarc=args.psarc.resolve(); modsrc=args.mod.resolve(); tools=args.tools.resolve(); output=args.output.resolve() psarc_tool=tools/"psp2psarc.exe"; gxt_tool=tools/"psp2gxt.exe" for p in (psarc,psarc_tool,gxt_tool): if not p.exists(): raise SystemExit(f"Missing required file: {p}") try: import PIL except ImportError: raise SystemExit("Pillow is required: py -m pip install Pillow") work=Path(tempfile.mkdtemp(prefix="ddbeekeepervita_")) try: mod=resolve_mod(modsrc,work) modwork=work/"beekeeper_class" shutil.copytree(mod,modwork) log(f"{APP_NAME} {VERSION}") log(f"Mod: {mod}") run([psarc_tool,"verify",psarc]) stage=work/"content" stage.mkdir() run(build_extract_command(psarc_tool,psarc,stage)) convert_textures(modwork,gxt_tool) overlay_mod(stage,modwork) prepare_localization(stage,modwork) # Do not load the PC campaign load-order file inside PSARC. for p in [stage/"audio"/"beekeeper.campaign.load_order.json"]: if p.exists(): p.unlink() if args.force_stagecoach: force_stagecoach(stage) update_manifest(stage) filelist=work/"files.txt" filelist.write_text("\n".join(sorted(p.relative_to(stage).as_posix() for p in stage.rglob("*") if p.is_file()))+"\n",encoding="ascii") repatch=output/"rePatch"; target=repatch/TITLE_ID target.mkdir(parents=True,exist_ok=True) outpsarc=target/"content_patch_13.psarc" run(build_create_command(psarc_tool,outpsarc,filelist),cwd=stage) run([psarc_tool,"verify",outpsarc]) prepare_audio_output(modwork,repatch) meta={ "tool":APP_NAME,"version":VERSION,"title_id":TITLE_ID, "force_stagecoach":bool(args.force_stagecoach), "source_psarc":psarc.name,"source_mod":modsrc.name } (output/"patch_report.json").write_text(json.dumps(meta,indent=2),encoding="utf-8") log(f"\nDONE\nCopy this folder to ux0:/\n{repatch}") finally: if args.keep_work: log(f"Work directory kept: {work}") else: shutil.rmtree(work,ignore_errors=True) if __name__=="__main__": main()