Skip to main content

着色器

案例

高斯模糊-适用于3.8.6

effect(注意将材质的"USE_TEXTURE"设为true)

// Eazax-CCC 高斯模糊(3.8.6 改写版)

CCEffect %{
techniques:
- passes:
- vert: sprite-vs:vert
frag: blur2-fs:frag
depthStencilState:
depthTest: false
depthWrite: false
blendState:
targets:
- blend: true
blendSrc: src_alpha
blendDst: one_minus_src_alpha
blendDstAlpha: one_minus_src_alpha
rasterizerState:
cullMode: none
properties:
size: { value: [500.0, 500.0], editor: { tooltip: '纹理/节点像素尺寸' } }
}%


CCProgram sprite-vs %{
precision highp float;
#include <builtin/uniforms/cc-global>
#if USE_LOCAL
#include <builtin/uniforms/cc-local>
#endif
#if SAMPLE_FROM_RT
#include <common/common-define>
#endif

in vec3 a_position;
in vec2 a_texCoord;
in vec4 a_color;

out vec4 color;
out vec2 uv0;

vec4 vert () {
vec4 pos = vec4(a_position, 1.0);

#if USE_LOCAL
pos = cc_matWorld * pos;
#endif

#if USE_PIXEL_ALIGNMENT
pos = cc_matView * pos;
pos.xyz = floor(pos.xyz);
pos = cc_matProj * pos;
#else
pos = cc_matViewProj * pos;
#endif

uv0 = a_texCoord;
#if SAMPLE_FROM_RT
CC_HANDLE_RT_SAMPLE_FLIP(uv0);
#endif
color = a_color;

return pos;
}
}%


CCProgram blur2-fs %{
precision highp float;

#include <builtin/internal/embedded-alpha>
#include <builtin/internal/alpha-test>

in vec4 color; // 顶点色(含 alpha)

// 与项目中其他 effect 一致的纹理采样器定义
#if USE_TEXTURE
in vec2 uv0;
#pragma builtin(local)
layout(set = 2, binding = 11) uniform sampler2D cc_spriteTexture;
#endif

// 属性常量缓冲
uniform Constant {
vec2 size; // 纹理/节点像素尺寸
};

// 模糊半径(编译期常量)。注意:半径过大将极大影响性能
const int RADIUS = 20; // 对应原版 20.0

// 计算加权盒式/近似高斯模糊(权重按距离线性衰减)
vec4 getBlurColor (vec2 pos) {
vec4 accum = vec4(0.0);
float sum = 0.0;
#if USE_TEXTURE
for (int r = -RADIUS; r <= RADIUS; ++r) {
for (int c = -RADIUS; c <= RADIUS; ++c) {
vec2 target = pos + vec2(float(r) / max(size.x, 1.0), float(c) / max(size.y, 1.0));
float wr = float(RADIUS) - abs(float(r));
float wc = float(RADIUS) - abs(float(c));
float w = max(wr, 0.0) * max(wc, 0.0);
accum += CCSampleWithAlphaSeparated(cc_spriteTexture, target) * w;
sum += w;
}
}
if (sum > 0.0) {
accum /= sum;
}
#endif
return accum;
}

vec4 frag () {
vec4 outColor = vec4(1.0);
#if USE_TEXTURE
vec4 blurred = getBlurColor(uv0);
outColor = blurred;
#endif
outColor *= color; // 应用顶点色与透明度
ALPHA_TEST(outColor);
return outColor;
}
}%