ShaderEffect QML类型

ShaderEffect QML Type

ShaderEffect QML类型

Applies custom shaders to a rectangle. More...

将自定义着色器应用于矩形。

Import Statement:import QtQuick
Inherits:

Item

导入声明import QtQuick
继承自

Item

Properties

属性

Detailed Description

详细描述

The ShaderEffect type applies a custom vertex and fragment (pixel) shader to a rectangle. It allows adding effects such as drop shadow, blur, colorize and page curl into the QML scene.

​ShaderEffect类型将自定义顶点和片段(像素)着色器应用于矩形。它允许在QML场景中添加阴影、模糊、着色和页面卷曲等效果。

Note: Depending on the Qt Quick scenegraph backend in use, the ShaderEffect type may not be supported. For example, with the software backend effects will not be rendered at all.

注意:根据使用的Qt Quick scenegraph后端,ShaderEffect类型可能不受支持。例如,使用software后端效果,根本不会渲染。

Shaders

着色器

In Qt 5, effects were provided in form of GLSL (OpenGL Shading Language) source code, often embedded as strings into QML. Starting with Qt 5.8, referring to files, either local ones or in the Qt resource system, became possible as well.

在Qt5中,效果以GLSL(OpenGL着色语言)源代码的形式提供,通常作为字符串嵌入到QML中。从Qt5.8开始,引用本地文件或Qt资源系统中的文件也成为可能。

In Qt 6, Qt Quick has support for graphics APIs, such as Vulkan, Metal, and Direct3D 11 as well. Therefore, working with GLSL source strings is no longer feasible. Rather, the new shader pipeline is based on compiling Vulkan-compatible GLSL code into SPIR-V, followed by gathering reflection information and translating into other shading languages, such as HLSL, the Metal Shading Language, and various GLSL versions. The resulting assets are packed together into a single package, typically stored in files with an extension of .qsb. This process is done offline or at application build time at latest. At run time, the scene graph and the underlying graphics abstraction consumes these .qsb files. Therefore, ShaderEffect expects file (local or qrc) references in Qt 6 in place of inline shader code.

​在Qt 6中,Qt Quick还支持图形API,如Vulkan、Metal和Direct3D 11。因此,使用GLSL源字符串不再可行。相反,新的着色器管道基于将Vulkan兼容的GLSL代码编译成SPIR-V,然后收集反射信息并翻译成其他着色语言,如HLSL、Metal着色语言和各种GLSL版本。生成的资产被打包到一个包中,通常存储在扩展名为.qsb的文件中。此过程在脱机或最迟在应用程序构建时完成。在运行时,场景图和底层图形抽象会调用这些.qsb文件资源。因此,ShaderEffect希望Qt 6中的文件(本地或资源文件)引用代替内联着色器代码。

The vertexShader and fragmentShader properties are URLs in Qt 6, and work very similarly to Image.source, for example. Only the file and qrc schemes are supported with ShaderEffect, however. It is also possible to omit the file scheme, allowing to specify a relative path in a convenient way. Such a path is resolved relative to the component's (the .qml file's) location.

​vertexShader和fragmentShader属性是Qt 6中的URL,其工作原理与Image非常相似。例如,来源。但是,ShaderEffect仅支持文件和资源文件方案。还可以省略文件方案,以便以方便的方式指定相对路径。这样的路径是相对于组件的位置(即.qml文件)解析的。

Shader Inputs and Resources

着色器输入和资源

There are two types of input to the vertexShader: uniforms and vertex inputs.

​vertexShader有两种类型的输入:uniforms 和顶点vertex输入。​

The following inputs are predefined:

以下输入是预定义的:

  • vec4 qt_Vertex with location 0 - vertex position, the top-left vertex has position (0, 0), the bottom-right (widthheight).
  • ​带有location 0的vec4 qt_Vertex-顶点位置,左上角顶点有位置(0,0),右下角(宽度,高度)。
  • vec2 qt_MultiTexCoord0 with location 1 - texture coordinate, the top-left coordinate is (0, 0), the bottom-right (1, 1). If supportsAtlasTextures is true, coordinates will be based on position in the atlas instead.
  • ​带有location 1的vec2 qt_MultiTexCoord0-纹理坐标,左上角坐标为(0,0),右下角坐标为(1,1)。如果SupportSatLastTextures为true,则坐标将基于地图集中的位置。

