SSRShader.js 9.3 KB

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