Ios 来自MTLBuffer发行的MTLTexture

Ios 来自MTLBuffer发行的MTLTexture,ios,fragment-shader,metal,metalkit,mtlbuffer,Ios,Fragment Shader,Metal,Metalkit,Mtlbuffer,我将计算着色器的结果存储在MTLBuffer中。MTLBuffer的每个元素都是一个UInt16。我试图将结果传递给片段着色器,该着色器通过将MTLBuffer的元素解释为0到255之间的颜色强度来显示结果。我使用下面的代码从这个MTLBuffer创建了一个MTLTexture,并将纹理传递给着色器。但是我认为在这个过程中有些东西是不正确的,因为输出是不正确的。我不确定这是否与像素格式和/或格式有关 转换 let textureDescriptor = MTLTextureDescrip

我将计算着色器的结果存储在MTLBuffer中。MTLBuffer的每个元素都是一个UInt16。我试图将结果传递给片段着色器,该着色器通过将MTLBuffer的元素解释为0到255之间的颜色强度来显示结果。我使用下面的代码从这个MTLBuffer创建了一个MTLTexture,并将纹理传递给着色器。但是我认为在这个过程中有些东西是不正确的,因为输出是不正确的。我不确定这是否与像素格式和/或格式有关 转换

    let textureDescriptor = MTLTextureDescriptor()
    textureDescriptor.textureType = .type2D
    textureDescriptor.pixelFormat = .r16Uint
    textureDescriptor.width = bufferWidth
    textureDescriptor.height = 256
    textureDescriptor.usage = [.shaderRead, .shaderWrite]


    let texture = buffer?.makeTexture(descriptor: textureDescriptor, offset: 0, bytesPerRow: bufferWidth*MemoryLayout<UInt16>.stride)
让textureDescriptor=MTLTextureDescriptor()
textureDescriptor.textureType=.type2D
textureDescriptor.pixelFormat=.r16Uint
textureDescriptor.width=缓冲区宽度
textureDescriptor.height=256
textureDescriptor.usage=[.shaderRead、.shaderWrite]
让纹理=缓冲区?.makeTexture(描述符:textureDescriptor,偏移量:0,bytesPerRow:bufferWidth*MemoryLayout.stride)
这是片段着色器代码

   fragment half4 fragmentShaderDisplay (MappedVertex in [[ stage_in ]],
                                              texture2d<ushort, access::sample> lumaTexture  [[ texture(0) ]]
                                              )
{
    constexpr sampler s(t_address::clamp_to_edge, r_address::clamp_to_edge, min_filter::linear, mag_filter::linear);

    float luma = lumaTexture.sample(s, in.textureCoordinate).r/255.0;

    luma = clamp(0.0, luma, 1.0);

   return half4(luma, luma, luma, 1.h);
}
fragment half4 fragmentShaderDisplay(在[[stage_in]]中映射顶点),
纹理2D LUMATEXTRATE[[纹理(0)]]
)
{
constexpr采样器s(t_地址::钳位到_边,r_地址::钳位到_边,最小过滤器::线性,最大过滤器::线性);
float-luma=lumaTexture.sample(s,in.textureCoordinate).r/255.0;
luma=夹具(0.0,luma,1.0);
返回half4(luma,luma,luma,1.h);
}

在什么意义上,您希望将缓冲区值解释为介于0和255之间?它们的固有范围为0到65535,浮点组件的范围通常为0.0到1.0。两者都不是0到255

如果你只需除以65535.0而不是255.0,你会得到你想要的值,一个介于0.0和1.0之间的值

另外,您对
clamp()
的调用似乎是错误的。根据您编写的参数顺序,将常量值0.0限制在
luma
和1.0之间。我想您希望将
luma
限制在0.0和1.0之间


碰巧的是,你写东西的方式基本上是可行的。如果
luma
是,我想解释0和255之间的数字,即使它们高于255,我也希望将它们钳制为255。钳制(x,minVal,maxVal)=min(max(x,minVal),maxVal)。在这种情况下,x和minVal的顺序重要吗?
clamp()
的文档特别指出,如果
minVal
大于
maxVal
或者在代码中使用的术语
luma
大于1.0,则其结果是未定义的。