Note: It is only the vertex input location that matters in practice. The names are freely changeable, while the location must always be 0 for vertex position, 1 for texture coordinates. However, be aware that this applies to vertex inputs only, and is not necessarily true for output variables from the vertex shader that are then used as inputs in the fragment shader (typically, the interpolated texture coordinates).

注意:实际上,只有顶点输入位置才重要。名称可以自由更改,而位置对于顶点位置必须始终为0,对于纹理坐标必须始终为1。但是,请注意,这仅适用于顶点输入,对于顶点着色器中的输出变量(然后用作片段着色器中的输入)(通常为插值纹理坐标),这不一定适用。

The following uniforms are predefined:

以下uniforms是预定义的:

  • mat4 qt_Matrix - combined transformation matrix, the product of the matrices from the root item to this ShaderEffect, and an orthogonal projection.
  • mat4 qt_Matrix - 组合变换矩阵,从根项到该着色器效果的矩阵的乘积,以及正交投影。
  • float qt_Opacity - combined opacity, the product of the opacities from the root item to this ShaderEffect.
  • float qt_Opacity - 组合不透明度,根项到该着色器效果的不透明度的乘积。

Note: Vulkan-style GLSL has no separate uniform variables. Instead, shaders must always use a uniform block with a binding point of 0.

注:Vulkan风格的GLSL没有单独的uniform变量。相反,着色器必须始终使用绑定点为0的uniform块。

Note: The uniform block layout qualifier must always be std140.

注:uniform块布局限定符必须始终为std140。

Note: Unlike vertex inputs, the predefined names (qt_Matrix, qt_Opacity) must not be changed.

注意:与顶点输入不同,预定义名称(qt_Matrix, qt_Opacity)不得更改。

In addition, any property that can be mapped to a GLSL type can be made available to the shaders. The following list shows how properties are mapped:

此外,可以映射到GLSL类型的任何属性都可以供着色器使用。以下列表显示了属性的映射方式:

  • bool, int, qreal -> bool, int, float - If the type in the shader is not the same as in QML, the value is converted automatically.
  • bool, int, qreal -> bool, int, float - 如果着色器中的类型与QML中的类型不同,则会自动转换该值。
  • QColor -> vec4 - When colors are passed to the shader, they are first premultiplied. Thus Qt.rgba(0.2, 0.6, 1.0, 0.5) becomes vec4(0.1, 0.3, 0.5, 0.5) in the shader, for example.
  • QColor -> vec4 - 当颜色被传递到着色器时,它们首先被预乘。因此Qt。例如,rgba(0.2,0.6,1.0,0.5)在着色器中变为vec4(0.1,0.3,0.5,0.5)。

  • QRectQRectF -> vec4 - Qt.rect(x, y, w, h) becomes vec4(x, y, w, h) in the shader.
  • QRectQRectF -> vec4 - Qt.rect(x, y, w, h) 在着色器中变为vec4(x,y,w,h)。

  • QPointQPointFQSizeQSizeF -> vec2
  • QVector3D -> vec3
  • QVector4D -> vec4
  • QTransform -> mat3
  • QMatrix4x4 -> mat4
  • QQuaternion -> vec4, scalar value is w.
  • Image -> sampler2D - Origin is in the top-left corner, and the color values are premultiplied. The texture is provided as is, excluding the Image item's fillMode. To include fillMode, use a ShaderEffectSource or Image::layer::enabled.
  • Image -> sampler2D - ​原点位于左上角,颜色值是预乘的。纹理按原样提供,不包括图像项的fillMode。要包括fillMode,请使用ShaderEffectSource或Image::layer::enabled。

  • ShaderEffectSource -> sampler2D - Origin is in the top-left corner, and the color values are premultiplied.
  • ShaderEffectSource -> sampler2D - 原点位于左上角,颜色值是预乘的。

Samplers are still declared as separate uniform variables in the shader code. The shaders are free to choose any binding point for these, except for 0 because that is reserved for the uniform block.

在着色器代码中,采样器仍然声明为单独的uniform变量。着色器可以自由选择除0之外的任何绑定点,因为0绑定点是uniform块保留的。

Some shading languages and APIs have a concept of separate image and sampler objects. Qt Quick always works with combined image sampler objects in shaders, as supported by SPIR-V. Therefore shaders supplied for ShaderEffect should always use layout(binding = 1) uniform sampler2D tex; style sampler declarations. The underlying abstraction layer and the shader pipeline takes care of making this work for all the supported APIs and shading languages, transparently to the applications.

