From ac363c3c5ee94d6f90dfa5ac26f80dc45454f3a1 Mon Sep 17 00:00:00 2001 From: Min Kang Date: Fri, 13 Nov 2026 05:18:45 +0000 Subject: [PATCH] Fix Earth layer seams and validate all planet texture paths --- apps/web/js/earthLookShaders.js | 35 ++++++++++++++--- tools/bundle_web.mjs | 2 +- tools/planet_appearance_validation.mjs | 53 +++++++++++++++++++++++--- 3 files changed, 77 insertions(+), 13 deletions(-) diff --git a/apps/web/js/earthLookShaders.js b/apps/web/js/earthLookShaders.js index 212ede8e..8ab6fb7c 100644 --- a/apps/web/js/earthLookShaders.js +++ b/apps/web/js/earthLookShaders.js @@ -29,7 +29,29 @@ const float PI=3.14159265359; // SOL's north axis is +z; the lab's is +y. No view-driven texture rotation. vec3 local(vec3 p){return p.xzy;} vec2 earthUv(vec3 p){p=normalize(p);return vec2(fract(atan(p.y,p.x)/(2.*PI)+.5),acos(clamp(p.z,-1.,1.))/PI);} -float earthCloud(vec3 point){vec2 uv=earthUv(point);uv.x=fract(uv.x-uCloudPhase);return texture(uCloudMap,uv).a;} +// Capture ray derivatives before any discard or divergent volume traversal. +// Cloud density/shadow lookups may execute in different iterations per pixel; +// they must not ask implicit derivatives to differentiate a wrapped UV there. +vec3 earthRayDx,earthRayDy; +vec3 earthPointGradient(vec3 point,vec3 rayGradient){ + vec3 delta=point-u_camObj;float distance=length(delta); + vec3 direction=delta/max(distance,1e-8); + float incidence=dot(point,direction); + incidence=incidence<0.?min(incidence,-1e-4):max(incidence,1e-4); + // Differentiate a ray's intersection with the local spherical shell. + // Displaced cloud-lighting taps use that shell's local footprint too. + return distance*(rayGradient-direction*dot(point,rayGradient)/incidence); +} +vec2 earthUvGradient(vec3 point,vec3 gradient){ + float horizontal2=dot(point.xy,point.xy),radius2=max(dot(point,point),1e-8); + return vec2(dot(vec2(-point.y,point.x),gradient.xy)/(2.*PI*max(horizontal2,1e-8)), + (point.z*dot(point.xy,gradient.xy)-horizontal2*gradient.z)/(PI*radius2*sqrt(max(horizontal2,1e-8)))); +} +vec4 earthSample(sampler2D source,vec3 point,vec2 uv){ + return textureGrad(source,uv,earthUvGradient(point,earthPointGradient(point,earthRayDx)), + earthUvGradient(point,earthPointGradient(point,earthRayDy))); +} +float earthCloud(vec3 point){vec2 uv=earthUv(point);uv.x=fract(uv.x-uCloudPhase);return earthSample(uCloudMap,point,uv).a;} ${EARTH_GLSL} ${volume} vec3 lookTone(vec3 value){value*=u_earthLookExposure;return pow(clamp((value*(2.51*value+.03))/(value*(2.43*value+.59)+.14),0.,1.),vec3(1./2.2));} @@ -57,6 +79,7 @@ vec2 perspectiveCloudVolume(vec3 closest,vec3 ray,float distance2,vec3 light,boo } void main(){ vec3 ray=normalize(v_obj-u_camObj); + earthRayDx=dFdx(ray);earthRayDy=dFdy(ray); vec3 closest=u_camObj-ray*dot(u_camObj,ray); // Cross-product form avoids subtracting two large squared camera distances. vec3 perpendicular=cross(u_camObj,ray);float distance2=dot(perpendicular,perpendicular); @@ -68,19 +91,19 @@ void main(){ vec3 color=vec3(0.); if(ground){ vec3 point=closest-ray*sqrt(max(0.,1.-distance2)),normal=normalize(point); - vec2 uv=earthUv(normal);vec3 encoded=texture(u_tex,uv).rgb; - vec3 albedo=gradeOcean(pow(encoded,vec3(2.2)),texture(u_oceanMask,uv).r); + vec2 uv=earthUv(normal);vec3 encoded=earthSample(u_tex,point,uv).rgb; + vec3 albedo=gradeOcean(pow(encoded,vec3(2.2)),earthSample(u_oceanMask,point,uv).r); // Texture-derived relief is a display choice, as in the Sites reference. float base=dot(encoded,vec3(.333)); - float dx=dot(texture(u_tex,uv+vec2(.001,0.)).rgb,vec3(.333))-base; - float dy=dot(texture(u_tex,uv+vec2(0.,.001)).rgb,vec3(.333))-base; + float dx=dot(earthSample(u_tex,point,uv+vec2(.001,0.)).rgb,vec3(.333))-base; + float dy=dot(earthSample(u_tex,point,uv+vec2(0.,.001)).rgb,vec3(.333))-base; vec3 right=normalize(cross(abs(cameraDirection.z)>.99?vec3(0.,1.,0.):vec3(0.,0.,1.),cameraDirection)); vec3 up=normalize(cross(cameraDirection,right)); vec3 shadingNormal=normalize(vec3(normal.xy,normal.z/u_oblate)+(right*dx+up*dy)*.375); float ndl=dot(shadingNormal,normalize(u_lightObj)),lighting=max(ndl,0.); if(u_earthWeather==1&&dot(normal,light)>0.)lighting*=mix(.18,1.,volumeTransmission(normal,light)); color=albedo*(lighting*.95+.018); - if(u_earthNight==1)color+=pow(texture(u_nightTex,uv).rgb,vec3(1.5))*(1.-smoothstep(-.18,.12,ndl))*.72; + if(u_earthNight==1)color+=pow(earthSample(u_nightTex,point,uv).rgb,vec3(1.5))*(1.-smoothstep(-.18,.12,ndl))*.72; if(u_earthAtmosphere==1)color+=air*pow(1.-max(dot(normal,-ray),0.),4.5)*.28*smoothstep(-.15,.5,dot(normal,light)); vec4 clip=u_mvp*vec4(point,1.);gl_FragDepth=clamp(.5+.5*clip.z/clip.w,0.,1.); } diff --git a/tools/bundle_web.mjs b/tools/bundle_web.mjs index 4f16fc61..71d15080 100644 --- a/tools/bundle_web.mjs +++ b/tools/bundle_web.mjs @@ -17,7 +17,7 @@ export const OPTIONAL_MODULES=new Set(['js/moonelements.js','js/starcatalog.js'] export const QA_ENTRIES=[ 'atmosphereColumnField','atmosphereColumnManifest','atmosphereIncident','atmosphereIncidentManifest', 'atmosphereOptics','atmosphereScattering','atmosphereShaders','bodyData','constellations','data', - 'destinationOverview','ephemerisContract','ephemerisSchema','explorer','galacticobjects','geography', + 'destinationOverview','earthLookShaders','ephemerisContract','ephemerisSchema','explorer','galacticobjects','geography', 'hdrPresentation','moonelements','moonorbits','moons','moonshadows','orbitCamera','orrery','orreryMath', 'orreryShaders','orreryTime','physicalProgramSources','planetAppearance','planetPhenomena','planetPhenomenaManifest', 'referenceDemand','releaseClient','ringTransportShaders','shaderPrograms','sky','skyEngine','skyPrivacy', diff --git a/tools/planet_appearance_validation.mjs b/tools/planet_appearance_validation.mjs index 773ff851..6a6f14fd 100644 --- a/tools/planet_appearance_validation.mjs +++ b/tools/planet_appearance_validation.mjs @@ -38,6 +38,8 @@ function moduleFile(relative) { const shadersFile = moduleFile("js/orreryShaders.js"), mappingFile = moduleFile("js/surfaceMapping.js"), rendererFile = moduleFile("js/orrery.js"); const { SPHERE_VS, SPHERE_FS, BASE_SPHERE_VS, BASE_SPHERE_FS } = await import(pathToFileURL(shadersFile.file).href); const { surfaceUv, srgbToLinear, linearToSrgb, nightLightWeight } = await import(pathToFileURL(mappingFile.file).href); +const earthFile = moduleFile('js/earthLookShaders.js'); +const {EARTH_LOOK_VS,EARTH_LOOK_FS,EARTH_LOOK_EXTENT} = await import(pathToFileURL(earthFile.file).href); const upload = rendererFile.bytes.toString("utf8").match(/function makeTexture\(img, repeatS, nearest = false(?:, premultiplyAlpha = false)?(?:, linearFilter = false)?\) \{[\s\S]*?\n\}/)?.[0]; assert.ok(upload, "actual image upload function could not be isolated"); @@ -51,6 +53,9 @@ const fixtures = new Map([ ["/quadrants.png", fixture(64, 32, (x, y) => colors[(y >= 16 ? 2 : 0) + (x >= 32 ? 1 : 0)])], ["/grid.png", fixture(256, 128, (x, y) => [x, 2 * y, 80, 255])], ["/seam.png", fixture(64, 32, x => x < 4 || x >= 60 ? [40, 120, 220, 255] : [220, 40, 30, 255])], + ["/seam-constant.png", fixture(64, 32, () => [40,120,220,255])], + ["/cloud-seam.png", fixture(64, 32, x => [255,255,255,x<4||x>=60 ? 0 : 255])], + ["/gray.png", fixture(64, 32, () => [128,128,128,255])], // Matching dark edges and a bright interior: a false coarse mip at the // longitude wrap becomes a bright strip in the actual moon contrast mode. ["/spatial-seam.png", fixture(64, 32, x => x < 4 || x >= 60 ? [32,32,32,255] : [224,224,224,255])], @@ -76,9 +81,9 @@ const fixtures = new Map([ const evidence = {schema_version: "planet-appearance-validation.v1", web_root: webRoot, release_namespace: release?.namespace ?? null, started_at: new Date().toISOString(), scope: "Synthetic fiducials through actual SPHERE_VS/SPHERE_FS and makeTexture; not astronomical calibration or application qualification", - source_sha256: {shaders: digest(shadersFile.bytes), surface_mapping: digest(mappingFile.bytes), renderer: digest(rendererFile.bytes)}, + source_sha256: {shaders: digest(shadersFile.bytes), earth_shaders:digest(earthFile.bytes), surface_mapping: digest(mappingFile.bytes), renderer: digest(rendererFile.bytes)}, compiled_shader_sha256: {physical_vertex:digest(SPHERE_VS),physical_fragment:digest(SPHERE_FS), - base_vertex:digest(BASE_SPHERE_VS),base_fragment:digest(BASE_SPHERE_FS)}, + base_vertex:digest(BASE_SPHERE_VS),base_fragment:digest(BASE_SPHERE_FS),earth_vertex:digest(EARTH_LOOK_VS),earth_fragment:digest(EARTH_LOOK_FS)}, fixture_sha256: Object.fromEntries([...fixtures].map(([key, value]) => [key, digest(value)])), checks: [], disabled_material_parity: []}; fs.mkdirSync(out, {recursive: true}); let browser, server, launchPromise, deadlineTimer, expired = false; @@ -118,7 +123,7 @@ async function run() { const cdp = await page.createCDPSession(); await cdp.send("Network.enable"); await cdp.send("Network.setBlockedURLs", {urls: ["https://*", "http://localhost/*"]}); await page.goto(`http://127.0.0.1:${server.address().port}/fixture.html`, {waitUntil: "domcontentloaded", timeout: 15000}); - evidence.gpu = await page.evaluate(async ({vertex, fragment, baseVertex, baseFragment, upload, images}) => { + evidence.gpu = await page.evaluate(async ({vertex, fragment, baseVertex, baseFragment, earthVertex,earthFragment,earthExtent,upload, images}) => { const gl = document.querySelector("canvas").getContext("webgl2", {antialias: false, preserveDrawingBuffer: true}); if (!gl) throw new Error("WebGL2 unavailable for actual shader gate"); const compile = (type, source) => { @@ -132,7 +137,7 @@ async function run() { if (!gl.getProgramParameter(result, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(result)); return result; }; - const programs = {physical:link(vertex, fragment), base:link(baseVertex, baseFragment)}; + const programs = {physical:link(vertex, fragment), base:link(baseVertex, baseFragment),earth:link(earthVertex,earthFragment)}; if (!gl.getExtension('EXT_color_buffer_float')) throw new Error('Linear material gate requires float readback'); const linearTarget=gl.createFramebuffer(), linearTexture=gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D,linearTexture); @@ -156,7 +161,7 @@ async function run() { // Coordinate-gradient probes use nearest to make source texel identity explicit. // Quadrants and seam exercise the renderer's actual linear/mipmap upload path. const maskedPhoto = ["/transparent.png", "/half-white.png", "/alpha-edge.png", "/color-alpha-edge.png"].includes(name); - textures[name] = textureFactory(image, true, !["/quadrants.png", "/seam.png", "/spatial-seam.png", "/checker.png", "/color-deposits.png", "/alpha-edge.png", "/color-alpha-edge.png"].includes(name), maskedPhoto); + textures[name] = textureFactory(image, true, !["/quadrants.png", "/seam.png", "/seam-constant.png", "/cloud-seam.png", "/gray.png", "/spatial-seam.png", "/checker.png", "/color-deposits.png", "/alpha-edge.png", "/color-alpha-edge.png"].includes(name), maskedPhoto); uploadPremultiplyStates.push({name, expected:maskedPhoto, actual:gl.getParameter(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL)}); if (name === "/quadrants.png") textures.flipped = flippedFactory(image, true, false); if (['/opaque-edge.png','/saturated-edge.png'].includes(name)) { @@ -237,9 +242,45 @@ async function run() { canvas.width = 1; canvas.height = 1; gl.viewport(0,0,1,1); return {width,height,pixels:Array.from(pixels)}; }; + // Actual perspective Earth shader, including relief, night and cloud paths. + // A planar proxy supplies rays through a small sphere patch straddling the + // longitude join inside a derivative quad; constant textures are controls. + window.earthSeamProbe = ({layer,control=false,phase=0,latitude=0,oblique=false}) => { + const canvas=document.querySelector('canvas'),width=8,height=4,span=(latitude||oblique) ? .002 : .05,offset=span*.25; + canvas.width=width;canvas.height=height;gl.viewport(0,0,width,height); + gl.bindFramebuffer(gl.FRAMEBUFFER,null);program=programs.earth;gl.useProgram(program); + const angle=2*Math.PI*(phase-.5),lat=latitude*Math.PI/180; + const center=[Math.cos(angle)*Math.cos(lat),Math.sin(angle)*Math.cos(lat),Math.sin(lat)],tangent=[-Math.sin(angle),Math.cos(angle),0]; + const up=[-Math.cos(angle)*Math.sin(lat),-Math.sin(angle)*Math.sin(lat),Math.cos(lat)]; + const vertices=[[-1,-1],[1,-1],[-1,1],[-1,1],[1,-1],[1,1]]; + gl.bufferData(gl.ARRAY_BUFFER,new Float32Array(vertices.flatMap(([x,y])=>center.map((v,k)=>(v+tangent[k]*(offset+span*x)+up[k]*span*y)/earthExtent))),gl.STATIC_DRAW); + const mvp=[tangent[0]/span,up[0]/span,0,0,tangent[1]/span,up[1]/span,0,0,tangent[2]/span,up[2]/span,0,0,-offset/span,0,0,1]; + gl.uniformMatrix4fv(location('u_mvp'),false,mvp); + v3('u_camObj',center.map((v,k)=>3*(oblique?v*.5+tangent[k]*Math.sqrt(.75):v)));v3('u_lightObj',center.map(v=>layer==='night'?-v:v)); + f('u_oblate',1);f('u_pixelDiameter',160);f('u_earthLookExposure',1.6);f('uCloudPhase',phase); + i('u_linearOutput',0);i('u_earthLookPass',0);i('u_earthAtmosphere',0); + i('u_earthWeather',layer==='cloud'?1:0);i('u_earthNight',layer==='night'?1:0); + const day=layer==='surface'?(control?'/seam-constant.png':'/seam.png'):layer==='minified'?(control?'/gray.png':'/checker.png'):'/black.png'; + bind(0,'u_tex',day);bind(1,'u_oceanMask','/black.png'); + bind(2,'u_nightTex',layer==='night'?(control?'/seam-constant.png':'/seam.png'):'/black.png'); + bind(3,'uCloudMap',layer==='cloud'&&!control?'/cloud-seam.png':'/transparent.png'); + gl.clearColor(1,0,1,1);gl.clear(gl.COLOR_BUFFER_BIT);gl.drawArrays(gl.TRIANGLES,0,6); + const pixels=new Uint8Array(width*height*4);gl.readPixels(0,0,width,height,gl.RGBA,gl.UNSIGNED_BYTE,pixels); + const error=gl.getError();if(error!==gl.NO_ERROR)throw Error(`Earth seam GL error ${error}`); + canvas.width=1;canvas.height=1;gl.viewport(0,0,1,1); + return Array.from(pixels); + }; const debug = gl.getExtension("WEBGL_debug_renderer_info"); return {renderer: debug ? gl.getParameter(debug.UNMASKED_RENDERER_WEBGL) : gl.getParameter(gl.RENDERER), version: gl.getParameter(gl.VERSION), uploadPremultiplyStates}; - }, {vertex: SPHERE_VS, fragment: SPHERE_FS, baseVertex: BASE_SPHERE_VS, baseFragment: BASE_SPHERE_FS, upload, images: [...fixtures.keys()]}); + }, {vertex: SPHERE_VS, fragment: SPHERE_FS, baseVertex: BASE_SPHERE_VS, baseFragment: BASE_SPHERE_FS,earthVertex:EARTH_LOOK_VS,earthFragment:EARTH_LOOK_FS,earthExtent:EARTH_LOOK_EXTENT,upload, images: [...fixtures.keys()]}); + for(const layer of ['surface','night','cloud','minified'])for(const phase of layer==='cloud'?[0,.3]:[0]){ + const result=await page.evaluate(options=>({actual:earthSeamProbe(options),control:earthSeamProbe({...options,control:true})}),{layer,phase}); + check(`Earth ${layer} wrap at phase ${phase} matches continuous control`,result.actual,result.control,2); + } + for(const geometry of [{latitude:80},{latitude:-80},{oblique:true}])for(const layer of ['surface','night','cloud']){ + const result=await page.evaluate(options=>({actual:earthSeamProbe(options),control:earthSeamProbe({...options,control:true})}),{layer,...geometry}); + check(`Earth ${layer} wrap ${JSON.stringify(geometry)} matches continuous control`,result.actual,result.control,2); + } // Every existing material/registration assertion still receives the physical // shader result. Independently execute the shipped constant-disabled program // with identical inputs, including spatial derivative patches, and retain both.