"""RHG-side final material conversion from the PMP20 channel bake receipt.""" import importlib.util,json,sys,math from pathlib import Path def verify_images(transfer,reference,texture_contract=None): from .texture_metrics import compare, CONTRACT contract_path=Path(texture_contract) if texture_contract is not None else CONTRACT contract=json.loads(contract_path.read_text(encoding='utf-8')) import numpy as np from PIL import Image receipt=json.loads((transfer/'bake-receipt.json').read_text());rows=[] for frame in receipt['converted']: name=frame['camera'].removeprefix('transfer_view_') original=np.asarray(Image.open(reference/(name+'.png')).convert('RGB'),dtype=float) converted=np.asarray(Image.open(transfer/frame['path']).convert('RGB'),dtype=float) if original.shape!=converted.shape:raise ValueError('Source/baked camera image dimensions differ') error=abs(original-converted) clarity=(compare(reference/(name+'.png'),transfer/frame['path'],name,contract) if name in contract['regions'] and original.shape[:2]==(720,960) else dict(clarity_passed=False,available=False,reason='No frozen ROI for this camera/resolution')) rows.append(dict(view=name,mae=float(error.mean()),p95=float(np.percentile(error,95)),clarity=clarity)) mean_passed=len(rows)==len(receipt['views']) and all(r['mae']<=5. for r in rows) clarity_passed=bool(rows) and all(r['clarity']['clarity_passed'] for r in rows) return dict(passed=mean_passed and clarity_passed,mean_error_passed=mean_passed, threshold_mae=5.,threshold_source='PMP20 source conversion contract', registration_or_exposure_fitting=False,views=rows, clarity_passed=clarity_passed,texture_contract=contract) def apply_baked(stage,transfer,output,shared): from pxr import Gf,Sdf,UsdGeom,UsdShade,Tf from .rparena_v16 import intern,sha worker=Path(__file__).resolve().parents[2]/'scripts/source_transfer' sys.path.insert(0,str(worker)) from usd_scene_transfer_worker import MDL_SCALARS,MDL_COLORS,MDL_MAPS receipt=json.loads((transfer/'bake-receipt.json').read_text());records={r['usd_material_name']:r for r in receipt['materials']} if 'texture_budget' in receipt: budget=receipt['texture_budget'] if budget['estimated_resident_bytes']>budget['budget_bytes']:raise ValueError('Scene texture budget exceeded') (output/'texture-budget.json').write_text(json.dumps(budget,indent=2)) spec=importlib.util.find_spec('isaacsim');base=Path(spec.origin).parent mdl=base/'kit/mdl/core/Base/OmniSurface.mdl' if not mdl.is_file():raise FileNotFoundError(mdl) changes=[];ray_changes=[] rays=json.loads((output/'source-ray-visibility.json').read_text())['objects'] ray_lookup=dict(rays) for name,value in rays.items(): key=Tf.MakeValidIdentifier(name) if key in ray_lookup and ray_lookup[key]!=value:raise ValueError('Ambiguous sanitized source visibility name') ray_lookup[key]=value for name,values in rays.items(): if not values['hide_render'] and any(not values[k] for k in ['visible_camera','visible_diffuse','visible_glossy','visible_transmission','visible_volume_scatter']): raise ValueError('Unsupported non-shadow source ray visibility: '+name) for p in stage.Traverse(): if p.IsA(UsdGeom.Mesh): q=p;names=[];settings=None while q: names=[q.GetName(),str(q.GetMetadata('displayName')),*[str(a.Get()) for a in q.GetAttributes() if a.GetName().endswith('object_name')]] settings=next((ray_lookup[n] for n in names if n in ray_lookup),None) if settings is not None:break q=q.GetParent() if settings is None:raise ValueError('Mesh has no source ray-visibility owner: '+str(p.GetPath())) p.CreateAttribute('primvars:doNotCastShadows',Sdf.ValueTypeNames.Bool).Set(not settings['visible_shadow']) if settings['hide_render']:UsdGeom.Imageable(p).CreateVisibilityAttr('invisible') if not settings['visible_shadow']:ray_changes.append(str(p.GetPath())) if p.GetName() in receipt['hidden_source_objects']: UsdGeom.Imageable(p).CreateVisibilityAttr('invisible') if p.IsA(UsdShade.Shader): sh=UsdShade.Shader(p);ior=sh.GetInput('ior') if sh.GetIdAttr().Get()=='UsdPreviewSurface' and ior and ior.Get() is not None and ior.Get()<1.: changes.append(dict(shader=str(p.GetPath()),source_ior=ior.Get(),ior=1.5,policy='PMP20_explicit_compatibility')) ior.Set(1.5) mdl_count=0;specular_mappings=[] for p in list(stage.Traverse()): if not p.IsA(UsdShade.Material) or p.GetName() not in records:continue r=records[p.GetName()] c=dict(r['constants']);level=float(c.get('Specular IOR Level',.5));source_ior=float(c.get('IOR',1.5)) opaque=c.get('Transmission Weight',0.)==0. and 'transmission' not in r['maps'] effective_ior=None if opaque and 'specular_weight' not in r['maps'] and abs(level-.5)>1e-6: # Cycles Principled adjusts dielectric F0, then converts back to # reflection IOR. A nonstandard PreviewSurface "specular" input # cannot preserve this value. Refraction is excluded from this path. f0=((source_ior-1.)/(source_ior+1.))**2*2.*max(level,0.) if not 0<=f0<1:raise ValueError('Unsupported source dielectric F0') root=math.sqrt(f0);effective_ior=(1.+root)/(1.-root) needs_separate_coat=effective_ior is not None and c.get('Coat Weight',0.)>0. if r['target_shader']!='OmniSurface' and not needs_separate_coat: if effective_ior is not None: from pxr import Usd shaders=[UsdShade.Shader(q) for q in Usd.PrimRange(p) if q.IsA(UsdShade.Shader) and UsdShade.Shader(q).GetIdAttr().Get()=='UsdPreviewSurface'] if len(shaders)!=1:raise ValueError('Ambiguous PreviewSurface source') shaders[0].CreateInput('ior',Sdf.ValueTypeNames.Float).Set(effective_ior) specular_mappings.append(dict(material=str(p.GetPath()),source_ior=source_ior,source_level=level,reflection_ior=effective_ior,shader='UsdPreviewSurface')) continue if needs_separate_coat and r['target_shader']!='OmniSurface': from scene_transfer import CHANNELS if any(channel not in r['maps'] and name not in c for channel,name in CHANNELS.items()): raise ValueError('Separate coat/base IOR requires complete source channel data: '+r['source_material']) m=UsdShade.Material(p);sh=UsdShade.Shader.Define(stage,str(p.GetPath())+'/RHGSourceSurface') sh.CreateImplementationSourceAttr(UsdShade.Tokens.sourceAsset);sh.SetSourceAsset(Sdf.AssetPath(str(mdl)),'mdl');sh.SetSourceAssetSubIdentifier('OmniSurface','mdl');sh.CreateOutput('out',Sdf.ValueTypeNames.Token) sh.CreateInput('diffuse_reflection_weight',Sdf.ValueTypeNames.Float).Set(1.);sh.CreateInput('enable_specular_transmission',Sdf.ValueTypeNames.Bool).Set(bool(c.get('Transmission Weight',0)>0 or 'transmission' in r['maps']));sh.CreateInput('specular_reflection_weight',Sdf.ValueTypeNames.Float).Set(1. if effective_ior is not None else min(1.,2.*level));sh.CreateInput('thin_walled',Sdf.ValueTypeNames.Bool).Set(False) for src,dest in MDL_SCALARS.items(): if src in c: v=float(c[src]);v=1.5 if src in ('IOR','Coat IOR') and v<1 else v sh.CreateInput(dest,Sdf.ValueTypeNames.Float).Set(v) for src,dest in MDL_COLORS.items(): if src in c:sh.CreateInput(dest,Sdf.ValueTypeNames.Color3f).Set(Gf.Vec3f(*c[src][:3])) if effective_ior is not None: sh.GetInput('specular_reflection_ior').Set(effective_ior) specular_mappings.append(dict(material=str(p.GetPath()),source_ior=source_ior,source_level=level,reflection_ior=effective_ior,shader='OmniSurface',coat_ior=c.get('Coat IOR'))) if c.get('Emission Strength',0)>0 or 'emission_strength' in r['maps']:sh.CreateInput('emission_weight',Sdf.ValueTypeNames.Float).Set(1.) for ch,image in r['maps'].items(): f=transfer/image.get('native_path',image['path']);name=sha(f)+f.suffix.lower();intern(f,output/'assets'/name,shared/name) sh.CreateInput(MDL_MAPS[ch],Sdf.ValueTypeNames.Asset).Set(Sdf.AssetPath('assets/'+name));sh.GetInput(MDL_MAPS[ch]).GetAttr().SetColorSpace('sRGB' if image['color_space']=='sRGB' else 'raw') m.CreateSurfaceOutput('mdl').ConnectToSource(sh.ConnectableAPI(),'out');m.CreateVolumeOutput('mdl').ConnectToSource(sh.ConnectableAPI(),'out');mdl_count+=1 return dict(source_bake_sha256=sha(transfer/'bake-receipt.json'),mdl_materials=mdl_count,ior_compatibility=changes,specular_ior_mappings=specular_mappings,source_no_shadow_meshes=ray_changes,runtime_dependencies={'OmniSurface.mdl':dict(path=str(mdl),sha256=sha(mdl))})