一些着色语言和API有单独图像和采样器对象的概念。Qt Quick始终与着色器中的组合图像采样器对象一起工作,如SPIR-V所支持。因此,为ShaderEffect提供的着色器应始终使用layout(binding = 1) uniform sampler2D tex;样式采样器声明。底层的抽象层和着色器管道负责使所有受支持的API和着色语言都能以透明的方式工作。

The QML scene graph back-end may choose to allocate textures in texture atlases. If a texture allocated in an atlas is passed to a ShaderEffect, it is by default copied from the texture atlas into a stand-alone texture so that the texture coordinates span from 0 to 1, and you get the expected wrap modes. However, this will increase the memory usage. To avoid the texture copy, set supportsAtlasTextures for simple shaders using qt_MultiTexCoord0, or for each "uniform sampler2D <name>" declare a "uniform vec4 qt_SubRect_<name>" which will be assigned the texture's normalized source rectangle. For stand-alone textures, the source rectangle is [0, 1]x[0, 1]. For textures in an atlas, the source rectangle corresponds to the part of the texture atlas where the texture is stored. The correct way to calculate the texture coordinate for a texture called "source" within a texture atlas is "qt_SubRect_source.xy + qt_SubRect_source.zw * qt_MultiTexCoord0".

​QML场景图后端可以选择在纹理图谱中分配纹理。如果在图集中分配的纹理被传递给ShaderEffect,则默认情况下会将其从纹理图集复制到独立纹理中,以便纹理坐标的范围为0到1,从而获得预期的包裹模式。然而,这将增加内存使用。要避免纹理复制,请使用qt_MultiTexCoord0为简单着色器设置SupportsAtlastTextures,或为每个“uniform sampler2D<name>”声明一个“uniform vec4 qt_SubRect_<name>”将被指定纹理的标准化源矩形。对于独立纹理,源矩形为[0,1]x[0,1]。对于图集中的纹理,源矩形对应于纹理图集中存储纹理的部分。在纹理图集中计算称为“源”的纹理的纹理坐标的正确方法是“qt_SubRect_source.xy+qt_SubRect_source.zw*qt_multiexcoord0”。

The output from the fragmentShader should be premultiplied. If blending is enabled, source-over blending is used. However, additive blending can be achieved by outputting zero in the alpha channel.

​fragmentShader的输出应该被预乘。如果启用了混合,则使用源过度混合。然而,加法混合可以通过在alpha通道中输出零来实现。

import QtQuick 2.0

Rectangle {
    width: 200; height: 100
    Row {
        Image { id: img;
                sourceSize { width: 100; height: 100 } source: "qt-logo.png" }
        ShaderEffect {
            width: 100; height: 100
            property variant src: img
            vertexShader: "myeffect.vert.qsb"
            fragmentShader: "myeffect.frag.qsb"
        }
    }
}

The example assumes myeffect.vert and myeffect.frag contain Vulkan-style GLSL code, processed by the qsb tool in order to generate the .qsb files.

该示例假设myeffect.vertmyeffect.frag包含Vulkan风格的GLSL代码,由qsb工具处理以生成.qsb文件。

#version 440
layout(location = 0) in vec4 qt_Vertex;
layout(location = 1) in vec2 qt_MultiTexCoord0;
layout(location = 0) out vec2 coord;
layout(std140, binding = 0) uniform buf {
    mat4 qt_Matrix;
    float qt_Opacity;
};
void main() {
    coord = qt_MultiTexCoord0;
    gl_Position = qt_Matrix * qt_Vertex;
}
#version 440
layout(location = 0) in vec2 coord;
layout(location = 0) out vec4 fragColor;
layout(std140, binding = 0) uniform buf {
    mat4 qt_Matrix;
    float qt_Opacity;
};
layout(binding = 1) uniform sampler2D src;
void main() {
    vec4 tex = texture(src, coord);
    fragColor = vec4(vec3(dot(tex.rgb, vec3(0.344, 0.5, 0.156))), tex.a) * qt_Opacity;
}

Note: Scene Graph textures have origin in the top-left corner rather than bottom-left which is common in OpenGL.

注意:场景图纹理的原点位于左上角,而不是OpenGL中常见的左下角。

Having One Shader Only

只有一个着色器

Specifying both vertexShader and fragmentShader is not mandatory. Many ShaderEffect implementations will want to provide a fragment shader only in practice, while relying on the default, built-in vertex shader.

​不强制同时指定vertexShader和fragmentShader。许多ShaderEffect实现只希望在实践中提供片段着色器,同时依赖默认的内置顶点着色器。

