Publish verified live restoration source snapshot and known limits

This commit is contained in:
0xcjy
2026-10-01 19:42:22 +08:00
parent 0dd0d3bdaa
commit d70a65c7ce
896 changed files with 105420 additions and 12745 deletions
-4
View File
@@ -1,4 +0,0 @@
# generated output of the asset tools (meta_plain.db, scan_*.csv, ...)
out/
__pycache__/
*.pyc
+379
View File
@@ -0,0 +1,379 @@
// Copied into Assets/Editor of an isolated project by tools/export_exclusive_models.py.
// Never execute this against the user's open Unity project.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using LibMMD.Model;
using LibMMD.Reader;
using Newtonsoft.Json;
using UnityEditor;
using UnityEditor.SceneManagement;
using UnityEngine;
public static class ExclusiveModelBatch
{
private sealed class Outfit
{
public int id;
public string name;
public string costume;
public string error;
public long bytes;
public int textures;
}
private sealed class State
{
public List<Outfit> outfits = new List<Outfit>();
public DateTime updatedUtc;
}
private static State state;
private static string root;
private static List<Outfit> queue;
private static string statePath;
private static int cursor;
private static int attempted;
private static int batchSize;
private static int readyFrames;
private static int cleanupFrames;
private static int cleanupStartFrame;
private static AsyncOperation cleanupOperation;
private static bool loading;
private static bool done;
private static DateTime started;
private static readonly Regex Body = new Regex(@"^3d/chara/body/bdy(?<id>\d+)_(?<costume>\d{2,3})/pfb_bdy\k<id>_\k<costume>$", RegexOptions.Compiled);
public static void Run()
{
root = Environment.GetEnvironmentVariable("UMA_EXCLUSIVE_OUTPUT");
if (string.IsNullOrEmpty(root)) throw new Exception("UMA_EXCLUSIVE_OUTPUT not set");
Directory.CreateDirectory(root);
statePath = Environment.GetEnvironmentVariable("UMA_EXCLUSIVE_REPORT") ?? throw new Exception("UMA_EXCLUSIVE_REPORT not set");
batchSize = Math.Max(1, int.Parse(Environment.GetEnvironmentVariable("UMA_EXCLUSIVE_BATCH") ?? "30"));
started = DateTime.UtcNow;
SessionState.SetBool("ExclusiveModelBatch.Active", true);
EditorApplication.update -= Tick;
EditorApplication.update += Tick;
EditorSceneManager.OpenScene("Assets/Scenes/Version2.unity");
EditorApplication.isPlaying = true;
Debug.Log("[ExclusiveModelBatch] Entering isolated play mode");
}
[InitializeOnLoadMethod]
private static void Resume()
{
if (!SessionState.GetBool("ExclusiveModelBatch.Active", false)) return;
root = Environment.GetEnvironmentVariable("UMA_EXCLUSIVE_OUTPUT");
if (string.IsNullOrEmpty(root)) return;
statePath = Environment.GetEnvironmentVariable("UMA_EXCLUSIVE_REPORT") ?? throw new Exception("UMA_EXCLUSIVE_REPORT not set");
batchSize = Math.Max(1, int.Parse(Environment.GetEnvironmentVariable("UMA_EXCLUSIVE_BATCH") ?? "30"));
started = DateTime.UtcNow;
EditorApplication.update -= Tick;
EditorApplication.update += Tick;
}
private static void Tick()
{
if (done || !EditorApplication.isPlaying || UmaViewerMain.Instance == null ||
UmaViewerUI.Instance == null || UmaViewerBuilder.Instance == null ||
UmaAssetManager.instance == null || UmaViewerMain.Instance.Characters.Count == 0 ||
UmaViewerBuilder.Instance.ShaderList == null || UmaViewerBuilder.Instance.ShaderList.Count == 0 ||
UmaViewerUI.Instance.ModelSettings == null) return;
if (state == null)
{
if (++readyFrames < 15) return;
Initialize();
return;
}
if (loading) return;
if (cleanupFrames > 0)
{
if (Time.frameCount < cleanupStartFrame + 2) return;
cleanupFrames = 0;
}
if (cleanupFrames == 0 && cleanupOperation == null && attempted > 0)
{
// Destroy from UnloadUma is deferred; never unload the mesh's bundle in that frame.
UmaAssetManager.UnloadAllBundle(true);
cleanupOperation = Resources.UnloadUnusedAssets();
cleanupFrames = -1;
return;
}
if (cleanupOperation != null)
{
if (!cleanupOperation.isDone) return;
cleanupOperation = null;
GC.Collect();
}
if (attempted >= batchSize || cursor >= queue.Count)
{
Finish();
return;
}
var outfit = queue[cursor++];
var chara = UmaViewerMain.Instance.Characters.FirstOrDefault(c => !c.IsMob && c.Id == outfit.id);
if (chara == null) { Fail(outfit, "Character absent from Main.Characters"); return; }
try
{
if (Validate(outfit, false)) return;
string path = $"3d/chara/body/bdy{outfit.id}_{outfit.costume}/pfb_bdy{outfit.id}_{outfit.costume}";
if (!UmaViewerMain.Instance.AbList.TryGetValue(path, out var body) || !File.Exists(body.Path))
{
Fail(outfit, "Dedicated body asset absent on disk: " + path);
return;
}
var list = new List<UmaDatabaseEntry>();
var main = UmaViewerMain.Instance;
string bodyPrefix = $"3d/chara/body/bdy{outfit.id}_{outfit.costume}/";
string headPrefix = $"3d/chara/head/chr{outfit.id}_{outfit.costume}/";
string baseHeadPrefix = $"3d/chara/head/chr{outfit.id}_00/";
string tailPrefix = $"3d/chara/tail/tail{outfit.id}_{outfit.costume}/";
list.AddRange(main.AbChara.Where(e => e.Name.StartsWith(bodyPrefix, StringComparison.Ordinal) ||
e.Name.StartsWith(headPrefix, StringComparison.Ordinal) ||
e.Name.StartsWith(baseHeadPrefix, StringComparison.Ordinal) ||
e.Name.StartsWith(tailPrefix, StringComparison.Ordinal)));
// The ordinary fallback tail may be shared with many characters; include its bundles too.
int tailId = Convert.ToInt32(UmaDatabaseController.ReadCharaData(chara)["tail_model_id"]);
if (tailId > 0)
{
string fallback = $"3d/chara/tail/tail{tailId:0000}_00/";
list.AddRange(main.AbChara.Where(e => e.Name.StartsWith(fallback, StringComparison.Ordinal)));
}
list.Add(main.AbList["3d/animator/drivenkeylocator"]);
attempted++;
loading = true;
UmaViewerUI.Instance.ModelSettings.SetHeadFix(false);
UmaViewerUI.Instance.ModelSettings.SetTPose(true);
UmaAssetManager.PreLoadAndRun(list, () =>
{
try
{
// LoadUma is synchronous up to its yield break, as in the existing UI callsite.
var routine = UmaViewerBuilder.Instance.LoadUma(chara, outfit.costume, false);
while (routine.MoveNext()) { }
var container = UmaViewerBuilder.Instance.CurrentUMAContainer;
if (container == null || container.Body == null || container.Head == null ||
container.CharaEntry != chara || container.IsGeneric)
throw new Exception("Builder did not construct a complete exclusive model");
string dir = OutfitDirectory(outfit);
// Drop an interrupted prior attempt entirely: PNG exporter skips filenames already present.
if (Directory.Exists(dir)) Directory.Delete(dir, true);
Directory.CreateDirectory(dir);
ModelExporter.ExportModel(container, Path.Combine(dir, "model.pmx"));
if (!Validate(outfit, true)) throw new Exception("PMX readback or texture verification failed");
outfit.error = null;
Debug.Log($"[ExclusiveModelBatch] PASS {outfit.id}_{outfit.costume} pmxBytes={outfit.bytes} textures={outfit.textures}");
}
catch (Exception ex)
{
Fail(outfit, ex.ToString());
try
{
string partial = OutfitDirectory(outfit);
if (Directory.Exists(partial)) Directory.Delete(partial, true);
}
catch (Exception cleanupError)
{
outfit.error += "\nFailed to remove partial output: " + cleanupError;
}
}
finally
{
try
{
UmaViewerBuilder.Instance.UnloadUma();
UmaViewerBuilder.Instance.CurrentUMAContainer = null;
}
catch (Exception ex) { Debug.LogError("[ExclusiveModelBatch] Cleanup: " + ex); }
// Destroy is deferred until Unity advances its play-mode frame.
cleanupStartFrame = Time.frameCount;
cleanupFrames = 1;
cleanupOperation = null;
loading = false;
Save();
}
});
}
catch (Exception ex) { Fail(outfit, ex.ToString()); loading = false; }
}
private static void Initialize()
{
var main = UmaViewerMain.Instance;
if (File.Exists(statePath)) state = JsonConvert.DeserializeObject<State>(File.ReadAllText(statePath));
if (state == null) state = new State();
var prior = state.outfits.ToDictionary(o => o.id + "_" + o.costume);
var characters = main.Characters.Where(c => !c.IsMob).ToDictionary(c => c.Id);
state.outfits = main.AbList.Keys.Select(key => Body.Match(key))
.Where(match => match.Success)
.Select(match => new { id = int.Parse(match.Groups["id"].Value), costume = match.Groups["costume"].Value })
.Where(x => characters.ContainsKey(x.id))
.GroupBy(x => x.id + "_" + x.costume).Select(group => group.First())
.OrderBy(x => x.id).ThenBy(x => x.costume)
.Select(x => prior.TryGetValue(x.id + "_" + x.costume, out var old)
? new Outfit { id = x.id, name = characters[x.id].Name, costume = x.costume, bytes = old.bytes, textures = old.textures, error = old.error }
: new Outfit { id = x.id, name = characters[x.id].Name, costume = x.costume })
.ToList();
foreach (var outfit in state.outfits.Where(o => o.bytes > 0))
{
long expected = outfit.bytes;
string pmx = Path.Combine(OutfitDirectory(outfit), "model.pmx");
if (!Validate(outfit, false) || outfit.bytes != expected || new FileInfo(pmx).Length != expected)
{
outfit.bytes = 0;
outfit.error = null;
}
}
string requested = Environment.GetEnvironmentVariable("UMA_EXCLUSIVE_RETRY_IDS") ?? "";
var retryIds = new HashSet<string>(requested.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries));
queue = state.outfits.Where(o => o.bytes == 0 &&
(o.error == null || retryIds.Contains(o.id + "_" + o.costume))).ToList();
string only = Environment.GetEnvironmentVariable("UMA_EXCLUSIVE_ONLY");
if (!string.IsNullOrEmpty(only))
{
var targetIds = new HashSet<string>(only.Split(','));
queue = queue.Where(o => targetIds.Contains(o.id + "_" + o.costume)).ToList();
}
// Missing local bundles are reportable candidates, never silently omitted from the asset/master intersection.
Debug.Log($"[ExclusiveModelBatch] DISCOVER characters={main.Characters.Count} exclusiveOutfits={state.outfits.Count} pending={queue.Count} batch={batchSize}");
Save();
}
private static string OutfitDirectory(Outfit outfit) => Path.Combine(root, "models", outfit.id.ToString(), outfit.costume);
private static bool Validate(Outfit outfit, bool strict)
{
string dir = OutfitDirectory(outfit);
string path = Path.Combine(dir, "model.pmx");
if (!File.Exists(path)) return false;
try
{
var pmx = new PMXReader().Read(path, new ModelConfig { GlobalToonPath = "Toon" });
if (pmx.Vertices == null || pmx.Vertices.Length == 0 || pmx.Parts == null || pmx.Parts.Length == 0 ||
pmx.Bones == null || pmx.Bones.Length == 0 || pmx.TextureList.Count == 0)
throw new Exception("PMX has empty geometry, bones, or texture table");
if (pmx.TriangleIndexes == null || pmx.TriangleIndexes.Length == 0 ||
pmx.Parts.Sum(part => part.TriangleIndexNum) != pmx.TriangleIndexes.Length)
throw new Exception("PMX material groups do not cover all triangle indices");
foreach (int index in pmx.TriangleIndexes)
if (index < 0 || index >= pmx.Vertices.Length)
throw new Exception("PMX triangle references an invalid vertex " + index);
foreach (var part in pmx.Parts)
if (part.TriangleIndexNum < 0 || part.TriangleIndexNum % 3 != 0 ||
part.Material == null || part.Material.Texture == null ||
!pmx.TextureList.Contains(part.Material.Texture))
throw new Exception("PMX has invalid material coverage or texture reference");
foreach (var vertex in pmx.Vertices)
{
if (!Finite(vertex.Coordinate.x) || !Finite(vertex.Coordinate.y) || !Finite(vertex.Coordinate.z) ||
!Finite(vertex.Normal.x) || !Finite(vertex.Normal.y) || !Finite(vertex.Normal.z) ||
!Finite(vertex.UvCoordinate.x) || !Finite(vertex.UvCoordinate.y))
throw new Exception("PMX contains non-finite vertex geometry");
ValidateSkinning(vertex.SkinningOperator, pmx.Bones.Length);
}
foreach (var texture in pmx.TextureList)
{
string relative = texture.TexturePath.Replace('\\', '/');
if (!relative.StartsWith("Texture2D/", StringComparison.Ordinal) || relative.Contains("..") ||
!relative.EndsWith(".png", StringComparison.OrdinalIgnoreCase))
throw new Exception("Invalid texture path " + relative);
string texturePath = Path.Combine(dir, relative.Replace('/', Path.DirectorySeparatorChar));
using (var file = File.OpenRead(texturePath))
{
var signature = new byte[8];
if (file.Length < 32 || file.Read(signature, 0, 8) != 8 ||
!signature.SequenceEqual(new byte[] {137, 80, 78, 71, 13, 10, 26, 10}))
throw new Exception("Missing/corrupt PNG " + relative);
}
}
outfit.bytes = new FileInfo(path).Length;
outfit.textures = pmx.TextureList.Count;
outfit.error = null;
return true;
}
catch (Exception ex)
{
if (strict) throw;
outfit.error = "Existing output invalid; re-export: " + ex.Message;
return false;
}
}
private static bool Finite(float value) => !float.IsNaN(value) && !float.IsInfinity(value);
private static void ValidateInfluence(int bone, float weight, int boneCount)
{
if (!Finite(weight) || weight < 0 || weight > 1 ||
(weight > 0 && (bone < 0 || bone >= boneCount)))
throw new Exception($"PMX has invalid bone influence bone={bone} weight={weight}");
}
private static void ValidateSkinning(SkinningOperator skin, int boneCount)
{
if (skin == null) throw new Exception("PMX vertex lacks bone skinning");
switch (skin.Type)
{
case SkinningOperator.SkinningType.SkinningBdef1:
ValidateInfluence(((SkinningOperator.Bdef1)skin.Param).BoneId, 1, boneCount);
break;
case SkinningOperator.SkinningType.SkinningBdef2:
var two = (SkinningOperator.Bdef2)skin.Param;
ValidateInfluence(two.BoneId[0], two.BoneWeight, boneCount);
ValidateInfluence(two.BoneId[1], 1 - two.BoneWeight, boneCount);
break;
case SkinningOperator.SkinningType.SkinningBdef4:
var four = (SkinningOperator.Bdef4)skin.Param;
float total = 0;
for (int i = 0; i < 4; i++)
{
ValidateInfluence(four.BoneId[i], four.BoneWeight[i], boneCount);
total += four.BoneWeight[i];
}
if (Math.Abs(total - 1) > 0.001f)
throw new Exception("PMX bone weights do not sum to one: " + total);
break;
case SkinningOperator.SkinningType.SkinningSdef:
var sdef = (SkinningOperator.Sdef)skin.Param;
ValidateInfluence(sdef.BoneId[0], sdef.BoneWeight, boneCount);
ValidateInfluence(sdef.BoneId[1], 1 - sdef.BoneWeight, boneCount);
break;
default:
throw new Exception("PMX vertex has unsupported skinning type " + skin.Type);
}
}
private static void Fail(Outfit outfit, string error)
{
outfit.bytes = 0;
outfit.textures = 0;
outfit.error = error;
Debug.LogError($"[ExclusiveModelBatch] FAIL {outfit.id}_{outfit.costume}: {error}");
Save();
}
private static void Save()
{
state.updatedUtc = DateTime.UtcNow;
string temp = statePath + ".tmp";
File.WriteAllText(temp, JsonConvert.SerializeObject(state, Formatting.Indented));
if (File.Exists(statePath)) File.Replace(temp, statePath, null);
else File.Move(temp, statePath);
}
private static void Finish()
{
done = true;
Save();
int valid = state.outfits.Count(o => o.bytes > 0 && o.error == null);
int failed = state.outfits.Count(o => o.error != null);
Debug.Log($"[ExclusiveModelBatch] DONE total={state.outfits.Count} valid={valid} failures={failed} attempted={attempted} duration={DateTime.UtcNow - started}");
SessionState.SetBool("ExclusiveModelBatch.Active", false);
EditorApplication.update -= Tick;
EditorApplication.Exit(0);
}
}
+54
View File
@@ -0,0 +1,54 @@
// Read-only IL2CPP method pointer lookup against a hash-verified recovered target.
// Accepts RVAs on the command line; outputs exact metadata matches, not guesses.
using System.Reflection;
using System.Security.Cryptography;
using AssetRipper.Primitives;
using LibCpp2IL;
using LibCpp2IL.Metadata;
const string root = @"D:\Projects\UmaTools\UmaViewer-master5\tmp";
var binaryPath = Path.Combine(root, "target-gameassembly-unpacked.dll");
var metadataPath = Path.Combine(root, "global-metadata.runtime.dat");
const string expectedHash = "E273B4F499E4449BBABC361C03C91F260178BF3E687825AA3ABE6E686664569B";
const string expectedMetadataHash = "88A465567FBB7189F00689D0DEC6C741F2BAD0915E123D6CE1415E3261F49D0D";
if (!SHA256.HashData(File.ReadAllBytes(binaryPath)).AsSpan().SequenceEqual(Convert.FromHexString(expectedHash)))
throw new InvalidDataException("Recovered target binary hash mismatch");
if (!SHA256.HashData(File.ReadAllBytes(metadataPath)).AsSpan().SequenceEqual(Convert.FromHexString(expectedMetadataHash)))
throw new InvalidDataException("Recovered target metadata hash mismatch");
var wanted = args.Select(a => Convert.ToUInt64(a.StartsWith("0x", StringComparison.OrdinalIgnoreCase) ? a[2..] : a, 16))
.ToHashSet();
if (wanted.Count == 0)
throw new ArgumentException("Pass one or more hexadecimal RVAs");
// LibCpp2IL emits several pages of initialization messages; keep the report bounded.
var stdout = Console.Out;
LibCpp2IlContext context;
try
{
Console.SetOut(TextWriter.Null);
context = LibCpp2IlMain.LoadFromFileAsContext(binaryPath, metadataPath, UnityVersion.Parse("2022.3.62f3"));
}
finally { Console.SetOut(stdout); }
var metadata = context.Metadata;
var found = new Dictionary<ulong, List<string>>();
for (int i = 0; i < metadata.TypeDefinitionCount; i++)
{
var index = (Il2CppVariableWidthIndex<Il2CppTypeDefinition>)Activator.CreateInstance(
typeof(Il2CppVariableWidthIndex<Il2CppTypeDefinition>),
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
binder: null, args: new object[] { i }, culture: null)!;
var type = metadata.GetTypeDefinitionFromIndex(index);
foreach (var method in type.Methods ?? Array.Empty<Il2CppMethodDefinition>())
{
ulong rva;
try { rva = method.Rva; }
catch { continue; }
if (!wanted.Contains(rva)) continue;
var name = $"{type.Namespace}.{type.Name}.{method.Name}";
if (!found.TryGetValue(rva, out var names)) found[rva] = names = new List<string>();
names.Add(name);
}
}
Console.WriteLine($"verified target SHA256={expectedHash}; metadataVersion={context.Binary.MetadataVersion}");
foreach (ulong rva in wanted.OrderBy(x => x))
Console.WriteLine($"0x{rva:x}: {(found.TryGetValue(rva, out var names) ? string.Join("; ", names) : "<no metadata method pointer>")}");
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<Reference Include="LibCpp2IL" HintPath="C:\Users\Administrator\.nuget\packages\assetripper.libcpp2il\1.0.8\lib\net10.0\LibCpp2IL.dll" Private="true" />
<Reference Include="AssetRipper.Primitives" HintPath="C:\Users\Administrator\.nuget\packages\assetripper.primitives\3.2.0\lib\net9.0\AssetRipper.Primitives.dll" Private="true" />
</ItemGroup>
</Project>
+80
View File
@@ -0,0 +1,80 @@
from pathlib import Path
import pefile, capstone, hashlib, json, re
DLL=Path(r'D:\Projects\UmaTools\UmaViewer-master5\tmp\target-gameassembly-unpacked.dll')
OUT=Path('tmp/flare-collision-static-20260925.txt')
RVAS={
'TryGetCharacterFlareCollisionPaths':0x1a68610,
'TryGetMasterDressData':0x1a68bd0,
'TryResolveNormalHeadModel':0x1a692a0,
'TryReadMasterInt':0x1a691a0,
'TryGetAssetEntryByOfficialPath':0x1a683b0,
'FormatA_19ba670':0x19ba670,
'FormatB_19bac20':0x19bac20,
'FormatC_19bb080':0x19bb080,
'GetLivePreloadEntries':0x1a5be60,
'InitializeCharacterFlareCollision':0x1a5d460,
'AddCharacterFlareCollision':0x1a59100,
}
expected='E273B4F499E4449BBABC361C03C91F260178BF3E687825AA3ABE6E686664569B'
actual=hashlib.sha256(DLL.read_bytes()).hexdigest().upper()
if actual!=expected: raise SystemExit(f'hash mismatch: {actual}')
pe=pefile.PE(str(DLL), fast_load=True)
base=pe.OPTIONAL_HEADER.ImageBase
md=capstone.Cs(capstone.CS_ARCH_X86,capstone.CS_MODE_64); md.detail=True
def va_from_rip(ins):
if ins.disp_size and ins.disp_size==4:
return ins.address+ins.size+ins.disp
def rva_from_va(va): return va-base
def read_at_va(va,n=512):
try:
off=pe.get_offset_from_rva(rva_from_va(va)); return pe.__data__[off:off+n]
except Exception:return b''
def text_at_va(va):
b=read_at_va(va,512)
for enc in ('utf-8','utf-16le'):
try:
s=b.decode(enc,errors='ignore').split('\x00',1)[0]
if len(s)>=4 and sum(c.isprintable() or c in '\\/:._{}-' for c in s)/len(s)>.8:
return enc+':'+s[:240]
except:pass
return ''
def fmt_target(op):
if op.type==capstone.x86.X86_OP_IMM:return f'VA=0x{op.imm:x} RVA=0x{op.imm-base:x}'
return ''
lines=[]
lines.append(f'DLL={DLL}')
lines.append(f'SHA256={actual}')
lines.append(f'ImageBase=0x{base:x}')
lines.append('This report is static only; no runtime behavior is inferred beyond direct instructions.')
for name,rva in RVAS.items():
va=base+rva; off=pe.get_offset_from_rva(rva); data=pe.__data__[off:off+0x1200]
lines.append(f'\n=== {name} RVA=0x{rva:x} VA=0x{va:x} fileoff=0x{off:x} ===')
calls=[]; riprefs=[]; count=0; ret_seen=False
for ins in md.disasm(data,va):
ops=[]
for op in ins.operands:
if op.type==capstone.x86.X86_OP_IMM:
ops.append(fmt_target(op))
elif op.type==capstone.x86.X86_OP_MEM and op.mem.base==capstone.x86.X86_REG_RIP:
t=va_from_rip(ins); riprefs.append(t)
tx=text_at_va(t)
ops.append(f'RIPVA=0x{t:x}'+((' '+tx) if tx else ''))
line=f'{ins.address:016x}: {ins.mnemonic:8s} {ins.op_str}'
if ops: line += ' ; ' + ' | '.join(ops)
lines.append(line)
if ins.mnemonic=='call' and ins.operands and ins.operands[0].type==capstone.x86.X86_OP_IMM:
calls.append(ins.operands[0].imm)
count+=1
if ins.mnemonic=='ret':
ret_seen=True; break
if count>500: break
lines.append(f'-- instructions={count} ret_seen={ret_seen}')
lines.append('-- direct calls: '+', '.join(f'0x{x:x}(rva 0x{x-base:x})' for x in dict.fromkeys(calls)))
lines.append('-- rip refs: '+', '.join(f'0x{x:x}(rva 0x{x-base:x})'+((' '+text_at_va(x)) if text_at_va(x) else '') for x in dict.fromkeys(riprefs)))
OUT.write_text('\n'.join(lines),encoding='utf-8')
print(OUT)
+50
View File
@@ -0,0 +1,50 @@
"""Compare exported game keys with Live logs; only non-interpolated intervals.
Input: live1176-effect-source.json exported from the local game asset typetree.
This checks parameter provenance, not target-viewer evaluation or pixel parity.
"""
import argparse
import json
from pathlib import Path
FIELDS = {"bloomThreshold": "threshold", "bloomIntensity": "intensity",
"bloomBlurSize": "BloomBlurSize", "bloomDofWeight": "bloomDofWeight",
"diffusionBright": "diffusionBright", "diffusionThreshold": "diffusionThreshold",
"diffusionBlurSize": "diffusionBlurSize", "diffusionSaturation": "diffusionSaturation",
"diffusionContrast": "diffusionContrast"}
def compare(source, records, song):
keys = source[0]["tracks"]["postEffectBloomDiffusionKeys"]["thisList"]
results = []
for r in records:
if r.get("type") != "live_frame" or r.get("songId") != song:
continue
# Old logs serialize absent diagnostic floats as zero: do not claim coverage.
if not r.get("bloomIntensity") or any(f not in r for f in FIELDS):
continue
frame = r.get("seconds", -1) * 60
before = [k for k in keys if k["frame"] <= frame]
after = [k for k in keys if k["frame"] > frame]
# Interpolation is selected by the NEXT key. Curves require Unity evaluation.
if frame < 0 or not before or (after and after[0]["interpolateType"] != 0):
continue
key = before[-1]
mismatches = {f: {"actual": r[f], "source": key[k]} for f, k in FIELDS.items()
if abs(r[f] - key[k]) > 0.0001}
results.append({"frame": r.get("liveFrame"), "sourceKey": key["frame"],
"mismatches": mismatches})
return results
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("source", type=Path)
parser.add_argument("logs", type=Path, nargs="+")
parser.add_argument("--song", type=int, default=1176)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
source = json.loads(args.source.read_text(encoding="utf-8-sig"))
result = []
for path in args.logs:
records = [json.loads(line) for line in path.read_text(encoding="utf-8-sig").splitlines() if line.strip()]
result.extend(dict(log=path.name, **r) for r in compare(source, records, args.song))
args.output.write_text(json.dumps(result, indent=2), encoding="utf-8")
print(f"Compared {len(result)} held-key snapshots; mismatching: {sum(bool(r['mismatches']) for r in result)}")
+35
View File
@@ -0,0 +1,35 @@
param([string]$Editor = "C:/Program Files/Unity/Hub/Editor/2022.3.62f1/Editor")
$root = Split-Path $PSScriptRoot -Parent
Push-Location $root
try {
$response = Get-ChildItem Library/Bee/artifacts -Filter umamusume.rsp -Recurse |
Sort-Object LastWriteTime -Descending | Select-Object -First 1
if (!$response) { throw "Open the project once in Unity to generate the compiler response file." }
$lines = Get-Content $response.FullName
$known = @{}
foreach ($line in $lines) { $known[$line.Trim('"').Replace('\', '/')] = $true }
$extra = Get-ChildItem Assets/Scripts/umamusume -Recurse -Filter *.cs | ForEach-Object {
$relative = $_.FullName.Substring($root.Length+1).Replace('\', '/')
if (!$known.ContainsKey($relative)) {
# Respect nested Unity assembly boundaries (including disabled legacy code).
$directory = $_.Directory
$nestedAssembly = $false
while ($directory.FullName -ne (Join-Path $root "Assets/Scripts/umamusume")) {
if (@(Get-ChildItem -LiteralPath $directory.FullName -Filter *.asmdef).Count -gt 0 -or
@(Get-ChildItem -LiteralPath $directory.FullName -Filter *.asmref).Count -gt 0) {
$nestedAssembly = $true
break
}
$directory = $directory.Parent
if ($null -eq $directory) { throw "Source outside assembly root: $relative" }
}
if (!$nestedAssembly) { $relative }
}
}
$output = Join-Path $root "tmp/live-validation-compile"
New-Item -ItemType Directory -Force $output | Out-Null
& "$Editor/Data/NetCoreRuntime/dotnet.exe" exec "$Editor/Data/DotNetSdkRoslyn/csc.dll" /nostdlib /noconfig "@$($response.FullName)" $extra "/out:$output/umamusume.dll" "/refout:$output/umamusume.ref.dll" 2>&1 |
Tee-Object "$output/compile.log"
if ($LASTEXITCODE -ne 0) { throw "Compilation failed: $output/compile.log" }
} finally { Pop-Location }
-158
View File
@@ -1,158 +0,0 @@
#!/usr/bin/env python3
"""Decrypt any game asset bundle and inspect it with UnityPy.
Given an asset path from the meta DB (e.g. ``3d/effect/live/pfb_eff_live1157``)
this locates the hashed file under ``dat/``, undoes the XOR cipher and hands
the result to UnityPy.
Usage
-----
PY=~/.venvs/umatools/bin/python
# list every object in the bundle
$PY tools/dump_bundle.py list 3d/env/live/live1014/pfb_env_live1014_controller000
# object names of one type only
$PY tools/dump_bundle.py list cutt/cutt_son1157/type_01 --type MonoBehaviour
# TypeTree schema of an object (by path_id, or the first of a type)
$PY tools/dump_bundle.py tree cutt/cutt_son1157/type_01 --type MonoBehaviour --depth 2
# deserialized object as JSON
$PY tools/dump_bundle.py json cutt/cutt_son1157/type_01 -o /tmp/ws.json
# write the decrypted bundle itself (loadable by UnityPy/AssetStudio)
$PY tools/dump_bundle.py save cutt/cutt_son1157/type_01 -o /tmp/type_01.unity3d
# game object hierarchy of a prefab bundle
$PY tools/dump_bundle.py gameobjects 3d/env/live/live1014/pfb_env_live1014_controller000
``--deps`` also loads the bundle's prerequisites, which is needed when an
object references assets living in another bundle.
"""
from __future__ import annotations
import argparse
import json
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import uma_common as uc # noqa: E402
def pick(env, args):
"""Objects selected by --type / --path-id, in file order."""
objs = list(env.objects)
if args.path_id is not None:
objs = [o for o in objs if o.path_id == args.path_id]
if args.type:
objs = [o for o in objs if o.type.name.lower() == args.type.lower()]
return objs
def obj_name(obj) -> str:
try:
d = obj.read_typetree()
return d.get("m_Name") or ""
except Exception:
return ""
def node_lines(node, depth=0, max_depth=99):
yield "%s%-46s %s" % (" " * depth, node.m_Type, node.m_Name)
if depth >= max_depth:
return
for ch in getattr(node, "m_Children", []) or []:
yield from node_lines(ch, depth + 1, max_depth)
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("cmd", choices=("list", "tree", "json", "save", "gameobjects"))
ap.add_argument("name", help="asset path as stored in the meta DB")
ap.add_argument("--type", default=None, help="filter by Unity class name (MonoBehaviour, Material, ...)")
ap.add_argument("--path-id", type=int, default=None)
ap.add_argument("--depth", type=int, default=99, help="depth limit for `tree`")
ap.add_argument("--deps", action="store_true", help="also load the bundle's dependencies")
ap.add_argument("-o", "--output", default=None)
uc.add_common_args(ap)
args = ap.parse_args(argv)
uc.require("apsw-sqlite3mc", "UnityPy")
with uc.MetaDb(args.game_path, args.region) as db:
entry = db.get(args.name)
if entry is None:
print("no meta entry named %s" % args.name, file=sys.stderr)
return 1
if args.cmd == "save":
out = args.output or (os.path.basename(entry.name) + ".unity3d")
with open(out, "wb") as fh:
fh.write(db.bundle_bytes(entry))
print("wrote %s (%d bytes, key=%d)" % (out, os.path.getsize(out), entry.key))
return 0
env = db.load(entry, with_deps=args.deps)
if args.cmd == "list":
counts: dict[str, int] = {}
for o in pick(env, args):
counts[o.type.name] = counts.get(o.type.name, 0) + 1
print("%-22s %-22d %s" % (o.type.name, o.path_id, obj_name(o)))
print("-- " + ", ".join("%s=%d" % kv for kv in sorted(counts.items())), file=sys.stderr)
return 0
if args.cmd == "gameobjects":
for o in env.objects:
if o.type.name != "GameObject":
continue
try:
d = o.read_typetree()
except Exception:
continue
print("%-22d %-40s active=%s components=%d" % (
o.path_id, d.get("m_Name", ""), d.get("m_IsActive"), len(d.get("m_Component", []))))
return 0
objs = pick(env, args)
if not objs:
print("no matching object", file=sys.stderr)
return 1
if args.cmd == "tree":
for o in objs:
node = getattr(getattr(o, "serialized_type", None), "node", None)
print("=" * 90)
print("%s path_id=%d %s" % (o.type.name, o.path_id, obj_name(o)))
print("=" * 90)
if node is None:
print(" (bundle carries no TypeTree for this object)")
continue
for line in node_lines(node, 0, args.depth):
print(line)
return 0
# json
data = []
for o in objs:
try:
data.append(o.read_typetree())
except Exception as exc:
print("skip %s %d: %s" % (o.type.name, o.path_id, exc), file=sys.stderr)
payload = data[0] if len(data) == 1 else data
text = json.dumps(payload, indent=1, ensure_ascii=False, default=str)
if args.output:
with open(args.output, "w", encoding="utf-8") as fh:
fh.write(text)
print("wrote %s (%d object(s))" % (args.output, len(data)))
else:
print(text)
return 0
if __name__ == "__main__":
raise SystemExit(main())
-187
View File
@@ -1,187 +0,0 @@
#!/usr/bin/env python3
"""Dump the real serialized field names of `LiveTimelineWorkSheet` from a
live (cutt) asset bundle, together with how much data each track carries.
Why this exists
---------------
The C# classes in ``Assets/Scripts/umamusume/Gallop/Live/Cutt/`` must declare
fields whose names match the game's serialization *exactly* (case sensitive),
otherwise Unity silently deserializes nothing. The game's cutt bundles ship
with full TypeTrees, so the authoritative names can simply be read back out.
Where the worksheets live
-------------------------
Each song has a bundle group ``cutt/cutt_son<id>/``:
cutt_son<id> prefab bundle (no worksheets)
data LiveTimelineData (no worksheets)
son<id>_camera WorkSheet "son<id>_Camera"
type_01 .. type_10 WorkSheet "Type_01" .. (only on newer songs)
A MonoBehaviour is treated as a worksheet when its TypeTree contains the field
``cameraPosKeys``.
Usage
-----
PY=~/.venvs/umatools/bin/python
# every worksheet of a song: field table with keyframe counts
$PY tools/dump_cutt_typetree.py 1157
# just the schema (field type + name), no bundle data needed
$PY tools/dump_cutt_typetree.py 1157 --fields
# only tracks that actually contain keys, one worksheet
$PY tools/dump_cutt_typetree.py 1157 --sheet Type_01 --nonzero
# nested schema of one track -- this is how you learn the key class fields
$PY tools/dump_cutt_typetree.py 1157 --tree laserList
# first keyframe of a track, as JSON (real values)
$PY tools/dump_cutt_typetree.py 1157 --sample laserList
# whole worksheet as JSON
$PY tools/dump_cutt_typetree.py 1157 --sheet Type_01 --json out.json
# any bundle path also works instead of a song id
$PY tools/dump_cutt_typetree.py cutt/cutt_son1001/son1001_camera
"""
from __future__ import annotations
import argparse
import json
import os
import re
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import uma_common as uc # noqa: E402
def bundles_for(db, target: str) -> list:
"""Resolve a song id or an explicit asset path into meta entries."""
if re.fullmatch(r"\d+", target):
entries = db.like("cutt/cutt_son%s/%%" % target)
if not entries:
raise SystemExit("no cutt bundles for song id %s" % target)
# the prefab/data bundles never hold worksheets - skip them cheaply
return [e for e in entries if not e.name.endswith(("/data", "/cutt_son%s" % target))]
e = db.get(target)
if e is None:
raise SystemExit("no meta entry named %s" % target)
return [e]
def node_lines(node, depth: int = 0, max_depth: int = 99):
yield "%s%-46s %s" % (" " * depth, node.m_Type, node.m_Name)
if depth >= max_depth:
return
for ch in getattr(node, "m_Children", []) or []:
yield from node_lines(ch, depth + 1, max_depth)
def field_nodes(root):
"""The WorkSheet's own fields, minus the four MonoBehaviour base fields."""
skip = {"m_GameObject", "m_Enabled", "m_Script", "m_Name"}
return [ch for ch in root.m_Children if ch.m_Name not in skip]
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("target", help="song id (e.g. 1157) or full asset path")
ap.add_argument("--sheet", default=None, help="only this worksheet (e.g. Type_01, son1157_Camera)")
ap.add_argument("--fields", action="store_true", help="print the schema only, skip deserialization")
ap.add_argument("--nonzero", action="store_true", help="hide tracks with no keyframes")
ap.add_argument("--tree", metavar="FIELD", help="print the nested TypeTree of one field")
ap.add_argument("--tree-depth", type=int, default=99, help="depth limit for --tree")
ap.add_argument("--sample", metavar="FIELD", help="print the first keyframe of one field as JSON")
ap.add_argument("--json", metavar="PATH", help="write the whole worksheet as JSON")
ap.add_argument("--groups", action="store_true", help="also list the group names of each track")
uc.add_common_args(ap)
args = ap.parse_args(argv)
uc.require("apsw-sqlite3mc", "UnityPy")
with uc.MetaDb(args.game_path, args.region) as db:
entries = bundles_for(db, args.target)
found_any = False
for entry in entries:
try:
env = db.load(entry)
except FileNotFoundError as exc:
print("skip %s: %s" % (entry.name, exc), file=sys.stderr)
continue
for name, obj, root in uc.worksheets(env):
if args.sheet and name.lower() != args.sheet.lower():
continue
found_any = True
fields = field_nodes(root)
print("=" * 100)
print("%s (%s) %d fields" % (name, entry.name, len(fields)))
print("=" * 100)
if args.tree:
node = next((f for f in fields if f.m_Name.lower() == args.tree.lower()), None)
if node is None:
print(" no such field: %s" % args.tree)
continue
for line in node_lines(node, 0, args.tree_depth):
print(line)
continue
if args.fields:
for i, f in enumerate(fields):
print("%3d %-50s %s" % (i, f.m_Type, f.m_Name))
continue
tree = obj.read_typetree()
if args.sample:
key = next((f.m_Name for f in fields if f.m_Name.lower() == args.sample.lower()), None)
if key is None:
print(" no such field: %s" % args.sample)
continue
val = tree.get(key)
if isinstance(val, list) and val:
val = val[0]
if isinstance(val, dict) and isinstance(val.get("thisList"), list):
val = dict(val, thisList=val["thisList"][:1])
if isinstance(val, dict) and isinstance(val.get("keys"), dict):
kl = val["keys"]
if isinstance(kl.get("thisList"), list):
val = dict(val, keys=dict(kl, thisList=kl["thisList"][:1]))
print(json.dumps(val, indent=2, ensure_ascii=False, default=str))
continue
if args.json:
with open(args.json, "w", encoding="utf-8") as fh:
json.dump(tree, fh, indent=1, ensure_ascii=False, default=str)
print("wrote %s" % args.json)
continue
print("%3s %-50s %-46s %7s %7s" % ("#", "serialized type", "field name", "groups", "keys"))
print("-" * 100)
total = 0
for i, f in enumerate(fields):
val = tree.get(f.m_Name)
keys = uc.count_keyframes(val)
groups = uc.count_groups(val)
total += keys
if args.nonzero and keys == 0 and groups == 0:
continue
print("%3d %-50s %-46s %7d %7d" % (i, f.m_Type, f.m_Name, groups, keys))
if args.groups:
for gn in uc.group_names(val):
print("%sname: %s" % (" " * 8, gn))
print("-" * 100)
print("total keyframes: %d" % total)
if not found_any:
print("no LiveTimelineWorkSheet found", file=sys.stderr)
return 1
return 0
if __name__ == "__main__":
raise SystemExit(main())
-171
View File
@@ -1,171 +0,0 @@
#!/usr/bin/env python3
"""Decrypt and query the game's `meta` database.
The meta DB maps an asset path (``cutt/cutt_son1157/type_01``) to the hashed
file name under ``dat/`` plus the per-bundle XOR key. It is a SQLite database
encrypted with SQLite3 Multiple Ciphers (ChaCha20); see ``uma_common.py`` for
the key derivation.
Usage
-----
PY=~/.venvs/umatools/bin/python
# write a plaintext copy you can open with any sqlite client
$PY tools/dump_meta.py plain # -> tools/out/meta_plain.db
$PY tools/dump_meta.py plain -o /tmp/meta.db
# search asset paths (SQL LIKE pattern, % is the wildcard)
$PY tools/dump_meta.py find 'cutt/cutt_son1157/%'
$PY tools/dump_meta.py find '%live1014%' --limit 20
# everything known about one asset, including where it lives on disk
$PY tools/dump_meta.py info cutt/cutt_son1157/type_01
# list the live song ids that have cutt bundles
$PY tools/dump_meta.py songs
Table ``a`` columns (see Assets/Scripts/UmaDatabase/UmaDatabaseEntry.cs):
i row id n asset path d ';'-joined dependencies
g ? l length c checksum
h hashed filename m asset type e per-bundle cipher key
"""
from __future__ import annotations
import argparse
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import uma_common as uc # noqa: E402
DEFAULT_OUT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "out")
def cmd_plain(args) -> int:
"""Copy the decrypted meta DB into a plaintext SQLite file.
``sqlite3_backup`` and ``VACUUM INTO`` both refuse / re-encrypt here (the
ChaCha20 codec reserves bytes per page, so source and target page layouts
are incompatible), so the schema and rows are copied explicitly.
"""
uc.require("apsw-sqlite3mc")
import apsw
out = args.output or os.path.join(DEFAULT_OUT_DIR, "meta_plain.db")
os.makedirs(os.path.dirname(os.path.abspath(out)), exist_ok=True)
for suffix in ("", "-journal", "-wal", "-shm"):
if os.path.exists(out + suffix):
os.remove(out + suffix)
with uc.MetaDb(args.game_path, args.region) as db:
dest = apsw.Connection(out)
try:
schema = list(
db.con.execute(
"SELECT type,name,sql FROM sqlite_master "
"WHERE sql IS NOT NULL AND name NOT LIKE 'sqlite\\_%' ESCAPE '\\'"
)
)
tables = [(n, sql) for t, n, sql in schema if t == "table"]
indexes = [(n, sql) for t, n, sql in schema if t == "index"]
total = 0
for name, sql in tables:
dest.execute(sql)
rows = list(db.con.execute('SELECT * FROM "%s"' % name))
if rows:
ph = ",".join("?" * len(rows[0]))
with dest:
dest.executemany('INSERT INTO "%s" VALUES (%s)' % (name, ph), rows)
total += len(rows)
print(" %-16s %8d rows" % (name, len(rows)))
for name, sql in indexes:
try:
dest.execute(sql)
except Exception as exc: # a stale index definition must not kill the dump
print(" index %s skipped (%s)" % (name, exc), file=sys.stderr)
finally:
dest.close()
print("wrote %s (%d rows total, %.1f MB)" % (out, total, os.path.getsize(out) / 1048576.0))
return 0
def cmd_find(args) -> int:
pattern = args.pattern if "%" in args.pattern else "%" + args.pattern + "%"
with uc.MetaDb(args.game_path, args.region) as db:
rows = db.like(pattern)
if args.limit:
rows = rows[: args.limit]
for e in rows:
on_disk = "" if os.path.isfile(e.path(db.game_path)) else " [NOT DOWNLOADED]"
print("%-60s %-34s key=%-22d%s" % (e.name, e.url, e.key, on_disk))
print("-- %d entr%s" % (len(rows), "y" if len(rows) == 1 else "ies"), file=sys.stderr)
return 0
def cmd_info(args) -> int:
with uc.MetaDb(args.game_path, args.region) as db:
e = db.get(args.name)
if e is None:
print("no such asset: %s" % args.name, file=sys.stderr)
return 1
p = e.path(db.game_path)
print("name : %s" % e.name)
print("type : %s" % e.type)
print("hash (url) : %s" % e.url)
print("path : %s%s" % (p, "" if os.path.isfile(p) else " [NOT DOWNLOADED]"))
if os.path.isfile(p):
print("size : %d bytes" % os.path.getsize(p))
print("checksum : %s" % e.checksum)
print("key : %d (%s)" % (e.key, "encrypted" if e.is_encrypted else "plaintext"))
if e.is_encrypted:
print("fkey : %s" % uc.build_fkey(e.key).hex())
deps = e.deps()
print("dependencies : %d" % len(deps))
for d in deps:
print(" %s" % d)
return 0
def cmd_songs(args) -> int:
with uc.MetaDb(args.game_path, args.region) as db:
ids = db.song_ids()
for sid in ids:
entries = db.like("cutt/cutt_son%s/%%" % sid)
missing = sum(0 if os.path.isfile(e.path(db.game_path)) else 1 for e in entries)
print("son%-8s %2d bundles%s" % (sid, len(entries), " (%d missing)" % missing if missing else ""))
print("-- %d songs" % len(ids), file=sys.stderr)
return 0
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
sub = ap.add_subparsers(dest="cmd", required=True)
p = sub.add_parser("plain", help="write a decrypted copy of the meta DB")
p.add_argument("-o", "--output", default=None, help="output path (default: tools/out/meta_plain.db)")
uc.add_common_args(p)
p.set_defaults(func=cmd_plain)
p = sub.add_parser("find", help="search asset paths with a LIKE pattern")
p.add_argument("pattern")
p.add_argument("--limit", type=int, default=0)
uc.add_common_args(p)
p.set_defaults(func=cmd_find)
p = sub.add_parser("info", help="show one asset's meta row and disk location")
p.add_argument("name")
uc.add_common_args(p)
p.set_defaults(func=cmd_info)
p = sub.add_parser("songs", help="list live song ids that have cutt bundles")
uc.add_common_args(p)
p.set_defaults(func=cmd_songs)
args = ap.parse_args(argv)
return args.func(args)
if __name__ == "__main__":
raise SystemExit(main())
+130
View File
@@ -0,0 +1,130 @@
"""Run the project's original PMX exporter in an isolated Unity 2022.3 batch Editor.
Usage: python tools/export_exclusive_models.py [--batch 24] [--once] [--retry-failures]
Checkpoint/report is exports/exclusive-model-report.json; re-launch resumes and validates each PMX.
"""
import argparse
import json
import os
from pathlib import Path
import shutil
import subprocess
import sys
import time
PROJECT = Path(__file__).resolve().parents[1]
SITE = PROJECT.parent / 'UmaAudioSite'
OUTPUT = SITE / 'data' / 'model-viewer'
REPORT = PROJECT / 'exports' / 'exclusive-model-report.json'
ISOLATED = PROJECT / 'tmp' / 'exclusive-model-batch'
UNITY = Path('C:/Program Files/Unity/Hub/Editor/2022.3.62f1/Editor/Unity.exe')
def prepare():
if not UNITY.is_file():
raise FileNotFoundError(UNITY)
if not (ISOLATED / 'Assets' / 'Scenes' / 'Version2.unity').is_file():
ISOLATED.mkdir(parents=True, exist_ok=True)
for name in ('Assets', 'Packages', 'ProjectSettings'):
shutil.copytree(PROJECT / name, ISOLATED / name, dirs_exist_ok=True)
shutil.copy2(PROJECT / 'Config.json', ISOLATED / 'Config.json')
shutil.copy2(PROJECT / 'tools' / 'ExclusiveModelBatch.cs', ISOLATED / 'Assets' / 'Editor' / 'ExclusiveModelBatch.cs')
shutil.copy2(PROJECT / 'Assets' / 'Scripts' / 'Exporters' / 'ModelExporter.cs',
ISOLATED / 'Assets' / 'Scripts' / 'Exporters' / 'ModelExporter.cs')
OUTPUT.mkdir(parents=True, exist_ok=True)
def status():
report = REPORT
if not report.is_file():
return 0, 0, 0, []
outfits = json.loads(report.read_text(encoding='utf-8'))['outfits']
valid = [o for o in outfits if o['bytes'] > 0 and not o.get('error')]
return len(outfits), len(valid), sum(o['bytes'] for o in valid), outfits
def catalog(outfits):
grouped = {}
for o in outfits:
directory = OUTPUT / 'models' / str(o['id']) / o['costume']
if not o.get('bytes') or o.get('error'):
if directory.exists():
shutil.rmtree(directory)
continue
pmx = directory / 'model.pmx'
if not pmx.is_file() or pmx.stat().st_size != o['bytes']:
raise ValueError(f'Catalog candidate changed since Unity readback: {pmx}')
chara = grouped.setdefault(o['id'], {'id': o['id'], 'name': o['name'], 'costumes': []})
chara['costumes'].append({'id': o['costume'], 'model': f"/data/model-viewer/models/{o['id']}/{o['costume']}/model.pmx"})
path = OUTPUT / 'catalog.json'
temporary = path.with_suffix('.json.tmp')
temporary.write_text(json.dumps({'characters': list(grouped.values())}, ensure_ascii=False, indent=2), encoding='utf-8')
temporary.replace(path)
return len(grouped)
def normalized_environment(batch, retry_ids, only=None):
# Unity/UPM on Windows chokes on duplicate case-insensitive keys from mixed runtimes.
env = {}
for key, value in os.environ.items():
env[key.upper()] = value
env['ALLUSERSPROFILE'] = os.environ.get('ALLUSERSPROFILE') or r'C:\ProgramData'
env['UMA_EXCLUSIVE_OUTPUT'] = str(OUTPUT)
env['UMA_EXCLUSIVE_BATCH'] = str(batch)
env['UMA_EXCLUSIVE_REPORT'] = str(REPORT)
env['UMA_EXCLUSIVE_RETRY_IDS'] = ','.join(retry_ids)
env['UMA_EXCLUSIVE_ONLY'] = only or ''
return env
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--batch', type=int, default=24)
parser.add_argument('--once', action='store_true')
parser.add_argument('--retry-failures', action='store_true', help='Reattempt reported failures after triage')
parser.add_argument('--only', help='Comma-separated character_costume IDs for targeted triage')
args = parser.parse_args()
prepare()
before = status()
pending = sum(not o.get('bytes') and not o.get('error') for o in before[3])
if args.retry_failures and pending and not args.only:
raise RuntimeError(f'{pending} outfits have not been attempted; complete ordinary export before retrying failures')
retry_ids = args.only.split(',') if args.only else [f"{o['id']}_{o['costume']}" for o in before[3] if o.get('error')]
before_remaining = pending
cycle = 0
while True:
cycle += 1
log = ISOLATED / f'exclusive-batch-{time.strftime("%Y%m%d-%H%M%S")}-{cycle:03d}.log'
print(f'Launching isolated Unity pass {cycle}, valid {before[1]}/{before[0]}, log={log}', flush=True)
with log.open('wb') as stream:
result = subprocess.run([str(UNITY), '-batchmode', '-projectPath', str(ISOLATED),
'-executeMethod', 'ExclusiveModelBatch.Run', '-logFile', str(log)],
env=normalized_environment(args.batch, retry_ids[:args.batch] if args.retry_failures or args.only else [], args.only), timeout=7200)
after = status()
chara_count = catalog(after[3]) if after[0] else 0
print(f'Unity exit={result.returncode}; available={after[0]} verified={after[1]} '
f'pmxBytes={after[2]} characters={chara_count}; log={log}', flush=True)
if result.returncode or not after[0]:
raise RuntimeError(f'Unity batch did not finish discovery; inspect {log}')
if args.retry_failures or args.only:
retry_ids = retry_ids[args.batch:]
if args.once or not retry_ids:
break
else:
remaining = sum(not o.get('bytes') and not o.get('error') for o in after[3])
if args.once or after[1] == after[0] or not remaining:
break
if remaining >= before_remaining:
raise RuntimeError(f'No checkpoint progress in isolated Unity batch; inspect {log}')
before_remaining = remaining
before = after
failures = [o for o in after[3] if o.get('error')]
print(f'FINAL {after[1]}/{after[0]} verified, {len(failures)} failures; '
f'report={REPORT}', flush=True)
for o in failures:
print(f'FAIL {o["id"]}_{o["costume"]}: {o["error"].splitlines()[0]}', flush=True)
return 0 if not failures else 2
if __name__ == '__main__':
sys.exit(main())
+85
View File
@@ -0,0 +1,85 @@
"""Bounded native call inventory for the already recovered local viewer binary.
Never execute target code. Reads the recovered PE and API address list only.
"""
from __future__ import annotations
import argparse
import collections
import hashlib
import pathlib
import re
import capstone
import pefile
BASE = pathlib.Path(r"D:\Projects\UmaTools\UmaViewer-master5\tmp")
API = BASE / "render-pipeline-api.txt"
PE = BASE / "target-gameassembly-unpacked.dll"
ORIGINAL = pathlib.Path(r"D:\Projects\UmaTools\UmaViewer\GameAssembly.dll")
EXPECTED_ORIGINAL_SHA256 = "d678a0713257af45a6cd499854a7c8a80cb5999f5cb79e320fd12e315b28b78d"
EXPECTED_RECOVERED_SHA256 = "e273b4f499e4449bbabc361c03c91f260178bf3e687825aa3abe6e686664569b"
def verify_inputs():
for path, expected in ((ORIGINAL, EXPECTED_ORIGINAL_SHA256),
(PE, EXPECTED_RECOVERED_SHA256)):
digest = hashlib.sha256(path.read_bytes()).hexdigest()
if digest != expected:
raise ValueError(f"Binary version mismatch: {path} (SHA256 {digest})")
def symbols():
table = collections.defaultdict(list)
for line in API.read_text(encoding="utf-8").splitlines():
match = re.match(r"METHOD\|([^|]+)\|(.+?)\|ptr=(0x[0-9a-fA-F]+)\|rva=(0x[0-9a-fA-F]+)\|", line)
if match:
table[int(match[3], 16)].append(match[1] + "." + match[2])
return table
def inspect(type_name: str, method_name: str, byte_limit: int):
verify_inputs()
table = symbols()
wanted = type_name + "." + method_name
candidates = [(address, names) for address, names in table.items() if wanted in names]
if len(candidates) != 1:
raise ValueError(f"Expected one method pointer for {wanted}; found {len(candidates)}")
address = candidates[0][0]
pe = pefile.PE(str(PE), fast_load=True)
rva = address - pe.OPTIONAL_HEADER.ImageBase
next_address = min((ptr for ptr in table if ptr > address), default=address + byte_limit)
size = min(byte_limit, next_address - address)
if size <= 0 or size > 65536:
raise ValueError("Unreasonable function extent")
offset = pe.get_offset_from_rva(rva)
data = PE.read_bytes()[offset:offset + size]
md = capstone.Cs(capstone.CS_ARCH_X86, capstone.CS_MODE_64)
md.detail = True
calls = []
branches = []
for instruction in md.disasm(data, address):
if instruction.mnemonic in ("call", "jmp") and len(instruction.operands) == 1:
op = instruction.operands[0]
if op.type == capstone.x86.X86_OP_IMM:
destination = op.imm
label = ";".join(table.get(destination, ("unmapped",)))
(calls if instruction.mnemonic == "call" else branches).append(
{"at": hex(instruction.address), "target": hex(destination), "name": label})
return {"method": wanted, "start": hex(address), "sizeLimit": size,
"calls": calls, "jumps": branches}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("type")
parser.add_argument("method")
parser.add_argument("--bytes", type=int, default=16384)
args = parser.parse_args()
result = inspect(args.type, args.method, args.bytes)
print(f"{result['method']} @ {result['start']} capped {result['sizeLimit']} bytes")
for call in result["calls"]:
print(f"{call['at']} -> {call['target']} {call['name']}")
print(f"calls={len(result['calls'])} jumps={len(result['jumps'])}")
if __name__ == "__main__":
main()
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env python3
"""Build a reproducible, SHA-pinned PostFilm-only GPU input from local real captures.
The tool does not read the application configuration or infer scene depth.
Power checks come from the captured runtime metadata, not screenshot pixels.
"""
import argparse
import hashlib
import json
from pathlib import Path
TRACKS = ("postFilmKeys", "postFilm2Keys", "postFilm3Keys")
def prepare(source: Path, capture: Path, frames: tuple[int, ...]) -> dict:
worksheets = json.loads(source.read_text(encoding="utf-8"))
camera = next(x for x in worksheets if x.get("worksheet") == "son1176_Camera")
tracks = []
for name in TRACKS:
track = camera["tracks"][name]
rows = []
for entry in track["thisList"]:
key = {k: v for k, v in entry.items() if k != "curve"}
curve = entry["curve"]
rows.append({"key": key, "curveKeys": curve["m_Curve"],
"preWrap": curve["m_PreInfinity"], "postWrap": curve["m_PostInfinity"]})
tracks.append({"name": name, "attribute": track["_attribute"],
"playMode": track["_playMode"], "rows": rows})
results = []
for frame in frames:
name = f"frame{frame:06d}"
image = capture / (name + "_off.png")
meta = capture / (name + "_on.txt")
assert image.is_file() and meta.is_file(), name
fields = dict(line.split("=", 1) for line in meta.read_text(encoding="utf-8-sig").splitlines() if "=" in line)
assert int(fields["requestedFrame"]) == frame, f"metadata mismatch {name}"
powers = [float(fields[f"film{i}"].split(":", 1)[1]) for i in (1, 2, 3)]
result = {"frame": frame, "imagePath": str(image.resolve()),
"sha256": hashlib.sha256(image.read_bytes()).hexdigest(),
"expectedPowers": powers}
if "filmBlinkLookup" in fields and "filmColor0" in fields:
status = fields["filmBlinkLookup"].split("|")
colors = [[float(v) for v in c.split(",")] for c in fields["filmColor0"].split("|")]
assert len(status) == len(colors) == 3 and all(len(c) == 4 for c in colors)
# Recover raw RGB only from an actively resolved Color0 sync whose authored
# key has identity brightness/adjustment. Never infer it from screenshot pixels.
candidates = []
for i, name in enumerate(TRACKS):
key = max((k for k in camera["tracks"][name]["thisList"] if k["frame"] <= frame),
key=lambda k: k["frame"])
if (status[i] == "resolved" and key["attribute"] & 0x200000 and
key["BlinkLightBrightnessPower"] == 1 and not key["IsAdjustedBlinkLightColor"]):
candidates.append(colors[i][:3])
if candidates:
raw = candidates[0]
assert all(max(abs(a-b) for a,b in zip(raw, c)) < 0.0002 for c in candidates), "inconsistent same-container raw Blink RGB"
result["rawBlinkRgb"] = {"r": raw[0], "g": raw[1], "b": raw[2], "a": 1.0}
result["expectedColor0"] = [{"r": c[0], "g": c[1], "b": c[2], "a": c[3]} for c in colors]
result["blinkLookup"] = "|".join(status)
results.append(result)
return {"tracks": tracks, "frames": results}
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--source", type=Path, default=Path("tmp/live1176-effect-source.json"))
parser.add_argument("--capture", type=Path, default=Path("captures/render-smoke/20260926_092541_878"))
parser.add_argument("--frames", default="308,868,3848")
parser.add_argument("--output", type=Path, default=Path("tmp/live1176-film-attribution-input.json"))
args = parser.parse_args()
data = prepare(args.source, args.capture, tuple(map(int, args.frames.split(","))))
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(json.dumps(data, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
print(f"Wrote {args.output} ({len(data['tracks'])} tracks, {len(data['frames'])} SHA-pinned frames)")
if __name__ == "__main__":
main()
-11
View File
@@ -1,11 +0,0 @@
# Python dependencies for the UmaViewer asset tools (tools/*.py).
#
# python3 -m venv ~/.venvs/umatools
# ~/.venvs/umatools/bin/python -m pip install -r tools/requirements.txt
#
# NOTE: it must be `apsw-sqlite3mc`, NOT plain `apsw`. Only that wheel bundles
# SQLite3 Multiple Ciphers, which is what decrypts the game's `meta` database
# (the same library the C# side loads as sqlite3mc_x64.dll).
UnityPy>=1.20
apsw-sqlite3mc>=3.46
-199
View File
@@ -1,199 +0,0 @@
#!/usr/bin/env python3
"""Scan every live song and report how many keyframes each timeline track has.
This is the "which track should I implement next" tool. It walks all
``cutt/cutt_son<id>/`` bundle groups, deserializes every LiveTimelineWorkSheet
inside them, and counts the keyframes of each of the ~124 track fields.
Outputs (default directory: tools/out/)
---------------------------------------
scan_keys.csv song x track matrix, cell = number of keyframes
scan_groups.csv song x track matrix, cell = number of track groups
(list length for grouped tracks, keyframe count for
plain key lists)
scan_summary.txt per-track totals, sorted by how many songs use the track
scan.json everything above in machine readable form, plus the
per-song worksheet inventory and the serialized type of
each field
Aggregation
-----------
A song usually ships several worksheets (``son<id>_Camera`` plus ``Type_01`` ..
``Type_10``); the type sheets are variations of one another. By default a
song's value for a track is the MAX over its worksheets, so ten near-identical
sheets do not inflate the number. ``--agg sum`` and ``--per-sheet`` are
available if you want the raw numbers.
Usage
-----
PY=~/.venvs/umatools/bin/python
$PY tools/scan_live_tracks.py # everything, to tools/out/
$PY tools/scan_live_tracks.py --songs 1157 1001 # only these songs
$PY tools/scan_live_tracks.py --per-sheet # one row per worksheet
$PY tools/scan_live_tracks.py --out-dir /tmp/x --quiet
# what the summary looks like:
# track field songs total keys max example songs
# blinkLightList 56 12345 410 1157, 1156, ...
"""
from __future__ import annotations
import argparse
import csv
import json
import os
import sys
import time
from collections import OrderedDict
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import uma_common as uc # noqa: E402
DEFAULT_OUT_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "out")
BASE_FIELDS = {"m_GameObject", "m_Enabled", "m_Script", "m_Name"}
# scalar header fields that are not tracks
SCALAR_FIELDS = {
"version", "targetCameraIndex", "enableAtRuntime", "enableAtEdit",
"TotalTimeLength", "Lyrics", "SheetType", "SheetVariationId", "IsVariationSheet",
}
def scan_song(db, song_id: str, verbose: bool = True):
"""Return ``{sheet_name: {field: (groups, keys)}}`` plus field types."""
sheets = OrderedDict()
types: dict[str, str] = {}
entries = db.like("cutt/cutt_son%s/%%" % song_id)
for entry in entries:
if entry.name.endswith(("/data", "/cutt_son%s" % song_id)):
continue # never carry worksheets, skip the decrypt cost
try:
env = db.load(entry)
except FileNotFoundError as exc:
if verbose:
print(" skip %s (%s)" % (entry.name, exc), file=sys.stderr)
continue
except Exception as exc:
print(" FAILED %s: %s" % (entry.name, exc), file=sys.stderr)
continue
for name, obj, root in uc.worksheets(env):
try:
tree = obj.read_typetree()
except Exception as exc:
print(" FAILED typetree %s/%s: %s" % (entry.name, name, exc), file=sys.stderr)
continue
row: dict[str, tuple[int, int]] = {}
for ch in root.m_Children:
f = ch.m_Name
if f in BASE_FIELDS or f in SCALAR_FIELDS:
continue
types.setdefault(f, ch.m_Type)
val = tree.get(f)
row[f] = (uc.count_groups(val), uc.count_keyframes(val))
sheets["%s|%s" % (song_id, name)] = row
return sheets, types
def write_matrix(path: str, rows: "OrderedDict[str, dict]", fields: list, idx: int) -> None:
with open(path, "w", newline="", encoding="utf-8") as fh:
w = csv.writer(fh)
w.writerow(["song"] + fields)
for row_name, values in rows.items():
w.writerow([row_name] + [values.get(f, (0, 0))[idx] for f in fields])
def main(argv=None) -> int:
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument("--songs", nargs="*", default=None, help="song ids to scan (default: all)")
ap.add_argument("--out-dir", default=DEFAULT_OUT_DIR)
ap.add_argument("--agg", choices=("max", "sum"), default="max", help="how to fold a song's worksheets")
ap.add_argument("--per-sheet", action="store_true", help="keep one row per worksheet instead of per song")
ap.add_argument("--quiet", action="store_true")
uc.add_common_args(ap)
args = ap.parse_args(argv)
uc.require("apsw-sqlite3mc", "UnityPy")
os.makedirs(args.out_dir, exist_ok=True)
t0 = time.time()
rows: "OrderedDict[str, dict]" = OrderedDict()
types: dict[str, str] = {}
inventory: dict[str, list] = {}
with uc.MetaDb(args.game_path, args.region) as db:
song_ids = args.songs or db.song_ids()
for i, sid in enumerate(song_ids, 1):
if not args.quiet:
print("[%2d/%d] son%s" % (i, len(song_ids), sid), file=sys.stderr)
sheets, t = scan_song(db, sid, verbose=not args.quiet)
types.update(t)
inventory[sid] = [k.split("|", 1)[1] for k in sheets]
if not sheets:
continue
if args.per_sheet:
rows.update(sheets)
else:
merged: dict[str, tuple[int, int]] = {}
for values in sheets.values():
for f, (g, k) in values.items():
pg, pk = merged.get(f, (0, 0))
merged[f] = (max(pg, g), max(pk, k)) if args.agg == "max" else (pg + g, pk + k)
rows["son%s" % sid] = merged
# keep the game's own field order (types dict is insertion ordered)
fields = list(types.keys())
keys_csv = os.path.join(args.out_dir, "scan_keys.csv")
groups_csv = os.path.join(args.out_dir, "scan_groups.csv")
write_matrix(groups_csv, rows, fields, 0)
write_matrix(keys_csv, rows, fields, 1)
stats = []
for f in fields:
vals = [(name, v.get(f, (0, 0))[1]) for name, v in rows.items()]
used = [n for n, k in vals if k > 0]
stats.append(
{
"field": f,
"type": types[f],
"songs": len(used),
"total": sum(k for _, k in vals),
"max": max([k for _, k in vals] or [0]),
"examples": used[:6],
}
)
stats.sort(key=lambda s: (-s["songs"], -s["total"]))
summary = os.path.join(args.out_dir, "scan_summary.txt")
with open(summary, "w", encoding="utf-8") as fh:
fh.write("LiveTimelineWorkSheet track usage over %d rows (%s)\n" % (len(rows), args.agg))
fh.write("%-46s %-50s %6s %9s %7s\n" % ("field", "serialized type", "songs", "total", "max"))
fh.write("-" * 125 + "\n")
for s in stats:
fh.write("%-46s %-50s %6d %9d %7d\n" % (s["field"], s["type"], s["songs"], s["total"], s["max"]))
js = os.path.join(args.out_dir, "scan.json")
with open(js, "w", encoding="utf-8") as fh:
json.dump(
{
"rows": {n: {f: list(v) for f, v in vals.items()} for n, vals in rows.items()},
"field_types": types,
"stats": stats,
"worksheets": inventory,
"aggregation": "per-sheet" if args.per_sheet else args.agg,
},
fh,
indent=1,
)
print("scanned %d rows / %d fields in %.1fs" % (len(rows), len(fields), time.time() - t0))
for p in (keys_csv, groups_csv, summary, js):
print(" %s" % p)
return 0
if __name__ == "__main__":
raise SystemExit(main())
+197
View File
@@ -0,0 +1,197 @@
"""Summarize one opt-in Live JSONL session without inventing resource counts.
Usage: python tools/summarize_live_diagnostics.py tmp/live-diagnostics-*.jsonl
"""
import argparse
import collections
import json
from pathlib import Path
def summarize_execution(events):
"""Check submitted pass chains per camera/Unity frame, retaining seek revisits."""
groups = collections.defaultdict(list)
scheduled = collections.defaultdict(list)
for event in events:
key = (event.get("unityFrame"), event.get("camera"))
if event.get("type") == "render_execute":
groups[key].append(event)
elif event.get("type") == "render_pass":
scheduled[key].append(event)
chains = []
for (unity_frame, camera), steps in groups.items():
issues = []
names = [e.get("renderStep") for e in steps]
repeated = [name for name, count in collections.Counter(names).items() if count > 1]
if repeated:
issues.append("Repeated recorded steps: " + ", ".join(repeated))
if names[0] != "SourceSetup":
issues.append("Missing leading SourceSetup")
for previous, current in zip(steps, steps[1:]):
if not previous.get("outputRT") or previous.get("outputRT") != current.get("inputRT"):
issues.append("RT handoff differs: %s -> %s" %
(previous.get("renderStep"), current.get("renderStep")))
if len({e.get("liveFrame") for e in steps}) != 1:
issues.append("Live frame changed within recorded chain")
enqueue = scheduled.get((unity_frame, camera), [])
expected = enqueue[0].get("rendererPassCount") if len(enqueue) == 1 else None
if expected is not None and expected != len(steps):
issues.append("Submitted record count differs from scheduled count")
camera_restored = (bool(steps[0].get("outputRT")) and
steps[-1].get("outputRT") == steps[0].get("outputRT"))
if not camera_restored:
issues.append("Last output differs from initial camera RT")
chains.append({
"unityFrame": unity_frame, "camera": camera,
"liveFrame": steps[0].get("liveFrame"), "seconds": steps[0].get("seconds"),
"steps": names, "scheduledPasses": expected,
"urpPostProcessing": enqueue[0].get("urpPostProcessing") if len(enqueue) == 1 else None,
"cameraOutputRestored": camera_restored,
"handoffs": [{k: e.get(k) for k in ("renderStep", "renderPassEvent", "inputRT", "outputRT")}
for e in steps],
"issues": issues,
})
return {
"recordCount": sum(len(items) for items in groups.values()),
"sampledCameraFrames": len(chains),
"chains": chains,
"scope": "Managed command-buffer submissions only; internal PostFilm/Shader draws and GPU pixels "
"are not traced. Adjacent Live frames are not exact reference captures. "
"No findings outside sampled frames are implied."
}
def summarize(path):
events = []
with path.open(encoding="utf-8-sig") as stream:
for line_number, line in enumerate(stream, 1):
if not line.strip():
continue
try:
events.append(json.loads(line))
except json.JSONDecodeError as exc:
raise ValueError(f"{path}:{line_number}: {exc}") from exc
if not events or events[0].get("type") != "session_begin":
raise ValueError("Missing session_begin: use a complete Live diagnostics session")
begin = events[0]
counts = next((e for e in events if e.get("type") == "preload_counts"), {})
root_counts = next((e for e in events if e.get("type") == "resource_roots"), {})
root_expansions = [e for e in events if e.get("type") == "preload_root"]
complete_index = next((i for i, e in enumerate(events)
if e.get("type") == "preload_complete"), None)
before = events[:complete_index] if complete_index is not None else events
after = events[complete_index + 1:] if complete_index is not None else []
preload_acquires = [e for e in before if e.get("type") == "bundle_acquire"]
runtime_acquires = [e for e in after if e.get("type") == "bundle_acquire"]
preload_names = [e.get("bundle", "") for e in preload_acquires]
runtime_requests = [e for e in after if e.get("type") == "bundle_request"]
instances = [e for e in events if e.get("type") == "instance_create"]
asset_loads = [e for e in events if e.get("type") == "asset_load"]
progress = [e for e in events if e.get("type") == "load_progress"]
frames = [e for e in events if e.get("type") == "live_frame"]
passes = [e for e in events if e.get("type") == "render_pass"]
targets = [e for e in frames if e.get("liveFrame") in (308, 868, 3848)]
bundle_inventories = [e for e in events if e.get("type") == "bundle_inventory"]
scene_inventories = [e for e in events if e.get("type") == "scene_inventory"]
indexed_bundles = [e for e in events if e.get("type") == "bundle_index"]
inventory_keys = ("phase", "uniqueLoadedHandles", "loadedAssetBundles",
"loadedNonBundles", "assetIndexCandidates", "assetIndexErrors")
scene_keys = ("phase", "loadedScenes", "sceneRoots", "totalTransforms",
"renderers", "lights", "particleSystems", "cameras", "videos", "outcome")
def count_outcomes(items):
return dict(sorted(collections.Counter(e.get("outcome") for e in items).items()))
def frame_snapshot(e):
keys = ("liveFrame", "seconds", "unityFrame", "camera", "width", "height",
"graphicsFormat", "characters", "stageObjects", "stageMapObjects",
"totalTransforms", "renderers", "lights", "particleSystems",
"dof", "bloom", "diffusion", "radial", "colorCorrection", "mode")
return {k: e[k] for k in keys if k in e}
return {
"session": begin.get("session"), "songId": begin.get("songId"),
"stageId": begin.get("stageId"), "characterSlots": begin.get("characters"),
"completePreload": complete_index is not None,
"preload": {
"roots": counts.get("roots"),
"rootSources": {
"director": root_counts.get("directorRoots"),
"normalCharacter": root_counts.get("normalRoots"),
"mobCharacter": root_counts.get("mobRoots"),
"normalCharacters": root_counts.get("normalCharacters"),
"mobCharacters": root_counts.get("mobCharacters"),
"skippedCharacters": root_counts.get("skippedCharacters"),
"uniqueBeforeDependencyExpansion": root_counts.get("roots"),
},
"uniqueExpandedDownloadEntries": counts.get("downloadEntriesUnique"),
"requestedItemsWithDuplicates": counts.get("loadItemsWithDuplicates"),
"perRootCoverage": {
"recordedRoots": len(root_expansions),
"requestsSummed": sum(e.get("requestCount", 0) for e in root_expansions),
"repeatedRequestsSummed": sum(e.get("repeatedRequests", 0) for e in root_expansions),
"agreesWithProgressTarget": (
sum(e.get("requestCount", 0) for e in root_expansions)
== counts["loadItemsWithDuplicates"]
if root_expansions and "loadItemsWithDuplicates" in counts else None),
"largestRoots": [
{k: e.get(k) for k in ("rootIndex", "bundle", "requestCount", "repeatedRequests")}
for e in sorted(root_expansions,
key=lambda e: (-e.get("requestCount", 0), e.get("rootIndex", -1)))[:20]
],
},
"observedAcquireAttempts": len(preload_acquires),
"observedUniqueBundleNames": len(set(preload_names)),
"observedRepeatedBundleRequests": len(preload_names) - len(set(preload_names)),
"acquireOutcomes": count_outcomes(preload_acquires),
"progressSamples": len(progress),
"progressFinal": next((e.get("progressTarget") for e in reversed(progress)
if e.get("progressTarget", -1) >= 0), None)
},
"runtime": {
"bundleRequestCalls": len(runtime_requests),
"uniqueRequestedBundleNames": len({e.get("bundle") for e in runtime_requests}),
"acquireAttempts": len(runtime_acquires),
"acquireOutcomes": count_outcomes(runtime_acquires),
"failedBundleNames": sorted({e.get("bundle") for e in runtime_acquires
if e.get("outcome") in ("file_missing", "load_failed", "exception")}),
"assetLoadCallsObserved": len(asset_loads),
"materializedAssetsInObservedCalls": sum(max(e.get("assetsLoaded", 0), 0) for e in asset_loads),
"matchingAssetsInObservedCalls": sum(max(e.get("assetsMatching", 0), 0) for e in asset_loads),
"assetLoadOperations": dict(sorted(collections.Counter(e.get("operation") for e in asset_loads).items())),
"instantiationsObserved": len(instances),
"instantiationSources": dict(sorted(collections.Counter(e.get("bundle") for e in instances).items())),
},
"phaseInventories": {
"bundles": [{k: e[k] for k in inventory_keys if k in e}
for e in bundle_inventories],
"sceneObjects": [{k: e[k] for k in scene_keys if k in e}
for e in scene_inventories],
"perPhaseIndexedBundles": dict(sorted(collections.Counter(
e.get("phase") for e in indexed_bundles).items())),
"indexFailures": [{"phase": e.get("phase"), "bundle": e.get("bundle")}
for e in indexed_bundles if e.get("outcome") in ("index_error", "bundle_unavailable")],
},
"playback": {
"frameSamples": len(frames), "renderPassSamples": len(passes),
"cameraPassCounts": dict(sorted(collections.Counter(e.get("camera") for e in passes).items())),
"referenceFrameSnapshots": [frame_snapshot(e) for e in targets],
"execution": summarize_execution(events),
},
"coverage": "Asset calls cover UmaDatabaseEntry.Get/GetAll and selected stage, part, "
"motion, flare, flash, monitor and cyalume paths. Other direct AssetBundle "
"calls may still be uncounted. bundle.name may not be an official index name. "
"Materialized assets can repeat across calls. Bundle catalog candidates are "
"GetAllAssetNames entries, not actual loaded assets. Scene inventories count "
"loaded SceneManager scenes, not DontDestroyOnLoad or Editor objects. "
"No compiled-viewer count is implied."
}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("session", type=Path, help="one complete Live JSONL file")
args = parser.parse_args()
print(json.dumps(summarize(args.session), ensure_ascii=False, indent=2))
if __name__ == "__main__":
main()
-436
View File
@@ -1,436 +0,0 @@
"""Shared library for the UmaViewer Python asset tools.
This is a Python re-implementation of the decryption logic that lives in the
C# side of this repository:
* ``Assets/Scripts/Config.cs`` -- the key constants
* ``Assets/Scripts/UmaAssetBundleStream.cs`` -- asset bundle XOR cipher
* ``Assets/Scripts/UmaDatabase/UmaDatabaseEntry.cs``-- per-bundle key expansion
* ``Assets/Scripts/UmaDatabase/UmaDatabaseController.cs`` -- meta DB cipher
Nothing here writes to the game folder; every file is opened read-only.
----------------------------------------------------------------------------
Setup
----------------------------------------------------------------------------
python3 -m venv ~/.venvs/umatools
~/.venvs/umatools/bin/python -m pip install -r tools/requirements.txt
Then run any tool with that interpreter, e.g.
~/.venvs/umatools/bin/python tools/dump_cutt_typetree.py 1157
----------------------------------------------------------------------------
Game folder
----------------------------------------------------------------------------
The tools look for the game's ``Persistent`` folder (the one containing
``meta`` and ``dat/``) in this order:
1. ``--game-path`` command line option
2. ``$UMA_GAME_PATH`` environment variable
3. the paths in :data:`DEFAULT_GAME_PATHS`
----------------------------------------------------------------------------
How the encryption works
----------------------------------------------------------------------------
meta database
A SQLite database encrypted with SQLite3 Multiple Ciphers, cipher index 3
(= ChaCha20 / "sqleet" scheme, non-legacy defaults). The passphrase is
``DBKey[i] XOR DBBaseKey[i % 13]`` (32 raw bytes, see :func:`meta_key`).
We hand those raw bytes to sqlite3mc through ``PRAGMA hexkey`` which is
the exact equivalent of the C# ``sqlite3_key(db, bytes, 32)`` call.
asset bundles
``dat/<first 2 chars of hash>/<hash>``. The first 256 bytes are stored in
the clear; every byte at file offset ``p >= 256`` is XORed with
``FKey[p % 88]`` where ``FKey`` is built from the 11-byte ``ABKey`` and the
per-bundle 64-bit key stored in the meta table (column ``e``):
FKey[i * 8 + j] = ABKey[i] XOR little_endian_int64(key)[j]
A key of 0 means the bundle is not encrypted.
"""
from __future__ import annotations
import os
import shutil
import struct
import sys
import tempfile
from dataclasses import dataclass
from typing import Iterable, Iterator, Optional
# --------------------------------------------------------------------------
# dependency check (friendly message instead of a bare ImportError)
# --------------------------------------------------------------------------
_MISSING: list[str] = []
try:
import apsw # provided by the `apsw-sqlite3mc` wheel
except ImportError: # pragma: no cover
apsw = None
_MISSING.append("apsw-sqlite3mc")
try:
import UnityPy
except ImportError: # pragma: no cover
UnityPy = None
_MISSING.append("UnityPy")
def require(*modules: str) -> None:
"""Abort with an actionable message if a needed dependency is absent."""
needed = [m for m in modules if m in _MISSING]
if not needed:
return
sys.stderr.write(
"\nMissing Python package(s): %s\n\n"
"Install them into a virtualenv, e.g.\n"
" python3 -m venv ~/.venvs/umatools\n"
" ~/.venvs/umatools/bin/python -m pip install -r %s\n"
"and re-run this script with ~/.venvs/umatools/bin/python\n\n"
% (", ".join(needed), os.path.join(os.path.dirname(__file__), "requirements.txt"))
)
raise SystemExit(2)
def has_sqlite3mc() -> bool:
"""True when the installed apsw build actually carries the MC ciphers."""
if apsw is None:
return False
try:
con = apsw.Connection(":memory:")
try:
list(con.execute("PRAGMA cipher"))
return True
finally:
con.close()
except Exception:
return False
# --------------------------------------------------------------------------
# keys -- verbatim from Assets/Scripts/Config.cs
# --------------------------------------------------------------------------
DB_BASE_KEY = bytes(
[0xF1, 0x70, 0xCE, 0xA4, 0xDF, 0xCE, 0xA3, 0xE1,
0xA5, 0xD8, 0xC7, 0x0B, 0xD1, 0x00, 0x00, 0x00]
)
DB_KEY = bytes(
[0x6D, 0x5B, 0x65, 0x33, 0x63, 0x36,
0x63, 0x25, 0x54, 0x71, 0x2D, 0x73,
0x50, 0x53, 0x63, 0x38, 0x6D, 0x34,
0x37, 0x7B, 0x35, 0x63, 0x70, 0x23,
0x37, 0x34, 0x53, 0x29, 0x73, 0x43,
0x36, 0x33]
)
GLOBAL_DB_KEY = bytes(
[0x56, 0x63, 0x6B, 0x63, 0x42, 0x72, 0x37, 0x76, 0x65, 0x70, 0x41, 0x62]
)
AB_KEY = bytes([0x53, 0x2B, 0x46, 0x31, 0xE4, 0xA7, 0xB9, 0x47, 0x3E, 0x7C, 0xFB])
HEADER_SIZE = 256
FKEY_LEN = len(AB_KEY) * 8 # 88
#: sqlite3mc cipher index used by UmaDatabaseController.ReadMetaFromEncryptedDb
META_CIPHER = "chacha20" # == sqlite3mc_config(db, "cipher", 3)
DEFAULT_GAME_PATHS = (
"/mnt/d/Umamusume/umamusume_Data/Persistent",
os.path.expandvars(r"%USERPROFILE%\AppData\LocalLow\Cygames\umamusume"),
)
def meta_key(region: str = "jp") -> bytes:
"""Final meta-DB passphrase: ``DBKey[i] XOR DBBaseKey[i % 13]``.
Mirrors ``UmaDatabaseController.GenFinalKey``.
"""
key = GLOBAL_DB_KEY if region.lower() in ("global", "en") else DB_KEY
return bytes(key[i] ^ DB_BASE_KEY[i % 13] for i in range(len(key)))
# --------------------------------------------------------------------------
# asset bundle cipher
# --------------------------------------------------------------------------
def build_fkey(key: int) -> bytes:
"""Expand a per-bundle 64-bit key into the 88-byte XOR keystream.
Mirrors ``UmaDatabaseEntry.FKey``.
"""
key_bytes = struct.pack("<q", key) # signed, little endian
out = bytearray(FKEY_LEN)
for i, b in enumerate(AB_KEY):
base = i << 3
for j in range(8):
out[base + j] = b ^ key_bytes[j]
return bytes(out)
def decrypt_bundle_bytes(data: bytes, key: int) -> bytes:
"""Decrypt a whole asset bundle image held in memory."""
if not key or len(data) <= HEADER_SIZE:
return bytes(data)
fk = build_fkey(key)
body = data[HEADER_SIZE:]
n = len(body)
# byte at file offset p uses fk[p % 88]; body[0] is at offset HEADER_SIZE
off = HEADER_SIZE % FKEY_LEN
rotated = fk[off:] + fk[:off]
stream = (rotated * (n // FKEY_LEN + 1))[:n]
plain = (int.from_bytes(body, "big") ^ int.from_bytes(stream, "big")).to_bytes(n, "big")
return bytes(data[:HEADER_SIZE]) + plain
def decrypt_bundle_file(path: str, key: int) -> bytes:
with open(path, "rb") as fh:
return decrypt_bundle_bytes(fh.read(), key)
# --------------------------------------------------------------------------
# meta database
# --------------------------------------------------------------------------
@dataclass
class MetaEntry:
"""One row of the meta ``a`` table (see UmaDatabaseEntry.cs)."""
type: str # column m, e.g. "_3d_cutt"
name: str # column n, the asset path, e.g. cutt/cutt_son1157/type_01
url: str # column h, the hashed filename under dat/
checksum: str # column c
prerequisites: str # column d, ';' separated dependency asset paths
key: int # column e, per-bundle cipher key (0 = plaintext bundle)
@property
def is_encrypted(self) -> bool:
return self.key != 0
def path(self, game_path: str) -> str:
return os.path.join(game_path, "dat", self.url[:2], self.url)
def deps(self) -> list[str]:
return [d for d in (self.prerequisites or "").split(";") if d]
def find_game_path(explicit: Optional[str] = None) -> str:
candidates = []
if explicit:
candidates.append(explicit)
env = os.environ.get("UMA_GAME_PATH")
if env:
candidates.append(env)
candidates.extend(DEFAULT_GAME_PATHS)
for c in candidates:
if c and os.path.isfile(os.path.join(c, "meta")):
return c
raise SystemExit(
"Could not locate the game's Persistent folder (needs a 'meta' file).\n"
"Tried: %s\nPass --game-path or set $UMA_GAME_PATH." % ", ".join(filter(None, candidates))
)
class MetaDb:
"""Read-only access to the encrypted ``meta`` SQLite database.
The game keeps ``meta`` open, so we work on a temporary copy by default.
"""
def __init__(self, game_path: Optional[str] = None, region: str = "jp", copy: bool = True,
readonly: bool = True):
require("apsw-sqlite3mc")
self.game_path = find_game_path(game_path)
self.meta_path = os.path.join(self.game_path, "meta")
self._tmp = None
src = self.meta_path
if copy:
fd, tmp = tempfile.mkstemp(prefix="uma_meta_", suffix=".db")
os.close(fd)
shutil.copyfile(self.meta_path, tmp)
self._tmp = tmp
src = tmp
elif not readonly:
raise ValueError("refusing to open the game's meta file writable; use copy=True")
flags = apsw.SQLITE_OPEN_READONLY if readonly else (
apsw.SQLITE_OPEN_READWRITE | apsw.SQLITE_OPEN_CREATE
)
self.con = apsw.Connection(src, flags=flags)
key = meta_key(region)
try:
list(self.con.execute("PRAGMA cipher='%s'" % META_CIPHER))
list(self.con.execute("PRAGMA hexkey='%s'" % key.hex()))
list(self.con.execute("SELECT name FROM sqlite_master LIMIT 1"))
except Exception as exc:
self.close()
raise SystemExit(
"Failed to decrypt the meta database (%s).\n"
"Either the keys in Assets/Scripts/Config.cs are out of date, or the\n"
"installed apsw build has no SQLite3MultipleCiphers support "
"(need the 'apsw-sqlite3mc' wheel, not plain 'apsw')." % exc
)
# -- lifecycle ---------------------------------------------------------
def close(self) -> None:
try:
self.con.close()
except Exception:
pass
if self._tmp and os.path.exists(self._tmp):
try:
os.remove(self._tmp)
except OSError:
pass
self._tmp = None
def __enter__(self) -> "MetaDb":
return self
def __exit__(self, *exc) -> None:
self.close()
# -- queries -----------------------------------------------------------
_COLS = "m,n,h,c,d,e"
def _rows(self, where: str, args: Iterable = ()) -> Iterator[MetaEntry]:
sql = "SELECT %s FROM a %s" % (self._COLS, where)
for m, n, h, c, d, e in self.con.execute(sql, tuple(args)):
yield MetaEntry(m or "", n or "", h or "", c or "", d or "", e or 0)
def get(self, name: str) -> Optional[MetaEntry]:
for e in self._rows("WHERE n = ?", (name,)):
return e
return None
def like(self, pattern: str) -> list[MetaEntry]:
return list(self._rows("WHERE n LIKE ? ORDER BY n", (pattern,)))
def all(self) -> list[MetaEntry]:
return list(self._rows("ORDER BY n"))
def song_ids(self) -> list[str]:
"""All live song ids that have a ``cutt/cutt_son<id>/`` bundle group."""
import re
ids = set()
for (n,) in self.con.execute("SELECT n FROM a WHERE n LIKE 'cutt/cutt_son%'"):
m = re.match(r"cutt/cutt_son(\d+)/", n or "")
if m:
ids.add(m.group(1))
return sorted(ids, key=int)
# -- bundle loading ----------------------------------------------------
def bundle_bytes(self, name_or_entry) -> bytes:
entry = name_or_entry if isinstance(name_or_entry, MetaEntry) else self.get(name_or_entry)
if entry is None:
raise KeyError("no meta entry named %r" % name_or_entry)
p = entry.path(self.game_path)
if not os.path.isfile(p):
raise FileNotFoundError(
"%s -> %s (not downloaded; open it once in the game or in UmaViewer)" % (entry.name, p)
)
return decrypt_bundle_file(p, entry.key)
def load(self, name_or_entry, with_deps: bool = False):
"""Decrypt and open a bundle with UnityPy; returns an Environment."""
require("UnityPy")
import io
entry = name_or_entry if isinstance(name_or_entry, MetaEntry) else self.get(name_or_entry)
if entry is None:
raise KeyError("no meta entry named %r" % name_or_entry)
env = UnityPy.Environment()
if with_deps:
for dep in entry.deps():
try:
env.load_file(io.BytesIO(self.bundle_bytes(dep)), name=dep, is_dependency=True)
except Exception as exc:
sys.stderr.write(" warning: dependency %s not loaded (%s)\n" % (dep, exc))
env.load_file(io.BytesIO(self.bundle_bytes(entry)), name=entry.name)
return env
# --------------------------------------------------------------------------
# helpers shared by the cutt tools
# --------------------------------------------------------------------------
#: A MonoBehaviour is a LiveTimelineWorkSheet when its TypeTree has this field.
WORKSHEET_MARKER = "cameraPosKeys"
def is_worksheet(obj) -> bool:
node = getattr(getattr(obj, "serialized_type", None), "node", None)
if node is None:
return False
return any(ch.m_Name == WORKSHEET_MARKER for ch in node.m_Children)
def worksheets(env):
"""Yield ``(name, obj, typetree_root_node)`` for each WorkSheet in *env*."""
for obj in env.objects:
if obj.type.name != "MonoBehaviour" or not is_worksheet(obj):
continue
node = obj.serialized_type.node
try:
name = obj.read_typetree().get("m_Name") or "?"
except Exception:
name = "?"
yield name, obj, node
def count_keyframes(value) -> int:
"""Total number of timeline keyframes reachable from *value*.
Every timeline key list is serialized as ``{_attribute, _playMode,
thisList}``; we sum the ``thisList`` lengths and never descend into the
keyframes themselves.
"""
if isinstance(value, dict):
if "thisList" in value:
tl = value["thisList"]
return len(tl) if isinstance(tl, list) else 0
return sum(count_keyframes(v) for v in value.values() if isinstance(v, (dict, list)))
if isinstance(value, list):
return sum(count_keyframes(v) for v in value if isinstance(v, (dict, list)))
return 0
def count_groups(value) -> int:
"""Size of the top-level container of a track field.
* key list (``thisList``) -> number of keyframes
* list of named track groups -> number of groups
* struct of several key lists -> number of sub key lists
"""
if isinstance(value, list):
return len(value)
if isinstance(value, dict):
if "thisList" in value:
tl = value["thisList"]
return len(tl) if isinstance(tl, list) else 0
return sum(1 for v in value.values() if isinstance(v, (dict, list)))
return 0
def group_names(value) -> list[str]:
"""Names of the track groups inside a list-style field, if any."""
if isinstance(value, list):
return [v.get("name", "") for v in value if isinstance(v, dict) and "name" in v]
return []
def add_common_args(parser) -> None:
parser.add_argument(
"--game-path",
default=None,
help="game Persistent folder (default: $UMA_GAME_PATH or %s)" % DEFAULT_GAME_PATHS[0],
)
parser.add_argument(
"--region", default="jp", choices=("jp", "global"), help="which DB key to use (default: jp)"
)