Flutter 小技巧之 Shader 实现酷炫的粒子动画

在之前的《不一样的思路实现炫酷 3D 翻页折叠动画》我们其实介绍过:如何使用 Shader 去实现一个 3D 的翻页效果,具体就是使用 Flutter 在 3.7 开始提供 Fragment Shader API ,因为每个像素都会过 Fragment Shader ,所以我们可以通过写一个 Fragment Shader 的 glsl 文件来处理图片的像素效果,例如下图这样的粒子化效果:

Flutter 小技巧之 Shader 实现酷炫的粒子动画 - 图1

这个效果来自于 thanos_snap_effect ,它巧妙地采用了多种组合方式实现了 UI 的粒子化效果:

  • 对当前控件进行截图
  • 通过 OverlayPortal 生成一个局部图层
  • 使用 shader 在局部图层对截图进行粒子画动画

Flutter 小技巧之 Shader 实现酷炫的粒子动画 - 图2

截图和 OverlayPortal 都是 Flutter 在 Dart 层面的 API 支持,而粒子化效果就确确实实需要用到 Shader 代码的实现,至于为什么需要用到 Shader,理由还是之前发过的性能对比:

image-20241107173423840

另外 Flutter 默认对图片的 API 支持能力本来就比较弱

简单来说,Flutter 里加载和启用一个 Shader ,只需要:

  • 通过 ui.FragmentProgram.fromAsset 加载 glsl 文件
  • 给 Shader 设置参数,参数是通过定义的顺序(0、1、2····)去设置,另外还可以通过同样方式,通过 setImageSampler 设置图片
  • 通过 canvas 绘制 Shader
  1. final ui.FragmentProgram program = _shaderCache[widget.shaderAsset] ??
  2. await ui.FragmentProgram.fromAsset(widget.shaderAsset);
  3. final shader = program.fragmentShader();
  4. ·····
  5. shader.setFloat(0, size.width);
  6. shader.setFloat(1, size.height);
  7. shader.setFloat(2, currentTime.inMilliseconds.toDouble() / 1000.0);
  8. shader.setImageSampler(0, snapshotInfo.image);
  9. final Paint paint = Paint()..shader = shader;
  10. canvas.drawRect(Offset.zero & size, paint);

参数的对应是按照顺序来决定,大概理解就是,vec2 就是两个 float 类型的值保存在了一起的意思,所以先声明的 vec2 resolution 就占据了索引 0 和 1 ,如下图所示,此时的 vec2vec3 分了就占据了 0-1 和 2-4 的索引:

image-20241107174128030

详细 Flutter Shader 基础教程,可见之前的 《Flutter 小技巧之不一样的思路实现炫酷 3D 翻页折叠动画》 或者张风捷特烈大佬的Flutter & GLSL系列: https://juejin.cn/post/7295948894328029193