The default vertex shader passes the texture coordinate along to the fragment shader as vec2 qt_TexCoord0 at location 0.

默认顶点着色器将纹理坐标作为vec2 qt_TexCoord0在位置0处传递给片段着色器。

The default fragment shader expects the texture coordinate to be passed from the vertex shader as vec2 qt_TexCoord0 at location 0, and it samples from a sampler2D named source at binding point 1.

默认片段着色器希望从顶点着色器传递的纹理坐标作为位置0处的vec2 qt_TexCoord0,并从绑定点1处的sampler2D命名源采样。

Warning: When only one of the shaders is specified, the writer of the shader must be aware of the uniform block layout expected by the default shaders: qt_Matrix must always be at offset 0, followed by qt_Opacity at offset 64. Any custom uniforms must be placed after these two. This is mandatory even when the application-provided shader does not use the matrix or the opacity, because at run time there is one single uniform buffer that is exposed to both the vertex and fragment shader.

警告:仅指定一个着色器时,着色器的编写者必须知道默认着色器所需的统一块布局:qt_Matrix必须始终位于偏移量0处,然后是偏移量64处的qt_Opacity。任何定制uniform都必须放在这两项之后。即使应用程序提供的着色器不使用矩阵或不透明度,这也是必需的,因为在运行时,有一个统一的缓冲区同时暴露给顶点和片段着色器。

Warning: Unlike with vertex inputs, passing data between the vertex and fragment shader may, depending on the underlying graphics API, require the same names to be used, a matching location is not always sufficient. Most prominently, when specifying a fragment shader while relying on the default, built-in vertex shader, the texture coordinates are passed on as qt_TexCoord0 at location 0, and therefore it is strongly advised that the fragment shader declares the input with the same name (qt_TexCoord0). Failing to do so may lead to issues on some platforms, for example when running with a non-core profile OpenGL context where the underlying GLSL shader source code has no location qualifiers and matching is based on the variable names during to shader linking process.

警告:与顶点输入不同,根据基础图形API,在顶点和片段着色器之间传递数据可能需要使用相同的名称,但匹配位置并不总是足够的。最重要的是,在依赖默认的内置顶点着色器指定片段着色器时,纹理坐标在位置0作为qt_TexCoord0传递,因此强烈建议片段着色器使用相同的名称(qt_TexCoord0)声明输入。如果不这样做,可能会在某些平台上导致问题,例如,在使用非核心概要文件OpenGL上下文运行时,底层GLSL着色器源代码没有位置限定符,并且在到着色器链接过程中,匹配基于变量名。

ShaderEffect and Item Layers

ShaderEffect和项层

The ShaderEffect type can be combined with layered items.

​ShaderEffect类型可以与分层项组合。

Layer with effect disabled 

Layer with effect enabled 

Item {
    id: layerRoot
    layer.enabled: true
    layer.effect: ShaderEffect {
       fragmentShader: "effect.frag.qsb"
    }
}
#version 440
layout(location = 0) in vec2 qt_TexCoord0;
layout(location = 0) out vec4 fragColor;
layout(std140, binding = 0) uniform buf {
    mat4 qt_Matrix;
    float qt_Opacity;
};
layout(binding = 1) uniform sampler2D source;
void main() {
    vec4 p = texture(source, qt_TexCoord0);
    float g = dot(p.xyz, vec3(0.344, 0.5, 0.156));
    fragColor = vec4(g, g, g, p.a) * qt_Opacity;
}

It is also possible to combine multiple layered items:

还可以组合多个分层项目:

Rectangle {
    id: gradientRect;
    width: 10
    height: 10
    gradient: Gradient {
        GradientStop { position: 0; color: "white" }
        GradientStop { position: 1; color: "steelblue" }
    }
    visible: false; // should not be visible on screen.
    layer.enabled: true;
    layer.smooth: true
 }
 Text {
    id: textItem
    font.pixelSize: 48
    text: "Gradient Text"
    anchors.centerIn: parent
    layer.enabled: true
    // This item should be used as the 'mask'
    layer.samplerName: "maskSource"
    layer.effect: ShaderEffect {
        property var colorSource: gradientRect;
        fragmentShader: "mask.frag.qsb"
    }
}
#version 440
layout(location = 0) in vec2 qt_TexCoord0;
layout(location = 0) out vec4 fragColor;
layout(std140, binding = 0) uniform buf {
    mat4 qt_Matrix;
    float qt_Opacity;
};
layout(binding = 1) uniform sampler2D colorSource;
layout(binding = 2) uniform sampler2D maskSource;
void main() {
    fragColor = texture(colorSource, qt_TexCoord0)
                    * texture(maskSource, qt_TexCoord0).a
                    * qt_Opacity;
}

