最近想研究一下shader的模糊效果,看了论坛里面关于卷积的相关问题,感觉此方法还是很不错,但是本次的shader也存在效率问题,就是模糊半径设置的越大就会越消耗性能。
高斯模糊完整代码:
// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
CCEffect %{
techniques:
- passes:
- vert: vs
frag: fs
blendState:
targets:
- blend: true
rasterizerState:
cullMode: none
properties:
texture: { value: white }
alphaThreshold: { value: 0.5 }
size: {value: [500.0,500.0],editor: {tooltip: "节点尺寸"}}
}%
CCProgram vs %{
precision highp float;
#include <cc-global>
#include <cc-local>
in vec3 a_position;
in vec4 a_color;
out vec4 v_color;
#if USE_TEXTURE
in vec2 a_uv0;
out vec2 v_uv0;
#endif
void main () {
vec4 pos = vec4(a_position, 1);
#if CC_USE_MODEL
pos = cc_matViewProj * cc_matWorld * pos;
#else
pos = cc_matViewProj * pos;
#endif
#if USE_TEXTURE
v_uv0 = a_uv0;
#endif
v_color = a_color;
gl_Position = pos;
}
}%
CCProgram fs %{
precision highp float;
#include <alpha-test>
#include <texture>
uniform ARGS {
vec2 size;
};
in vec4 v_color;
#if USE_TEXTURE
in vec2 v_uv0;
uniform sampler2D texture;
#endif
const float rd = 15.0;
vec4 getBlurColor(vec2 pos) {
vec4 color = vec4(0.);
float sum = 0.;
for(float r = -rd; r <= rd; r++) {
for(float c = -rd; c <= rd; c++) {
vec2 target = pos + vec2(r / size.x,c / size.y);
/** 距离中心点越远的像素点权重越小 类似函数y = a * (x - b) b一直变化并且范围为0-20 */
float weight = (rd - abs(r)) * (rd - abs(c));
color += texture2D(texture,target) * weight;
sum += weight;
}
}
color /= sum;
return color;
}
void main () {
vec4 o = vec4(1, 1, 1, 1);
#if USE_TEXTURE
CCTexture(texture, v_uv0, o);
#endif
o *= v_color;
ALPHA_TEST(o);
gl_FragColor = o;
vec4 c = getBlurColor(v_uv0);
c.a = v_color.a;
gl_FragColor = c;
}
}%
rd值越大对性能的消耗就越大,fps就会降到很低,所以这里取了一个15的值,效果还可以,
size是需要计算的像素值,size越小就会变形,size越大就会尽可能的模糊原来的图片,size可以大一点模糊效果更好