Qt Quick 3D - 自定义特效示例
演示如何编写自定义后处理特效。
该示例实现了自己的自定义后处理特效,然后通过SceneEnvironment::effects 将其应用到场景中。该示例既演示了只使用片段着色器的最简单特效,也演示了同时使用顶点和片段着色器并在两者之间传递数据的更高级特效。
简单的特效只使用一个片段着色器,并从图像文件中添加纹理输入:
Effect { id: eff1 property TextureInput tex: TextureInput { id: qtLogo texture: Texture { source: "qt_logo_rect.png" } } passes: Pass { shaders: Shader { id: fs1 stage: Shader.Fragment shader: "effect.frag" } } }
该特效使用了非常简单的片段着色器,只需将包含场景的输入纹理与图像纹理相乘即可:
void MAIN() { vec4 c = texture(tex, TEXTURE_UV); FRAGCOLOR = c * texture(INPUT, INPUT_UV); }
.vert
和.frag
文件中的着色器片段是使用Effect 文档中描述的内置关键字编写的。具有基本类型的自定义属性以及具有TextureInput 类型的属性会自动作为制服和采样器暴露给着色器。
第二种效果更为复杂。它指定了一个顶点着色器和一个片段着色器,以及两个属性:uRed
和uGreen
,并在uRed
上设置了动画:
Effect { id: eff2 property real uRed: 0.0 SequentialAnimation { running: radioEff2.checked || radioEff3.checked loops: Animation.Infinite NumberAnimation { target: eff2; property: "uRed"; from: 0; to: 1; duration: 2000 } NumberAnimation { target: eff2; property: "uRed"; from: 1; to: 0; duration: 2000 } } property real uGreen: 1.0 Shader { id: vs2 stage: Shader.Vertex shader: "effect2.vert" } Shader { id: fs2 stage: Shader.Fragment shader: "effect2.frag" } passes: Pass { shaders: [ vs2, fs2 ] } }
该效果的片段着色器通过修改采样坐标来产生变形。计算使用center_vec
,它来自片段着色器。最后,着色器使用uRed
和uGreen
制服调整颜色。请注意,着色器中不必声明这些制服:
VARYING vec2 center_vec; void MAIN() { float radius = 0.25; float dist_to_center = length(center_vec) / radius; vec2 texcoord = INPUT_UV; if (dist_to_center <= 1.0) { float rotation_amount = (1.0 - dist_to_center) * (1.0 - dist_to_center); float r = radians(360.0) * rotation_amount / 4.0; float cos_r = cos(r); float sin_r = sin(r); mat2 rotation = mat2(cos_r, sin_r, -sin_r, cos_r); texcoord = vec2(0.5, 0.5) + rotation * (INPUT_UV - vec2(0.5, 0.5)); } vec4 c = texture(INPUT, texcoord); c.r *= uRed; c.g *= uGreen; FRAGCOLOR = c; }
© 2025 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.