Other Notes

其他注意事项

By default, the ShaderEffect consists of four vertices, one for each corner. For non-linear vertex transformations, like page curl, you can specify a fine grid of vertices by specifying a mesh resolution.

​默认情况下,ShaderEffect由四个顶点组成,每个顶点对应一个角点。对于非线性顶点变换(如页面卷曲),可以通过指定网格分辨率来指定顶点的精细网格。

Migrating From Qt 5

从Qt 5迁移

For Qt 5 applications with ShaderEffect items the migration to Qt 6 involves:

对于具有ShaderEffect项的Qt 5应用程序,迁移到Qt 6涉及:

  • Moving the shader code to separate .vert and .frag files,
  • 将着色器代码“分离”成.vert和.frag文件
  • updating the shaders to Vulkan-compatible GLSL,
  • 将着色器更新为Vulkan兼容的GLSL,
  • running the qsb tool on them,
  • 运行qsb工具,
  • including the resulting .qsb files in the executable with the Qt resource system,
  • 使用Qt资源系统,引入生成的.qsb文件到可执行文件中,
  • and referencing the file in the vertexShader and fragmentShader properties.
  • ​以及在vertexShader和fragmentShader属性中引用文件。​

As described in the Qt Shader Tools module some of these steps can be automated by letting CMake invoke the qsb tool at build time. See Qt Shader Tools Build System Integration for more information and examples.

​如Qt着色器工具模块中所述,通过让CMake在构建时调用qsb工具,可以自动执行其中一些步骤。有关更多信息和示例,请参见Qt着色器工具构建系统集成。

When it comes to updating the shader code, below is an overview of the commonly required changes.

在更新着色器代码时,下面概述了通常需要的更改。

Vertex shader in Qt 5Vertex shader in Qt 6
attribute highp vec4 qt_Vertex;
attribute highp vec2 qt_MultiTexCoord0;
varying highp vec2 coord;
uniform highp mat4 qt_Matrix;
void main() {
    coord = qt_MultiTexCoord0;
    gl_Position = qt_Matrix * qt_Vertex;
}
#version 440
layout(location = 0) in vec4 qt_Vertex;
layout(location = 1) in vec2 qt_MultiTexCoord0;
layout(location = 0) out vec2 coord;
layout(std140, binding = 0) uniform buf {
    mat4 qt_Matrix;
    float qt_Opacity;
};
void main() {
    coord = qt_MultiTexCoord0;
    gl_Position = qt_Matrix * qt_Vertex;
}

The conversion process mostly involves updating the code to be compatible with GL_KHR_vulkan_glsl. It is worth noting that Qt Quick uses a subset of the features provided by GLSL and Vulkan, and therefore the conversion process for typical ShaderEffect shaders is usually straightforward.

