第7.3章:可替换内置函数

Cocos Creator提供了丰富的内置函数来处理各种渲染任务,但有时我们需要根据特定需求重写这些函数。本章将深入探讨如何安全地替换内置函数,扩展系统功能,并避免潜在的兼容性问题。

🎯 学习目标

通过本章学习,你将掌握:

  • Cocos Creator内置函数的分类和作用
  • 内置函数的重写机制和安全实践
  • 常用内置函数的自定义实现
  • 函数重写的性能考虑和优化技巧
  • 大型项目中的函数替换管理策略

💡 内置函数概览

Cocos Creator主要内置函数分类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
// 1. 变换矩阵相关
uniform mat4 cc_matWorld; // 世界变换矩阵
uniform mat4 cc_matWorldIT; // 世界变换逆转置矩阵
uniform mat4 cc_matView; // 视图矩阵
uniform mat4 cc_matProj; // 投影矩阵
uniform mat4 cc_matViewProj; // 视图投影矩阵
uniform mat4 cc_matWorldViewProj; // 世界视图投影矩阵

// 2. 光照相关
uniform vec4 cc_mainLitDir; // 主光源方�?uniform vec4 cc_mainLitColor; // 主光源颜�?uniform vec4 cc_ambientSky; // 环境天空�?uniform vec4 cc_ambientGround; // 环境地面�?
// 3. 相机相关
uniform vec4 cc_cameraPos; // 相机位置
uniform vec2 cc_screenSize; // 屏幕尺寸
uniform vec2 cc_screenScale; // 屏幕缩放

// 4. 时间相关
uniform vec4 cc_time; // 时间信息 (t/20, t, t*2, t*3)
uniform vec4 cc_deltaTime; // 时间�?
// 5. 雾效相关
uniform vec4 cc_fogColor; // 雾颜�?uniform vec4 cc_fogBase; // 雾基础参数
uniform vec4 cc_fogAdd; // 雾附加参�?```

### 内置函数的分�?
```glsl
// A. 顶点变换函数
vec4 cc_matrixMVP(vec4 position); // MVP变换
vec3 cc_worldToView(vec3 worldPos); // 世界空间到视图空�?vec3 cc_viewToWorld(vec3 viewPos); // 视图空间到世界空�?
// B. 光照计算函数
vec3 cc_ambientLighting(vec3 albedo); // 环境光计�?vec3 cc_directionalLighting(vec3 normal, vec3 albedo); // 方向光计�?float cc_shadow(vec4 shadowCoord); // 阴影计算

// C. 表面着色器函数
void SurfaceVertex(inout SurfaceIn v); // 顶点处理
void SurfaceFragment(inout SurfaceOut o); // 片元处理

// D. 工具函数
vec3 cc_screenToWorld(vec2 screenPos); // 屏幕到世界坐�?vec2 cc_worldToScreen(vec3 worldPos); // 世界到屏幕坐�?float cc_linearDepth(float depth); // 线性深度转�?```

## 🔧 基础函数重写

### 1. 变换函数重写

