SSRShader.js 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. import {
  2. Matrix4,
  3. Vector2
  4. } from 'three';
  5. /**
  6. * References:
  7. * https://lettier.github.io/3d-game-shaders-for-beginners/screen-space-reflection.html
  8. */
  9. const SSRShader = {
  10. defines: {
  11. MAX_STEP: 0,
  12. PERSPECTIVE_CAMERA: true,
  13. DISTANCE_ATTENUATION: true,
  14. FRESNEL: true,
  15. INFINITE_THICK: false,
  16. SELECTIVE: false,
  17. },
  18. uniforms: {
  19. 'tDiffuse': { value: null },
  20. 'tNormal': { value: null },
  21. 'tMetalness': { value: null },
  22. 'tDepth': { value: null },
  23. 'cameraNear': { value: null },
  24. 'cameraFar': { value: null },
  25. 'resolution': { value: new Vector2() },
  26. 'cameraProjectionMatrix': { value: new Matrix4() },
  27. 'cameraInverseProjectionMatrix': { value: new Matrix4() },
  28. 'opacity': { value: .5 },
  29. 'maxDistance': { value: 180 },
  30. 'cameraRange': { value: 0 },
  31. 'thickness': { value: .018 }
  32. },
  33. vertexShader: /* glsl */`
  34. varying vec2 vUv;
  35. void main() {
  36. vUv = uv;
  37. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  38. }
  39. `,
  40. fragmentShader: /* glsl */`
  41. // precision highp float;
  42. precision highp sampler2D;
  43. varying vec2 vUv;
  44. uniform sampler2D tDepth;
  45. uniform sampler2D tNormal;
  46. uniform sampler2D tMetalness;
  47. uniform sampler2D tDiffuse;
  48. uniform float cameraRange;
  49. uniform vec2 resolution;
  50. uniform float opacity;
  51. uniform float cameraNear;
  52. uniform float cameraFar;
  53. uniform float maxDistance;
  54. uniform float thickness;
  55. uniform mat4 cameraProjectionMatrix;
  56. uniform mat4 cameraInverseProjectionMatrix;
  57. #include <packing>
  58. float pointToLineDistance(vec3 x0, vec3 x1, vec3 x2) {
  59. //x0: point, x1: linePointA, x2: linePointB
  60. //https://mathworld.wolfram.com/Point-LineDistance3-Dimensional.html
  61. return length(cross(x0-x1,x0-x2))/length(x2-x1);
  62. }
  63. float pointPlaneDistance(vec3 point,vec3 planePoint,vec3 planeNormal){
  64. // https://mathworld.wolfram.com/Point-PlaneDistance.html
  65. //// https://en.wikipedia.org/wiki/Plane_(geometry)
  66. //// http://paulbourke.net/geometry/pointlineplane/
  67. float a=planeNormal.x,b=planeNormal.y,c=planeNormal.z;
  68. float x0=point.x,y0=point.y,z0=point.z;
  69. float x=planePoint.x,y=planePoint.y,z=planePoint.z;
  70. float d=-(a*x+b*y+c*z);
  71. float distance=(a*x0+b*y0+c*z0+d)/sqrt(a*a+b*b+c*c);
  72. return distance;
  73. }
  74. float getDepth( const in vec2 uv ) {
  75. return texture2D( tDepth, uv ).x;
  76. }
  77. float getViewZ( const in float depth ) {
  78. #ifdef PERSPECTIVE_CAMERA
  79. return perspectiveDepthToViewZ( depth, cameraNear, cameraFar );
  80. #else
  81. return orthographicDepthToViewZ( depth, cameraNear, cameraFar );
  82. #endif
  83. }
  84. vec3 getViewPosition( const in vec2 uv, const in float depth/*clip space*/, const in float clipW ) {
  85. vec4 clipPosition = vec4( ( vec3( uv, depth ) - 0.5 ) * 2.0, 1.0 );//ndc
  86. clipPosition *= clipW; //clip
  87. return ( cameraInverseProjectionMatrix * clipPosition ).xyz;//view
  88. }
  89. vec3 getViewNormal( const in vec2 uv ) {
  90. return unpackRGBToNormal( texture2D( tNormal, uv ).xyz );
  91. }
  92. vec2 viewPositionToXY(vec3 viewPosition){
  93. vec2 xy;
  94. vec4 clip=cameraProjectionMatrix*vec4(viewPosition,1);
  95. xy=clip.xy;//clip
  96. float clipW=clip.w;
  97. xy/=clipW;//NDC
  98. xy=(xy+1.)/2.;//uv
  99. xy*=resolution;//screen
  100. return xy;
  101. }
  102. void main(){
  103. #ifdef SELECTIVE
  104. float metalness=texture2D(tMetalness,vUv).r;
  105. if(metalness==0.) return;
  106. #endif
  107. float depth = getDepth( vUv );
  108. float viewZ = getViewZ( depth );
  109. if(-viewZ>=cameraFar) return;
  110. float clipW = cameraProjectionMatrix[2][3] * viewZ+cameraProjectionMatrix[3][3];
  111. vec3 viewPosition=getViewPosition( vUv, depth, clipW );
  112. vec2 d0=gl_FragCoord.xy;
  113. vec2 d1;
  114. vec3 viewNormal=getViewNormal( vUv );
  115. #ifdef PERSPECTIVE_CAMERA
  116. vec3 viewIncidentDir=normalize(viewPosition);
  117. vec3 viewReflectDir=reflect(viewIncidentDir,viewNormal);
  118. #else
  119. vec3 viewIncidentDir=vec3(0,0,-1);
  120. vec3 viewReflectDir=reflect(viewIncidentDir,viewNormal);
  121. #endif
  122. float maxReflectRayLen=maxDistance/dot(-viewIncidentDir,viewNormal);
  123. // dot(a,b)==length(a)*length(b)*cos(theta) // https://www.mathsisfun.com/algebra/vectors-dot-product.html
  124. // if(a.isNormalized&&b.isNormalized) dot(a,b)==cos(theta)
  125. // maxDistance/maxReflectRayLen=cos(theta)
  126. // maxDistance/maxReflectRayLen==dot(a,b)
  127. // maxReflectRayLen==maxDistance/dot(a,b)
  128. vec3 d1viewPosition=viewPosition+viewReflectDir*maxReflectRayLen;
  129. #ifdef PERSPECTIVE_CAMERA
  130. if(d1viewPosition.z>-cameraNear){
  131. //https://tutorial.math.lamar.edu/Classes/CalcIII/EqnsOfLines.aspx
  132. float t=(-cameraNear-viewPosition.z)/viewReflectDir.z;
  133. d1viewPosition=viewPosition+viewReflectDir*t;
  134. }
  135. #endif
  136. d1=viewPositionToXY(d1viewPosition);
  137. float totalLen=length(d1-d0);
  138. float xLen=d1.x-d0.x;
  139. float yLen=d1.y-d0.y;
  140. float totalStep=max(abs(xLen),abs(yLen));
  141. float xSpan=xLen/totalStep;
  142. float ySpan=yLen/totalStep;
  143. for(float i=0.;i<float(MAX_STEP);i++){
  144. if(i>=totalStep) break;
  145. vec2 xy=vec2(d0.x+i*xSpan,d0.y+i*ySpan);
  146. if(xy.x<0.||xy.x>resolution.x||xy.y<0.||xy.y>resolution.y) break;
  147. float s=length(xy-d0)/totalLen;
  148. vec2 uv=xy/resolution;
  149. float d = getDepth(uv);
  150. float vZ = getViewZ( d );
  151. if(-vZ>=cameraFar) continue;
  152. float cW = cameraProjectionMatrix[2][3] * vZ+cameraProjectionMatrix[3][3];
  153. vec3 vP=getViewPosition( uv, d, cW );
  154. #ifdef PERSPECTIVE_CAMERA
  155. // https://comp.nus.edu.sg/~lowkl/publications/lowk_persp_interp_techrep.pdf
  156. float recipVPZ=1./viewPosition.z;
  157. float viewReflectRayZ=1./(recipVPZ+s*(1./d1viewPosition.z-recipVPZ));
  158. #else
  159. float viewReflectRayZ=viewPosition.z+s*(d1viewPosition.z-viewPosition.z);
  160. #endif
  161. // if(viewReflectRayZ>vZ) continue; // will cause "npm run make-screenshot webgl_postprocessing_ssr" high probability hang.
  162. // https://github.com/mrdoob/three.js/pull/21539#issuecomment-821061164
  163. if(viewReflectRayZ<=vZ){
  164. bool hit;
  165. #ifdef INFINITE_THICK
  166. hit=true;
  167. #else
  168. float away=pointToLineDistance(vP,viewPosition,d1viewPosition);
  169. float minThickness;
  170. vec2 xyNeighbor=xy;
  171. xyNeighbor.x+=1.;
  172. vec2 uvNeighbor=xyNeighbor/resolution;
  173. vec3 vPNeighbor=getViewPosition(uvNeighbor,d,cW);
  174. minThickness=vPNeighbor.x-vP.x;
  175. minThickness*=3.;
  176. float tk=max(minThickness,thickness);
  177. hit=away<=tk;
  178. #endif
  179. if(hit){
  180. vec3 vN=getViewNormal( uv );
  181. if(dot(viewReflectDir,vN)>=0.) continue;
  182. float distance=pointPlaneDistance(vP,viewPosition,viewNormal);
  183. if(distance>maxDistance) break;
  184. float op=opacity;
  185. #ifdef DISTANCE_ATTENUATION
  186. float ratio=1.-(distance/maxDistance);
  187. float attenuation=ratio*ratio;
  188. op=opacity*attenuation;
  189. #endif
  190. #ifdef FRESNEL
  191. float fresnelCoe=(dot(viewIncidentDir,viewReflectDir)+1.)/2.;
  192. op*=fresnelCoe;
  193. #endif
  194. vec4 reflectColor=texture2D(tDiffuse,uv);
  195. gl_FragColor.xyz=reflectColor.xyz;
  196. gl_FragColor.a=op;
  197. break;
  198. }
  199. }
  200. }
  201. }
  202. `
  203. };
  204. const SSRDepthShader = {
  205. defines: {
  206. 'PERSPECTIVE_CAMERA': 1
  207. },
  208. uniforms: {
  209. 'tDepth': { value: null },
  210. 'cameraNear': { value: null },
  211. 'cameraFar': { value: null },
  212. },
  213. vertexShader: /* glsl */`
  214. varying vec2 vUv;
  215. void main() {
  216. vUv = uv;
  217. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  218. }
  219. `,
  220. fragmentShader: /* glsl */`
  221. uniform sampler2D tDepth;
  222. uniform float cameraNear;
  223. uniform float cameraFar;
  224. varying vec2 vUv;
  225. #include <packing>
  226. float getLinearDepth( const in vec2 uv ) {
  227. #if PERSPECTIVE_CAMERA == 1
  228. float fragCoordZ = texture2D( tDepth, uv ).x;
  229. float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );
  230. return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );
  231. #else
  232. return texture2D( tDepth, uv ).x;
  233. #endif
  234. }
  235. void main() {
  236. float depth = getLinearDepth( vUv );
  237. float d = 1.0 - depth;
  238. // d=(d-.999)*1000.;
  239. gl_FragColor = vec4( vec3( d ), 1.0 );
  240. }
  241. `
  242. };
  243. const SSRBlurShader = {
  244. uniforms: {
  245. 'tDiffuse': { value: null },
  246. 'resolution': { value: new Vector2() },
  247. 'opacity': { value: .5 },
  248. },
  249. vertexShader: /* glsl */`
  250. varying vec2 vUv;
  251. void main() {
  252. vUv = uv;
  253. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  254. }
  255. `,
  256. fragmentShader: /* glsl */`
  257. uniform sampler2D tDiffuse;
  258. uniform vec2 resolution;
  259. varying vec2 vUv;
  260. void main() {
  261. //reverse engineering from PhotoShop blur filter, then change coefficient
  262. vec2 texelSize = ( 1.0 / resolution );
  263. vec4 c=texture2D(tDiffuse,vUv);
  264. vec2 offset;
  265. offset=(vec2(-1,0))*texelSize;
  266. vec4 cl=texture2D(tDiffuse,vUv+offset);
  267. offset=(vec2(1,0))*texelSize;
  268. vec4 cr=texture2D(tDiffuse,vUv+offset);
  269. offset=(vec2(0,-1))*texelSize;
  270. vec4 cb=texture2D(tDiffuse,vUv+offset);
  271. offset=(vec2(0,1))*texelSize;
  272. vec4 ct=texture2D(tDiffuse,vUv+offset);
  273. // float coeCenter=.5;
  274. // float coeSide=.125;
  275. float coeCenter=.2;
  276. float coeSide=.2;
  277. float a=c.a*coeCenter+cl.a*coeSide+cr.a*coeSide+cb.a*coeSide+ct.a*coeSide;
  278. vec3 rgb=(c.rgb*c.a*coeCenter+cl.rgb*cl.a*coeSide+cr.rgb*cr.a*coeSide+cb.rgb*cb.a*coeSide+ct.rgb*ct.a*coeSide)/a;
  279. gl_FragColor=vec4(rgb,a);
  280. }
  281. `
  282. };
  283. export { SSRShader, SSRDepthShader, SSRBlurShader };