​转换过程主要涉及更新代码以与GL_KHR_vulkan_glsl兼容。值得注意的是,Qt Quick使用了GLSL和Vulkan提供的一部分功能,因此典型ShaderEffect着色器的转换过程通常很简单。​

  • The version directive should state 440 or 450, although specifying other GLSL version may work too, because the GL_KHR_vulkan_glsl extension is written for GLSL 140 and higher.
  • ​指令版本应是440或450,尽管指定其他GLSL版本也可能起作用,因为GL_KHR_vulkan_GLSL扩展是为GLSL 140及更高版本编写的。​
  • Inputs and outputs must use the modern GLSL in and out keywords. In addition, specifying a location is required. The input and output location namespaces are separate, and therefore assigning locations starting from 0 for both is safe.
  • 输入和输出必须使用现代GLSL in和out关键字。此外,还需要指定位置。输入和输出位置名称空间是独立的,因此为这两个名称空间分配从0开始的位置是安全的。
  • When it comes to vertex shader inputs, the only possibilities with ShaderEffect are location 0 for vertex position (traditionally named qt_Vertex) and location 1 for texture coordinates (traditionally named qt_MultiTexCoord0).
  • 说到顶点着色器输入,ShaderEffect的唯一可能性是顶点位置的位置0(传统上称为qt_Vertex)和纹理坐标的位置1(传统上称为qt_MultiTexCoord0)。
  • The vertex shader outputs and fragment shader inputs are up to the shader code to define. The fragment shader must have a vec4 output at location 0 (typically called fragColor). For maximum portability, vertex outputs and fragment inputs should use both the same location number and the same name. When specifying only a fragment shader, the texture coordinates are passed in from the built-in vertex shader as vec2 qt_TexCoord0 at location 0, as shown in the example snippets above.
  • 顶点着色器输出和片段着色器输入由着色器代码定义。片段着色器必须在位置0处具有vec4输出(通常称为fragColor)。为了实现最大的可移植性,顶点输出和片段输入应使用相同的位置号和名称。仅指定片段着色器时,纹理坐标从内置顶点着色器作为位置0处的vec2 qt_TexCoord0传入,如上面的示例片段所示。
  • Uniform variables outside a uniform block are not legal. Rather, uniform data must be declared in a uniform block with binding point 0.
  • uniform块之外的uniform变量是不合法的。相反,uniform数据必须在绑定点为0的统一块中声明。
  • The uniform block is expected to use the std140 qualifier.
  • uniform块应该使用std140限定符。
  • At run time, the vertex and fragment shader will get the same uniform buffer bound to binding point 0. Therefore, as a general rule, the uniform block declarations must be identical between the shaders. This also includes members that are not used in one of the shaders. The member names must match, because with some graphics APIs the uniform block is converted to a traditional struct uniform, transparently to the application.
  • 在运行时,顶点和片段着色器将获得绑定到绑定点0的相同uniform缓冲区。因此,作为一般规则,着色器之间的uniform块声明必须相同。这还包括未在其中一个着色器中使用的成员。成员名称必须匹配,因为在某些图形API中,统一块被转换为传统的uniform结构体,对应用程序来说是透明的。
  • When providing one of the shaders only, watch out for the fact that the built-in shaders expect qt_Matrix and qt_Opacity at the top of the uniform block. (more precisely, at offset 0 and 64, respectively) As a general rule, always include these as the first and second members in the block.
  • 当只提供其中一个着色器时,请注意这样一个事实,即内置着色器在uniform块顶部的qt_Matrix和qqt_Opacity。(更准确地说,偏移量分别为0和64)作为一般规则,始终将这些作为块中的第一个和第二个成员。
  • In the example the uniform block specifies the block name buf. This name can be changed freely, but must match between the shaders. Using an instance name, such as layout(...) uniform buf { ... } instance_name; is optional. When specified, all accesses to the members must be qualified with instance_name.
  • 在本例中,uniform块指定块名buf。此名称可以自由更改,但必须在着色器之间匹配。使用实例名称,例如layout(...) uniform buf { ... } instance_name;是可选的。指定时,对成员的所有访问都必须使用instance_name限定。
Fragment shader in Qt 5Fragment shader in Qt 6
varying highp vec2 coord;
uniform lowp float qt_Opacity;
uniform sampler2D src;
void main() {
    lowp vec4 tex = texture2D(src, coord);
    gl_FragColor = vec4(vec3(dot(tex.rgb,
                        vec3(0.344, 0.5, 0.156))),
                             tex.a) * qt_Opacity;
}
#version 440
layout(location = 0) in vec2 coord;
layout(location = 0) out vec4 fragColor;
layout(std140, binding = 0) uniform buf {
    mat4 qt_Matrix;
    float qt_Opacity;
};
layout(binding = 1) uniform sampler2D src;
void main() {
    vec4 tex = texture(src, coord);
    fragColor = vec4(vec3(dot(tex.rgb,
                     vec3(0.344, 0.5, 0.156))),
                          tex.a) * qt_Opacity;
}
  • Precision qualifiers (lowpmediumphighp) are not currently used.
  • 精度限定符(lowp、mediump、highp)目前未使用。
  • Calling built-in GLSL functions must follow the modern GLSL names, most prominently, texture() instead of texture2D().
  • 调用内置GLSL函数必须遵循现代的GLSL名称,最突出的是texture(),而不是texture2D()。
  • Samplers must use binding points starting from 1.
  • 取样器必须从1开始使用绑定点。

See also Item LayersQSB Manual, and Qt Shader Tools Build System Integration.

Property Documentation

属性文档

blending : bool

If this property is true, the output from the fragmentShader is blended with the background using source-over blend mode. If false, the background is disregarded. Blending decreases the performance, so you should set this property to false when blending is not needed. The default value is true.

​如果此属性为true,则使用“源叠加混合”模式将fragmentShader的输出与背景混合。如果为false,则忽略背景。混合会降低性能,因此当不需要混合时,应将此属性设置为false。默认值为true。

