SSRShader.js 9.2 KB

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