```glsl
// 原始MVP变换函数的增强版�?vec4 cc_matrixMVP_Enhanced(vec4 position) {
// 添加顶点动画或变�? position.xyz += calculateVertexAnimation(position.xyz);

// 应用标准MVP变换
return cc_matWorldViewProj * position;
}

// 自定义世界空间变�?vec3 cc_worldToView_Custom(vec3 worldPos) {
// 添加自定义相机偏�? vec3 cameraOffset = calculateDynamicCameraOffset();
vec3 adjustedWorldPos = worldPos + cameraOffset;

return (cc_matView * vec4(adjustedWorldPos, 1.0)).xyz;
}

// 增强的屏幕空间转�?vec2 cc_worldToScreen_Enhanced(vec3 worldPos) {
// 自定义投影变�? vec4 clipPos = cc_matViewProj * vec4(worldPos, 1.0);

// 添加屏幕扭曲效果
vec2 screenPos = clipPos.xy / clipPos.w;
screenPos = applyScreenDistortion(screenPos);

// 转换到屏幕坐�? return (screenPos * 0.5 + 0.5) * cc_screenSize;
}

// 函数重映�?#define cc_matrixMVP cc_matrixMVP_Enhanced
#define cc_worldToView cc_worldToView_Custom
#define cc_worldToScreen cc_worldToScreen_Enhanced

2. 光照函数重写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// 增强的环境光计算
vec3 cc_ambientLighting_Enhanced(vec3 albedo) {
// 基础环境�? vec3 skyLight = cc_ambientSky.rgb * cc_ambientSky.a;
vec3 groundLight = cc_ambientGround.rgb * cc_ambientGround.a;

// 添加环境光遮�? float ao = calculateAmbientOcclusion();

// 球谐光照近似
vec3 sphericalHarmonics = calculateSphericalHarmonics(albedo);

return (skyLight + groundLight + sphericalHarmonics) * albedo * ao;
}

// 增强的方向光计算
vec3 cc_directionalLighting_Enhanced(vec3 normal, vec3 albedo) {
vec3 lightDir = normalize(-cc_mainLitDir.xyz);
vec3 lightColor = cc_mainLitColor.rgb * cc_mainLitColor.a;

// 计算基础漫反�? float NdotL = max(dot(normal, lightDir), 0.0);

// 添加子表面散射近�? float subsurface = calculateSubsurfaceScattering(normal, lightDir);

// 添加大气散射
vec3 atmosphericScattering = calculateAtmosphericScattering(lightDir);

return (NdotL + subsurface) * lightColor * albedo + atmosphericScattering;
}

// 增强的阴影计�?float cc_shadow_Enhanced(vec4 shadowCoord) {
// PCF软阴�? float shadow = 0.0;
vec2 texelSize = 1.0 / textureSize(cc_shadowMap, 0);

for(int x = -1; x <= 1; ++x) {
for(int y = -1; y <= 1; ++y) {
vec2 offset = vec2(x, y) * texelSize;
float pcfDepth = texture(cc_shadowMap, shadowCoord.xy + offset).r;
shadow += shadowCoord.z > pcfDepth ? 0.0 : 1.0;
}
}
shadow /= 9.0;

// 添加阴影柔化
return smoothstep(0.3, 0.7, shadow);
}

// 函数重映�?#define cc_ambientLighting cc_ambientLighting_Enhanced
#define cc_directionalLighting cc_directionalLighting_Enhanced
#define cc_shadow cc_shadow_Enhanced

3. Surface函数重写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// 增强的Surface顶点函数
void SurfaceVertex_Enhanced(inout SurfaceIn v) {
// 调用原始处理
SurfaceVertex_Original(v);

// 添加顶点动画
v.worldPos += calculateWindAnimation(v.worldPos, v.worldNormal);

// 更新法向�? v.worldNormal = calculateAnimatedNormal(v.worldNormal, v.worldPos);

// 添加自定义UV变换
v.uv = applyCustomUVTransform(v.uv);

// 计算自定义顶点数�? v.customData = calculateCustomVertexData(v);
}

// 增强的Surface片元函数
void SurfaceFragment_Enhanced(inout SurfaceOut o) {
// 预处�? o.albedo = applyColorCorrection(o.albedo);
o.normal = normalizeAndValidate(o.normal);

// 调用原始处理
SurfaceFragment_Original(o);

// 后处�? o.albedo.rgb = applyToneMapping(o.albedo.rgb);
o.emissive = enhanceEmission(o.emissive);

// 添加特殊效果
applySpecialEffects(o);
}

// 自定义Surface入口函数
void surf_Custom(in SurfaceIn In, inout SurfaceOut Out) {
// 材质数据采样
vec4 albedoTex = texture(mainTexture, In.uv);
vec3 normalTex = texture(normalTexture, In.uv).xyz * 2.0 - 1.0;

// 基础属性设�? Out.albedo = albedoTex;
Out.normal = applyNormalMapping(In, normalTex);
Out.metallic = 0.0;
Out.roughness = 0.5;
Out.ao = 1.0;
Out.emissive = vec3(0.0);

// 自定义光照计�? vec3 customLighting = calculateCustomLighting(In, Out);
Out.albedo.rgb *= customLighting;
}

// 函数重映�?#define SurfaceVertex SurfaceVertex_Enhanced
#define SurfaceFragment SurfaceFragment_Enhanced
#define surf surf_Custom

🎨 高级内置函数重写

1. 纹理采样函数重写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
// 增强的纹理采样函�?vec4 texture_Enhanced(sampler2D tex, vec2 uv) {
// 添加纹理�? vec2 streamUV = applyTextureStreaming(uv);

// 各向异性过滤模�? vec4 color = textureAnisotropic(tex, streamUV);

// 颜色空间转换
color.rgb = sRGBToLinear(color.rgb);

// 动态范围压�? color.rgb = applyDynamicRange(color.rgb);

return color;
}

// 智能纹理采样(根据距离选择LOD�?vec4 textureSmart(sampler2D tex, vec2 uv, float distance) {
// 根据距离计算LOD
float lod = calculateLOD(distance);

// 自适应采样
if (lod < 1.0) {
return textureGrad(tex, uv, dFdx(uv), dFdy(uv));
} else {
return textureLod(tex, uv, lod);
}
}

// 体积纹理采样增强
vec4 texture3D_Enhanced(sampler3D tex, vec3 uvw) {
// 三线性插值增�? vec4 color = texture(tex, uvw);

// 添加体积光照
color.rgb += calculateVolumetricLighting(uvw);

// 体积密度调整
color.a = adjustVolumeDensity(color.a, uvw);

return color;
}

// 函数重映�?#define texture texture_Enhanced
#define textureSmart textureSmart
#define texture3D texture3D_Enhanced

2. 数学函数重写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// 安全的数学函数重�?float pow_Safe(float base, float exponent) {
// 防止负数底数和非整数指数的问�? if (base < 0.0 && fract(exponent) != 0.0) {
return 0.0;
}
return pow(max(abs(base), 0.0001), exponent);
}

float sqrt_Safe(float x) {
return sqrt(max(x, 0.0));
}

float inversesqrt_Safe(float x) {
return inversesqrt(max(x, 0.0001));
}

vec3 normalize_Safe(vec3 v) {
float len = length(v);
return len > 0.0001 ? v / len : vec3(0.0, 1.0, 0.0);
}

// 快速近似函�?float fastPow(float x, float y) {
return exp2(y * log2(x));
}

float fastExp(float x) {
return exp2(x * 1.44269504);
}

float fastLog(float x) {
return log2(x) * 0.69314718;
}

// 高精度数学函�?float preciseAtan2(float y, float x) {
// 提高atan2的精�? if (x == 0.0) {
return sign(y) * 1.5707963267948966; // PI/2
}

float angle = atan(y / x);
if (x < 0.0) {
angle += sign(y) * 3.141592653589793; // PI
}
return angle;
}

// 函数重映�?#define pow pow_Safe
#define sqrt sqrt_Safe
#define inversesqrt inversesqrt_Safe
#define normalize normalize_Safe

3. 颜色处理函数重写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
// 增强的颜色空间转�?vec3 sRGBToLinear_Enhanced(vec3 color) {
// 更精确的sRGB转换
vec3 linear = color / 12.92;
vec3 curved = pow((color + 0.055) / 1.055, vec3(2.4));
return mix(linear, curved, step(vec3(0.04045), color));
}

vec3 linearToSRGB_Enhanced(vec3 color) {
// 更精确的线性转�? vec3 linear = color * 12.92;
vec3 curved = 1.055 * pow(color, vec3(1.0/2.4)) - 0.055;
return mix(linear, curved, step(vec3(0.0031308), color));
}

// 色调映射函数重写
vec3 toneMapping_Enhanced(vec3 color) {
// ACES色调映射
const float a = 2.51;
const float b = 0.03;
const float c = 2.43;
const float d = 0.59;
const float e = 0.14;

color = (color * (a * color + b)) / (color * (c * color + d) + e);
return clamp(color, 0.0, 1.0);
}

// 颜色校正函数
vec3 colorCorrection_Enhanced(vec3 color) {
// 曝光调整
color *= exposure;

// 对比度调�? color = (color - 0.5) * contrast + 0.5;

// 饱和度调�? float luminance = dot(color, vec3(0.299, 0.587, 0.114));
color = mix(vec3(luminance), color, saturation);

// 色彩平衡
color.r *= colorBalance.r;
color.g *= colorBalance.g;
color.b *= colorBalance.b;

return color;
}

// 函数重映�?#define sRGBToLinear sRGBToLinear_Enhanced
#define linearToSRGB linearToSRGB_Enhanced
#define toneMapping toneMapping_Enhanced
#define colorCorrection colorCorrection_Enhanced

🔧 系统级函数重�?

1. 渲染管线函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// 自定义深度处�?float processDepth_Custom(vec4 clipPos) {
float depth = clipPos.z / clipPos.w;

// 非线性深度分布优�? depth = 2.0 * zNear * zFar / (zFar + zNear - depth * (zFar - zNear));

// 深度精度增强
depth = log2(max(1e-6, 1.0 + depth)) / log2(1.0 + zFar);

return depth;
}

// 自定义裁剪函�?bool customClipping(vec4 clipPos) {
// 标准裁剪测试
if (any(lessThan(clipPos.xyz, -clipPos.www)) ||
any(greaterThan(clipPos.xyz, clipPos.www))) {
return false;
}

// 自定义裁剪平�? vec3 worldPos = (cc_matWorldViewProj * clipPos).xyz;
for (int i = 0; i < MAX_CLIP_PLANES; i++) {
if (dot(vec4(worldPos, 1.0), clipPlanes[i]) < 0.0) {
return false;
}
}

return true;
}

// 自定义混合函�?vec4 customBlending(vec4 srcColor, vec4 dstColor, int blendMode) {
switch(blendMode) {
case 0: // Alpha blend
return srcColor * srcColor.a + dstColor * (1.0 - srcColor.a);
case 1: // Additive
return srcColor + dstColor;
case 2: // Multiply
return srcColor * dstColor;
case 3: // Screen
return 1.0 - (1.0 - srcColor) * (1.0 - dstColor);
case 4: // Overlay
return mix(2.0 * srcColor * dstColor,
1.0 - 2.0 * (1.0 - srcColor) * (1.0 - dstColor),
step(0.5, dstColor.rgb).x);
default:
return srcColor;
}
}

2. 光照系统重写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
// 自定义光照衰�?float calculateAttenuation_Custom(vec3 lightPos, vec3 worldPos, float lightRange) {
float distance = length(lightPos - worldPos);

// 物理衰减
float physicalAttenuation = 1.0 / (distance * distance);

// 平滑衰减边界
float smoothAttenuation = 1.0 - smoothstep(0.0, lightRange, distance);

// 窗口函数衰减
float windowAttenuation = pow(max(0.0, 1.0 - pow(distance / lightRange, 4.0)), 2.0);

return physicalAttenuation * smoothAttenuation * windowAttenuation;
}

// 自定义阴影级�?float calculateCascadedShadow(vec4 worldPos) {
// 确定级联层级
float viewDepth = length(cc_cameraPos.xyz - worldPos.xyz);
int cascadeIndex = 0;

for (int i = 0; i < MAX_CASCADE_COUNT - 1; i++) {
if (viewDepth > cascadeDistances[i]) {
cascadeIndex = i + 1;
}
}

// 采样对应级联的阴影贴�? vec4 shadowCoord = cascadeMatrices[cascadeIndex] * worldPos;
shadowCoord.xyz /= shadowCoord.w;
shadowCoord.xyz = shadowCoord.xyz * 0.5 + 0.5;

// PCF采样
float shadow = 0.0;
vec2 texelSize = 1.0 / textureSize(cascadeShadowMaps[cascadeIndex], 0);

for (int x = -1; x <= 1; x++) {
for (int y = -1; y <= 1; y++) {
vec2 offset = vec2(x, y) * texelSize;
float depth = texture(cascadeShadowMaps[cascadeIndex], shadowCoord.xy + offset).r;
shadow += shadowCoord.z > depth + shadowBias ? 0.0 : 1.0;
}
}

return shadow / 9.0;
}

// 自定义IBL计算
vec3 calculateIBL_Custom(vec3 normal, vec3 viewDir, float roughness, vec3 F0) {
vec3 R = reflect(-viewDir, normal);

// 漫反射IBL
vec3 irradiance = texture(irradianceMap, normal).rgb;
vec3 diffuse = irradiance * (1.0 - F0) * (1.0 - roughness);

// 镜面反射IBL
float lod = roughness * MAX_REFLECTION_LOD;
vec3 prefilteredColor = textureLod(prefilterMap, R, lod).rgb;

// BRDF LUT采样
float NdotV = max(dot(normal, viewDir), 0.0);
vec2 brdf = texture(brdfLUT, vec2(NdotV, roughness)).rg;
vec3 specular = prefilteredColor * (F0 * brdf.x + brdf.y);

return diffuse + specular;
}

3. 后处理函数重�?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
// 自定义抗锯齿
vec4 antiAliasing_Custom(sampler2D sceneTexture, vec2 uv) {
vec2 texelSize = 1.0 / textureSize(sceneTexture, 0);

// FXAA实现
vec3 rgbNW = texture(sceneTexture, uv + vec2(-1.0, -1.0) * texelSize).rgb;
vec3 rgbNE = texture(sceneTexture, uv + vec2(1.0, -1.0) * texelSize).rgb;
vec3 rgbSW = texture(sceneTexture, uv + vec2(-1.0, 1.0) * texelSize).rgb;
vec3 rgbSE = texture(sceneTexture, uv + vec2(1.0, 1.0) * texelSize).rgb;
vec3 rgbM = texture(sceneTexture, uv).rgb;

float lumaNW = dot(rgbNW, vec3(0.299, 0.587, 0.114));
float lumaNE = dot(rgbNE, vec3(0.299, 0.587, 0.114));
float lumaSW = dot(rgbSW, vec3(0.299, 0.587, 0.114));
float lumaSE = dot(rgbSE, vec3(0.299, 0.587, 0.114));
float lumaM = dot(rgbM, vec3(0.299, 0.587, 0.114));

float lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));
float lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));

vec2 dir = vec2(
-((lumaNW + lumaNE) - (lumaSW + lumaSE)),
((lumaNW + lumaSW) - (lumaNE + lumaSE))
);

float dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) * 0.25 * 0.1667, 0.0833);
float rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);

dir = min(vec2(8.0), max(vec2(-8.0), dir * rcpDirMin)) * texelSize;

vec3 rgbA = 0.5 * (
texture(sceneTexture, uv + dir * (1.0/3.0 - 0.5)).rgb +
texture(sceneTexture, uv + dir * (2.0/3.0 - 0.5)).rgb
);

vec3 rgbB = rgbA * 0.5 + 0.25 * (
texture(sceneTexture, uv + dir * -0.5).rgb +
texture(sceneTexture, uv + dir * 0.5).rgb
);

float lumaB = dot(rgbB, vec3(0.299, 0.587, 0.114));

if ((lumaB < lumaMin) || (lumaB > lumaMax)) {
return vec4(rgbA, 1.0);
} else {
return vec4(rgbB, 1.0);
}
}

// 自定义屏幕空间反�?vec3 screenSpaceReflection(vec3 worldPos, vec3 normal, vec3 viewDir, sampler2D sceneTexture, sampler2D depthTexture) {
// 计算反射方向
vec3 reflectDir = reflect(-viewDir, normal);

// 光线步进
vec3 rayOrigin = worldPos;
vec3 rayDirection = reflectDir;
float stepSize = 0.1;

for (int i = 0; i < MAX_SSR_STEPS; i++) {
vec3 samplePos = rayOrigin + rayDirection * stepSize * float(i);

// 转换到屏幕空�? vec4 clipPos = cc_matViewProj * vec4(samplePos, 1.0);
vec2 screenUV = (clipPos.xy / clipPos.w) * 0.5 + 0.5;

// 边界检�? if (any(lessThan(screenUV, vec2(0.0))) || any(greaterThan(screenUV, vec2(1.0)))) {
break;
}

// 深度比较
float sceneDepth = texture(depthTexture, screenUV).r;
float sampleDepth = clipPos.z / clipPos.w;

if (sampleDepth > sceneDepth + 0.001) {
// 击中表面,返回颜�? return texture(sceneTexture, screenUV).rgb;
}
}

return vec3(0.0); // 未击中任何表�?}

📋 函数替换管理策略

1. 版本兼容性管�?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
// 版本检测系�?#define CC_VERSION_3_8_0 380
#define CC_VERSION_3_8_1 381
#define CC_VERSION_3_9_0 390

#ifndef CC_ENGINE_VERSION
#define CC_ENGINE_VERSION CC_VERSION_3_8_0
#endif

// 版本兼容的函数重�?#if CC_ENGINE_VERSION >= CC_VERSION_3_9_0
// 新版本特�? vec3 calculateLighting_v390(SurfaceIn In, vec3 albedo, vec3 normal) {
// 使用新的光照系统
return newLightingSystem(In, albedo, normal);
}
#define calculateLighting calculateLighting_v390
#elif CC_ENGINE_VERSION >= CC_VERSION_3_8_1
// 中等版本兼容
vec3 calculateLighting_v381(SurfaceIn In, vec3 albedo, vec3 normal) {
// 兼容性实�? return compatibleLighting(In, albedo, normal);
}
#define calculateLighting calculateLighting_v381
#else
// 旧版本兼�? vec3 calculateLighting_v380(SurfaceIn In, vec3 albedo, vec3 normal) {
// 基础实现
return basicLighting(In, albedo, normal);
}
#define calculateLighting calculateLighting_v380
#endif

2. 功能开关管�?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// 功能开关系�?#pragma define-meta ENABLE_ENHANCED_LIGHTING editor { tab: "Enhanced Features", type: boolean }
#pragma define-meta ENABLE_CUSTOM_SHADOWS editor { tab: "Enhanced Features", type: boolean }
#pragma define-meta ENABLE_SSR editor { tab: "Enhanced Features", type: boolean }
#pragma define-meta ENABLE_TEMPORAL_AA editor { tab: "Enhanced Features", type: boolean }

// 条件函数重写
#if ENABLE_ENHANCED_LIGHTING
#define cc_directionalLighting cc_directionalLighting_Enhanced
#define cc_ambientLighting cc_ambientLighting_Enhanced
#endif

#if ENABLE_CUSTOM_SHADOWS
#define cc_shadow calculateCascadedShadow
#endif

#if ENABLE_SSR
#define calculateReflection screenSpaceReflection
#endif

#if ENABLE_TEMPORAL_AA
#define antiAliasing temporalAntiAliasing
#else
#define antiAliasing antiAliasing_Custom
#endif

3. 性能分级管理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
// 性能等级定义
#define PERFORMANCE_LOW 0
#define PERFORMANCE_MEDIUM 1
#define PERFORMANCE_HIGH 2
#define PERFORMANCE_ULTRA 3

#ifndef PERFORMANCE_LEVEL
#define PERFORMANCE_LEVEL PERFORMANCE_MEDIUM
#endif

// 基于性能等级的函数选择
#if PERFORMANCE_LEVEL >= PERFORMANCE_ULTRA
// 最高质量实�? #define calculateLighting calculateLighting_Ultra
#define processTexture processTexture_Ultra
#define calculateShadow calculateShadow_Ultra
#elif PERFORMANCE_LEVEL >= PERFORMANCE_HIGH
// 高质量实�? #define calculateLighting calculateLighting_High
#define processTexture processTexture_High
#define calculateShadow calculateShadow_High
#elif PERFORMANCE_LEVEL >= PERFORMANCE_MEDIUM
// 中等质量实现
#define calculateLighting calculateLighting_Medium
#define processTexture processTexture_Medium
#define calculateShadow calculateShadow_Medium
#else
// 低质量实�? #define calculateLighting calculateLighting_Low
#define processTexture processTexture_Low
#define calculateShadow calculateShadow_Low
#endif

4. 调试和测试框�?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
// 调试模式开�?#ifdef DEBUG_MODE
#define ENABLE_FUNCTION_VALIDATION 1
#define ENABLE_PERFORMANCE_MONITORING 1
#define ENABLE_ERROR_CHECKING 1
#else
#define ENABLE_FUNCTION_VALIDATION 0
#define ENABLE_PERFORMANCE_MONITORING 0
#define ENABLE_ERROR_CHECKING 0
#endif

// 函数验证包装�?#if ENABLE_FUNCTION_VALIDATION
vec3 validateResult(vec3 result, vec3 expected, string functionName) {
vec3 diff = abs(result - expected);
if (any(greaterThan(diff, vec3(0.01)))) {
// 记录验证失败
logValidationError(functionName, result, expected);
}
return result;
}

#define VALIDATE_FUNCTION(func, expected) validateResult(func, expected, #func)
#else
#define VALIDATE_FUNCTION(func, expected) func
#endif

// 性能监控包装�?#if ENABLE_PERFORMANCE_MONITORING
float performanceTimer = 0.0;

#define PERF_BEGIN() performanceTimer = cc_time.x
#define PERF_END(name) logPerformance(name, cc_time.x - performanceTimer)
#else
#define PERF_BEGIN()
#define PERF_END(name)
#endif

// 错误检查包装器
#if ENABLE_ERROR_CHECKING
#define CHECK_NORMAL(n) (length(n) > 0.9 && length(n) < 1.1)
#define CHECK_COLOR(c) all(greaterThanEqual(c, vec3(0.0))) && all(lessThanEqual(c, vec3(1.0)))
#define CHECK_UV(uv) all(greaterThanEqual(uv, vec2(0.0))) && all(lessThanEqual(uv, vec2(1.0)))
#else
#define CHECK_NORMAL(n) true
#define CHECK_COLOR(c) true
#define CHECK_UV(uv) true
#endif

📖 本章总结

通过本章学习,我们深入掌握了�?

  • �?内置函数分类:变换、光照、Surface和工具函数的完整概览
  • �?基础函数重写:变换函数、光照函数和Surface函数的安全重�?- �?高级函数重写:纹理采样、数学函数和颜色处理的增强实�?- �?**系统级重�?*:渲染管线、光照系统和后处理的深度定制
  • �?管理策略:版本兼容性、功能开关、性能分级和调试框�?- �?**最佳实�?*:安全重写、性能考虑和兼容性维�?

🚀 下一步学�?

掌握了可替换内置函数后,建议继续学习�?
👉 �?.4章:高级宏编程技巧

💡 实践练习

  1. 基础练习:重写一个内置光照函数,添加自定义效�?2. 进阶练习:实现基于性能等级的函数自动选择系统
  2. 高级练习:创建完整的函数替换管理框架

*参考资�?

系列导航