cullMode : enumeration

This property defines which sides of the item should be visible.

此属性定义项目的哪些面应可见。

The default is NoCulling.

默认设置是NoCulling。

fragmentShader : url

This property contains a reference to a file with the preprocessed fragment shader package, typically with an extension of .qsb. The value is treated as a URL, similarly to other QML types, such as Image. It must either be a local file or use the qrc scheme to access files embedded via the Qt resource system. The URL may be absolute, or relative to the URL of the component.

​此属性包含对带有预处理片段着色器包的文件的引用,通常扩展名为.qsb。该值被视为URL,类似于其他QML类型,例如图像Image。它必须是本地文件,或者使用qrc方案访问通过Qt资源系统嵌入的文件。URL可以是绝对的,也可以是相对于组件的URL的。

See also vertexShader.

log : string

This property holds a log of warnings and errors from the latest attempt at compiling the shaders. It is updated at the same time status is set to Compiled or Error.

​此属性保存最近编译着色器时出现的警告和错误日志。它会在状态设置为已编译或错误的同时更新。

Note: In Qt 6, the shader pipeline promotes compiling and translating the Vulkan-style GLSL shaders offline, or at build time at latest. This does not necessarily mean there is no shader compilation happening at run time, but even if there is, ShaderEffect is not involved in that, and syntax and similar errors should not occur anymore at that stage. Therefore the value of this property is typically empty.

​注意:在Qt 6中,着色器管道促进离线或最迟在构建时编译和翻译Vulkan样式的GLSL着色器。这并不一定意味着在运行时不会发生着色器编译,但即使有,ShaderEffect也不会参与其中,并且在该阶段不应再出现语法和类似错误。因此,此属性的值通常为空。

See also status.

mesh : variant

This property defines the mesh used to draw the ShaderEffect. It can hold any GridMesh object. If a size value is assigned to this property, the ShaderEffect implicitly uses a GridMesh with the value as mesh resolution. By default, this property is the size 1x1.

​此属性定义用于绘制ShaderEffect的网格。它可以容纳任何网格对象。如果将“大小”值指定给此属性,则ShaderEffect会隐式使用网格分辨率值为的网格。默认情况下,此属性的大小为1x1。

See also GridMesh.

status : enumeration

This property tells the current status of the shaders.

此属性表示着色器的当前状态。

  • ShaderEffect.Compiled - the shader program was successfully compiled and linked.
  • ShaderEffect.Compiled - 着色器程序已成功编译并链接。
  • ShaderEffect.Uncompiled - the shader program has not yet been compiled.
  • ShaderEffect.Uncompiled - 着色器程序尚未编译。
  • ShaderEffect.Error - the shader program failed to compile or link.
  • ShaderEffect.Error - 着色器程序未能编译或链接。

When setting the fragment or vertex shader source code, the status will become Uncompiled. The first time the ShaderEffect is rendered with new shader source code, the shaders are compiled and linked, and the status is updated to Compiled or Error.

​设置片段或顶点着色器源代码时,状态将变为“未编译”。首次使用新着色器源代码渲染ShaderEffect时,将编译和链接着色器,并将状态更新为“已编译”或“错误”。

When runtime compilation is not in use and the shader properties refer to files with bytecode, the status is always Compiled. The contents of the shader is not examined (apart from basic reflection to discover vertex input elements and constant buffer data) until later in the rendering pipeline so potential errors (like layout or root signature mismatches) will only be detected at a later point.

如果未使用运行时编译,并且着色器属性引用具有字节码的文件,则状态始终为已编译。着色器的内容直到渲染管道中的后期才会被检查(除了基本反射以发现顶点输入元素和恒定缓冲区数据),因此潜在的错误(如布局或根签名不匹配)只会在稍后检测到。

See also log.

[since QtQuick 2.4]supportsAtlasTextures : bool

Set this property true to confirm that your shader code doesn't rely on qt_MultiTexCoord0 ranging from (0,0) to (1,1) relative to the mesh. In this case the range of qt_MultiTexCoord0 will rather be based on the position of the texture within the atlas. This property currently has no effect if there is less, or more, than one sampler uniform used as input to your shader.

将此属性设置为true,以确认着色器代码不依赖于相对于网格的范围从(0,0)到(1,1)的qt_MultiTexCoord0。在这种情况下,qt_MultiTexCoord0的范围将基于纹理在图集中的位置。如果用作着色器输入的采样器均匀性少于或多于一个,则此属性当前无效。

