SnowEffect.js 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. (function () {
  2. function SnowEffect(viewer, options) {
  3. if (!viewer) throw new Error("viewer is undefined")
  4. this.viewer = viewer;
  5. this.speed = Cesium.defaultValue(options.speed, 10)
  6. this.enabled = Cesium.defaultValue(options.enabled, true)
  7. this.init();
  8. }
  9. SnowEffect.prototype.init = function () {
  10. this.snowStage = new Cesium.PostProcessStage({
  11. name: 'czm_snow',
  12. fragmentShader: this.FragmentShader_Snow(),
  13. uniforms: {
  14. speed: () => { return this.speed; }
  15. }
  16. });
  17. this.snowStage.enabled = this.enabled
  18. this.viewer.scene.postProcessStages.add(this.snowStage)
  19. }
  20. //定义下雪场景 着色器
  21. SnowEffect.prototype.FragmentShader_Snow = function () {
  22. return `uniform sampler2D colorTexture; //输入的场景渲染照片
  23. varying vec2 v_textureCoordinates;
  24. uniform float speed;
  25. float snow(vec2 uv,float scale){
  26. float time = czm_frameNumber * speed / 1000.0 ;
  27. float w=smoothstep(1.0,0.0,-uv.y*(scale/10.0));
  28. if(w<0.1)return 0.0;
  29. uv+=time/scale;
  30. uv.y+=time*2.0/scale;
  31. uv.x+=sin(uv.y+time*0.5)/scale;
  32. uv*=scale;
  33. vec2 s=floor(uv),f=fract(uv),p;
  34. float k=3.0,d;
  35. p=0.5+0.35*sin(11.0*fract(sin((s+p+scale)*mat2(7,3,6,5))*5.0))-f;
  36. d=length(p);k=min(d,k);
  37. k=smoothstep(0.0,k,sin(f.x+f.y)*0.01);
  38. return k*w;
  39. }
  40. void main(void){
  41. vec2 resolution = czm_viewport.zw;
  42. vec2 uv=(gl_FragCoord.xy*2.-resolution.xy)/min(resolution.x,resolution.y);
  43. float c = 0.0;
  44. c+=snow(uv,15.);
  45. c+=snow(uv,10.);
  46. c+=snow(uv,9.);
  47. c+=snow(uv,8.);
  48. c+=snow(uv,7.);
  49. c+=snow(uv,6.);
  50. c+=snow(uv,5.);
  51. c+=snow(uv,4.);
  52. vec3 finalColor=(vec3(c)); //屏幕上雪的颜色
  53. gl_FragColor = mix(texture2D(colorTexture, v_textureCoordinates), vec4(finalColor,1.0), 0.5); //将雪和三维场景融合
  54. }
  55. `
  56. }
  57. SnowEffect.prototype.show = function (visible) {
  58. this.snowStage.enabled = visible;
  59. }
  60. SnowEffect.prototype.destroy = function (visible) {
  61. if (!this.viewer || !this.snowStage) return;
  62. this.viewer.scene.postProcessStages.remove(this.snowStage);
  63. this.snowStage.destroy();
  64. delete this.speed
  65. }
  66. Cesium.SnowEffect = SnowEffect
  67. })(Cesium)