InfiniteGridHelper.js 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131
  1. // Author: Fyrestar https://mevedia.com (https://github.com/Fyrestar/THREE.InfiniteGridHelper)
  2. class InfiniteGridHelper extends THREE.Mesh{
  3. constructor(size1, size2, color, distance, opacity1=0.2, opacity2=1){
  4. color = color || new THREE.Color('white');
  5. size1 = size1 || 10;
  6. size2 = size2 || 100;
  7. distance = distance || 8000; //可视距离?越远越模糊
  8. const geometry = new THREE.PlaneBufferGeometry(2, 2, 1, 1);
  9. const material = new THREE.ShaderMaterial({
  10. side: THREE.DoubleSide,
  11. uniforms: {
  12. uSize1: {
  13. value: size1
  14. },
  15. uSize2: {
  16. value: size2
  17. },
  18. opacity1:{//线条1的
  19. value: opacity1
  20. },
  21. opacity2:{//线条2的
  22. value: opacity2
  23. },
  24. uColor: {
  25. value: color
  26. },
  27. uDistance: {
  28. value: distance
  29. }
  30. },
  31. transparent: true,
  32. vertexShader: `
  33. varying vec3 worldPosition;
  34. uniform float uDistance;
  35. void main() {
  36. vec3 pos = position.xyz * uDistance;
  37. pos.xy += cameraPosition.xy;
  38. worldPosition = pos;
  39. gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);
  40. }
  41. `,
  42. fragmentShader: `
  43. varying vec3 worldPosition;
  44. uniform float uSize1;
  45. uniform float uSize2;
  46. uniform float opacity1;
  47. uniform float opacity2;
  48. uniform vec3 uColor;
  49. uniform float uDistance;
  50. float getGrid(float size) {
  51. vec2 r = worldPosition.xy / size;
  52. vec2 grid = abs(fract(r - 0.5) - 0.5) / fwidth(r);
  53. float line = min(grid.x, grid.y);
  54. return 1.0 - min(line, 1.0);
  55. }
  56. //为何侧面看不到线,因为mesh的正侧面都看不到?
  57. void main() {
  58. float d = 1.0 - min(distance(cameraPosition.xy, worldPosition.xy) / uDistance, 1.0);
  59. float g1 = getGrid(uSize1);
  60. float g2 = getGrid(uSize2);
  61. gl_FragColor = vec4(uColor.rgb, mix(g2, g1, g1) * pow(d, 3.0));
  62. //gl_FragColor.a = mix(0.5 * gl_FragColor.a, gl_FragColor.a, g2);
  63. gl_FragColor.a = mix(opacity1 * gl_FragColor.a, opacity2 * gl_FragColor.a, g2);
  64. if ( gl_FragColor.a <= 0.0 ) discard;
  65. }
  66. `,
  67. extensions: {
  68. derivatives: true
  69. }
  70. })
  71. super(geometry, material)
  72. this.frustumCulled = false;
  73. }
  74. };