NormalMapShader.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import {
  2. Vector2
  3. } from 'three';
  4. /**
  5. * @module NormalMapShader
  6. * @three_import import { NormalMapShader } from 'three/addons/shaders/NormalMapShader.js';
  7. */
  8. /**
  9. * Normal map shader, compute normals from heightmap.
  10. * @constant
  11. * @type {ShaderMaterial~Shader}
  12. */
  13. const NormalMapShader = {
  14. name: 'NormalMapShader',
  15. uniforms: {
  16. 'heightMap': { value: null },
  17. 'resolution': { value: new Vector2( 512, 512 ) },
  18. 'scale': { value: new Vector2( 1, 1 ) },
  19. 'height': { value: 0.05 }
  20. },
  21. vertexShader: /* glsl */`
  22. varying vec2 vUv;
  23. void main() {
  24. vUv = uv;
  25. gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
  26. }`,
  27. fragmentShader: /* glsl */`
  28. uniform float height;
  29. uniform vec2 resolution;
  30. uniform sampler2D heightMap;
  31. varying vec2 vUv;
  32. void main() {
  33. float val = texture2D( heightMap, vUv ).x;
  34. float valU = texture2D( heightMap, vUv + vec2( 1.0 / resolution.x, 0.0 ) ).x;
  35. float valV = texture2D( heightMap, vUv + vec2( 0.0, 1.0 / resolution.y ) ).x;
  36. gl_FragColor = vec4( ( 0.5 * normalize( vec3( val - valU, val - valV, height ) ) + 0.5 ), 1.0 );
  37. }`
  38. };
  39. export { NormalMapShader };