接下来我们主要看粒子动画的完整代码,可以看到抛开注释之外,其实代码并不复杂,这也是因为对于 Fragment Shader 而言,每个像素都需要经过这段代码处理,所以在处理像素效果上天然就要比在 Dart 利索:

  1. #version 460 core
  2. #include<flutter/runtime_effect.glsl>
  3. #define min_movement_angle -2.2
  4. #define max_movement_angle -0.76
  5. #define movement_angles_count 10
  6. #define movement_angle_step (max_movement_angle - min_movement_angle) / movement_angles_count
  7. #define pi 3.14159265359
  8. // Current animation value, from 0.0 to 1.0.
  9. uniform float animationValue;
  10. uniform float particleLifetime;
  11. uniform float fadeOutDuration;
  12. uniform float particlesInRow;
  13. uniform float particlesInColumn;
  14. uniform float particleSpeed;
  15. uniform vec2 uSize;
  16. uniform sampler2D uImageTexture;
  17. out vec4 fragColor;
  18. float delayFromParticleCenterPos(float x)
  19. {
  20. return (1. - particleLifetime)*x;
  21. }
  22. float delayFromColumnIndex(int i)
  23. {
  24. return (1. - particleLifetime) * (i / (particlesInRow));
  25. }
  26. float randomAngle(int i)
  27. {
  28. float randomValue = fract(sin(float(i) * 12.9898 + 78.233) * 43758.5453);
  29. return min_movement_angle + floor(randomValue * movement_angles_count) * movement_angle_step;
  30. }
  31. int calculateInitialParticleIndex(vec2 point, float angle, float animationValue, float particleWidth, float particleHeight)
  32. {
  33. // x0 value is calculated from the following equation:
  34. // Given:
  35. // x = x0 + t * cos(angle) * particle_speed
  36. // t = animationValue - delay
  37. // delay = (1 - particle_lifetime) * x0
  38. // Getting the x0 from the equation:
  39. // t = animationValue - (1 - particle_lifetime) * x0
  40. // x = x0 + (animationValue - (1 - particle_lifetime) * x0) * cos(angle) * particle_speed
  41. // x = x0 + animationValue * cos(angle) * particle_speed - (1 - particle_lifetime) * x0 * cos(angle) * particle_speed
  42. // x = x0 - (1 - particle_lifetime) * x0 * cos(angle) * particle_speed + animationValue * cos(angle) * particle_speed
  43. // x = x0 * (1 - (1 - particle_lifetime) * cos(angle) * particle_speed) + animationValue * cos(angle) * particle_speed
  44. // x - animationValue * cos(angle) * particle_speed = x0 * (1 - (1 - particle_lifetime) * cos(angle) * particle_speed)
  45. // x0 = (x - animationValue * cos(angle) * particle_speed) / (1 - (1 - particle_lifetime) * cos(angle) * particle_speed)
  46. float x0 = (point.x - animationValue * cos(angle) * particleSpeed) / (1. - (1. - particleLifetime) * cos(angle) * particleSpeed);
  47. float delay = delayFromParticleCenterPos(x0);
  48. float y0 = point.y - (animationValue - delay) * sin(angle) * particleSpeed;
  49. // If particle is not yet moved, animationValue is less than delay, and particle moves to an opposite direction so we should calculate a particle index from the original point.
  50. // If the particle is supposed to move to the left, but it moves to the right (because of the reason above), return the original point particle index.
  51. if (angle <= - pi / 2 && point.x >= x0)
  52. {
  53. return (int(point.x / particleWidth) + int(point.y / particleHeight) * int(1 / particleWidth));
  54. }
  55. // If the particle is supposed to move to the right, but it moves to the left (because of the reason above), return the original point particle index.
  56. if (angle >= - pi / 2 && point.x < x0)
  57. {
  58. return (int(point.x / particleWidth) + int(point.y / particleHeight) * int(1 / particleWidth));
  59. }
  60. return int(x0 / particleWidth) + int(y0 / particleHeight) * int(1 / particleWidth);
  61. }
  62. void main()
  63. {
  64. vec2 uv=FlutterFragCoord().xy / uSize.xy;
  65. float particleWidth = 1.0 / particlesInRow;
  66. float particleHeight = 1.0 / particlesInColumn;
  67. float particlesCount = (1 / particleWidth) * (1 / particleHeight);
  68. for (float searchMovementAngle = min_movement_angle; searchMovementAngle <= max_movement_angle; searchMovementAngle += movement_angle_step)
  69. {
  70. int i = calculateInitialParticleIndex(uv, searchMovementAngle, animationValue, particleWidth, particleHeight);
  71. if (i < 0 || i >= particlesCount)
  72. {
  73. continue;
  74. }
  75. float angle = randomAngle(i);
  76. vec2 particleCenterPos = vec2(mod(float(i), 1 / particleWidth) * particleWidth + particleWidth / 2, int(float(i) / (1 / particleWidth)) * particleHeight + particleHeight / 2);
  77. float delay = delayFromParticleCenterPos(particleCenterPos.x);
  78. float adjustedTime = max(0.0, animationValue - delay);
  79. vec2 zeroPointPixelPos = vec2(uv.x - adjustedTime * cos(angle) * particleSpeed, uv.y - adjustedTime * sin(angle) * particleSpeed);
  80. if (zeroPointPixelPos.x >= particleCenterPos.x - particleWidth / 2 && zeroPointPixelPos.x <= particleCenterPos.x + particleWidth / 2 &&
  81. zeroPointPixelPos.y >= particleCenterPos.y - particleHeight / 2 && zeroPointPixelPos.y <= particleCenterPos.y + particleHeight / 2)
  82. {
  83. vec4 zeroPointPixelColor = texture(uImageTexture, zeroPointPixelPos);
  84. float alpha = zeroPointPixelColor.a;
  85. float fadeOutLivetime = max(0.0, adjustedTime - (particleLifetime - fadeOutDuration));
  86. fragColor = zeroPointPixelColor * (1.0 - fadeOutLivetime / fadeOutDuration);
  87. return;
  88. }
  89. }
  90. fragColor = vec4(0.0, 0.0, 0.0, 0.0);
  91. }

