"""0.4.0 offscreen behavior regressions. No Minecraft, Oculus patcher or AMD driver."""
import json,shutil
from pathlib import Path
from render_support import *
results=[]
def ck(name,truth,**metrics):
 results.append({'name':name,'passed':bool(truth),'metrics':metrics})
 if not truth:print('FAIL',name,metrics,flush=True)
def finite(name,a):ck(name,np.isfinite(a).all())
def depth(z):
 q=persp()@np.array([0.,0.,z,1.]);return float(q[2]/q[3]*.5+.5)
probe=ROOT/'weather_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/sky.glsl"
#include "/lib/fog.glsl"
#include "/lib/surfaces.glsl"
in vec2 vUV;
void main(){'''+code+'}\n')
def run(**kwargs):return draw('probe',folder='weather_fixture',**kwargs)
try:
 body('gl_FragData[0]=hollowFogVolume(safeNormalize(fogColor),far,1.0,false);')
 env={'fogColor':(0.,0.,-1.),'far':100.,'cameraPosition':(3.,64.,5.)}
 options={'DISTANCE_FOG':'0'}
 short=run(values={**env,'far':4.},overrides=options)[0]
 long=run(values=env,overrides=options)[0]
 off=run(values=env,overrides={**options,'FOG_DENSITY':'0.0'})[0]
 high=run(values={**env,'cameraPosition':(3.,190.,5.)},overrides=options)[0]
 rainy=run(values={**env,'rainStrength':1.},overrides=options)[0]
 ck('Nearby clear radius has no atmosphere wash',np.allclose(short[:,:,:3],0.) and np.allclose(short[:,:,3],1.))
 ck('Fog integrates distance rather than uniform overlay',float(long[:,:,3].mean())<.9,T=float(long[:,:,3].mean()))
 ck('Fog density zero removes integrated fog',np.allclose(off[:,:,:3],0.) and np.allclose(off[:,:,3],1.))
 ck('High altitude has less ground fog',float(high[:,:,3].mean())>float(long[:,:,3].mean())+.1)
 ck('Rain thickens fog',float(rainy[:,:,3].mean())<float(long[:,:,3].mean()))
 moved=run(values={**env,'frameTimeCounter':90.},overrides=options)[0]
 ck('Fog banks move slowly in world space',not np.allclose(moved,long))
 for quality in ['0','1','2']:
  a=run(values=env,overrides={**options,'FOG_QUALITY':quality})[0]
  finite('Fog quality '+quality+' finite',a)
  ck('Fog quality '+quality+' bounded',float(a[:,:,3].min())>=0. and float(a[:,:,3].max())<=1.)
 body('gl_FragData[0]=hollowFogVolume(safeNormalize(vec3((vUV-0.5)*0.9,-1.0)),far,1.0,false);')
 a=run(values=env,overrides=options)[0]
 ck('Spatial density produces different fog along different rays',float(a[:,:,3].std())>.005,std=float(a[:,:,3].std()))
 body('gl_FragData[0]=hollowFogVolume(safeNormalize(fogColor),far*1.35,1.0,true);')
 horizon=run(values=env)[0];up=run(values={**env,'fogColor':(0.,1.,0.)})[0]
 ck('Horizon closes while upper sky stays readable',float(horizon[:,:,3].mean())<.02 and float(up[:,:,3].mean())>.7, horizon=float(horizon[:,:,3].mean()), upper_sky=float(up[:,:,3].mean()))
 body('float d,p;vec3 m=hollowSurfaceProperties(entityId,vec3((vUV.x-0.5)*128.0,64.0,(vUV.y-0.5)*128.0),vec3(0.,1.,0.),vec2(0.,fogColor.x),d,p);gl_FragData[0]=vec4(m,1.);gl_FragData[1]=vec4(d,p,0.,1.);')
 env={'entityId':0,'fogColor':(1.,0.,0.)}
 dry=run(values=env);wet=run(values={**env,'wetness':1.,'rainStrength':1.})
 ck('Rough dry stone has no mirror coat',float(dry[0][:,:,1].max())==0. and float(dry[1][:,:,0].max())==0.)
 ck('Rain increases stone reflectance',float(wet[0][:,:,1].mean())>.025)
 ck('Rain smooths wettable stone',float(wet[0][:,:,0].mean())<float(dry[0][:,:,0].mean()))
 ck('Puddles are spatial patches rather than universal mirror',float(wet[1][:,:,1].std())>.05 and float((wet[1][:,:,1]>.2).mean())<.8)
 indoor=run(values={**env,'wetness':1.,'rainStrength':1.,'fogColor':(0.,0.,0.)})
 ck('Zero skylight suppresses indoor wetness',float(indoor[1][:,:,0].max())==0.)
 cold=run(values={**env,'wetness':1.,'rainStrength':1.,'hollowWetClimate':0.})
 ck('Snowy or dry climate has no rain puddles',float(cold[1][:,:,:2].max())==0.)
 snow=run(values={**env,'entityId':1407,'wetness':1.,'rainStrength':1.})
 ck('Snow material is not turned into wet mirror',float(snow[0][:,:,1].max())==0. and float(snow[1][:,:,:2].max())==0.)
 drying=run(values={**env,'wetness':.6,'rainStrength':0.})
 ck('Surface film persists after rainfall until wetness decays',float(drying[1][:,:,0].mean())>.5)
 for mat in [1401,1402,1403,1404]:
  a=run(values={**env,'entityId':mat})
  ck('Dry reflective material '+str(mat)+' has base reflection',float(a[0][:,:,1].mean())>.02)
  finite('Material '+str(mat)+' metadata finite',a[0])
 body('vec2 n=hollowRainRipple((vUV-0.5)*3.0);gl_FragData[0]=vec4(n,0.,1.);')
 dry=run()[0];rain=run(values={'rainStrength':1.,'wetness':1.})[0]
 cold=run(values={'rainStrength':1.,'hollowWetClimate':0.})[0]
 stopped=run(values={'rainStrength':0.,'wetness':1.})[0]
 ck('Dry weather has no rain rings',np.allclose(dry[:,:,:2],0.))
 ck('Active rain creates ripple gradients',float(np.abs(rain[:,:,:2]).max())>.002)
 ck('Snow does not create water rain rings',np.allclose(cold[:,:,:2],0.))
 ck('Rain rings stop while ground remains wet',np.allclose(stopped[:,:,:2],0.))
 later=run(values={'rainStrength':1.,'frameTimeCounter':20.2})[0]
 ck('Rain rings animate',not np.allclose(rain,later))
 disabled=run(values={'rainStrength':1.},overrides={'RAIN_RIPPLES':'0'})[0]
 ck('Ripple option disables effect cleanly',np.allclose(disabled[:,:,:2],0.))
 # Packed metadata uses all 2048 exactly-representable small integers in fp16.
 codes=np.tile(np.arange(2048,dtype=np.float32),4).reshape(H,W)
 quant=codes.astype(np.float16).astype(np.float32)
 ck('All 2048 material codes survive half-float storage',np.array_equal(codes,quant))
 arr=np.zeros((H,W,4),np.float32);arr[:,:,3]=quant
 body('vec3 m=hollowUnpackSurface(texture2D(gtexture,vUV).a);gl_FragData[0]=vec4(m,hollowPackSurface(m));')
 a=run(textures={'gtexture':texture(arr)})[0]
 ck('GPU decode and re-encode preserve every material code',np.allclose(a[:,:,3],codes,atol=.05))
 body('vec3 n=safeNormalize(fogColor);gl_FragData[0]=vec4(hollowOctDecode(hollowOctEncode(n)),1.0);')
 for vec in [(0,1,0),(0,-1,0),(0,0,1),(0,0,-1),(1,0,0),(-1,0,0),(.4,.6,-.8)]:
  n=np.array(vec,dtype=float);n/=np.linalg.norm(n);a=run(values={'fogColor':tuple(float(x) for x in vec)})[0]
  ck('Normal roundtrip '+str(vec),np.allclose(a[:,:,:3],n,atol=1e-5))
 body('float q=hollowBlockCloudOccupancy((vUV-0.5)*900.0);gl_FragData[0]=vec4(vec3(q),1.);')
 a=run()[0];frac=float((a[:,:,0]>.5).mean())
 ck('Normal block clouds have visible gaps and solid shapes',.05<frac<.95,coverage=frac)
 ck('Cloud silhouettes are mostly solid or empty, not smeared streaks',float(((a[:,:,0]<.05)|(a[:,:,0]>.95)).mean())>.70)
 body('gl_FragData[0]=cloudLayer(safeNormalize(fogColor),vUV,far);')
 before=run(values={'fogColor':(.1,1.,.1),'far':40.})[0]
 ck('Block clouds respect foreground occlusion',np.allclose(before[:,:,:3],0.) and np.allclose(before[:,:,3],1.))
 for y in [64.,230.,236.,260.,400.]:
  a=run(values={'fogColor':(1.,.01,0.),'far':1000.,'cameraPosition':(0.,y,0.)})[0]
  finite('Cloud camera height '+str(y),a)
finally:shutil.rmtree(probe)
# White glow is independent of underlying native eye colors.
for native in ([1.,0.,0.,1.],[0.,1.,.2,1.],[.2,.1,.9,1.]):
 a=draw('gbuffers_spidereyes',geometry=True,values={'entityId':3091},textures={'gtexture':texture(native)})[1]
 ck('Native colored eyes become neutral white '+str(native),np.allclose(a[:,:,0],a[:,:,1]) and np.allclose(a[:,:,1],a[:,:,2]) and float(a[:,:,:3].max())>0.)
mask=texture(np.full((64,64,4),[.2,.3,.1,1.],np.float32))
a=draw('gbuffers_entities',geometry=True,values={'entityId':3001},textures={'gtexture':mask})[3]
ck('Templated mob eyes default to neutral white',np.allclose(a[:,:,0],a[:,:,1]) and np.allclose(a[:,:,1],a[:,:,2]) and float(a[:,:,:3].max())>0.)
# Opaque SSR is verified through the real composite program, not only the helper.
metadata=texture(np.full((H,W,4),[0.,0.,.5,1.],np.float32));payload=texture(np.full((H,W,4),[0.,0.,0.,3.+5.*16.],np.float32))
zero=texture([0.,0.,0.,0.]);snapshot=texture([.8,.1,.05,8.]);base=texture([.05,.05,.05,1.])
inputs={'depthtex0':texture([depth(-3.)]*3+[1.]),'depthtex1':texture([depth(-8.)]*3+[1.]),'colortex0':base,'colortex1':zero,'colortex2':metadata,'colortex3':payload,'colortex7':snapshot}
opts={'FOG_DENSITY':'0.0','DISTANCE_FOG':'0','CLOUD_GEOMETRY':'0','CONTACT_AO':'0'}
on=draw('composite',textures=inputs,overrides=opts)[0]
off=draw('composite',textures=inputs,overrides={**opts,'SURFACE_REFLECTIONS':'0'})[0]
ck('Opaque-surface reflections run in the composite pass',float(np.abs(on-off).max())>.05,max_delta=float(np.abs(on-off).max()))
noReflect=draw('composite',textures={**inputs,'colortex3':texture(np.zeros((H,W,4),np.float32))},overrides=opts)[0]
ck('Unmapped rough dry surfaces bypass reflections',np.allclose(noReflect,off))
water=draw('composite',textures={**inputs,'colortex2':texture(np.full((H,W,4),[0.,1.,.5,1.],np.float32))},overrides=opts)[0]
ck('Water does not receive second opaque reflection coat',np.allclose(water,off))
hand=draw('composite',textures={**inputs,'colortex2':texture(np.full((H,W,4),[1.,0.,.5,1.],np.float32))},overrides=opts)[0]
ck('First-person hands do not become wet mirror surfaces',np.allclose(hand,off))
# Check the real terrain/water output contracts, not only isolated helper values.
dry=draw('gbuffers_terrain',geometry=True,lm=(0.,1.),normal=(0.,1.,0.))
wet=draw('gbuffers_terrain',geometry=True,lm=(0.,1.),normal=(0.,1.,0.),values={'rainStrength':1.,'wetness':1.})
ck('Wet terrain writes changed surface metadata to actual eye-buffer alpha',not np.allclose(dry[3][:,:,3],wet[3][:,:,3]))
ck('Rain darkens suitable surfaces in the actual terrain pass',float(wet[0][:,:,:3].mean())<float(dry[0][:,:,:3].mean()))
ck('Wet terrain still writes zero eye glow',float(wet[3][:,:,:3].max())==0.)
waterargs=dict(geometry=True,material=1001,lm=(0.,1.),normal=(0.,1.,0.),textures={'colortex7':snapshot,'depthtex1':texture([depth(-8.)]*3+[1.])})
# Sparse contact events need a time interval, not an assertion that a thin
# synthetic geometry strip contains an active ring at every instant.
ripple_delta=0.0
for tm in [20.,20.2,20.4,20.6,20.8,21.]:
 w0=draw('gbuffers_water',**waterargs,values={'rainStrength':1.,'wetness':1.,'frameTimeCounter':tm},overrides={'RAIN_RIPPLES':'0'})
 w1=draw('gbuffers_water',**waterargs,values={'rainStrength':1.,'wetness':1.,'frameTimeCounter':tm})
 ripple_delta=max(ripple_delta,float(np.abs(w0[2]-w1[2]).max()))
ck('Rain ripples change actual water-surface normals',ripple_delta>.0001,max_delta=ripple_delta)
finite('Rainy water remains finite',w1[0])
report={'release':'0.4.2','scope':'Real OpenGL programs with synthetic textures and uniforms; not Minecraft, Oculus preprocessing, AMD-driver testing or actual mob UV/model alignment.','passed':sum(x['passed'] for x in results),'total':len(results),'checks':results}
(ROOT.parent/'docs/weather_polish_report.json').write_text(json.dumps(report,indent=2)+'\n')
print('WEATHER POLISH CHECKS',report['passed'],'/',report['total'])
raise SystemExit(0 if report['passed']==report['total'] else 1)
