ShaderUtils.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661
  1. /**
  2. * @author alteredq / http://alteredqualia.com/
  3. * @author mr.doob / http://mrdoob.com/
  4. */
  5. if ( THREE.WebGLRenderer ) {
  6. THREE.ShaderUtils = {
  7. lib: {
  8. /* -------------------------------------------------------------------------
  9. // Fresnel shader
  10. // - based on Nvidia Cg tutorial
  11. ------------------------------------------------------------------------- */
  12. 'fresnel': {
  13. uniforms: {
  14. "mRefractionRatio": { type: "f", value: 1.02 },
  15. "mFresnelBias": { type: "f", value: 0.1 },
  16. "mFresnelPower": { type: "f", value: 2.0 },
  17. "mFresnelScale": { type: "f", value: 1.0 },
  18. "tCube": { type: "t", value: 1, texture: null }
  19. },
  20. fragmentShader: [
  21. "uniform samplerCube tCube;",
  22. "varying vec3 vReflect;",
  23. "varying vec3 vRefract[3];",
  24. "varying float vReflectionFactor;",
  25. "void main() {",
  26. "vec4 reflectedColor = textureCube( tCube, vec3( -vReflect.x, vReflect.yz ) );",
  27. "vec4 refractedColor = vec4( 1.0, 1.0, 1.0, 1.0 );",
  28. "refractedColor.r = textureCube( tCube, vec3( -vRefract[0].x, vRefract[0].yz ) ).r;",
  29. "refractedColor.g = textureCube( tCube, vec3( -vRefract[1].x, vRefract[1].yz ) ).g;",
  30. "refractedColor.b = textureCube( tCube, vec3( -vRefract[2].x, vRefract[2].yz ) ).b;",
  31. "refractedColor.a = 1.0;",
  32. "gl_FragColor = mix( refractedColor, reflectedColor, clamp( vReflectionFactor, 0.0, 1.0 ) );",
  33. "}"
  34. ].join("\n"),
  35. vertexShader: [
  36. "uniform float mRefractionRatio;",
  37. "uniform float mFresnelBias;",
  38. "uniform float mFresnelScale;",
  39. "uniform float mFresnelPower;",
  40. "varying vec3 vReflect;",
  41. "varying vec3 vRefract[3];",
  42. "varying float vReflectionFactor;",
  43. "void main() {",
  44. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  45. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  46. "vec3 nWorld = normalize ( mat3( objectMatrix[0].xyz, objectMatrix[1].xyz, objectMatrix[2].xyz ) * normal );",
  47. "vec3 I = mPosition.xyz - cameraPosition;",
  48. "vReflect = reflect( I, nWorld );",
  49. "vRefract[0] = refract( normalize( I ), nWorld, mRefractionRatio );",
  50. "vRefract[1] = refract( normalize( I ), nWorld, mRefractionRatio * 0.99 );",
  51. "vRefract[2] = refract( normalize( I ), nWorld, mRefractionRatio * 0.98 );",
  52. "vReflectionFactor = mFresnelBias + mFresnelScale * pow( 1.0 + dot( normalize( I ), nWorld ), mFresnelPower );",
  53. "gl_Position = projectionMatrix * mvPosition;",
  54. "}"
  55. ].join("\n")
  56. },
  57. /* -------------------------------------------------------------------------
  58. // Normal map shader
  59. // - Blinn-Phong
  60. // - normal + diffuse + specular + AO + displacement maps
  61. // - point and directional lights (use with "lights: true" material option)
  62. ------------------------------------------------------------------------- */
  63. 'normal' : {
  64. uniforms: THREE.UniformsUtils.merge( [
  65. THREE.UniformsLib[ "lights" ],
  66. {
  67. "enableAO" : { type: "i", value: 0 },
  68. "enableDiffuse" : { type: "i", value: 0 },
  69. "enableSpecular": { type: "i", value: 0 },
  70. "tDiffuse" : { type: "t", value: 0, texture: null },
  71. "tNormal" : { type: "t", value: 2, texture: null },
  72. "tSpecular" : { type: "t", value: 3, texture: null },
  73. "tAO" : { type: "t", value: 4, texture: null },
  74. "uNormalScale": { type: "f", value: 1.0 },
  75. "tDisplacement": { type: "t", value: 5, texture: null },
  76. "uDisplacementBias": { type: "f", value: 0.0 },
  77. "uDisplacementScale": { type: "f", value: 1.0 },
  78. "uDiffuseColor": { type: "c", value: new THREE.Color( 0xeeeeee ) },
  79. "uSpecularColor": { type: "c", value: new THREE.Color( 0x111111 ) },
  80. "uAmbientColor": { type: "c", value: new THREE.Color( 0x050505 ) },
  81. "uShininess": { type: "f", value: 30 },
  82. "uOpacity": { type: "f", value: 1 }
  83. }
  84. ] ),
  85. fragmentShader: [
  86. "uniform vec3 uAmbientColor;",
  87. "uniform vec3 uDiffuseColor;",
  88. "uniform vec3 uSpecularColor;",
  89. "uniform float uShininess;",
  90. "uniform float uOpacity;",
  91. "uniform bool enableDiffuse;",
  92. "uniform bool enableSpecular;",
  93. "uniform bool enableAO;",
  94. "uniform sampler2D tDiffuse;",
  95. "uniform sampler2D tNormal;",
  96. "uniform sampler2D tSpecular;",
  97. "uniform sampler2D tAO;",
  98. "uniform float uNormalScale;",
  99. "varying vec3 vTangent;",
  100. "varying vec3 vBinormal;",
  101. "varying vec3 vNormal;",
  102. "varying vec2 vUv;",
  103. "uniform vec3 ambientLightColor;",
  104. "#if MAX_DIR_LIGHTS > 0",
  105. "uniform vec3 directionalLightColor[ MAX_DIR_LIGHTS ];",
  106. "uniform vec3 directionalLightDirection[ MAX_DIR_LIGHTS ];",
  107. "#endif",
  108. "#if MAX_POINT_LIGHTS > 0",
  109. "uniform vec3 pointLightColor[ MAX_POINT_LIGHTS ];",
  110. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  111. "#endif",
  112. "varying vec3 vViewPosition;",
  113. "void main() {",
  114. "gl_FragColor = vec4( 1.0 );",
  115. "vec4 mColor = vec4( uDiffuseColor, uOpacity );",
  116. "vec4 mSpecular = vec4( uSpecularColor, uOpacity );",
  117. "vec3 specularTex = vec3( 1.0 );",
  118. "vec3 normalTex = texture2D( tNormal, vUv ).xyz * 2.0 - 1.0;",
  119. "normalTex.xy *= uNormalScale;",
  120. "normalTex = normalize( normalTex );",
  121. "if( enableDiffuse )",
  122. "gl_FragColor = gl_FragColor * texture2D( tDiffuse, vUv );",
  123. "if( enableAO )",
  124. "gl_FragColor = gl_FragColor * texture2D( tAO, vUv );",
  125. "if( enableSpecular )",
  126. "specularTex = texture2D( tSpecular, vUv ).xyz;",
  127. "mat3 tsb = mat3( vTangent, vBinormal, vNormal );",
  128. "vec3 finalNormal = tsb * normalTex;",
  129. "vec3 normal = normalize( finalNormal );",
  130. "vec3 viewPosition = normalize( vViewPosition );",
  131. // point lights
  132. "#if MAX_POINT_LIGHTS > 0",
  133. "vec4 pointTotal = vec4( 0.0 );",
  134. "for ( int i = 0; i < MAX_POINT_LIGHTS; i ++ ) {",
  135. "vec3 pointVector = normalize( vPointLight[ i ].xyz );",
  136. "vec3 pointHalfVector = normalize( vPointLight[ i ].xyz + vViewPosition );",
  137. "float pointDistance = vPointLight[ i ].w;",
  138. "float pointDotNormalHalf = dot( normal, pointHalfVector );",
  139. "float pointDiffuseWeight = max( dot( normal, pointVector ), 0.0 );",
  140. "float pointSpecularWeight = 0.0;",
  141. "if ( pointDotNormalHalf >= 0.0 )",
  142. "pointSpecularWeight = specularTex.r * pow( pointDotNormalHalf, uShininess );",
  143. "pointTotal += pointDistance * vec4( pointLightColor[ i ], 1.0 ) * ( mColor * pointDiffuseWeight + mSpecular * pointSpecularWeight * pointDiffuseWeight );",
  144. "}",
  145. "#endif",
  146. // directional lights
  147. "#if MAX_DIR_LIGHTS > 0",
  148. "vec4 dirTotal = vec4( 0.0 );",
  149. "for( int i = 0; i < MAX_DIR_LIGHTS; i++ ) {",
  150. "vec4 lDirection = viewMatrix * vec4( directionalLightDirection[ i ], 0.0 );",
  151. "vec3 dirVector = normalize( lDirection.xyz );",
  152. "vec3 dirHalfVector = normalize( lDirection.xyz + vViewPosition );",
  153. "float dirDotNormalHalf = dot( normal, dirHalfVector );",
  154. "float dirDiffuseWeight = max( dot( normal, dirVector ), 0.0 );",
  155. "float dirSpecularWeight = 0.0;",
  156. "if ( dirDotNormalHalf >= 0.0 )",
  157. "dirSpecularWeight = specularTex.r * pow( dirDotNormalHalf, uShininess );",
  158. "dirTotal += vec4( directionalLightColor[ i ], 1.0 ) * ( mColor * dirDiffuseWeight + mSpecular * dirSpecularWeight * dirDiffuseWeight );",
  159. "}",
  160. "#endif",
  161. // all lights contribution summation
  162. "vec4 totalLight = vec4( ambientLightColor * uAmbientColor, uOpacity );",
  163. "#if MAX_DIR_LIGHTS > 0",
  164. "totalLight += dirTotal;",
  165. "#endif",
  166. "#if MAX_POINT_LIGHTS > 0",
  167. "totalLight += pointTotal;",
  168. "#endif",
  169. "gl_FragColor = gl_FragColor * totalLight;",
  170. "}"
  171. ].join("\n"),
  172. vertexShader: [
  173. "attribute vec4 tangent;",
  174. "#ifdef VERTEX_TEXTURES",
  175. "uniform sampler2D tDisplacement;",
  176. "uniform float uDisplacementScale;",
  177. "uniform float uDisplacementBias;",
  178. "#endif",
  179. "varying vec3 vTangent;",
  180. "varying vec3 vBinormal;",
  181. "varying vec3 vNormal;",
  182. "varying vec2 vUv;",
  183. "#if MAX_POINT_LIGHTS > 0",
  184. "uniform vec3 pointLightPosition[ MAX_POINT_LIGHTS ];",
  185. "uniform float pointLightDistance[ MAX_POINT_LIGHTS ];",
  186. "varying vec4 vPointLight[ MAX_POINT_LIGHTS ];",
  187. "#endif",
  188. "varying vec3 vViewPosition;",
  189. "void main() {",
  190. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  191. "vViewPosition = cameraPosition - mPosition.xyz;",
  192. "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );",
  193. "vNormal = normalize( normalMatrix * normal );",
  194. // tangent and binormal vectors
  195. "vTangent = normalize( normalMatrix * tangent.xyz );",
  196. "vBinormal = cross( vNormal, vTangent ) * tangent.w;",
  197. "vBinormal = normalize( vBinormal );",
  198. "vUv = uv;",
  199. // point lights
  200. "#if MAX_POINT_LIGHTS > 0",
  201. "for( int i = 0; i < MAX_POINT_LIGHTS; i++ ) {",
  202. "vec4 lPosition = viewMatrix * vec4( pointLightPosition[ i ], 1.0 );",
  203. "vec3 lVector = lPosition.xyz - mvPosition.xyz;",
  204. "float lDistance = 1.0;",
  205. "if ( pointLightDistance[ i ] > 0.0 )",
  206. "lDistance = 1.0 - min( ( length( lVector ) / pointLightDistance[ i ] ), 1.0 );",
  207. "lVector = normalize( lVector );",
  208. "vPointLight[ i ] = vec4( lVector, lDistance );",
  209. "}",
  210. "#endif",
  211. // displacement mapping
  212. "#ifdef VERTEX_TEXTURES",
  213. "vec3 dv = texture2D( tDisplacement, uv ).xyz;",
  214. "float df = uDisplacementScale * dv.x + uDisplacementBias;",
  215. "vec4 displacedPosition = vec4( vNormal.xyz * df, 0.0 ) + mvPosition;",
  216. "gl_Position = projectionMatrix * displacedPosition;",
  217. "#else",
  218. "gl_Position = projectionMatrix * mvPosition;",
  219. "#endif",
  220. "}"
  221. ].join("\n")
  222. },
  223. /* -------------------------------------------------------------------------
  224. // Cube map shader
  225. ------------------------------------------------------------------------- */
  226. 'cube': {
  227. uniforms: { "tCube": { type: "t", value: 1, texture: null } },
  228. vertexShader: [
  229. "varying vec3 vViewPosition;",
  230. "void main() {",
  231. "vec4 mPosition = objectMatrix * vec4( position, 1.0 );",
  232. "vViewPosition = cameraPosition - mPosition.xyz;",
  233. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  234. "}"
  235. ].join("\n"),
  236. fragmentShader: [
  237. "uniform samplerCube tCube;",
  238. "varying vec3 vViewPosition;",
  239. "void main() {",
  240. "vec3 wPos = cameraPosition - vViewPosition;",
  241. "gl_FragColor = textureCube( tCube, vec3( - wPos.x, wPos.yz ) );",
  242. "}"
  243. ].join("\n")
  244. },
  245. /* ------------------------------------------------------------------------
  246. // Convolution shader
  247. // - ported from o3d sample to WebGL / GLSL
  248. // http://o3d.googlecode.com/svn/trunk/samples/convolution.html
  249. ------------------------------------------------------------------------ */
  250. 'convolution': {
  251. uniforms: {
  252. "tDiffuse" : { type: "t", value: 0, texture: null },
  253. "uImageIncrement" : { type: "v2", value: new THREE.Vector2( 0.001953125, 0.0 ) },
  254. "cKernel" : { type: "fv1", value: [] }
  255. },
  256. vertexShader: [
  257. "varying vec2 vUv;",
  258. "uniform vec2 uImageIncrement;",
  259. //"#define KERNEL_SIZE 25.0",
  260. "void main(void) {",
  261. "vUv = uv - ((KERNEL_SIZE - 1.0) / 2.0) * uImageIncrement;",
  262. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  263. "}"
  264. ].join("\n"),
  265. fragmentShader: [
  266. "varying vec2 vUv;",
  267. "uniform sampler2D tDiffuse;",
  268. "uniform vec2 uImageIncrement;",
  269. //"#define KERNEL_SIZE 25",
  270. "uniform float cKernel[KERNEL_SIZE];",
  271. "void main(void) {",
  272. "vec2 imageCoord = vUv;",
  273. "vec4 sum = vec4( 0.0, 0.0, 0.0, 0.0 );",
  274. "for( int i=0; i<KERNEL_SIZE; ++i ) {",
  275. "sum += texture2D( tDiffuse, imageCoord ) * cKernel[i];",
  276. "imageCoord += uImageIncrement;",
  277. "}",
  278. "gl_FragColor = sum;",
  279. "}"
  280. ].join("\n")
  281. },
  282. /* -------------------------------------------------------------------------
  283. // Film grain & scanlines shader
  284. // - ported from HLSL to WebGL / GLSL
  285. // http://www.truevision3d.com/forums/showcase/staticnoise_colorblackwhite_scanline_shaders-t18698.0.html
  286. // Screen Space Static Postprocessor
  287. //
  288. // Produces an analogue noise overlay similar to a film grain / TV static
  289. //
  290. // Original implementation and noise algorithm
  291. // Pat 'Hawthorne' Shearon
  292. //
  293. // Optimized scanlines + noise version with intensity scaling
  294. // Georg 'Leviathan' Steinrohder
  295. // This version is provided under a Creative Commons Attribution 3.0 License
  296. // http://creativecommons.org/licenses/by/3.0/
  297. ------------------------------------------------------------------------- */
  298. 'film': {
  299. uniforms: {
  300. tDiffuse: { type: "t", value: 0, texture: null },
  301. time: { type: "f", value: 0.0 },
  302. nIntensity: { type: "f", value: 0.5 },
  303. sIntensity: { type: "f", value: 0.05 },
  304. sCount: { type: "f", value: 4096 },
  305. grayscale: { type: "i", value: 1 }
  306. },
  307. vertexShader: [
  308. "varying vec2 vUv;",
  309. "void main() {",
  310. "vUv = vec2( uv.x, 1.0 - uv.y );",
  311. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  312. "}"
  313. ].join("\n"),
  314. fragmentShader: [
  315. "varying vec2 vUv;",
  316. "uniform sampler2D tDiffuse;",
  317. // control parameter
  318. "uniform float time;",
  319. "uniform bool grayscale;",
  320. // noise effect intensity value (0 = no effect, 1 = full effect)
  321. "uniform float nIntensity;",
  322. // scanlines effect intensity value (0 = no effect, 1 = full effect)
  323. "uniform float sIntensity;",
  324. // scanlines effect count value (0 = no effect, 4096 = full effect)
  325. "uniform float sCount;",
  326. "void main() {",
  327. // sample the source
  328. "vec4 cTextureScreen = texture2D( tDiffuse, vUv );",
  329. // make some noise
  330. "float x = vUv.x * vUv.y * time * 1000.0;",
  331. "x = mod( x, 13.0 ) * mod( x, 123.0 );",
  332. "float dx = mod( x, 0.01 );",
  333. // add noise
  334. "vec3 cResult = cTextureScreen.rgb + cTextureScreen.rgb * clamp( 0.1 + dx * 100.0, 0.0, 1.0 );",
  335. // get us a sine and cosine
  336. "vec2 sc = vec2( sin( vUv.y * sCount ), cos( vUv.y * sCount ) );",
  337. // add scanlines
  338. "cResult += cTextureScreen.rgb * vec3( sc.x, sc.y, sc.x ) * sIntensity;",
  339. // interpolate between source and result by intensity
  340. "cResult = cTextureScreen.rgb + clamp( nIntensity, 0.0,1.0 ) * ( cResult - cTextureScreen.rgb );",
  341. // convert to grayscale if desired
  342. "if( grayscale ) {",
  343. "cResult = vec3( cResult.r * 0.3 + cResult.g * 0.59 + cResult.b * 0.11 );",
  344. "}",
  345. "gl_FragColor = vec4( cResult, cTextureScreen.a );",
  346. "}"
  347. ].join("\n")
  348. },
  349. /* -------------------------------------------------------------------------
  350. // Full-screen textured quad shader
  351. ------------------------------------------------------------------------- */
  352. 'screen': {
  353. uniforms: {
  354. tDiffuse: { type: "t", value: 0, texture: null },
  355. opacity: { type: "f", value: 1.0 }
  356. },
  357. vertexShader: [
  358. "varying vec2 vUv;",
  359. "void main() {",
  360. "vUv = vec2( uv.x, 1.0 - uv.y );",
  361. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  362. "}"
  363. ].join("\n"),
  364. fragmentShader: [
  365. "varying vec2 vUv;",
  366. "uniform sampler2D tDiffuse;",
  367. "uniform float opacity;",
  368. "void main() {",
  369. "vec4 texel = texture2D( tDiffuse, vUv );",
  370. "gl_FragColor = opacity * texel;",
  371. "}"
  372. ].join("\n")
  373. },
  374. /* -------------------------------------------------------------------------
  375. // Simple test shader
  376. ------------------------------------------------------------------------- */
  377. 'basic': {
  378. uniforms: {},
  379. vertexShader: [
  380. "void main() {",
  381. "gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );",
  382. "}"
  383. ].join("\n"),
  384. fragmentShader: [
  385. "void main() {",
  386. "gl_FragColor = vec4( 1.0, 0.0, 0.0, 0.5 );",
  387. "}"
  388. ].join("\n")
  389. }
  390. },
  391. buildKernel: function( sigma ) {
  392. // We lop off the sqrt(2 * pi) * sigma term, since we're going to normalize anyway.
  393. function gauss( x, sigma ) {
  394. return Math.exp( - ( x * x ) / ( 2.0 * sigma * sigma ) );
  395. }
  396. var i, values, sum, halfWidth, kMaxKernelSize = 25, kernelSize = 2 * Math.ceil( sigma * 3.0 ) + 1;
  397. if ( kernelSize > kMaxKernelSize ) kernelSize = kMaxKernelSize;
  398. halfWidth = ( kernelSize - 1 ) * 0.5
  399. values = new Array( kernelSize );
  400. sum = 0.0;
  401. for ( i = 0; i < kernelSize; ++i ) {
  402. values[ i ] = gauss( i - halfWidth, sigma );
  403. sum += values[ i ];
  404. }
  405. // normalize the kernel
  406. for ( i = 0; i < kernelSize; ++i ) values[ i ] /= sum;
  407. return values;
  408. }
  409. };
  410. };