SSRShader.js 9.4 KB

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