在金属着色语言中创建全局可访问的常量缓冲区

t91*_*t91 2 ios metal


我有一个关于Metal中常量缓冲区的问题。假设我有类似的东西:

...list of includes goes here...

using namespace metal; 

struct ConstantBuffer {
     float ANY_VALUE;
};

struct VS_INPUTS { 
    float4 i_pos_ms [ [ attribute ( 0 ) ] ] ; 
} ; 

struct V2P_STRUCT { 
    float4 v_pos_out [ [ position ] ] ;  
} ; 

float3 CalcSomething() {
    return float3(ANY_VALUE, ANY_VALUE, ANY_VALUE); // !!!!!!!!
}

vertex V2P_STRUCT VertexFunc(VS_INPUTS vs_inputs [ [ stage_in ] ] , 
                             constant ConstantBuffer& cb [ [ buffer (1) ] ] )
{
    V2P_STRUCT vs_outputs;

    vs_outputs.v_pos_out.xyz = CalcSomething();
    vs_outputs.v_pos_out.w = cb.ANY_VALUE; // that's OK

    return vs_outputs;
}
Run Code Online (Sandbox Code Playgroud)

是否可以在不传递ANY_VALUE作为输入参数的情况下调用CalcSomething()?
例如,在DX11或OpenGL中,您将创建常量缓冲区,可以从着色器代码中的每个位置访问常量缓冲区。

我考虑将“ cb”的内容复制到临时全局对象中,但是我不知道该怎么做(由于地址空间恒定)。

另一个想法是在全局范围内以某种方式声明“ cb”(但不幸的是[[buffer]]仅用于参数)。有什么窍门吗?

t91*_*t91 5

解决我的问题的方法:

#include <metal_stdlib> 
#include <metal_graphics> 
#include <metal_texture> 
#include <metal_matrix> 
#include <metal_math> 
#include <metal_geometric> 
#include <metal_common> 

using namespace metal; 

constant float MyVariable = 4;

struct ConstantBuffer 
{
    float ANY_VALUE;
};

struct VS_INPUTS { 
    float4 i_pos_ms [ [ attribute ( 0 ) ] ] ; 
}; 

struct V2P_STRUCT { 
    float4 v_pos_out [ [ position ] ] ;  
}; 

struct VertexShader 
{
    thread VS_INPUTS& vs_inputs;
    thread texture2d<float> img;

    constant ConstantBuffer& cb;

    VertexShader(thread VS_INPUTS& inputs, constant ConstantBuffer& b, thread texture2d<float>& texture) 
        : cb(b) 
        , vs_inputs(inputs)
        , img(texture)
    {}

    float3 CalcSomething() {
        return float3(cb.ANY_VALUE, cb.ANY_VALUE, cb.ANY_VALUE); // !!!!!!!!
    }

    V2P_STRUCT majn()
    { 
        V2P_STRUCT vs_outputs;

        vs_outputs.v_pos_out.xyz = CalcSomething();
        vs_outputs.v_pos_out.w = cb.ANY_VALUE * vs_inputs.i_pos_ms.x * MyVariable; // that's OK

        return vs_outputs;
    }
};

vertex V2P_STRUCT VertexFunc(VS_INPUTS vs_inputs [ [ stage_in ] ] , 
                         constant ConstantBuffer& cb [ [ buffer (1) ] ] ,
                         texture2d<float> img [[ texture(0) ]]
                         )
{
    VertexShader vs(vs_inputs, cb, img);
    return vs.majn();
}
Run Code Online (Sandbox Code Playgroud)

我创建一个包含整个原始着色器的结构。参数作为对构造函数的引用传递。任何函数都可以从常量缓冲区读取,而无需接收大量参数。为了解决ANY_VALUE问题,该问题现在已成为cb的一部分,我使用了宏:

#define ANY_VALUE cb.ANY_VALUE.
Run Code Online (Sandbox Code Playgroud)