【问题标题】:Metal + ARKit — Get z distance to current fragment in fragment shaderMetal + ARKit — 在片段着色器中获取到当前片段的 z 距离
【发布时间】:2021-03-21 18:58:46
【问题描述】:

我有一个金属着色器(为 ARKit 应用程序编写为 SCNProgram),它获取从 smoothedSceneDepth 捕获的当前场景的深度图。我想使用捕获的深度信息来丢弃位于真实世界对象后面的任何虚拟对象的部分。但是,我无法在我的着色器中获得预期的片段深度。

这是我的基本片段着色器:

struct ColorInOut {
    float4 position [[ position ]];
    float2 depthTexCoords;
};

fragment float4 fragmentShader(
    const ColorInOut in [[ stage_in ]],
    depth2d<float, access::sample> sceneDepthTexture [[ texture(1) ]]
) {
    constexpr sampler textureSampler(mag_filter::linear, min_filter::linear);
    
    // Closest = 0.0m, farthest = 5.0m (lidar max)
    // Seems to be in meters?
    const float lidarDepth = sceneDepthTexture.sample(textureSampler, in.depthTexCoords);
 
    float fragDepth = // ??? somehow get z distance to the current fragment in meters ???

    // Compare the distances
    const float zMargin = 0.1
    if (lidarDepth < fragDepth - zMargin) {
         discard_fragement()
    }

    ...
}

我的理解是片段着色器中的position.z 应该在最接近=0 到最远=1 的范围内。但是,当我尝试使用当前的相机平面将其转换回现实世界的距离时,结果似乎不对:

const float zNear = 0.001;
const float zFar = 1000;

float fragDepth = in.position.z * (zFar - zNear);

当我使用return float4(fragDepth, 0, 0, 1); 调试着色器时,红色在我最接近对象时最亮,然后在我后退时消失。即使我使用fragDepth = 1 - fragDepth,深度似乎也与lidarDepth不同。

这里使用1 - fragDepth:

(我也尝试使用来自 this answer 的映射,但无法正常工作)

所以我的问题是:

  • in.position.z 在什么坐标系中?

  • 如何将in.position.z 转换为一个深度值,以便与我已经拥有的捕获的深度信息进行比较? (反之亦然)

【问题讨论】:

  • « 即使我使用fragDepth = 1 - fragDepth,深度似乎与lidarDepth 不同 » 它们有多大不同?你有截图吗?你试过用SCNSceneBuffer的inverseProjectionTransform吗?
  • 有一个相当硬的边缘,深度从全黑到中间红色。我已经添加了这个截图。如果fragDepth 以米为单位,这应该更加渐进。核心问题是我不知道in.position.z 在哪个坐标空间中,因为我根本不希望1 - fragDepth 是必需的

标签: ios scenekit arkit metal


【解决方案1】:

好的,我还没有完全说服自己以下解决方案是正确的,但它似乎适用于我非常基本的应用程序:

在顶点着色器中,我写出眼睛空间中的位置:

// in vertex shader
out.fragEyePosition = scn_node.modelViewTransform * float4(in.position, 1.0);

在片段着色器中,我可以使用-in.fragEyePosition.z 进行深度测试:

// in fragment shader

float depth = -in.fragEyePosition.z;

const float zMargin = 0.1;
if (lidarDepth - depth < -zMargin) {
    discard_fragment();
}

...

我希望能解释一下为什么会这样以及为什么我之前使用.position 的尝试没有(或者如果我这里的解决方案有问题,请更正)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-08-30
    • 2019-01-24
    • 1970-01-01
    • 2021-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多