"""Targeted 0.4.2 GPU regressions. Synthetic fixtures, not Minecraft screenshots."""
import json, shutil, math
from pathlib import Path
from render_support import *
checks=[]
def ck(n,c,**m):
 checks.append(dict(name=n,passed=bool(c),metrics=m))
 print(('PASS ' if c else 'FAIL ')+n,flush=True)
def dep(z):
 p=persp()@np.array([0.,0.,z,1.]);return float(p[2]/p[3]*.5+.5)
probe=ROOT/'repairs_fixture';probe.mkdir(exist_ok=True)
(probe/'probe.vsh').write_text('#version 330 compatibility\n#define DIMENSION 0\n#include "/program/fullscreen.vsh"\n')
def body(code):
 (probe/'probe.fsh').write_text('''#version 330 compatibility
#define DIMENSION 0
#include "/lib/settings.glsl"
#include "/lib/uniforms.glsl"
#include "/lib/math.glsl"
#include "/lib/shadows.glsl"
#include "/lib/materials.glsl"
#include "/lib/sky.glsl"
#include "/lib/lighting.glsl"
#include "/lib/surfaces.glsl"
#include "/lib/reflections.glsl"
in vec2 vUV;
void main(){'''+code+'}\n')
def run(**kw):return draw('probe',folder='repairs_fixture',**kw)[0]
try:
 # The cloud mask must not darken moonlit surfaces.
 body('vec3 p=vec3((vUV.x-.5)*600.,0.,(vUV.y-.5)*600.);gl_FragData[0]=vec4(illumination(p,vec3(0.,0.,-10.),vec3(0.,1.,0.),vec3(0.,1.,0.),vec2(.03125,1.)),1.);')
 night={'sunPosition':(0.,-80.,-30.),'moonPosition':(0.,80.,30.),'shadowLightPosition':(0.,80.,30.)}
 opts={'SHADOWS':'0','CLOUD_COVERAGE':'0.75','HAND_LIGHTS':'0'}
 on=run(values=night,overrides={**opts,'CLOUD_SHADOWS':'1'});off=run(values=night,overrides={**opts,'CLOUD_SHADOWS':'0'})
 ck('No cloud shadow mask at night',np.allclose(on,off,atol=1e-7))
 on=run(overrides={**opts,'CLOUD_SHADOWS':'1'});off=run(overrides={**opts,'CLOUD_SHADOWS':'0'})
 ck('Daylight cloud shadows retained',float(abs(on-off).max())>.02)
 # Passive IDs formerly mapped must have zero invented emission.
 for id in [3007,3008,3009,3010,3011,3012,3015,3017,3029,3030,3049,3052,0]:
  a=draw('gbuffers_entities',geometry=True,values={'entityId':id},textures={'gtexture':texture(np.ones((64,64,4),np.float32))})[3]
  ck('No artificial eye glow for excluded ID '+str(id),np.allclose(a[:,:,:3],0.))
 coverage=json.loads((ROOT.parent/'docs/eye_templates.json').read_text())
 for e in coverage['templates']:
  w,h=e['size'];a=draw('gbuffers_entities',geometry=True,values={'entityId':e['id']},textures={'gtexture':texture(np.ones((h,w,4),np.float32))})[3]
  ck('Hostile eye template white '+str(e['id']),np.allclose(a[:,:,0],a[:,:,1]) and np.allclose(a[:,:,1],a[:,:,2]) and float(a[:,:,:3].max())>0.)
 for id in (3090,3091):
  a=draw('gbuffers_spidereyes',geometry=True,values={'entityId':id},textures={'gtexture':texture([.9,.2,.1,1.])})[3]
  ck('Spider red native layer' if id==3090 else 'Other hostile native eyes white',float(a[:,:,0].max())>0 and ((float(a[:,:,1].max())<float(a[:,:,0].max())*.02) if id==3090 else np.allclose(a[:,:,0],a[:,:,2])))
 body('float wet,puddle;vec3 m=hollowSurfaceProperties(entityId,vec3(vUV.x*32.,64.,vUV.y*32.),vec3(0.,1.,0.),vec2(.03125,1.),wet,puddle);gl_FragData[0]=vec4(m.x,m.y,wet,puddle);')
 for id in [0,1405,1406,1409,1410]:
  a=run(values={'entityId':id});ck('Dry rough surface has no reflection '+str(id),np.allclose(a[:,:,1],0.))
 for id in [1401,1402,1403,1404,1408]:
  a=run(values={'entityId':id});ck('Dry reflective material remains reflective '+str(id),float(a[:,:,1].max())>.02)
 wetEnv={'rainStrength':1.,'wetness':1.,'entityId':1409}
 a=run(values=wetEnv);ck('Wet farmland and paths stay rough',float(a[:,:,0].min())>=.88 and float(a[:,:,1].max())<.008 and float(a[:,:,3].max())==0.)
 soil=run(values={**wetEnv,'entityId':1406});stone=run(values={**wetEnv,'entityId':0})
 ck('Soil less reflective than wet stone',float(soil[:,:,1].mean())<float(stone[:,:,1].mean()) and float(soil[:,:,0].mean())>float(stone[:,:,0].mean()))
 ck('Wet stone develops irregular puddles',float(stone[:,:,3].max())>.05 and float(stone[:,:,3].min())==0.)
 for id in [1407,1302]:
  a=run(values={**wetEnv,'entityId':id});ck('Snow/plants do not become puddle mirrors '+str(id),np.allclose(a[:,:,2:],0.))
 cold=run(values={**wetEnv,'entityId':0,'hollowWetClimate':0.});ck('Snow climate excludes rain film',np.allclose(cold[:,:,2:],0.))
 # Reflection source has linear depth matching its color, not another depth buffer.
 body('gl_FragData[0]=hollowScreenReflection(fogColor,safeNormalize(skyColor),0.2,vec3(0.,1.,0.));')
 ray={'fogColor':(0.,-1.,-3.),'skyColor':(.1,.3,-1.)}
 snapshot=texture([.7,.2,.1,8.]);textures={'colortex7':snapshot,'depthtex1':texture([dep(-3.2)]*3+[1.])}
 hit=run(values=ray,textures=textures);ck('SSR hits real opaque geometry',float(hit[:,:,3].mean())>.6,confidence=float(hit[:,:,3].mean()))
 ck('SSR radiance comes from matching snapshot',np.allclose(hit[:,:,:3],[.7,.2,.1],atol=1e-5))
 other=run(values=ray,textures={**textures,'depthtex1':texture([dep(-20.)]*3+[1.])})
 ck('Under-ice depth cannot mismatch opaque snapshot radiance',np.array_equal(hit,other))
 for label,tex in [('sky',[.7,.2,.1,0.]),('hand',[.7,.2,.1,-8.])]:
  a=run(values=ray,textures={'colortex7':texture(tex)});ck('SSR excludes '+label,float(a[:,:,3].max())==0.)
 below=run(values={**ray,'skyColor':(.1,-.3,-1.)},textures={'colortex7':snapshot})
 ck('SSR rejects geometry below receiver plane',float(below[:,:,3].max())==0.)
 selfHit=run(values=ray,textures={'colortex7':texture([.7,.2,.1,3.])})
 ck('SSR avoids immediate self intersection',float(selfHit[:,:,3].max())==0.)
 # Snapshot output itself; a hand silhouette is dilated and signed negative.
 sz=np.zeros((H,W,4),np.float32);sz[:,W//2:W//2+3,0]=1.
 snap=draw('deferred1',textures={'depthtex0':texture(np.full((H,W,4),[dep(-6.),dep(-6.),dep(-6.),1.],np.float32)),'colortex0':texture(np.full((H,W,4),[.4,.3,.2,1.],np.float32)),'colortex2':texture(sz)})[1]
 ck('Snapshot stores linear depth',np.allclose(snap[:,:W//2-2,3],6.,atol=.005))
 ck('Snapshot excludes/dilates hands',np.all(snap[:,W//2-1:W//2+4,3]<0.))
 # Four low-steepness waves; coherent motion, bounded slopes.
 body('vec2 s=hollowWaterSlope((vUV-.5)*20.);gl_FragData[0]=vec4(s,0.,1.);')
 a=run();b=run(values={'frameTimeCounter':20.016});c=run(values={'frameTimeCounter':21.})
 ck('Water slope bounded and finite',np.isfinite(a).all() and float(np.abs(a[:,:,:2]).max())<.09)
 ck('Water moves smoothly between frames',float(abs(a-b).max())<.01 and not np.allclose(a,c))
 body('gl_FragData[0]=hollowRainImpact((vUV-.5)*4.);')
 wet={'rainStrength':1.,'wetness':1.}
 dry=run();rain=run(values=wet);later=run(values={**wet,'frameTimeCounter':20.15})
 ck('No contact rings when rain stops',np.allclose(dry,0.))
 ck('Rain creates expanding rings and impact crowns',float(rain[:,:,2].max())>.2 and float(rain[:,:,3].max())>.05)
 ck('Contact events animate',not np.allclose(rain,later))
 ck('Contact events remain finite',np.isfinite(rain).all())
 ck('Cold precipitation produces no rain impacts',np.allclose(run(values={**wet,'hollowWetClimate':0.}),0.))
 ck('Both contact switches off disable effects',np.allclose(run(values=wet,overrides={'RAIN_SPLASHES':'0','RAIN_RIPPLES':'0'}),0.))
 body('gl_FragData[0]=vec4(vec3(hollowRainDropAlpha(vUV)),1.);')
 a=run();fraction=float((a[:,:,0]>.01).mean())
 ck('Rain streaks leave gaps rather than solid curtains',.01<fraction<.30,coverage=fraction)
 ck('Rain streaks have soft intensity edges',len(np.unique(a[:,:,0]))>20)
 # Actual geometry receives wet-contact metadata, never hands/entities/snow.
 for id in [0,1402,1409,1407,1302]:
  a=draw('gbuffers_terrain',geometry=True,normal=(0.,1.,0.),lm=(.03125,1.),material=id,values=wet)[2]
  ck('Rain contact eligibility '+str(id),float(a[:,:,0].min())<0. if id in [0,1402,1409] else np.allclose(a[:,:,0],0.))
 a=draw('gbuffers_entities',geometry=True,normal=(0.,1.,0.),lm=(.03125,1.),values=wet)[2]
 ck('Rain splashes do not attach to mobs',np.allclose(a[:,:,0],0.))
 # Construct a real perspective ground plane for depth-tested above-ground beads.
 angle=math.radians(30);rot=np.eye(4,dtype=np.float32);rot[1:3,1:3]=[[math.cos(angle),-math.sin(angle)],[math.sin(angle),math.cos(angle)]];inv=rot.T.copy()
 ys,xs=np.mgrid[0:H,0:W];uv=np.stack(((xs+.5)/W,(ys+.5)/H),axis=-1)
 clip=np.concatenate((uv*2-1,np.zeros((H,W,1)),np.ones((H,W,1))),axis=2)
 v=clip@np.linalg.inv(persp()).T;v=v[:,:,:3]/v[:,:,3:];r=v@inv[:3,:3].T
 t=-2./np.minimum(r[:,:,1],-.0001);points=r*t[:,:,None];vp=points@rot[:3,:3].T
 cp=np.concatenate((vp,np.ones((H,W,1))),axis=2)@persp().T;depths=cp[:,:,2]/cp[:,:,3]*.5+.5
 valid=(r[:,:,1]<-.001)&(t>0);depths=np.where(valid,depths,1.)
 depthtex=texture(np.stack([depths,depths,depths,np.ones_like(depths)],axis=2))
 metadata=np.full((H,W,4),[-1.,0.,.5,1.],np.float32);metadata[~valid,0]=0.
 env={**wet,'gbufferModelView':rot,'gbufferModelViewInverse':inv,'cameraPosition':(0.,2.,0.)}
 inputs={'depthtex0':depthtex,'colortex2':texture(metadata)}
 body('vec3 v=viewAt(vUV,texture2D(depthtex0,vUV).r);gl_FragData[0]=vec4(hollowNearRainSplashes(vUV,v,vec3(.5)),1.);')
 strength=0.;images=[]
 for tm in [1.,1.12,1.24,1.36]:
  img=run(values={**env,'frameTimeCounter':tm},textures=inputs);images.append(img);strength=max(strength,float(img[:,:,:3].max()))
 ck('Depth-tested beads visible above a real perspective floor',strength>1e-5,max_bead=strength)
 ck('Above-ground impact beads animate',not np.allclose(images[0],images[-1],atol=1e-7))
 dry=run(values={**env,'rainStrength':0.},textures=inputs)
 ck('No splash beads after rain stops',np.allclose(dry[:,:,:3],0.))
 roof=run(values=env,textures={**inputs,'colortex2':texture([0.,0.,.5,1.])})
 ck('No splash beads without exposed receivers',np.allclose(roof[:,:,:3],0.))
 walls=run(values=env,textures={**inputs,'colortex2':texture([-1.,0.,.5,.5])})
 ck('No splash beads on vertical walls',np.allclose(walls[:,:,:3],0.))
 off=run(values=env,textures=inputs,overrides={'RAIN_SPLASHES':'0'})
 ck('Splash switch disables above-ground beads',np.allclose(off[:,:,:3],0.))
 body('gl_FragData[0]=vec4(vec3(hollowRainBead(vUV,vec3(0.,0.,-4.),0.04,3.)),1.);')
 blocked=run();ck('Foreground depth occludes splash beads',np.allclose(blocked[:,:,:3],0.))
finally:shutil.rmtree(probe)
report={'release':'0.4.2','passed':sum(q['passed'] for q in checks),'total':len(checks),'scope':'Local software OpenGL synthetic geometry/texture fixtures. Not Oculus, Minecraft, AMD or in-game frame tests.','checks':checks}
(ROOT.parent/'docs/repairs_042_report.json').write_text(json.dumps(report,indent=2)+'\n')
print('TARGETED',report['passed'],'/',report['total']);sys.exit(0 if report['passed']==report['total'] else 1)
