1.效果
2.原理
将一张图片分割成n*n个格子,将得到的uv判断出所在的格子,将uv坐标偏移到格子的中间。
3.代码
// 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 }
mosaic_factor: {
value: 10,
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>
in vec4 v_color;
#if USE_TEXTURE
in vec2 v_uv0;
uniform sampler2D texture;
#endif
uniform Constant{
float mosaic_factor;
};
/**
* 得到马赛克的uv坐标
*/
vec2 getMosaicUV(vec2 uv) {
float mosaic = 1.0 / mosaic_factor;
if(mosaic<=0.0){
mosaic = 1.0;
}
//计算新的uv
uv.x = floor(uv.x / mosaic)*mosaic + mosaic *0.5;
uv.y = floor(uv.y / mosaic)*mosaic + mosaic *0.5;
return uv;
}
void main () {
vec4 o = vec4(1, 1, 1, 1);
vec2 mosaic_uv = getMosaicUV(v_uv0);
#if USE_TEXTURE
CCTexture(texture, mosaic_uv, o);
#endif
o *= v_color;
ALPHA_TEST(o);
gl_FragColor = o;
}
}%