This differs from providing qt_SubRect_<name> uniforms in that the latter allows drawing one or more textures from the atlas in a single ShaderEffect item, while supportsAtlasTextures allows multiple instances of a ShaderEffect component using a different source image from the atlas to be batched in a single draw. Both prevent a texture from being copied out of the atlas when referenced by a ShaderEffect.

​这与提供qt_SubRect_<name> uniforms不同,后者允许在单个ShaderEffect项中绘制来自图集的一个或多个纹理,而SupportsAtlastTextures允许在单个绘制中批处理使用来自图集的不同源图像的ShaderEffect组件的多个实例。这两种方法都可以防止纹理被ShaderEffect引用时从图集中复制出来。

The default value is false.

默认值为false。

This property was introduced in QtQuick 2.4.

该属性在QtQuick 2.4中引入。

vertexShader : url

This property contains a reference to a file with the preprocessed vertex shader package, typically with an extension of .qsb. The value is treated as a URL, similarly to other QML types, such as Image. It must either be a local file or use the qrc scheme to access files embedded via the Qt resource system. The URL may be absolute, or relative to the URL of the component.

​此属性包含对带有预处理顶点着色器包的文件的引用,通常扩展名为.qsb。该值被视为URL,类似于其他QML类型,例如图像Image。它必须是本地文件,或者使用qrc方案访问通过Qt资源系统嵌入的文件。URL可以是绝对的,也可以是相对于组件的URL的。

See also fragmentShader.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
QML中,我们可以使用ShaderEffect来实现一些比较复杂的图形效果,包括实现拖尾效果。下面是一个使用ShaderEffect实现拖尾效果的示例代码: ```qml import QtQuick 2.15 Rectangle { id: root width: 640 height: 480 property variant trailImage: "trail.png" property int trailLength: 100 property real trailWidth: 30 property real trailFade: 0.1 Image { id: trail source: root.trailImage visible: false } ShaderEffect { id: effect property real fade: 0.5 property real trailLength: root.trailLength property real trailWidth: root.trailWidth property real trailFade: root.trailFade property variant trailTexture: trail.texture fragmentShader: " uniform lowp float qt_Opacity; uniform sampler2D texture; uniform sampler2D trailTexture; uniform lowp float fade; uniform lowp float trailLength; uniform lowp float trailWidth; uniform lowp float trailFade; varying highp vec2 qt_TexCoord0; void main() { lowp vec4 color = texture2D(texture, qt_TexCoord0) * qt_Opacity; lowp vec4 trailColor = texture2D(trailTexture, vec2(qt_TexCoord0.x, qt_TexCoord0.y - trailLength / textureSize(trailTexture, 0).y)); lowp float trailAlpha = smoothstep(0.0, trailWidth / textureSize(trailTexture, 0).y, abs(qt_TexCoord0.y - trailLength / textureSize(trailTexture, 0).y - 0.5)); color = mix(color, trailColor, trailAlpha * trailFade); gl_FragColor = vec4(color.rgb, color.a * fade); } " property variant source: root property bool running: true NumberAnimation on running { loops: Animation.Infinite from: 0 to: 1 duration: 500 } } MouseArea { anchors.fill: parent onPositionChanged: { if (effect.running) { trail.x = mouse.x - trail.width / 2 trail.y = mouse.y - trail.height / 2 trail.visible = true effect.source = trail } else { trail.visible = false } } } } ``` 这段代码中,我们使用ShaderEffect来实现拖尾效果。首先,在界面中添加一个Image控件,用于显示拖尾样式的图片。然后,创建一个ShaderEffect控件,并设置其fragmentShader属性为一个GLSL着色器程序。该着色器程序会将当前显示的图像和拖尾样式的图片进行混合,以实现拖尾效果。 在着色器程序中,我们使用了一些uniform变量来控制拖尾效果的参数,包括拖尾长度、拖尾宽度、拖尾的淡出程度等。我们还使用了smoothstep函数和mix函数来实现图像和拖尾样式的混合效果。 最后,在界面中添加一个MouseArea控件,用于捕获鼠标移动事件。在鼠标移动时,我们将拖尾样式的图片设置为ShaderEffect的source属性,并将其显示出来。当鼠标停止移动时,我们将拖尾样式的图片隐藏起来。 需要注意的是,以上代码中的trail.png文件需要自己准备一张拖尾样式的图片,并将其放置在与QML文件相同的目录下。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值