如何在Metal片段着色器中动态获取渲染目标的尺寸?

6
这个金属着色器基于此处的教程。

http://metalkit.org/2016/10/01/using-metalkit-part-2-3-2.html

它绘制了页面上第三张图中看到的黄蓝渐变。 enter image description here 我的目标是使用片段/顶点对而不是计算着色器来绘制此着色器。
这个着色器的结果通过一个MTKView的子类在MacOS Swift Playground中可见。
着色器代码:
#include <metal_stdlib>
using namespace metal;

struct Vertex {
    float4 position [[position]];
    float4 color;
};

vertex Vertex vertex_func(constant Vertex *vertices [[buffer(0)]],
                      uint vid [[vertex_id]]) {
    Vertex in = vertices[vid];
    Vertex out;
    out.position = float4(in.position);
    out.color = in.color;
    return out;
}

fragment float4 fragment_func(Vertex vert [[stage_in]],
                          constant float &timer [[buffer(0)]]) {

    float4 fragColor;

    int width = 400;
    int height = 400;

    float2 resolution = float2(width,height);

    float2 uv = vert.position.xy * 0.5 / resolution;

    float3 color = mix(float3(1.0, 0.6, 0.1), float3(0.5, 0.8, 1.0), sqrt(1 - uv.y));

    fragColor = float4(color,1);

    return(fragColor);
}

Swift顶点和索引代码:

        let vertexData = [
            Vertex(pos: [-1.0, -1.0, 0.0,  1.0], col: [1, 0, 0, 1]),
            Vertex(pos: [ 1.0, -1.0, 0.0,  1.0], col: [0, 1, 0, 1]),
            Vertex(pos: [ 1.0,  1.0, 0.0,  1.0], col: [0, 0, 1, 1]),
            Vertex(pos: [-1.0,  1.0, 0.0,  1.0], col: [1, 1, 1, 1])
        ]

        let indexData: [UInt16] = [
            0, 1, 2, 2, 3, 0
        ]

最终图像的尺寸被硬编码为400x400。是否有一种方法可以动态获取渲染目标的尺寸?
1个回答

3

我不知道有没有一种方法可以直接从片段函数中查询渲染目标的尺寸。

一个技巧是通过缓冲区传递尺寸信息。应用程序代码将使用渲染目标纹理的属性填充该缓冲区。您已经为timer参数有效地执行了此操作。您可以扩展它,例如:

struct params
{
    float timer;
    uint2 size;
};

然后,在您的函数参数列表中将float &timer替换为params &params。在函数体中使用params.timer替代对timer的使用。使用params.size替代resolution
当然,您的应用程序代码必须更改如何设置缓冲区0,以使其成为适当大小和布局的结构体,并将计时器和渲染目标尺寸存储到其中。
我认为还可以通过渲染命令编码器的片段纹理表将渲染目标纹理作为参数传递给函数(通过参数传递)。您的片段函数将声明另一个参数,例如texture2d<float, access::read> rt [[texture(0)]],来接收该纹理参数。然后,您可以调用rt.get_width()rt.get_height()来获取其尺寸。

谢谢...我想我会采用纹理方法。 - Chester Fritz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接