From baad01da25985db3aa500d8cde3e3bcdb998fe1b Mon Sep 17 00:00:00 2001 From: keiya01 Date: Wed, 28 Jun 2023 13:19:06 +0900 Subject: [PATCH] feat: support IBL for terrain --- web/src/beta/lib/core/Map/types/index.ts | 7 + .../engines/Cesium/Feature/Model/index.tsx | 2 +- .../engines/Cesium/Feature/Tileset/index.tsx | 2 +- .../CustomShaders/NonPBRLightingShader.ts | 0 .../OverriddenShaders/GlobeFS/Cesium.glsl | 654 ++++++++++++++++++ .../OverriddenShaders/GlobeFS/Customs.glsl | 54 ++ .../GlobeFS/Definitions.glsl | 4 + .../Shaders/OverriddenShaders/README.md | 23 + .../lib/core/engines/Cesium/core/Globe.tsx | 23 +- web/src/beta/lib/core/engines/Cesium/hooks.ts | 52 ++ .../beta/lib/core/engines/Cesium/type.d.ts | 16 + web/src/beta/lib/core/engines/Cesium/types.ts | 14 +- .../engines/Cesium/useOverrideGlobeShader.ts | 83 +++ web/src/beta/lib/core/hooks/useRefFunction.ts | 10 + 14 files changed, 935 insertions(+), 9 deletions(-) rename web/src/beta/lib/core/engines/Cesium/{ => Shaders}/CustomShaders/NonPBRLightingShader.ts (100%) create mode 100644 web/src/beta/lib/core/engines/Cesium/Shaders/OverriddenShaders/GlobeFS/Cesium.glsl create mode 100644 web/src/beta/lib/core/engines/Cesium/Shaders/OverriddenShaders/GlobeFS/Customs.glsl create mode 100644 web/src/beta/lib/core/engines/Cesium/Shaders/OverriddenShaders/GlobeFS/Definitions.glsl create mode 100644 web/src/beta/lib/core/engines/Cesium/Shaders/OverriddenShaders/README.md create mode 100644 web/src/beta/lib/core/engines/Cesium/type.d.ts create mode 100644 web/src/beta/lib/core/engines/Cesium/useOverrideGlobeShader.ts create mode 100644 web/src/beta/lib/core/hooks/useRefFunction.ts diff --git a/web/src/beta/lib/core/Map/types/index.ts b/web/src/beta/lib/core/Map/types/index.ts index a9b3d58fe5..ab273fb9f0 100644 --- a/web/src/beta/lib/core/Map/types/index.ts +++ b/web/src/beta/lib/core/Map/types/index.ts @@ -249,9 +249,13 @@ export type TerrainProperty = { terrainCesiumIonAccessToken?: string; terrainCesiumIonUrl?: string; terrainUrl?: string; + terrainNormal?: boolean; }; export type SceneProperty = { + debugs?: { + debugSphericalHarmonicCoefficients: boolean; + }; default?: { camera?: Camera; allowEnterGround?: boolean; @@ -293,6 +297,9 @@ export type SceneProperty = { brightness_shift?: number; hue_shift?: number; surturation_shift?: number; + sphericalHarmonicCoefficients?: { x: number; y: number; z: number }[]; + globeShadowDarkness?: number; + globeImageBasedLighting?: boolean; }; timeline?: { animation?: boolean; diff --git a/web/src/beta/lib/core/engines/Cesium/Feature/Model/index.tsx b/web/src/beta/lib/core/engines/Cesium/Feature/Model/index.tsx index 75d1e285ec..85c6e4606f 100644 --- a/web/src/beta/lib/core/engines/Cesium/Feature/Model/index.tsx +++ b/web/src/beta/lib/core/engines/Cesium/Feature/Model/index.tsx @@ -6,7 +6,7 @@ import { toColor } from "@reearth/beta/utils/value"; import type { ModelAppearance } from "../../.."; import { colorBlendMode, heightReference, shadowMode } from "../../common"; -import { NonPBRLightingShader } from "../../CustomShaders/NonPBRLightingShader"; +import { NonPBRLightingShader } from "../../Shaders/CustomShaders/NonPBRLightingShader"; import { EntityExt, extractSimpleLayerData, diff --git a/web/src/beta/lib/core/engines/Cesium/Feature/Tileset/index.tsx b/web/src/beta/lib/core/engines/Cesium/Feature/Tileset/index.tsx index bab9a60519..86f763c689 100644 --- a/web/src/beta/lib/core/engines/Cesium/Feature/Tileset/index.tsx +++ b/web/src/beta/lib/core/engines/Cesium/Feature/Tileset/index.tsx @@ -3,7 +3,7 @@ import { Cesium3DTileset } from "resium"; import type { Cesium3DTilesAppearance, ComputedLayer } from "../../.."; import { colorBlendModeFor3DTile, shadowMode } from "../../common"; -import { NonPBRLightingShader } from "../../CustomShaders/NonPBRLightingShader"; +import { NonPBRLightingShader } from "../../Shaders/CustomShaders/NonPBRLightingShader"; import Box from "../Box"; import { type FeatureComponentConfig, type FeatureProps } from "../utils"; diff --git a/web/src/beta/lib/core/engines/Cesium/CustomShaders/NonPBRLightingShader.ts b/web/src/beta/lib/core/engines/Cesium/Shaders/CustomShaders/NonPBRLightingShader.ts similarity index 100% rename from web/src/beta/lib/core/engines/Cesium/CustomShaders/NonPBRLightingShader.ts rename to web/src/beta/lib/core/engines/Cesium/Shaders/CustomShaders/NonPBRLightingShader.ts diff --git a/web/src/beta/lib/core/engines/Cesium/Shaders/OverriddenShaders/GlobeFS/Cesium.glsl b/web/src/beta/lib/core/engines/Cesium/Shaders/OverriddenShaders/GlobeFS/Cesium.glsl new file mode 100644 index 0000000000..760869a6fa --- /dev/null +++ b/web/src/beta/lib/core/engines/Cesium/Shaders/OverriddenShaders/GlobeFS/Cesium.glsl @@ -0,0 +1,654 @@ +// Ref: cesium v1.106 https://github.com/CesiumGS/cesium/blob/1.106/packages/engine/Source/Shaders/GlobeFS.glsl + +uniform vec4 u_initialColor; + +#if TEXTURE_UNITS > 0 +uniform sampler2D u_dayTextures[TEXTURE_UNITS]; +uniform vec4 u_dayTextureTranslationAndScale[TEXTURE_UNITS]; +uniform bool u_dayTextureUseWebMercatorT[TEXTURE_UNITS]; + +#ifdef APPLY_ALPHA +uniform float u_dayTextureAlpha[TEXTURE_UNITS]; +#endif + +#ifdef APPLY_DAY_NIGHT_ALPHA +uniform float u_dayTextureNightAlpha[TEXTURE_UNITS]; +uniform float u_dayTextureDayAlpha[TEXTURE_UNITS]; +#endif + +#ifdef APPLY_SPLIT +uniform float u_dayTextureSplit[TEXTURE_UNITS]; +#endif + +#ifdef APPLY_BRIGHTNESS +uniform float u_dayTextureBrightness[TEXTURE_UNITS]; +#endif + +#ifdef APPLY_CONTRAST +uniform float u_dayTextureContrast[TEXTURE_UNITS]; +#endif + +#ifdef APPLY_HUE +uniform float u_dayTextureHue[TEXTURE_UNITS]; +#endif + +#ifdef APPLY_SATURATION +uniform float u_dayTextureSaturation[TEXTURE_UNITS]; +#endif + +#ifdef APPLY_GAMMA +uniform float u_dayTextureOneOverGamma[TEXTURE_UNITS]; +#endif + +#ifdef APPLY_IMAGERY_CUTOUT +uniform vec4 u_dayTextureCutoutRectangles[TEXTURE_UNITS]; +#endif + +#ifdef APPLY_COLOR_TO_ALPHA +uniform vec4 u_colorsToAlpha[TEXTURE_UNITS]; +#endif + +uniform vec4 u_dayTextureTexCoordsRectangle[TEXTURE_UNITS]; +#endif + +#ifdef SHOW_REFLECTIVE_OCEAN +uniform sampler2D u_waterMask; +uniform vec4 u_waterMaskTranslationAndScale; +uniform float u_zoomedOutOceanSpecularIntensity; +#endif + +#ifdef SHOW_OCEAN_WAVES +uniform sampler2D u_oceanNormalMap; +#endif + +#if defined(ENABLE_DAYNIGHT_SHADING) || defined(GROUND_ATMOSPHERE) +uniform vec2 u_lightingFadeDistance; +#endif + +#ifdef TILE_LIMIT_RECTANGLE +uniform vec4 u_cartographicLimitRectangle; +#endif + +#ifdef GROUND_ATMOSPHERE +uniform vec2 u_nightFadeDistance; +#endif + +#ifdef ENABLE_CLIPPING_PLANES +uniform highp sampler2D u_clippingPlanes; +uniform mat4 u_clippingPlanesMatrix; +uniform vec4 u_clippingPlanesEdgeStyle; +#endif + +#if defined(GROUND_ATMOSPHERE) || defined(FOG) && defined(DYNAMIC_ATMOSPHERE_LIGHTING) && (defined(ENABLE_VERTEX_LIGHTING) || defined(ENABLE_DAYNIGHT_SHADING)) +uniform float u_minimumBrightness; +#endif + +#ifdef COLOR_CORRECT +uniform vec3 u_hsbShift; // Hue, saturation, brightness +#endif + +#ifdef HIGHLIGHT_FILL_TILE +uniform vec4 u_fillHighlightColor; +#endif + +#ifdef TRANSLUCENT +uniform vec4 u_frontFaceAlphaByDistance; +uniform vec4 u_backFaceAlphaByDistance; +uniform vec4 u_translucencyRectangle; +#endif + +#ifdef UNDERGROUND_COLOR +uniform vec4 u_undergroundColor; +uniform vec4 u_undergroundColorAlphaByDistance; +#endif + +#ifdef ENABLE_VERTEX_LIGHTING +uniform float u_lambertDiffuseMultiplier; +uniform float u_vertexShadowDarkness; +#endif + +in vec3 v_positionMC; +in vec3 v_positionEC; +in vec3 v_textureCoordinates; +in vec3 v_normalMC; +in vec3 v_normalEC; + +#ifdef APPLY_MATERIAL +in float v_height; +in float v_slope; +in float v_aspect; +#endif + +#if defined(FOG) || defined(GROUND_ATMOSPHERE) || defined(UNDERGROUND_COLOR) || defined(TRANSLUCENT) +in float v_distance; +#endif + +#if defined(GROUND_ATMOSPHERE) || defined(FOG) +in vec3 v_atmosphereRayleighColor; +in vec3 v_atmosphereMieColor; +in float v_atmosphereOpacity; +#endif + +#if defined(UNDERGROUND_COLOR) || defined(TRANSLUCENT) +float interpolateByDistance(vec4 nearFarScalar, float distance) +{ + float startDistance = nearFarScalar.x; + float startValue = nearFarScalar.y; + float endDistance = nearFarScalar.z; + float endValue = nearFarScalar.w; + float t = clamp((distance - startDistance) / (endDistance - startDistance), 0.0, 1.0); + return mix(startValue, endValue, t); +} +#endif + +#if defined(UNDERGROUND_COLOR) || defined(TRANSLUCENT) || defined(APPLY_MATERIAL) +vec4 alphaBlend(vec4 sourceColor, vec4 destinationColor) +{ + return sourceColor * vec4(sourceColor.aaa, 1.0) + destinationColor * (1.0 - sourceColor.a); +} +#endif + +#ifdef TRANSLUCENT +bool inTranslucencyRectangle() +{ + return + v_textureCoordinates.x > u_translucencyRectangle.x && + v_textureCoordinates.x < u_translucencyRectangle.z && + v_textureCoordinates.y > u_translucencyRectangle.y && + v_textureCoordinates.y < u_translucencyRectangle.w; +} +#endif + +vec4 sampleAndBlend( + vec4 previousColor, + sampler2D textureToSample, + vec2 tileTextureCoordinates, + vec4 textureCoordinateRectangle, + vec4 textureCoordinateTranslationAndScale, + float textureAlpha, + float textureNightAlpha, + float textureDayAlpha, + float textureBrightness, + float textureContrast, + float textureHue, + float textureSaturation, + float textureOneOverGamma, + float split, + vec4 colorToAlpha, + float nightBlend) +{ + // This crazy step stuff sets the alpha to 0.0 if this following condition is true: + // tileTextureCoordinates.s < textureCoordinateRectangle.s || + // tileTextureCoordinates.s > textureCoordinateRectangle.p || + // tileTextureCoordinates.t < textureCoordinateRectangle.t || + // tileTextureCoordinates.t > textureCoordinateRectangle.q + // In other words, the alpha is zero if the fragment is outside the rectangle + // covered by this texture. Would an actual 'if' yield better performance? + vec2 alphaMultiplier = step(textureCoordinateRectangle.st, tileTextureCoordinates); + textureAlpha = textureAlpha * alphaMultiplier.x * alphaMultiplier.y; + + alphaMultiplier = step(vec2(0.0), textureCoordinateRectangle.pq - tileTextureCoordinates); + textureAlpha = textureAlpha * alphaMultiplier.x * alphaMultiplier.y; + +#if defined(APPLY_DAY_NIGHT_ALPHA) && defined(ENABLE_DAYNIGHT_SHADING) + textureAlpha *= mix(textureDayAlpha, textureNightAlpha, nightBlend); +#endif + + vec2 translation = textureCoordinateTranslationAndScale.xy; + vec2 scale = textureCoordinateTranslationAndScale.zw; + vec2 textureCoordinates = tileTextureCoordinates * scale + translation; + vec4 value = texture(textureToSample, textureCoordinates); + vec3 color = value.rgb; + float alpha = value.a; + +#ifdef APPLY_COLOR_TO_ALPHA + vec3 colorDiff = abs(color.rgb - colorToAlpha.rgb); + colorDiff.r = max(max(colorDiff.r, colorDiff.g), colorDiff.b); + alpha = czm_branchFreeTernary(colorDiff.r < colorToAlpha.a, 0.0, alpha); +#endif + +#if !defined(APPLY_GAMMA) + vec4 tempColor = czm_gammaCorrect(vec4(color, alpha)); + color = tempColor.rgb; + alpha = tempColor.a; +#else + color = pow(color, vec3(textureOneOverGamma)); +#endif + +#ifdef APPLY_SPLIT + float splitPosition = czm_splitPosition; + // Split to the left + if (split < 0.0 && gl_FragCoord.x > splitPosition) { + alpha = 0.0; + } + // Split to the right + else if (split > 0.0 && gl_FragCoord.x < splitPosition) { + alpha = 0.0; + } +#endif + +#ifdef APPLY_BRIGHTNESS + color = mix(vec3(0.0), color, textureBrightness); +#endif + +#ifdef APPLY_CONTRAST + color = mix(vec3(0.5), color, textureContrast); +#endif + +#ifdef APPLY_HUE + color = czm_hue(color, textureHue); +#endif + +#ifdef APPLY_SATURATION + color = czm_saturation(color, textureSaturation); +#endif + + float sourceAlpha = alpha * textureAlpha; + float outAlpha = mix(previousColor.a, 1.0, sourceAlpha); + outAlpha += sign(outAlpha) - 1.0; + + vec3 outColor = mix(previousColor.rgb * previousColor.a, color, sourceAlpha) / outAlpha; + + // When rendering imagery for a tile in multiple passes, + // some GPU/WebGL implementation combinations will not blend fragments in + // additional passes correctly if their computation includes an unmasked + // divide-by-zero operation, + // even if it's not in the output or if the output has alpha zero. + // + // For example, without sanitization for outAlpha, + // this renders without artifacts: + // if (outAlpha == 0.0) { outColor = vec3(0.0); } + // + // but using czm_branchFreeTernary will cause portions of the tile that are + // alpha-zero in the additional pass to render as black instead of blending + // with the previous pass: + // outColor = czm_branchFreeTernary(outAlpha == 0.0, vec3(0.0), outColor); + // + // So instead, sanitize against divide-by-zero, + // store this state on the sign of outAlpha, and correct on return. + + return vec4(outColor, max(outAlpha, 0.0)); +} + +vec3 colorCorrect(vec3 rgb) { +#ifdef COLOR_CORRECT + // Convert rgb color to hsb + vec3 hsb = czm_RGBToHSB(rgb); + // Perform hsb shift + hsb.x += u_hsbShift.x; // hue + hsb.y = clamp(hsb.y + u_hsbShift.y, 0.0, 1.0); // saturation + hsb.z = hsb.z > czm_epsilon7 ? hsb.z + u_hsbShift.z : 0.0; // brightness + // Convert shifted hsb back to rgb + rgb = czm_HSBToRGB(hsb); +#endif + return rgb; +} + +vec4 computeDayColor(vec4 initialColor, vec3 textureCoordinates, float nightBlend); +vec4 computeWaterColor(vec3 positionEyeCoordinates, vec2 textureCoordinates, mat3 enuToEye, vec4 imageryColor, float specularMapValue, float fade); + +const float fExposure = 2.0; + +vec3 computeEllipsoidPosition() +{ + float mpp = czm_metersPerPixel(vec4(0.0, 0.0, -czm_currentFrustum.x, 1.0), 1.0); + vec2 xy = gl_FragCoord.xy / czm_viewport.zw * 2.0 - vec2(1.0); + xy *= czm_viewport.zw * mpp * 0.5; + + vec3 direction = normalize(vec3(xy, -czm_currentFrustum.x)); + czm_ray ray = czm_ray(vec3(0.0), direction); + + vec3 ellipsoid_center = czm_view[3].xyz; + + czm_raySegment intersection = czm_rayEllipsoidIntersectionInterval(ray, ellipsoid_center, czm_ellipsoidInverseRadii); + + vec3 ellipsoidPosition = czm_pointAlongRay(ray, intersection.start); + return (czm_inverseView * vec4(ellipsoidPosition, 1.0)).xyz; +} + +void main() +{ +#ifdef TILE_LIMIT_RECTANGLE + if (v_textureCoordinates.x < u_cartographicLimitRectangle.x || u_cartographicLimitRectangle.z < v_textureCoordinates.x || + v_textureCoordinates.y < u_cartographicLimitRectangle.y || u_cartographicLimitRectangle.w < v_textureCoordinates.y) + { + discard; + } +#endif + +#ifdef ENABLE_CLIPPING_PLANES + float clipDistance = clip(gl_FragCoord, u_clippingPlanes, u_clippingPlanesMatrix); +#endif + +#if defined(SHOW_REFLECTIVE_OCEAN) || defined(ENABLE_DAYNIGHT_SHADING) || defined(HDR) + vec3 normalMC = czm_geodeticSurfaceNormal(v_positionMC, vec3(0.0), vec3(1.0)); // normalized surface normal in model coordinates + vec3 normalEC = czm_normal3D * normalMC; // normalized surface normal in eye coordiantes +#endif + +#if defined(APPLY_DAY_NIGHT_ALPHA) && defined(ENABLE_DAYNIGHT_SHADING) + float nightBlend = 1.0 - clamp(czm_getLambertDiffuse(czm_lightDirectionEC, normalEC) * 5.0, 0.0, 1.0); +#else + float nightBlend = 0.0; +#endif + + // The clamp below works around an apparent bug in Chrome Canary v23.0.1241.0 + // where the fragment shader sees textures coordinates < 0.0 and > 1.0 for the + // fragments on the edges of tiles even though the vertex shader is outputting + // coordinates strictly in the 0-1 range. + vec4 color = computeDayColor(u_initialColor, clamp(v_textureCoordinates, 0.0, 1.0), nightBlend); + +#ifdef SHOW_TILE_BOUNDARIES + if (v_textureCoordinates.x < (1.0/256.0) || v_textureCoordinates.x > (255.0/256.0) || + v_textureCoordinates.y < (1.0/256.0) || v_textureCoordinates.y > (255.0/256.0)) + { + color = vec4(1.0, 0.0, 0.0, 1.0); + } +#endif + +#if defined(ENABLE_DAYNIGHT_SHADING) || defined(GROUND_ATMOSPHERE) + float cameraDist; + if (czm_sceneMode == czm_sceneMode2D) + { + cameraDist = max(czm_frustumPlanes.x - czm_frustumPlanes.y, czm_frustumPlanes.w - czm_frustumPlanes.z) * 0.5; + } + else if (czm_sceneMode == czm_sceneModeColumbusView) + { + cameraDist = -czm_view[3].z; + } + else + { + cameraDist = length(czm_view[3]); + } + float fadeOutDist = u_lightingFadeDistance.x; + float fadeInDist = u_lightingFadeDistance.y; + if (czm_sceneMode != czm_sceneMode3D) { + vec3 radii = czm_ellipsoidRadii; + float maxRadii = max(radii.x, max(radii.y, radii.z)); + fadeOutDist -= maxRadii; + fadeInDist -= maxRadii; + } + float fade = clamp((cameraDist - fadeOutDist) / (fadeInDist - fadeOutDist), 0.0, 1.0); +#else + float fade = 0.0; +#endif + +#ifdef SHOW_REFLECTIVE_OCEAN + vec2 waterMaskTranslation = u_waterMaskTranslationAndScale.xy; + vec2 waterMaskScale = u_waterMaskTranslationAndScale.zw; + vec2 waterMaskTextureCoordinates = v_textureCoordinates.xy * waterMaskScale + waterMaskTranslation; + waterMaskTextureCoordinates.y = 1.0 - waterMaskTextureCoordinates.y; + + float mask = texture(u_waterMask, waterMaskTextureCoordinates).r; + + if (mask > 0.0) + { + mat3 enuToEye = czm_eastNorthUpToEyeCoordinates(v_positionMC, normalEC); + + vec2 ellipsoidTextureCoordinates = czm_ellipsoidWgs84TextureCoordinates(normalMC); + vec2 ellipsoidFlippedTextureCoordinates = czm_ellipsoidWgs84TextureCoordinates(normalMC.zyx); + + vec2 textureCoordinates = mix(ellipsoidTextureCoordinates, ellipsoidFlippedTextureCoordinates, czm_morphTime * smoothstep(0.9, 0.95, normalMC.z)); + + color = computeWaterColor(v_positionEC, textureCoordinates, enuToEye, color, mask, fade); + } +#endif + +#ifdef APPLY_MATERIAL + czm_materialInput materialInput; + materialInput.st = v_textureCoordinates.st; + materialInput.normalEC = normalize(v_normalEC); + materialInput.positionToEyeEC = -v_positionEC; + materialInput.tangentToEyeMatrix = czm_eastNorthUpToEyeCoordinates(v_positionMC, normalize(v_normalEC)); + materialInput.slope = v_slope; + materialInput.height = v_height; + materialInput.aspect = v_aspect; + czm_material material = czm_getMaterial(materialInput); + vec4 materialColor = vec4(material.diffuse, material.alpha); + color = alphaBlend(materialColor, color); +#endif + +#ifdef ENABLE_VERTEX_LIGHTING + vec4 finalColor = reearth_computeImageBasedLightingColor(color); +#elif defined(ENABLE_DAYNIGHT_SHADING) + float diffuseIntensity = clamp(czm_getLambertDiffuse(czm_lightDirectionEC, normalEC) * 5.0 + 0.3, 0.0, 1.0); + diffuseIntensity = mix(1.0, diffuseIntensity, fade); + vec4 finalColor = vec4(color.rgb * czm_lightColor * diffuseIntensity, color.a); +#else + vec4 finalColor = color; +#endif + +#ifdef ENABLE_CLIPPING_PLANES + vec4 clippingPlanesEdgeColor = vec4(1.0); + clippingPlanesEdgeColor.rgb = u_clippingPlanesEdgeStyle.rgb; + float clippingPlanesEdgeWidth = u_clippingPlanesEdgeStyle.a; + + if (clipDistance < clippingPlanesEdgeWidth) + { + finalColor = clippingPlanesEdgeColor; + } +#endif + +#ifdef HIGHLIGHT_FILL_TILE + finalColor = vec4(mix(finalColor.rgb, u_fillHighlightColor.rgb, u_fillHighlightColor.a), finalColor.a); +#endif + +#if defined(DYNAMIC_ATMOSPHERE_LIGHTING_FROM_SUN) + vec3 atmosphereLightDirection = czm_sunDirectionWC; +#else + vec3 atmosphereLightDirection = czm_lightDirectionWC; +#endif + +#if defined(GROUND_ATMOSPHERE) || defined(FOG) + if (!czm_backFacing()) + { + bool dynamicLighting = false; + #if defined(DYNAMIC_ATMOSPHERE_LIGHTING) && (defined(ENABLE_DAYNIGHT_SHADING) || defined(ENABLE_VERTEX_LIGHTING)) + dynamicLighting = true; + #endif + + vec3 rayleighColor; + vec3 mieColor; + float opacity; + + vec3 positionWC; + vec3 lightDirection; + + // When the camera is far away (camera distance > nightFadeOutDistance), the scattering is computed in the fragment shader. + // Otherwise, the scattering is computed in the vertex shader. + #ifdef PER_FRAGMENT_GROUND_ATMOSPHERE + positionWC = computeEllipsoidPosition(); + lightDirection = czm_branchFreeTernary(dynamicLighting, atmosphereLightDirection, normalize(positionWC)); + computeAtmosphereScattering( + positionWC, + lightDirection, + rayleighColor, + mieColor, + opacity + ); + #else + positionWC = v_positionMC; + lightDirection = czm_branchFreeTernary(dynamicLighting, atmosphereLightDirection, normalize(positionWC)); + rayleighColor = v_atmosphereRayleighColor; + mieColor = v_atmosphereMieColor; + opacity = v_atmosphereOpacity; + #endif + + rayleighColor = colorCorrect(rayleighColor); + mieColor = colorCorrect(mieColor); + + vec4 groundAtmosphereColor = computeAtmosphereColor(positionWC, lightDirection, rayleighColor, mieColor, opacity); + + // Fog is applied to tiles selected for fog, close to the Earth. + #ifdef FOG + vec3 fogColor = groundAtmosphereColor.rgb; + + // If there is lighting, apply that to the fog. + #if defined(DYNAMIC_ATMOSPHERE_LIGHTING) && (defined(ENABLE_VERTEX_LIGHTING) || defined(ENABLE_DAYNIGHT_SHADING)) + float darken = clamp(dot(normalize(czm_viewerPositionWC), atmosphereLightDirection), u_minimumBrightness, 1.0); + fogColor *= darken; + #endif + + #ifndef HDR + fogColor.rgb = czm_acesTonemapping(fogColor.rgb); + fogColor.rgb = czm_inverseGamma(fogColor.rgb); + #endif + + const float modifier = 0.15; + finalColor = vec4(czm_fog(v_distance, finalColor.rgb, fogColor.rgb, modifier), finalColor.a); + + #else + // The transmittance is based on optical depth i.e. the length of segment of the ray inside the atmosphere. + // This value is larger near the "circumference", as it is further away from the camera. We use it to + // brighten up that area of the ground atmosphere. + const float transmittanceModifier = 0.5; + float transmittance = transmittanceModifier + clamp(1.0 - groundAtmosphereColor.a, 0.0, 1.0); + + vec3 finalAtmosphereColor = finalColor.rgb + groundAtmosphereColor.rgb * transmittance; + + #if defined(DYNAMIC_ATMOSPHERE_LIGHTING) && (defined(ENABLE_VERTEX_LIGHTING) || defined(ENABLE_DAYNIGHT_SHADING)) + float fadeInDist = u_nightFadeDistance.x; + float fadeOutDist = u_nightFadeDistance.y; + + float sunlitAtmosphereIntensity = clamp((cameraDist - fadeOutDist) / (fadeInDist - fadeOutDist), 0.05, 1.0); + float darken = clamp(dot(normalize(positionWC), atmosphereLightDirection), 0.0, 1.0); + vec3 darkenendGroundAtmosphereColor = mix(groundAtmosphereColor.rgb, finalAtmosphereColor.rgb, darken); + + finalAtmosphereColor = mix(darkenendGroundAtmosphereColor, finalAtmosphereColor, sunlitAtmosphereIntensity); + #endif + + #ifndef HDR + finalAtmosphereColor.rgb = vec3(1.0) - exp(-fExposure * finalAtmosphereColor.rgb); + #else + finalAtmosphereColor.rgb = czm_saturation(finalAtmosphereColor.rgb, 1.6); + #endif + + finalColor.rgb = mix(finalColor.rgb, finalAtmosphereColor.rgb, fade); + #endif + } +#endif + +#ifdef UNDERGROUND_COLOR + if (czm_backFacing()) + { + float distanceFromEllipsoid = max(czm_eyeHeight, 0.0); + float distance = max(v_distance - distanceFromEllipsoid, 0.0); + float blendAmount = interpolateByDistance(u_undergroundColorAlphaByDistance, distance); + vec4 undergroundColor = vec4(u_undergroundColor.rgb, u_undergroundColor.a * blendAmount); + finalColor = alphaBlend(undergroundColor, finalColor); + } +#endif + +#ifdef TRANSLUCENT + if (inTranslucencyRectangle()) + { + vec4 alphaByDistance = gl_FrontFacing ? u_frontFaceAlphaByDistance : u_backFaceAlphaByDistance; + finalColor.a *= interpolateByDistance(alphaByDistance, v_distance); + } +#endif + + out_FragColor = finalColor; +} + + +#ifdef SHOW_REFLECTIVE_OCEAN + +float waveFade(float edge0, float edge1, float x) +{ + float y = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0); + return pow(1.0 - y, 5.0); +} + +float linearFade(float edge0, float edge1, float x) +{ + return clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0); +} + +// Based on water rendering by Jonas Wagner: +// http://29a.ch/2012/7/19/webgl-terrain-rendering-water-fog + +// low altitude wave settings +const float oceanFrequencyLowAltitude = 825000.0; +const float oceanAnimationSpeedLowAltitude = 0.004; +const float oceanOneOverAmplitudeLowAltitude = 1.0 / 2.0; +const float oceanSpecularIntensity = 0.5; + +// high altitude wave settings +const float oceanFrequencyHighAltitude = 125000.0; +const float oceanAnimationSpeedHighAltitude = 0.008; +const float oceanOneOverAmplitudeHighAltitude = 1.0 / 2.0; + +vec4 computeWaterColor(vec3 positionEyeCoordinates, vec2 textureCoordinates, mat3 enuToEye, vec4 imageryColor, float maskValue, float fade) +{ + vec3 positionToEyeEC = -positionEyeCoordinates; + float positionToEyeECLength = length(positionToEyeEC); + + // The double normalize below works around a bug in Firefox on Android devices. + vec3 normalizedPositionToEyeEC = normalize(normalize(positionToEyeEC)); + + // Fade out the waves as the camera moves far from the surface. + float waveIntensity = waveFade(70000.0, 1000000.0, positionToEyeECLength); + +#ifdef SHOW_OCEAN_WAVES + // high altitude waves + float time = czm_frameNumber * oceanAnimationSpeedHighAltitude; + vec4 noise = czm_getWaterNoise(u_oceanNormalMap, textureCoordinates * oceanFrequencyHighAltitude, time, 0.0); + vec3 normalTangentSpaceHighAltitude = vec3(noise.xy, noise.z * oceanOneOverAmplitudeHighAltitude); + + // low altitude waves + time = czm_frameNumber * oceanAnimationSpeedLowAltitude; + noise = czm_getWaterNoise(u_oceanNormalMap, textureCoordinates * oceanFrequencyLowAltitude, time, 0.0); + vec3 normalTangentSpaceLowAltitude = vec3(noise.xy, noise.z * oceanOneOverAmplitudeLowAltitude); + + // blend the 2 wave layers based on distance to surface + float highAltitudeFade = linearFade(0.0, 60000.0, positionToEyeECLength); + float lowAltitudeFade = 1.0 - linearFade(20000.0, 60000.0, positionToEyeECLength); + vec3 normalTangentSpace = + (highAltitudeFade * normalTangentSpaceHighAltitude) + + (lowAltitudeFade * normalTangentSpaceLowAltitude); + normalTangentSpace = normalize(normalTangentSpace); + + // fade out the normal perturbation as we move farther from the water surface + normalTangentSpace.xy *= waveIntensity; + normalTangentSpace = normalize(normalTangentSpace); +#else + vec3 normalTangentSpace = vec3(0.0, 0.0, 1.0); +#endif + + vec3 normalEC = enuToEye * normalTangentSpace; + + const vec3 waveHighlightColor = vec3(0.3, 0.45, 0.6); + + // Use diffuse light to highlight the waves + float diffuseIntensity = czm_getLambertDiffuse(czm_lightDirectionEC, normalEC) * maskValue; + vec3 diffuseHighlight = waveHighlightColor * diffuseIntensity * (1.0 - fade); + +#ifdef SHOW_OCEAN_WAVES + // Where diffuse light is low or non-existent, use wave highlights based solely on + // the wave bumpiness and no particular light direction. + float tsPerturbationRatio = normalTangentSpace.z; + vec3 nonDiffuseHighlight = mix(waveHighlightColor * 5.0 * (1.0 - tsPerturbationRatio), vec3(0.0), diffuseIntensity); +#else + vec3 nonDiffuseHighlight = vec3(0.0); +#endif + + // Add specular highlights in 3D, and in all modes when zoomed in. + float specularIntensity = czm_getSpecular(czm_lightDirectionEC, normalizedPositionToEyeEC, normalEC, 10.0); + float surfaceReflectance = mix(0.0, mix(u_zoomedOutOceanSpecularIntensity, oceanSpecularIntensity, waveIntensity), maskValue); + float specular = specularIntensity * surfaceReflectance; + +#ifdef HDR + specular *= 1.4; + + float e = 0.2; + float d = 3.3; + float c = 1.7; + + vec3 color = imageryColor.rgb + (c * (vec3(e) + imageryColor.rgb * d) * (diffuseHighlight + nonDiffuseHighlight + specular)); +#else + vec3 color = imageryColor.rgb + diffuseHighlight + nonDiffuseHighlight + specular; +#endif + + return vec4(color, imageryColor.a); +} + +#endif // #ifdef SHOW_REFLECTIVE_OCEAN \ No newline at end of file diff --git a/web/src/beta/lib/core/engines/Cesium/Shaders/OverriddenShaders/GlobeFS/Customs.glsl b/web/src/beta/lib/core/engines/Cesium/Shaders/OverriddenShaders/GlobeFS/Customs.glsl new file mode 100644 index 0000000000..45453fdbb7 --- /dev/null +++ b/web/src/beta/lib/core/engines/Cesium/Shaders/OverriddenShaders/GlobeFS/Customs.glsl @@ -0,0 +1,54 @@ +// Derived from: +// https://github.com/CesiumGS/cesium/blob/1.106/packages/engine/Source/Shaders/Model/ImageBasedLightingStageFS.glsl +// Specular term was removed, as I never apply it on terrain. +vec3 reearth_imageBasedLightingStage(vec3 positionEC, vec3 normalEC, + vec3 lightDirectionEC, vec3 lightColorHdr, + czm_pbrParameters pbrParameters) { + vec3 v = -positionEC; + vec3 n = normalEC; + vec3 l = normalize(lightDirectionEC); + vec3 h = normalize(v + l); + float NdotV = abs(dot(n, v)) + 0.001; + float VdotH = clamp(dot(v, h), 0.0, 1.0); + + const mat3 yUpToZUp = mat3(-1.0, 0.0, 0.0, 0.0, 0.0, -1.0, 0.0, 1.0, 0.0); + // Reference frame matrix can be computed only by world position and normal. + mat3 referenceFrameMatrix = + czm_transpose(czm_eastNorthUpToEyeCoordinates(v_positionMC, normalEC)); + vec3 cubeDir = + normalize(yUpToZUp * referenceFrameMatrix * normalize(reflect(-v, n))); + vec3 diffuseIrradiance = + czm_sphericalHarmonics(cubeDir, u_reearth_sphericalHarmonicCoefficients); + + return pbrParameters.diffuseColor * diffuseIrradiance; +} + +vec4 reearth_computeImageBasedLightingColor(vec4 color) { + if (u_reearth_globeImageBasedLighting) { + czm_pbrParameters pbrParameters; + pbrParameters.diffuseColor = color.rgb; + + vec3 normalEC = normalize(v_normalEC); + vec3 lighting = + czm_pbrLighting(v_positionEC, normalEC, czm_lightDirectionEC, + czm_lightColorHdr, pbrParameters); + lighting += reearth_imageBasedLightingStage( + v_positionEC, normalEC, czm_lightDirectionEC, + czm_lightColorHdr, pbrParameters) * + u_vertexShadowDarkness; + +#ifdef HDR + lighting = czm_acesTonemapping(lighting); + lighting = czm_linearToSrgb(lighting); +#endif + + return vec4(color.rgb * lighting, color.a); + } else { + float diffuseIntensity = clamp( + czm_getLambertDiffuse(czm_lightDirectionEC, normalize(v_normalEC)) * + u_lambertDiffuseMultiplier + + u_vertexShadowDarkness, + 0.0, 1.0); + return vec4(color.rgb * czm_lightColor * diffuseIntensity, color.a); + } +} diff --git a/web/src/beta/lib/core/engines/Cesium/Shaders/OverriddenShaders/GlobeFS/Definitions.glsl b/web/src/beta/lib/core/engines/Cesium/Shaders/OverriddenShaders/GlobeFS/Definitions.glsl new file mode 100644 index 0000000000..7a60f89224 --- /dev/null +++ b/web/src/beta/lib/core/engines/Cesium/Shaders/OverriddenShaders/GlobeFS/Definitions.glsl @@ -0,0 +1,4 @@ +uniform vec3 u_reearth_sphericalHarmonicCoefficients[9]; +uniform bool u_reearth_globeImageBasedLighting; + +vec4 reearth_computeImageBasedLightingColor(vec4 color); diff --git a/web/src/beta/lib/core/engines/Cesium/Shaders/OverriddenShaders/README.md b/web/src/beta/lib/core/engines/Cesium/Shaders/OverriddenShaders/README.md new file mode 100644 index 0000000000..32b3627d6e --- /dev/null +++ b/web/src/beta/lib/core/engines/Cesium/Shaders/OverriddenShaders/README.md @@ -0,0 +1,23 @@ +# OverriddenShaders + +This is a set of shaders to override Cesium's shader. + +The structure have to be as follow. + +``` +ShaderName/ + Cesium.glsl ... Clone of Cesium's shader + Customs.glsl ... Define your own custom functions + Definitions.glsl ... Definition for each variable or function. +``` + +In Cesium.glsl, you need to specify the source of the reference as below. Please don't change this file as much as possible, because we need to update this file depending on Cesium's updates. You must only use functions defined in `Custom.glsl`. + +``` +// Ref: cesium {{VERSION}} {{URL_FOR_THE_SOURCE}} +// ex. Ref: cesium v1.106 https://github.com/CesiumGS/cesium/blob/1.106/packages/engine/Source/Shaders/GlobeFS.glsl +``` + +Please note that the URL must refer the specific version of Cesium like `https://github.com/CesiumGS/cesium/blob/{{VERSION}}/path`. + +In Customs.glsl, you must set `reearth_` prefix to the name of the function like `reearth_own_function()`. Also you must set `reearth_` to the name of the uniform and attribute like `u_reearth_variable` or `v_reearth_variable`. diff --git a/web/src/beta/lib/core/engines/Cesium/core/Globe.tsx b/web/src/beta/lib/core/engines/Cesium/core/Globe.tsx index 6e14a7eee1..e5b064851b 100644 --- a/web/src/beta/lib/core/engines/Cesium/core/Globe.tsx +++ b/web/src/beta/lib/core/engines/Cesium/core/Globe.tsx @@ -31,6 +31,7 @@ export default function Globe({ property, cesiumIonAccessToken }: Props): JSX.El const opts = { terrain: terrainProperty?.terrain, terrainType: terrainProperty?.terrainType, + terrainNormal: terrainProperty?.terrainNormal, terrainCesiumIonAccessToken: terrainProperty?.terrainCesiumIonAccessToken || cesiumIonAccessToken, terrainCesiumIonAsset: terrainProperty?.terrainCesiumIonAsset, @@ -44,6 +45,7 @@ export default function Globe({ property, cesiumIonAccessToken }: Props): JSX.El terrainProperty?.terrainCesiumIonAccessToken, terrainProperty?.terrainCesiumIonAsset, terrainProperty?.terrainCesiumIonUrl, + terrainProperty?.terrainNormal, cesiumIonAccessToken, ]); @@ -82,24 +84,33 @@ const terrainProviders: { | (( opts: Pick< TerrainProperty, - "terrainCesiumIonAccessToken" | "terrainCesiumIonAsset" | "terrainCesiumIonUrl" + | "terrainCesiumIonAccessToken" + | "terrainCesiumIonAsset" + | "terrainCesiumIonUrl" + | "terrainNormal" >, ) => TerrainProvider | null); } = { - cesium: ({ terrainCesiumIonAccessToken }) => + cesium: ({ terrainCesiumIonAccessToken, terrainNormal }) => // https://github.com/CesiumGS/cesium/blob/main/Source/Core/createWorldTerrain.js new CesiumTerrainProvider({ url: IonResource.fromAssetId(1, { accessToken: terrainCesiumIonAccessToken, }), - requestVertexNormals: false, + requestVertexNormals: terrainNormal, requestWaterMask: false, }), - arcgis: () => + arcgis: ({ terrainNormal }) => new ArcGISTiledElevationTerrainProvider({ url: "https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer", + requestVertexNormals: terrainNormal, }), - cesiumion: ({ terrainCesiumIonAccessToken, terrainCesiumIonAsset, terrainCesiumIonUrl }) => + cesiumion: ({ + terrainCesiumIonAccessToken, + terrainCesiumIonAsset, + terrainCesiumIonUrl, + terrainNormal, + }) => terrainCesiumIonAsset ? new CesiumTerrainProvider({ url: @@ -107,7 +118,7 @@ const terrainProviders: { IonResource.fromAssetId(parseInt(terrainCesiumIonAsset, 10), { accessToken: terrainCesiumIonAccessToken, }), - requestVertexNormals: true, + requestVertexNormals: terrainNormal, }) : null, }; diff --git a/web/src/beta/lib/core/engines/Cesium/hooks.ts b/web/src/beta/lib/core/engines/Cesium/hooks.ts index 965a01b354..1d1c64b96b 100644 --- a/web/src/beta/lib/core/engines/Cesium/hooks.ts +++ b/web/src/beta/lib/core/engines/Cesium/hooks.ts @@ -39,6 +39,7 @@ import { getCamera, isDraggable, isSelectable, getLocationFromScreen } from "./c import { getTag, type Context as FeatureContext } from "./Feature"; import { InternalCesium3DTileFeature } from "./types"; import useEngineRef from "./useEngineRef"; +import { useOverrideGlobeShader } from "./useOverrideGlobeShader"; import { convertCartesian3ToPosition, findEntity, getEntityContent } from "./utils"; export default ({ @@ -334,6 +335,57 @@ export default ({ [engineAPI], ); + const sphericalHarmonicCoefficients = useMemo( + () => + !property?.debugs?.debugSphericalHarmonicCoefficients + ? property?.atmosphere?.sphericalHarmonicCoefficients?.map( + v => new Cartesian3(v.x, v.y, v.z), + ) ?? [ + new Cartesian3(), + new Cartesian3(), + new Cartesian3(), + new Cartesian3(), + new Cartesian3(), + new Cartesian3(), + new Cartesian3(), + new Cartesian3(), + new Cartesian3(), + ] + : [ + new Cartesian3(0.499745965003967, 0.499196201562881, 0.500154078006744), // L00, irradiance, pre-scaled base + new Cartesian3(0.265826553106308, -0.266099184751511, 0.265922993421555), // L1-1, irradiance, pre-scaled base + new Cartesian3(0.243236944079399, 0.266723394393921, -0.265380442142487), // L10, irradiance, pre-scaled base + new Cartesian3(-0.266895800828934, 0.265416264533997, 0.266921550035477), // L11, irradiance, pre-scaled base + new Cartesian3(0.000195000306121, -0.000644546060357, -0.000383183418307), // L2-2, irradiance, pre-scaled base + new Cartesian3(-0.000396036746679, -0.000622032093816, 0.000262127199676), // L2-1, irradiance, pre-scaled base + new Cartesian3(-0.000214280473301, 0.00004872302452, -0.000059724134189), // L20, irradiance, pre-scaled base + new Cartesian3(0.000107143961941, -0.000126510843984, -0.000425444566645), // L21, irradiance, pre-scaled base + new Cartesian3(-0.000069071611506, 0.000134039684781, -0.000119135256682), // L22, irradiance, pre-scaled base + ], + [ + property?.atmosphere?.sphericalHarmonicCoefficients, + property?.debugs?.debugSphericalHarmonicCoefficients, + ], + ); + + useEffect(() => { + if (!cesium.current?.cesiumElement) return; + + cesium.current.cesiumElement.scene.sphericalHarmonicCoefficients = + sphericalHarmonicCoefficients; + }, [sphericalHarmonicCoefficients]); + + useOverrideGlobeShader({ + cesium, + sphericalHarmonicCoefficients: sphericalHarmonicCoefficients, + globeShadowDarkness: property?.atmosphere?.globeShadowDarkness, + globeImageBasedLighting: property?.atmosphere?.globeImageBasedLighting, + hasVertexNormals: + property?.atmosphere?.enable_lighting && + property.terrain?.terrain && + property.terrain.terrainNormal, + }); + const handleMouseWheel = useCallback( (delta: number) => { engineAPI.mouseEventCallbacks.wheel?.({ delta }); diff --git a/web/src/beta/lib/core/engines/Cesium/type.d.ts b/web/src/beta/lib/core/engines/Cesium/type.d.ts new file mode 100644 index 0000000000..7b938c1c0a --- /dev/null +++ b/web/src/beta/lib/core/engines/Cesium/type.d.ts @@ -0,0 +1,16 @@ +declare module "@cesium/engine" { + export class ShaderSource { + sources: string[]; + defines: string[]; + constructor(options: { sources: string[]; defines: string[] }); + } + + // Cesium's type definition is wrong. The parameter type of raiseEvent() + // should be (...args: Parameter) instead of + // (...args: Parameter[]). + // This cannot be fixed by augmentation but by overloading. + export interface Event void = (...args: any[]) => void> { + // eslint-disable-next-line @typescript-eslint/method-signature-style + raiseEvent(...arguments: Parameters): void; + } +} diff --git a/web/src/beta/lib/core/engines/Cesium/types.ts b/web/src/beta/lib/core/engines/Cesium/types.ts index c7f68142d4..90c1e7e849 100644 --- a/web/src/beta/lib/core/engines/Cesium/types.ts +++ b/web/src/beta/lib/core/engines/Cesium/types.ts @@ -1,3 +1,15 @@ -import type { Cesium3DTileFeature, Cesium3DTilePointFeature, Model } from "cesium"; +import type { ShaderSource } from "@cesium/engine"; +import type { Cesium3DTileFeature, Cesium3DTilePointFeature, Globe, Model } from "cesium"; export type InternalCesium3DTileFeature = Cesium3DTileFeature | Cesium3DTilePointFeature | Model; + +export type PrivateCesiumGlobe = Globe & { + _surface: { + _tileProvider: { + materialUniformMap?: Record unknown>; + }; + }; + _surfaceShaderSet: { + baseFragmentShaderSource: ShaderSource; + }; +}; diff --git a/web/src/beta/lib/core/engines/Cesium/useOverrideGlobeShader.ts b/web/src/beta/lib/core/engines/Cesium/useOverrideGlobeShader.ts new file mode 100644 index 0000000000..69dd8435f8 --- /dev/null +++ b/web/src/beta/lib/core/engines/Cesium/useOverrideGlobeShader.ts @@ -0,0 +1,83 @@ +import { ShaderSource } from "@cesium/engine"; +import { Viewer, Globe, Material, Cartesian3 } from "cesium"; +import { RefObject, useEffect } from "react"; +import { CesiumComponentRef } from "resium"; + +import { useImmutableFunction } from "../../hooks/useRefFunction"; + +import CesiumGlobeFS from "./Shaders/OverriddenShaders/GlobeFS/Cesium.glsl?raw"; +import GlobeFSCustoms from "./Shaders/OverriddenShaders/GlobeFS/Customs.glsl?raw"; +import GlobeFSDefinitions from "./Shaders/OverriddenShaders/GlobeFS/Definitions.glsl?raw"; +import { PrivateCesiumGlobe } from "./types"; + +function makeGlobeShadersDirty(globe: Globe): void { + // Invoke the internal makeShadersDirty() by setting a material to globe to + // reset surface shader source to the initial state (assuming that we never + // use custom material on globe). + // ref: https://github.com/CesiumGS/cesium/blob/1.106/packages/engine/Source/Scene/Globe.js#L562-L572 + const material = globe.material; + if (material == null) { + globe.material = Material.fromType("Color"); + globe.material = undefined; + } else { + globe.material = undefined; + globe.material = material; + } +} + +export const useOverrideGlobeShader = ({ + cesium, + sphericalHarmonicCoefficients, + globeShadowDarkness, + globeImageBasedLighting, + hasVertexNormals, +}: { + cesium: RefObject>; + sphericalHarmonicCoefficients: Cartesian3[]; + globeShadowDarkness?: number; + globeImageBasedLighting?: boolean; + hasVertexNormals?: boolean; +}) => { + const sphericalHarmonicCoefficientsRefFunc = useImmutableFunction(sphericalHarmonicCoefficients); + const globeImageBasedLightingRefFunc = useImmutableFunction(globeImageBasedLighting); + + useEffect(() => { + if (!cesium.current?.cesiumElement || !globeShadowDarkness || !hasVertexNormals) return; + const globe = cesium.current.cesiumElement.scene.globe as PrivateCesiumGlobe; + + globe.vertexShadowDarkness = globeShadowDarkness; + }, [cesium, globeShadowDarkness, hasVertexNormals]); + + // This need to be invoked before Globe is updated. + useEffect(() => { + if (!cesium.current?.cesiumElement || !hasVertexNormals) return; + const globe = cesium.current.cesiumElement.scene.globe as PrivateCesiumGlobe; + + makeGlobeShadersDirty(globe); + + globe._surface._tileProvider.materialUniformMap = { + ...globe._surface._tileProvider.materialUniformMap, + u_reearth_sphericalHarmonicCoefficients: sphericalHarmonicCoefficientsRefFunc, + u_reearth_globeImageBasedLighting: globeImageBasedLightingRefFunc, // Avoid to rerender globe. + }; + + const surfaceShaderSet = globe._surfaceShaderSet; + const baseFragmentShaderSource = surfaceShaderSet.baseFragmentShaderSource; + surfaceShaderSet.baseFragmentShaderSource = new ShaderSource({ + sources: [ + ...baseFragmentShaderSource.sources.slice(0, -1), + GlobeFSDefinitions + CesiumGlobeFS + GlobeFSCustoms, + ], + defines: baseFragmentShaderSource.defines, + }); + return () => { + // Reset customized shader to default + makeGlobeShadersDirty(globe); + }; + }, [ + sphericalHarmonicCoefficientsRefFunc, + globeImageBasedLightingRefFunc, + cesium, + hasVertexNormals, + ]); +}; diff --git a/web/src/beta/lib/core/hooks/useRefFunction.ts b/web/src/beta/lib/core/hooks/useRefFunction.ts new file mode 100644 index 0000000000..02198362bc --- /dev/null +++ b/web/src/beta/lib/core/hooks/useRefFunction.ts @@ -0,0 +1,10 @@ +import { useCallback, useEffect, useRef } from "react"; + +export const useImmutableFunction = (v: T) => { + const valueRef = useRef(v); + const immutableFunc = useCallback(() => valueRef.current, []); + useEffect(() => { + valueRef.current = v; + }, [v]); + return immutableFunc; +};