这里简单介绍这段代码的一些实现逻辑,首先就是角度,这部分代码直接定义了粒子移动的方向范围,可以移动的角度在 -2.2-0.76 之间:

  1. #define min_movement_angle -2.2
  2. #define max_movement_angle -0.76
  3. #define movement_angles_count 10
  4. #define movement_angle_step (max_movement_angle - min_movement_angle) / movement_angles_count
  5. #define pi 3.14159265359

如果用 Dart 的 Canvas 来表示,可以看到大概就是如下图所示这样的角度,然后在这个范围内有 10 个方向可以“随机”选择:

  1. class AnglePainter extends CustomPainter {
  2. @override
  3. void paint(Canvas canvas, Size size) {
  4. final paint = Paint()
  5. ..color = Colors.black
  6. ..strokeWidth = 4;
  7. final center = Offset(size.width / 2, size.height / 2);
  8. final radius = 80.0;
  9. print("##### ${-2.2 / pi * 180}");
  10. final p1 = center;
  11. final p2 = Offset(center.dx + radius, center.dy);
  12. canvas.drawLine(p1, p2, paint);
  13. ///final angle = -126 * pi / 180; // Convert degrees to radians
  14. final angle = -2.2;
  15. final p3 = Offset(
  16. center.dx + radius * cos(angle), center.dy + radius * sin(angle));
  17. canvas.drawLine(p1, p3, paint);
  18. }
  19. @override
  20. bool shouldRepaint(covariant CustomPainter oldDelegate) {
  21. return false;
  22. }
  23. }

Flutter 小技巧之 Shader 实现酷炫的粒子动画 - 图5

