) {
StartupAvatarRepository.request(context,{base=it},{pack=it.getOrThrow()});waitReady()
if(base!!.body.width==720) {
val poster=FramedAvatarPoster(context)
- for((w,h) in listOf(720 to 1280,360 to 800,800 to 480)) {
+ for((w,h) in listOf(720 to 1280,360 to 800,800 to 480,540 to 540)) {
poster.onSizeChanged(w,h,0,0)
val zoom=com.gorios.lanvoice.BuildConfig.AVATAR_FRAME_ZOOM
val center=com.gorios.lanvoice.BuildConfig.AVATAR_FRAME_CENTER_Y
val fitted=bodyFit(w,h,180,320)
- val composed=bodyFit(w,h,720,1280,zoom,center)
+ val composed=bodyFit(w,h,720,1280,zoom,center,com.gorios.lanvoice.BuildConfig.AVATAR_FRAMING_PRESET)
val displayedTop=h/2f+(fitted.top-h/2f)*poster.scaleY+poster.translationY
check(poster.scaleX==zoom && poster.scaleY==zoom && kotlin.math.abs(displayedTop-composed.top)<.001f)
}
- println("POSTER_FRAMING|viewports=3|matches_compositor=true|zoom=${com.gorios.lanvoice.BuildConfig.AVATAR_FRAME_ZOOM}|center_y=${com.gorios.lanvoice.BuildConfig.AVATAR_FRAME_CENTER_Y}|device=false")
+ println("POSTER_FRAMING|viewports=4|matches_compositor=true|zoom=${com.gorios.lanvoice.BuildConfig.AVATAR_FRAME_ZOOM}|center_y=${com.gorios.lanvoice.BuildConfig.AVATAR_FRAME_CENTER_Y}|device=false")
}
check(base!!.body.frameCount==97 && base!!.patches.isEmpty() && base!!.curves.isEmpty())
check(pack!!.emotionAdmission=="accepted" && pack!!.emotionAction!!.packages.size==5)
@@ -313,7 +314,10 @@ if args.user_asset_candidate and index.get('waiting'):
with tempfile.TemporaryDirectory(prefix='baji-runtime-audit-') as td:
tmp=Path(td);files=[]
for path in (ROOT/'tests/avatar').glob('*.kt'):
- if path.name not in ('Pack.kt','Context.kt','Graphics.kt','BuildConfig.kt') and not((args.startup_loader or args.waiting_session) and path.name=='Clock.kt') and not(args.waiting_session and path.name=='AndroidLog.kt'):files.append(path)
+ if path.name not in ('Pack.kt','Context.kt','Graphics.kt','BuildConfig.kt') and not(args.framing_preset=='square540-headchest' and path.name=='View.kt') and not((args.startup_loader or args.waiting_session) and path.name=='Clock.kt') and not(args.waiting_session and path.name=='AndroidLog.kt'):files.append(path)
+ if args.framing_preset=='square540-headchest':
+ square_view=(ROOT/'tests/avatar/View.kt').read_text().replace('val width = 480; val height = 848','val width = 540; val height = 540')
+ p=tmp/'View.kt';p.write_text(square_view);files.append(p)
if args.startup_loader:
clock=(ROOT/'tests/avatar/Clock.kt').read_text().replace('fun getMainLooper() = main','private val owner=Thread.currentThread();fun myLooper(): Looper?=if(Thread.currentThread()===owner) main else null;fun getMainLooper() = main')
clock=clock.replace(' fun add(', ' @Synchronized fun add(').replace(' fun remove(', ' @Synchronized fun remove(').replace(' fun advanceBy(', ' @Synchronized fun advanceBy(')
diff --git a/scripts/check-avatar-shader.py b/scripts/check-avatar-shader.py
index b840181..458d884 100644
--- a/scripts/check-avatar-shader.py
+++ b/scripts/check-avatar-shader.py
@@ -29,9 +29,10 @@ def golden(body,patch,x,y,opacity,w,h,crop,zoom=1,center_y=.5):
def main():
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('--runtime',type=Path);parser.add_argument('--synthetic-shape',choices=['480x848','720x1280'],default='720x1280');parser.add_argument('--output',type=Path,required=True)
+ parser.add_argument('--framing-preset',choices=['legacy','square540-headchest'],default='legacy')
parser.add_argument('--zoom',type=float,default=1);parser.add_argument('--center-y',type=float,default=.5)
args=parser.parse_args();args.output.mkdir(parents=True,exist_ok=True)
- assert 1<=args.zoom<=2 and .4<=args.center_y<=.6
+ assert (args.framing_preset=='legacy' and 1<=args.zoom<=2 and .4<=args.center_y<=.6) or (args.framing_preset=='square540-headchest' and abs(args.zoom-32/9)<1e-7 and args.center_y==.128125)
m=json.loads((args.runtime/'manifest.json').read_text()) if args.runtime else None
bw,bh=(m['body']['width'],m['body']['height']) if m else map(int,args.synthetic_shape.split('x'))
source=(ROOT/'app/src/main/java/com/gorios/lanvoice/avatar/ContinuousBodyRenderer.kt').read_text()
@@ -57,7 +58,7 @@ def main():
yy,xx=np.mgrid[:bh,:bw];body=np.empty((bh,bw,4),np.uint8)
body[:,:,0]=xx%256;body[:,:,1]=yy%256;body[:,:,2]=((xx//16+yy//16)%2)*255;body[:,:,3]=255
patch=np.zeros((22,40,4),np.uint8);patch[:,:,:3]=[211,70,39];patch[:,:,3]=np.arange(40,dtype=np.uint8)[None,:]*6
- for w,h in [(bw,bh),(360,800),(800,480)]:
+ for w,h in [(bw,bh),(360,800),(800,480),(540,540)]:
for opacity in [0,.5,1]:check(body,patch,211.25,112.5,opacity,w,h,f'synthetic-{w}x{h}-opacity{opacity}')
check(body,patch,211.25,112.5,1,bw,bh,'synthetic-transform-crop',1)
if m is None:
@@ -75,7 +76,8 @@ def main():
body=np.frombuffer(raw,np.uint8).reshape(bh,bw,4)
for level in (0,1,2,3,4):
patch=np.asarray(Image.open(args.runtime/row['levels'][level]['path']).convert('RGBA'))
- check(body,patch,row['x'],row['y'],0 if level==0 else 1,bw,bh,f'frame{i}-level{level}')
+ for vw,vh in ([(bw,bh),(540,540)] if args.framing_preset!='legacy' else [(bw,bh)]):
+ check(body,patch,row['x'],row['y'],0 if level==0 else 1,vw,vh,f'frame{i}-level{level}')
assert pipe.stdout.read(1)==b'';assert pipe.wait(timeout=10)==0
finally:
if pipe.poll() is None:pipe.kill();pipe.wait()
diff --git a/scripts/check-square540-framing.py b/scripts/check-square540-framing.py
new file mode 100644
index 0000000..e3d8773
--- /dev/null
+++ b/scripts/check-square540-framing.py
@@ -0,0 +1,64 @@
+#!/usr/bin/env python3
+"""Finite real GLES preview of the immutable Liam media at the controlled square preset.
+No generated media, source mutation, Android OES/device/performance claim.
+"""
+import argparse, hashlib, importlib.util, json, os, re, subprocess, tempfile
+from pathlib import Path
+import cv2
+import numpy as np
+from PIL import Image, ImageDraw
+ROOT=Path(__file__).resolve().parents[1]
+
+def main():
+ p=argparse.ArgumentParser(description=__doc__);p.add_argument('--output',type=Path,required=True);a=p.parse_args()
+ a.output.mkdir(parents=True,exist_ok=False)
+ catalog=json.loads((ROOT/'manifests/character-build-profiles.json').read_bytes());preset=catalog['framingPresets']['square540-headchest'];media=catalog['mediaBundles'][preset['mediaBundle']]
+ root=ROOT/'app/src/main/assets'/media['assetRoot'];raw=(root/'manifest.json').read_bytes();assert hashlib.sha256(raw).hexdigest()==preset['indexSha256'];index=json.loads(raw)
+ source=(ROOT/'app/src/main/java/com/gorios/lanvoice/avatar/ContinuousBodyRenderer.kt').read_text()
+ vertex=re.search(r'const val VERTEX="""([\s\S]*?)"""',source)[1]
+ fragment=re.search(r'const val FRAGMENT="""([\s\S]*?)"""',source)[1].replace('#extension GL_OES_EGL_image_external : require','').replace('samplerExternalOES','sampler2D')
+ spec=importlib.util.spec_from_file_location('golden',ROOT/'scripts/check-avatar-shader.py');golden=importlib.util.module_from_spec(spec);spec.loader.exec_module(golden)
+ refs=[r['runtimeManifest'] for r in index['conversationPackages']]+[e['mouthRuntimeManifest'] for e in index['edges'] if 'mouthRuntimeManifest' in e]
+ runtimes={}
+ for ref in refs:
+ m=json.loads((root/ref['path']).read_bytes());runtimes[(Path(ref['path']).parent/m['body']['path']).as_posix()]=(m,root/Path(ref['path']).parent)
+ rows=[];measurements=[];tiles=[]
+ with tempfile.TemporaryDirectory(prefix='square540-gles-') as td:
+ t=Path(td);(t/'vertex').write_text(vertex);(t/'fragment').write_text(fragment)
+ subprocess.run(['cc','-O2',str(ROOT/'tests/avatar-pixels/gles-golden.c'),'-lEGL','-lGLESv2','-lm','-o',str(t/'golden')],check=True)
+ env=dict(os.environ,EGL_PLATFORM='surfaceless',LIBGL_ALWAYS_SOFTWARE='1')
+ for n,clip in enumerate(sorted(root.rglob('*.mp4'))):
+ rel=clip.relative_to(root).as_posix();cap=cv2.VideoCapture(str(clip));total=int(cap.get(cv2.CAP_PROP_FRAME_COUNT));selected={0,total//3,2*total//3,total-1};bounds=[];i=0
+ while True:
+ ok,bgr=cap.read()
+ if not ok:break
+ # Conservative head + raised-hand upper silhouette, not a face landmark detector.
+ ys,xs=np.where(np.max(bgr[:180,170:550],axis=2)<150)
+ if len(ys):bounds.append([int(xs.min())+170,int(ys.min()),int(xs.max())+170,int(ys.max())])
+ if i in selected:
+ body=cv2.cvtColor(bgr,cv2.COLOR_BGR2RGBA);(t/'body').write_bytes(body.tobytes())
+ levels=[0,4] if rel in runtimes else [0]
+ for level in levels:
+ if level:
+ runtime,base=runtimes[rel];row=runtime['patches'][i];patch=np.asarray(Image.open(base/row['levels'][level]['path']).convert('RGBA'));x,y=row['x'],row['y'];opacity=1
+ else:patch=np.array([[[255,0,255,255]]],dtype=np.uint8);x=y=0;opacity=0
+ (t/'patch').write_bytes(patch.tobytes())
+ r=subprocess.run([str(t/'golden'),str(t/'vertex'),str(t/'fragment'),str(t/'body'),str(t/'patch'),str(t/'out'),str(patch.shape[1]),str(patch.shape[0]),str(x),str(y),str(opacity),'540','540','0','720','1280',str(preset['zoom']),str(preset['centerY'])],env=env,capture_output=True,text=True,check=True)
+ actual=np.frombuffer((t/'out').read_bytes(),np.uint8).reshape(540,540,4)[::-1,:,:3]
+ expected=golden.golden(body,patch,x,y,opacity,540,540,0,preset['zoom'],preset['centerY']);diff=np.abs(actual.astype(int)-expected.astype(int));assert diff.max()<=2,(rel,i,level,diff.max())
+ name=f'{n:02d}-{clip.stem}-f{i:03d}-L{level}.png';Image.fromarray(actual).save(a.output/name)
+ rows.append({'clip':rel,'frame':i,'mouthLevel':level,'viewport':[540,540],'maxAbsRGB':int(diff.max()),'image':name})
+ if not level:tiles.append((name,Image.fromarray(actual)))
+ i+=1
+ cap.release();assert i==total
+ measurements.append({'clip':rel,'frames':total,'upperDarkEnvelope':[min(b[0] for b in bounds),min(b[1] for b in bounds),max(b[2] for b in bounds),max(b[3] for b in bounds)],'method':'all decoded frames; RGB<150; search x170:550 y0:180; silhouette includes raised hands; representative head/chin visually reviewed'})
+ sheet=Image.new('RGB',(7*270,8*294),'white');draw=ImageDraw.Draw(sheet)
+ for i,(name,im) in enumerate(tiles):sheet.paste(im.resize((270,270)),((i%7)*270,(i//7)*294));draw.text(((i%7)*270,(i//7)*294+272),name[:40],fill='black')
+ sheet.save(a.output/'contact.jpg',quality=94)
+ report={'status':'passed','preset':preset,'indexSha256':media['indexSha256'],'decodedFrames':sum(r['frames'] for r in measurements),'clipMeasurements':measurements,'glesCases':rows,'device':'not_run','scope':'Production shader strings + decoded 2D texture surrogate on host EGL; original media unchanged; no Android OES/codec/device claim.'}
+ (a.output/'report.json').write_text(json.dumps(report,indent=2)+'\n')
+ html='Liam square540 code42 previewLiam 540×540 head + upper chest
Source ROI (180,-16)–(540,344), zoom=32/9, centerY=.128125. Real offline GLES; device not tested. No media bytes changed.
Measurement / GLES report
'
+ for row in rows:html+=f'
{row["image"]}'
+ (a.output/'index.html').write_text(html)
+ print(json.dumps({'status':'passed','clips':len(measurements),'decoded_frames':report['decodedFrames'],'gles_cases':len(rows),'output':str(a.output)}))
+if __name__=='__main__':main()
diff --git a/scripts/package-character-test.py b/scripts/package-character-test.py
index 2dd19d7..28a9aa2 100644
--- a/scripts/package-character-test.py
+++ b/scripts/package-character-test.py
@@ -12,6 +12,7 @@ from pathlib import Path
import re
import shutil
import subprocess
+import struct
import tempfile
import urllib.request
import zipfile
@@ -32,10 +33,47 @@ def file_sha(p):
return hashlib.file_digest(f, 'sha256').hexdigest()
+def dex_float_fields(raw, descriptor='Lcom/gorios/lanvoice/BuildConfig;'):
+ """Read encoded FLOAT bits: dexdump prints only six significant digits."""
+ def uleb(pos):
+ value=0
+ for shift in range(0,35,7):
+ byte=raw[pos];pos+=1;value|=(byte&127)<>5)+1
+ if kind in (0x1e,0x1f):continue # null/boolean have no payload
+ require(kind in (0,2,3,4,6,16,17,23,24,25,26,27), 'unexpected BuildConfig DEX value')
+ payload=raw[values:values+length];values+=length
+ if kind==16:
+ require(length<=4,'invalid DEX float')
+ floats[name]=struct.unpack('=42,'fresh square540 code required');pack.require(not a.output.exists(),'new report required')
+ if a.publish:pack.require(not (ROOT/'artifacts'/pack.artifact_name(PROFILE,a.version_code)).exists(),'published artifact immutable')
+ if a.build:subprocess.run([str(ROOT/'scripts/build.sh'),':app:assembleDebug',':app:compileDebugAndroidTestKotlin',*pack.flags(PROFILE,a.version_code,MEDIA),'-PavatarFramingPreset='+PRESET],check=True,cwd=ROOT)
+ report=pack.verify(pack.build_dir(PROFILE)/'outputs/apk/debug/app-debug.apk',PROFILE,a.version_code,MEDIA)
+ if a.publish:report=pack.publish(pack.build_dir(PROFILE)/'outputs/apk/debug/app-debug.apk',report)
+ a.output.parent.mkdir(parents=True,exist_ok=True)
+ with a.output.open('x') as out:out.write(json.dumps(report,indent=2,ensure_ascii=False)+'\n')
+ print(json.dumps(report,indent=2,ensure_ascii=False))
diff --git a/scripts/select-character-assets.py b/scripts/select-character-assets.py
index 65bd143..2081729 100644
--- a/scripts/select-character-assets.py
+++ b/scripts/select-character-assets.py
@@ -34,10 +34,31 @@ def digest(data):
def catalog():
data = json.loads(CATALOG.read_bytes())
- require(data['schemaVersion'] == 1 and set(data['profiles']) == {'main', 'lvbu-test', 'liam-test'}, 'unsupported profile catalog')
+ require(data['schemaVersion'] == 1 and set(data['profiles']) == {'main', 'lvbu-test', 'liam-test', 'liam-test-square540'}, 'unsupported profile catalog')
return data
+def framing(profile, media_bundle, preset=None):
+ data = catalog(); role = data['profiles'][profile]
+ expected = role.get('framingPreset', 'legacy')
+ preset = expected if preset is None else preset
+ require(preset == expected, 'profile/framing preset mismatch')
+ if preset == 'legacy':
+ return {'id': preset, 'zoom': 1, 'centerY': .5}
+ row = data['framingPresets'][preset]
+ require(row['profile'] == profile and row['mediaBundle'] == media_bundle and
+ row['indexSha256'] == data['mediaBundles'][media_bundle]['indexSha256'], 'preset/media pin mismatch')
+ return {'id': preset, **row}
+
+
+def build_directory(profile, preset=None):
+ role = catalog()['profiles'][profile]
+ expected = role.get('framingPreset', 'legacy')
+ require(preset is None or preset == expected, 'profile/framing build directory mismatch')
+ base = ROOT / ('app/build' if profile == 'main' else 'app/build/characters/' + profile)
+ return base if expected == 'legacy' else base / 'framing' / expected
+
+
def authorized_debug_sha(pin):
return any(row.get('userAuthorizedDebug') is True and row['indexSha256']==pin
for row in catalog()['mediaBundles'].values())
@@ -53,6 +74,7 @@ def selection(assets, profile='main', *, emotion_sha='', user_assets=False, mout
allowed = [role['mediaSelection'], *role.get('additionalMediaSelections', [])]
require((role['mediaSelection'] == 'existing-build-flags' and bundle_id in (None,'black-correct03','white-full04')) or
bundle_id in allowed and mouth and startup, 'profile/media flags mismatch')
+ preset = framing(profile, bundle_id)
bundle = data['mediaBundles'][bundle_id] if bundle_id else None
if bundle:
require(emotion_sha == bundle['indexSha256'], 'selected exact index mismatch')
@@ -126,13 +148,13 @@ def selection(assets, profile='main', *, emotion_sha='', user_assets=False, mout
resource = ROOT / bundle.get('resourceDirectory','app/src/main/res') / 'drawable-nodpi' / (bundle['posterResource'] + '.png')
require(resource.read_bytes() == poster, 'drawable/bootstrap poster mismatch')
return {'schemaVersion': 1, 'profile': profile, 'application_id': role['applicationId'],
- 'persona': role['persona'], 'media_bundle': bundle_id, 'media_identity': bundle['identityId'] if bundle else 'a01',
+ 'persona': role['persona'], 'framing_preset': preset['id'], 'media_bundle': bundle_id, 'media_identity': bundle['identityId'] if bundle else 'a01',
'index_sha256': emotion_sha, 'files': files, 'file_count': len(files)}
def stage(assets, output, report):
output = Path(output)
- expected = ROOT / ('app/build' if report['profile'] == 'main' else 'app/build/characters/' + report['profile']) / 'generated/packagedAssets'
+ expected = build_directory(report['profile'], report.get('framing_preset')) / 'generated/packagedAssets'
require(not output.is_symlink() and output.resolve() == expected, 'staging must use isolated app build output')
output.parent.mkdir(parents=True, exist_ok=True)
temporary = Path(tempfile.mkdtemp(prefix='.character-assets-', dir=output.parent))
diff --git a/tests/avatar-pixels/gles-golden.c b/tests/avatar-pixels/gles-golden.c
index 43841b3..702ac61 100644
--- a/tests/avatar-pixels/gles-golden.c
+++ b/tests/avatar-pixels/gles-golden.c
@@ -39,7 +39,7 @@ int main(int argc,char **v) {
glActiveTexture(GL_TEXTURE1);texture(ids[1],pw,ph,v[4]);glUniform1i(glGetUniformLocation(p,"uPatch"),1);
glUniform2f(glGetUniformLocation(p,"uBodySize"),bw,bh);
float zoom=argc==18?atof(v[16]):1,centerY=argc==18?atof(v[17]):.5f;
- assert(isfinite(zoom)&&zoom>=1&&zoom<=2&&isfinite(centerY)&¢erY>=.4f&¢erY<=.6f);
+ assert((isfinite(zoom)&&zoom>=1&&zoom<=2&&isfinite(centerY)&¢erY>=.4f&¢erY<=.6f) || (fabsf(zoom-32.f/9.f)<.000001f && centerY==.128125f && bw*16==bh*9));
float scale=fminf((float)w/bw,(float)h/bh)*zoom,mw=bw*scale,mh=bh*scale,left=(w-mw)/2,top=h/2.f-mh*centerY;
GLfloat pos[]={left/w*2-1,1-(top+mh)/h*2,(left+mw)/w*2-1,1-(top+mh)/h*2,left/w*2-1,1-top/h*2,(left+mw)/w*2-1,1-top/h*2};
GLfloat uv[]={0,0,1,0,0,1,1,1};
diff --git a/tests/avatar/BuildConfig.kt b/tests/avatar/BuildConfig.kt
index 93612c2..57b972f 100644
--- a/tests/avatar/BuildConfig.kt
+++ b/tests/avatar/BuildConfig.kt
@@ -1,2 +1,2 @@
package com.gorios.lanvoice
-object BuildConfig { const val AVATAR_USER_ASSET_CANDIDATE=false;const val STARTUP_POSTER_RES_ID=1;const val AVATAR_FRAME_ZOOM=1f;const val AVATAR_FRAME_CENTER_Y=0.5f }
+object BuildConfig { const val AVATAR_FRAMING_PRESET="legacy"; const val AVATAR_USER_ASSET_CANDIDATE=false;const val STARTUP_POSTER_RES_ID=1;const val AVATAR_FRAME_ZOOM=1f;const val AVATAR_FRAME_CENTER_Y=0.5f }
diff --git a/tests/avatar/DynamicBodyCheck.kt b/tests/avatar/DynamicBodyCheck.kt
index 5a18ed9..a6909cf 100644
--- a/tests/avatar/DynamicBodyCheck.kt
+++ b/tests/avatar/DynamicBodyCheck.kt
@@ -129,6 +129,18 @@ fun dynamicBodyCheck() {
val sourceX=(displayX-zoomed.left)*720/zoomed.width
check(near(sourceX,patch.x+patch.width/2f))
}
+ val square=bodyFit(540,540,720,1280,32f/9f,.128125f,"square540-headchest")
+ fun squareNear(a: Float,b: Float)=kotlin.math.abs(a-b)<.001f
+ check(squareNear(square.left,-270f) && squareNear(square.top,24f))
+ check(squareNear(square.width,1080f) && squareNear(square.height,1920f))
+ // ROI corners and own-mouth source pixels undergo the same single transform.
+ check(squareNear((0-square.left)*720/square.width,180f))
+ check(squareNear((0-square.top)*1280/square.height,-16f))
+ check(squareNear((540-square.top)*1280/square.height,344f))
+ check(runCatching { bodyFit(540,540,720,1280,32f/9f,.128125f) }.isFailure)
+ check(runCatching { bodyFit(540,540,720,1280,3.6f,.128125f,"square540-headchest") }.isFailure)
+ check(runCatching { bodyFit(540,540,480,848,32f/9f,.128125f,"square540-headchest") }.isFailure)
+ check(runCatching { bodyFit(540,540,720,1280,1f,.5f,"unknown") }.isFailure)
for(zoom in listOf(Float.NaN,Float.POSITIVE_INFINITY,.9f,2.1f))check(runCatching { bodyFit(720,1280,720,1280,zoom) }.isFailure)
for(center in listOf(Float.NaN,.39f,.61f))check(runCatching { bodyFit(720,1280,720,1280,1.45f,center) }.isFailure)
fun render(codecW: Int,codecH: Int): Pair,List> {
diff --git a/tests/packaging/test_character_profiles.py b/tests/packaging/test_character_profiles.py
index 5614c20..e19fd5b 100644
--- a/tests/packaging/test_character_profiles.py
+++ b/tests/packaging/test_character_profiles.py
@@ -220,3 +220,57 @@ class WaitingPackTests(unittest.TestCase):
self.assertEqual(provenance['sourceInventoryMismatches'],['HANDOFF.md'])
self.assertEqual(len(provenance['sourceInventoryOmissions']),7)
self.assertFalse(provenance['runtimeReadyOverridden'])
+
+
+class Square540Tests(unittest.TestCase):
+ def test_same_exact_media_separate_identity_and_output(self):
+ media=select.catalog()['mediaBundles']['char-waiting-poses-r01']
+ def get(profile):
+ return select.selection(ASSETS,profile,emotion_sha=media['indexSha256'],user_assets=True,mouth=True,startup=True,media_bundle='char-waiting-poses-r01')
+ old,new=get('liam-test'),get('liam-test-square540')
+ self.assertEqual(old['files'],new['files']);self.assertEqual(new['file_count'],3192)
+ self.assertEqual(new['persona'],'liam');self.assertEqual(new['application_id'],'com.gorios.lanvoice.liamtest.square540')
+ self.assertEqual(new['framing_preset'],'square540-headchest');self.assertEqual(old['framing_preset'],'legacy')
+ self.assertEqual(select.build_directory('liam-test'),ROOT/'app/build/characters/liam-test')
+ self.assertEqual(select.build_directory('liam-test-square540'),ROOT/'app/build/characters/liam-test-square540/framing/square540-headchest')
+ with self.assertRaises(ValueError):select.stage(ASSETS,select.build_directory('liam-test')/'generated/packagedAssets',new)
+ self.assertFalse(select.catalog()['profiles']['liam-test-square540']['allowBackup'])
+ self.assertFalse(select.catalog()['profiles']['liam-test-square540']['permissionConnectionRetention'])
+
+ def test_controlled_preset_cannot_bleed_into_legacy_or_different_media(self):
+ for profile in ('main','lvbu-test','liam-test'):
+ with self.assertRaises(ValueError):select.framing(profile,'char-waiting-poses-r01','square540-headchest')
+ for media in ('white-full04','black-correct03','char-expressions-r02',None):
+ with self.assertRaises(ValueError):select.framing('liam-test-square540',media)
+ with self.assertRaises(ValueError):select.build_directory('liam-test-square540','legacy')
+ with self.assertRaises(ValueError):select.framing('liam-test-square540','char-waiting-poses-r01','legacy')
+ p=select.framing('liam-test-square540','char-waiting-poses-r01')
+ self.assertEqual(p['sourceRect'],[180,-16,540,344]);self.assertAlmostEqual(p['zoom'],1280/360)
+ self.assertAlmostEqual(p['centerY'],164/1280)
+ text=(ROOT/'app/build.gradle').read_text()
+ self.assertIn('Controlled preset cannot be overridden',text)
+ self.assertIn("avatarFrameZoom > 2f",text);self.assertIn("avatarFrameCenterY < 0.4f",text)
+
+ def test_independent_entry_keeps_old_wrapper_and_names(self):
+ spec=importlib.util.spec_from_file_location('pack',ROOT/'scripts/package-character-test.py');pack=importlib.util.module_from_spec(spec);spec.loader.exec_module(pack)
+ self.assertEqual(pack.artifact_name('liam-test-square540',42),'lan-voice-v0714-liam-test-square540-code42-arm64-debug.apk')
+ flags=pack.flags('liam-test-square540',42,'char-waiting-poses-r01')
+ self.assertIn('-PavatarUserNetworkActions=true',flags)
+ self.assertTrue(any(f.startswith('--project-cache-dir=') and 'liam-test-square540/square540-headchest' in f for f in flags))
+ self.assertFalse(any(f.startswith('--project-cache-dir=') for f in pack.flags('liam-test',41,'char-waiting-poses-r01')))
+ yangmi=(ROOT/'scripts/package-avatar-framing.py').read_text()
+ self.assertIn("'-PavatarFrameZoom=1.45','-PavatarFrameCenterY=0.489'",yangmi)
+
+ def test_actual_dex_float_bits_preserve_existing_framing(self):
+ import struct
+ spec=importlib.util.spec_from_file_location('pack',ROOT/'scripts/package-character-test.py');pack=importlib.util.module_from_spec(spec);spec.loader.exec_module(pack)
+ # Known immutable prior APK: ensure exact float bits, independent of dexdump text rounding.
+ with zipfile.ZipFile(ROOT/'artifacts/lan-voice-v0714-yangmi-framing145-code39-arm64-debug.apk') as z:
+ values=None
+ for name in z.namelist():
+ if name.startswith('classes') and name.endswith('.dex'):
+ try:values=pack.dex_float_fields(z.read(name));break
+ except ValueError:pass
+ self.assertIsNotNone(values)
+ for field,value in [('AVATAR_FRAME_ZOOM',1.45),('AVATAR_FRAME_CENTER_Y',.489)]:
+ self.assertEqual(values[field],struct.unpack('