接下来 main 里面的代码,这部分代码主要就是:

  • 归一化坐标为 0-1
  • 根据行列数计算出每一「块粒子」该有的大小
  • 计算出粒子的总数
  • 在可移动角度里寻找“适合”移动的方向
  1. vec2 uv=FlutterFragCoord().xy / uSize.xy;
  2. float particleWidth = 1.0 / particlesInRow;
  3. float particleHeight = 1.0 / particlesInColumn;
  4. float particlesCount = (1 / particleWidth) * (1 / particleHeight);
  5. for (float searchMovementAngle = min_movement_angle; searchMovementAngle <= max_movement_angle; searchMovementAngle += movement_angle_step)
  6. {

可以看到,glsl 里的代码很多都是浮点计算,因为浮点计算其实是 GPU 的强项

calculateInitialParticleIndex 这个函数主要是将当前像素归集到某个「粒子块」里,因为每个「粒子块」都是有具体大小,所以一个「粒子块」都是由「一批像素」组成,也就是需要根据当前「粒子块」的 index 去确定像素属于哪一个「粒子块」。

  1. int i = calculateInitialParticleIndex(uv, searchMovementAngle, animationValue, particleWidth, particleHeight);
  2. int calculateInitialParticleIndex(vec2 point, float angle, float animationValue, float particleWidth, float particleHeight)
  3. {
  4. // x0 value is calculated from the following equation:
  5. // Given:
  6. // x = x0 + t * cos(angle) * particle_speed
  7. // t = animationValue - delay
  8. // delay = (1 - particle_lifetime) * x0
  9. // Getting the x0 from the equation:
  10. // t = animationValue - (1 - particle_lifetime) * x0
  11. // x = x0 + (animationValue - (1 - particle_lifetime) * x0) * cos(angle) * particle_speed
  12. // x = x0 + animationValue * cos(angle) * particle_speed - (1 - particle_lifetime) * x0 * cos(angle) * particle_speed
  13. // x = x0 - (1 - particle_lifetime) * x0 * cos(angle) * particle_speed + animationValue * cos(angle) * particle_speed
  14. // x = x0 * (1 - (1 - particle_lifetime) * cos(angle) * particle_speed) + animationValue * cos(angle) * particle_speed
  15. // x - animationValue * cos(angle) * particle_speed = x0 * (1 - (1 - particle_lifetime) * cos(angle) * particle_speed)
  16. // x0 = (x - animationValue * cos(angle) * particle_speed) / (1 - (1 - particle_lifetime) * cos(angle) * particle_speed)
  17. float x0 = (point.x - animationValue * cos(angle) * particleSpeed) / (1. - (1. - particleLifetime) * cos(angle) * particleSpeed);
  18. float delay = delayFromParticleCenterPos(x0);
  19. float y0 = point.y - (animationValue - delay) * sin(angle) * particleSpeed;
  20. .
  21. if (angle <= - pi / 2 && point.x >= x0)
  22. {
  23. return (int(point.x / particleWidth) + int(point.y / particleHeight) * int(1 / particleWidth));
  24. }
  25. if (angle >= - pi / 2 && point.x < x0)
  26. {
  27. return (int(point.x / particleWidth) + int(point.y / particleHeight) * int(1 / particleWidth));
  28. }
  29. return int(x0 / particleWidth) + int(y0 / particleHeight) * int(1 / particleWidth);
  30. }

另外这里是根据粒子移动的过的路径去反推出它原本的位置,从而再确定它原本属于哪个粒子块,因为在后续移动的时候,像素是:

  • vec2 zeroPointPixelPos = vec2(uv.x - adjustedTime cos(angle) particleSpeed
  • float adjustedTime = max(0.0, animationValue - delay);
  • float delay = delayFromParticleCenterPos(particleCenterPos.x);
  • delayFromParticleCenterPos = (1. - particleLifetime)*x;

所以进来的移动后的粒子像素,可以这个移动公式,如注释那样,反推出它原本的 x 和 y 位置,从而确定它最初的「粒子块 index」 。

另外这里做了 (angle <= - pi / 2 && point.x >= x0)(angle >= - pi / 2 && point.x < x0) 的判断,也就是此时这些条件下,这些粒子本身属于并没有移动过,只需要按照原本计算其归属 index 就可以了。

Flutter 小技巧之 Shader 实现酷炫的粒子动画 - 图6

如果没有上面两个 if 判断,那么在动画过程中就会是这样的效果,还没有移动的像素因为「归属块」不对,出现在了错误的位置:

Flutter 小技巧之 Shader 实现酷炫的粒子动画 - 图7

剩下的就是正常测粒子移动还有透明化的效果:

  • randomAngle 其实就是一个伪随机实现,他主要和「粒子块」归属的 index 有关系,同一个块(i)的移动角度是一致的
  • particleCenterPos 是计算出粒子块的中心位置
  • delayFromParticleCenterPos 其实就是根据粒子的生命周期时间 particleLifetime 结合位置去计算一个延迟,简单说就是根据 animationValue 的数值,还没有粒子化的像素块不移动
  • zeroPointPixelPos 就是根据角度移动后 x 和 y 的位置
  • 接下来就是确定移动后的像素位于粒子块
  • 如果不在粒子块内的,就透明处理 vec4(0.0, 0.0, 0.0, 0.0);
  1. float angle = randomAngle(i);
  2. vec2 particleCenterPos = vec2(mod(float(i), 1 / particleWidth) * particleWidth + particleWidth / 2, int(float(i) / (1 / particleWidth)) * particleHeight + particleHeight / 2);
  3. float delay = delayFromParticleCenterPos(particleCenterPos.x);
  4. float adjustedTime = max(0.0, animationValue - delay);
  5. vec2 zeroPointPixelPos = vec2(uv.x - adjustedTime * cos(angle) * particleSpeed, uv.y - adjustedTime * sin(angle) * particleSpeed);
  6. if (zeroPointPixelPos.x >= particleCenterPos.x - particleWidth / 2 && zeroPointPixelPos.x <= particleCenterPos.x + particleWidth / 2 &&
  7. zeroPointPixelPos.y >= particleCenterPos.y - particleHeight / 2 && zeroPointPixelPos.y <= particleCenterPos.y + particleHeight / 2)
  8. {
  9. vec4 zeroPointPixelColor = texture(uImageTexture, zeroPointPixelPos);
  10. float alpha = zeroPointPixelColor.a;
  11. float fadeOutLivetime = max(0.0, adjustedTime - (particleLifetime - fadeOutDuration));
  12. fragColor = zeroPointPixelColor * (1.0 - fadeOutLivetime / fadeOutDuration);
  13. return;
  14. }
  15. fragColor = vec4(0.0, 0.0, 0.0, 0.0);

可以看到粒子化后的效果其实挺酷炫的,最终效果是对指定的 UI 进行粒子化动画,并且通过 OverlayPortal 做到页面内图层区分渲染,整体性能比起在 Dart 实现效果确实优秀不少:

Flutter 小技巧之 Shader 实现酷炫的粒子动画 - 图8

其实很多已有的 glsl 效果都可以移植到 Flutter ,例如 shadertoy 上的各种效果,举个例子,shadertoy 上经典的 water shader 就可以通过修改移植到 Flutter :

  1. uniform vec2 iResolution;
  2. uniform float iTime;
  3. uniform float SEA_HEIGHT;
  4. vec2 iMouse = vec2(0);
  5. out vec4 fragColor;
  6. // Ported from https://www.shadertoy.com/view/Ms2SD1 to Flutter
  7. const int NUM_STEPS = 8;
  8. const float PI = 3.141592;
  9. const float EPSILON = 1e-3;
  10. #define EPSILON_NRM (0.1 / iResolution.x)
  11. #define AA
  12. // sea
  13. const int ITER_GEOMETRY = 3;
  14. const int ITER_FRAGMENT = 5;
  15. const float SEA_CHOPPY = 4.0;
  16. const float SEA_SPEED = 0.8;
  17. const float SEA_FREQ = 0.16;
  18. const vec3 SEA_BASE = vec3(0.0,0.09,0.18);
  19. const vec3 SEA_WATER_COLOR = vec3(0.8,0.9,0.6)*0.6;
  20. #define SEA_TIME (1.0 + iTime * SEA_SPEED)
  21. const mat2 octave_m = mat2(1.6,1.2,-1.2,1.6);
  22. // math
  23. mat3 fromEuler(vec3 ang) {
  24. vec2 a1 = vec2(sin(ang.x),cos(ang.x));
  25. vec2 a2 = vec2(sin(ang.y),cos(ang.y));
  26. vec2 a3 = vec2(sin(ang.z),cos(ang.z));
  27. mat3 m;
  28. m[0] = vec3(a1.y*a3.y+a1.x*a2.x*a3.x,a1.y*a2.x*a3.x+a3.y*a1.x,-a2.y*a3.x);
  29. m[1] = vec3(-a2.y*a1.x,a1.y*a2.y,a2.x);
  30. m[2] = vec3(a3.y*a1.x*a2.x+a1.y*a3.x,a1.x*a3.x-a1.y*a3.y*a2.x,a2.y*a3.y);
  31. return m;
  32. }
  33. float hash( vec2 p ) {
  34. float h = dot(p,vec2(127.1,311.7));
  35. return fract(sin(h)*43758.5453123);
  36. }
  37. float noise( in vec2 p ) {
  38. vec2 i = floor( p );
  39. vec2 f = fract( p );
  40. vec2 u = f*f*(3.0-2.0*f);
  41. return -1.0+2.0*mix( mix( hash( i + vec2(0.0,0.0) ),
  42. hash( i + vec2(1.0,0.0) ), u.x),
  43. mix( hash( i + vec2(0.0,1.0) ),
  44. hash( i + vec2(1.0,1.0) ), u.x), u.y);
  45. }
  46. // lighting
  47. float diffuse(vec3 n,vec3 l,float p) {
  48. return pow(dot(n,l) * 0.4 + 0.6,p);
  49. }
  50. float specular(vec3 n,vec3 l,vec3 e,float s) {
  51. float nrm = (s + 8.0) / (PI * 8.0);
  52. return pow(max(dot(reflect(e,n),l),0.0),s) * nrm;
  53. }
  54. // sky
  55. vec3 getSkyColor(vec3 e) {
  56. e.y = (max(e.y,0.0)*0.8+0.2)*0.8;
  57. return vec3(pow(1.0-e.y,2.0), 1.0-e.y, 0.6+(1.0-e.y)*0.4) * 1.1;
  58. }
  59. // sea
  60. float sea_octave(vec2 uv, float choppy) {
  61. uv += noise(uv);
  62. vec2 wv = 1.0-abs(sin(uv));
  63. vec2 swv = abs(cos(uv));
  64. wv = mix(wv,swv,wv);
  65. return pow(1.0-pow(wv.x * wv.y,0.65),choppy);
  66. }
  67. float map(vec3 p) {
  68. float freq = SEA_FREQ;
  69. float amp = SEA_HEIGHT;
  70. float choppy = SEA_CHOPPY;
  71. vec2 uv = p.xz; uv.x *= 0.75;
  72. float d, h = 0.0;
  73. for(int i = 0; i < ITER_GEOMETRY; i++) {
  74. d = sea_octave((uv+SEA_TIME)*freq,choppy);
  75. d += sea_octave((uv-SEA_TIME)*freq,choppy);
  76. h += d * amp;
  77. uv *= octave_m; freq *= 1.9; amp *= 0.22;
  78. choppy = mix(choppy,1.0,0.2);
  79. }
  80. return p.y - h;
  81. }
  82. float map_detailed(vec3 p) {
  83. float freq = SEA_FREQ;
  84. float amp = SEA_HEIGHT;
  85. float choppy = SEA_CHOPPY;
  86. vec2 uv = p.xz; uv.x *= 0.75;
  87. float d, h = 0.0;
  88. for(int i = 0; i < ITER_FRAGMENT; i++) {
  89. d = sea_octave((uv+SEA_TIME)*freq,choppy);
  90. d += sea_octave((uv-SEA_TIME)*freq,choppy);
  91. h += d * amp;
  92. uv *= octave_m; freq *= 1.9; amp *= 0.22;
  93. choppy = mix(choppy,1.0,0.2);
  94. }
  95. return p.y - h;
  96. }
  97. vec3 getSeaColor(vec3 p, vec3 n, vec3 l, vec3 eye, vec3 dist) {
  98. float fresnel = clamp(1.0 - dot(n,-eye), 0.0, 1.0);
  99. fresnel = pow(fresnel,3.0) * 0.5;
  100. vec3 reflected = getSkyColor(reflect(eye,n));
  101. vec3 refracted = SEA_BASE + diffuse(n,l,80.0) * SEA_WATER_COLOR * 0.12;
  102. vec3 color = mix(refracted,reflected,fresnel);
  103. float atten = max(1.0 - dot(dist,dist) * 0.001, 0.0);
  104. color += SEA_WATER_COLOR * (p.y - SEA_HEIGHT) * 0.18 * atten;
  105. color += vec3(specular(n,l,eye,60.0));
  106. return color;
  107. }
  108. // tracing
  109. vec3 getNormal(vec3 p, float eps) {
  110. vec3 n;
  111. n.y = map_detailed(p);
  112. n.x = map_detailed(vec3(p.x+eps,p.y,p.z)) - n.y;
  113. n.z = map_detailed(vec3(p.x,p.y,p.z+eps)) - n.y;
  114. n.y = eps;
  115. return normalize(n);
  116. }
  117. float heightMapTracing(vec3 ori, vec3 dir, out vec3 p) {
  118. float tm = 0.0;
  119. float tx = 1000.0;
  120. float hx = map(ori + dir * tx);
  121. if(hx > 0.0) {
  122. p = ori + dir * tx;
  123. return tx;
  124. }
  125. float hm = map(ori + dir * tm);
  126. float tmid = 0.0;
  127. for(int i = 0; i < NUM_STEPS; i++) {
  128. tmid = mix(tm,tx, hm/(hm-hx));
  129. p = ori + dir * tmid;
  130. float hmid = map(p);
  131. if(hmid < 0.0) {
  132. tx = tmid;
  133. hx = hmid;
  134. } else {
  135. tm = tmid;
  136. hm = hmid;
  137. }
  138. }
  139. return tmid;
  140. }
  141. vec3 getPixel(in vec2 coord, float time) {
  142. vec2 uv = coord / iResolution.xy;
  143. uv = uv * 2.0 - 1.0;
  144. uv.x *= iResolution.x / iResolution.y;
  145. // ray
  146. vec3 ang = vec3(sin(time*3.0)*0.1,sin(time)*0.2+0.3,time);
  147. vec3 ori = vec3(0.0,3.5,time*5.0);
  148. vec3 dir = normalize(vec3(uv.xy,-2.0)); dir.z += length(uv) * 0.14;
  149. dir = normalize(dir) * fromEuler(ang);
  150. // tracing
  151. vec3 p;
  152. heightMapTracing(ori,dir,p);
  153. vec3 dist = p - ori;
  154. vec3 n = getNormal(p, dot(dist,dist) * EPSILON_NRM);
  155. vec3 light = normalize(vec3(0.0,1.0,0.8));
  156. // color
  157. return mix(
  158. getSkyColor(dir),
  159. getSeaColor(p,n,light,dir,dist),
  160. pow(smoothstep(0.0,-0.02,dir.y),0.2));
  161. }
  162. void main() {
  163. float time = iTime * 0.3 + iMouse.x*0.01;
  164. vec3 color = getPixel(gl_FragCoord.xy, time);
  165. // post
  166. fragColor = vec4(pow(color,vec3(0.65)), 1.0);
  167. }

Flutter 小技巧之 Shader 实现酷炫的粒子动画 - 图9

还有在之前介绍过用纯 Dart 实现了《霓虹灯文本的「故障」效果的实现》 如下所示是纯 dart 代码的实现:

Flutter 小技巧之 Shader 实现酷炫的粒子动画 - 图10

  1. uniform vec2 iResolution;
  2. uniform float iTime;
  3. uniform sampler2D iChannel0;
  4. out vec4 fragColor;
  5. vec3 iMouse = vec3(0.0, 0.0, 0.0);
  6. // change these values to 0.0 to turn off individual effects
  7. float vertJerkOpt = 1.0;
  8. float vertMovementOpt = 1.0;
  9. float bottomStaticOpt = 1.0;
  10. float scalinesOpt = 1.0;
  11. float rgbOffsetOpt = 1.0;
  12. float horzFuzzOpt = 1.0;
  13. // Noise generation functions borrowed from:
  14. // https://github.com/ashima/webgl-noise/blob/master/src/noise2D.glsl
  15. vec3 mod289(vec3 x) {
  16. return x - floor(x * (1.0 / 289.0)) * 289.0;
  17. }
  18. vec2 mod289(vec2 x) {
  19. return x - floor(x * (1.0 / 289.0)) * 289.0;
  20. }
  21. vec3 permute(vec3 x) {
  22. return mod289(((x*34.0)+1.0)*x);
  23. }
  24. float snoise(vec2 v)
  25. {
  26. const vec4 C = vec4(0.211324865405187, // (3.0-sqrt(3.0))/6.0
  27. 0.366025403784439, // 0.5*(sqrt(3.0)-1.0)
  28. -0.577350269189626, // -1.0 + 2.0 * C.x
  29. 0.024390243902439); // 1.0 / 41.0
  30. // First corner
  31. vec2 i = floor(v + dot(v, C.yy) );
  32. vec2 x0 = v - i + dot(i, C.xx);
  33. // Other corners
  34. vec2 i1;
  35. //i1.x = step( x0.y, x0.x ); // x0.x > x0.y ? 1.0 : 0.0
  36. //i1.y = 1.0 - i1.x;
  37. i1 = (x0.x > x0.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0);
  38. // x0 = x0 - 0.0 + 0.0 * C.xx ;
  39. // x1 = x0 - i1 + 1.0 * C.xx ;
  40. // x2 = x0 - 1.0 + 2.0 * C.xx ;
  41. vec4 x12 = x0.xyxy + C.xxzz;
  42. x12.xy -= i1;
  43. // Permutations
  44. i = mod289(i); // Avoid truncation effects in permutation
  45. vec3 p = permute( permute( i.y + vec3(0.0, i1.y, 1.0 ))
  46. + i.x + vec3(0.0, i1.x, 1.0 ));
  47. vec3 m = max(0.5 - vec3(dot(x0,x0), dot(x12.xy,x12.xy), dot(x12.zw,x12.zw)), 0.0);
  48. m = m*m ;
  49. m = m*m ;
  50. // Gradients: 41 points uniformly over a line, mapped onto a diamond.
  51. // The ring size 17*17 = 289 is close to a multiple of 41 (41*7 = 287)
  52. vec3 x = 2.0 * fract(p * C.www) - 1.0;
  53. vec3 h = abs(x) - 0.5;
  54. vec3 ox = floor(x + 0.5);
  55. vec3 a0 = x - ox;
  56. // Normalise gradients implicitly by scaling m
  57. // Approximation of: m *= inversesqrt( a0*a0 + h*h );
  58. m *= 1.79284291400159 - 0.85373472095314 * ( a0*a0 + h*h );
  59. // Compute final noise value at P
  60. vec3 g;
  61. g.x = a0.x * x0.x + h.x * x0.y;
  62. g.yz = a0.yz * x12.xz + h.yz * x12.yw;
  63. return 130.0 * dot(m, g);
  64. }
  65. float staticV(vec2 uv) {
  66. float staticHeight = snoise(vec2(9.0,iTime*1.2+3.0))*0.3+5.0;
  67. float staticAmount = snoise(vec2(1.0,iTime*1.2-6.0))*0.1+0.3;
  68. float staticStrength = snoise(vec2(-9.75,iTime*0.6-3.0))*2.0+2.0;
  69. return (1.0-step(snoise(vec2(5.0*pow(iTime,2.0)+pow(uv.x*7.0,1.2),pow((mod(iTime,100.0)+100.0)*uv.y*0.3+3.0,staticHeight))),staticAmount))*staticStrength;
  70. }
  71. void main()
  72. {
  73. vec2 uv = gl_FragCoord.xy/iResolution.xy;
  74. float jerkOffset = (1.0-step(snoise(vec2(iTime*1.3,5.0)),0.8))*0.05;
  75. float fuzzOffset = snoise(vec2(iTime*15.0,uv.y*80.0))*0.003;
  76. float largeFuzzOffset = snoise(vec2(iTime*1.0,uv.y*25.0))*0.004;
  77. float vertMovementOn = (1.0-step(snoise(vec2(iTime*0.2,8.0)),0.4))*vertMovementOpt;
  78. float vertJerk = (1.0-step(snoise(vec2(iTime*1.5,5.0)),0.6))*vertJerkOpt;
  79. float vertJerk2 = (1.0-step(snoise(vec2(iTime*5.5,5.0)),0.2))*vertJerkOpt;
  80. float yOffset = abs(sin(iTime)*4.0)*vertMovementOn+vertJerk*vertJerk2*0.3;
  81. float y = mod(uv.y+yOffset,1.0);
  82. float xOffset = (fuzzOffset + largeFuzzOffset) * horzFuzzOpt;
  83. float staticVal = 0.0;
  84. for (float y = -1.0; y <= 1.0; y += 1.0) {
  85. float maxDist = 5.0/200.0;
  86. float dist = y/200.0;
  87. staticVal += staticV(vec2(uv.x,uv.y+dist))*(maxDist-abs(dist))*1.5;
  88. }
  89. staticVal *= bottomStaticOpt;
  90. float red = texture( iChannel0, vec2(uv.x + xOffset -0.01*rgbOffsetOpt,y)).r+staticVal;
  91. float green = texture( iChannel0, vec2(uv.x + xOffset, y)).g+staticVal;
  92. float blue = texture( iChannel0, vec2(uv.x + xOffset +0.01*rgbOffsetOpt,y)).b+staticVal;
  93. vec3 color = vec3(red,green,blue);
  94. float scanline = sin(uv.y*800.0)*0.04*scalinesOpt;
  95. color -= scanline;
  96. fragColor = vec4(color,1.0);
  97. }

其实可以移植另外的 gl 实现,修改为 webgl-noise 上的 glsl 效果,如下图所示,可以看到修改后的文本有了不一样的「故障」效果:

Flutter 小技巧之 Shader 实现酷炫的粒子动画 - 图11

最后,现在通过 flutter_shaders 就可以在 Flutter 很方便的接入各种 glsl 代码效果,只需要配置对应的属性,控制变量参数即可,当然 thanos_snap_effect 粒子效果的有趣之处,在于他结合了截图和 OverlayPortal 封装出一个更有意思的实现,所以可以看出来,其实 shader 在 Flutter 上还是有着需要玩法,这样看,更期待后续 Flutter GPU 的落地了。