【问题标题】:Moving an image using Metal shader使用金属着色器移动图像
【发布时间】:2021-06-29 10:05:15
【问题描述】:

我正在尝试编写一个简单的金属着色器以在 Swift 中使用,它会拍摄一张照片并将其从左向右移动。假设我想要图片 x 以 screenwidth - image.size.width 开始并移动 x 直到 image.x = screenwidth.x。我使用了 Metalpetal,我的代码扭曲了图像。

         fragment float4 SimplePanFragmentRight(VertexOut vertexIn [[ stage_in ]],
                                    texture2d<float, access::sample> fromTexture [[ texture(0) ]],
                                    texture2d<float, access::sample> toTexture [[ texture(1) ]],
                                    constant float & scale [[ buffer(0) ]],
                                    constant float & rotations [[ buffer(1) ]],
                                    constant float2 & center [[ buffer(2) ]],
                                    constant float4 & backColor [[ buffer(3) ]],
                                    constant float & ratio [[ buffer(4) ]],
                                    constant float & progress [[ buffer(5) ]],
                                    sampler textureSampler [[ sampler(0) ]])
     {
     float2 uv = vertexIn.textureCoordinate;
     uv.y = 1.0 - uv.y;
     float _fromR = float(fromTexture.get_width())/float(fromTexture.get_height());
     float _toR = float(toTexture.get_width())/float(toTexture.get_height());
     float t = 1.0;
     float pro = progress / 0.25;
     // hence bad code
     uv = adjustPos( uv, pro);
    // ****
  return mix(
         getFromColor(uv, fromTexture, ratio, _fromR),
         getToColor(uv, toTexture, ratio, _toR),
         t);
   }

而我操纵 x 位置的“简单函数”是

     float2 adjustPos(
             float2 uv, float amount) {
      uv.x = uv.x * amount;
     return uv;
  }

如何根据进度比移动线性 x 位置而没有任何图像失真?

【问题讨论】:

  • 你不应该这个数量而不是相乘吗? uv.x = uv.x + amount

标签: swift metal metalkit


【解决方案1】:

您想在 vertex 着色器中而不是在 fragment 着色器中进行顶点转换。基本上,vertex 着色器是模型(图像)顶点发生变换的地方,这可能是因为您移动了“相机”(即改变视角),也可能是因为物体在环境中移动。输入时,网格坐标将位于您的图片坐标或虚拟世界坐标中,具体取决于您调用着色器的方式。您将其转换为相对于视锥体的坐标(即相对于相机的位置、方向和方向)。对于 2-D 渲染,您通常可以忽略平截头体坐标的 z 部分(只需将其设置为 0,因此它正好在视图平面上),这使其与屏幕坐标相同。

fragment 着色器是您对图像本身进行效果的地方,例如模糊、颜色映射、纹理映射等...

【讨论】:

    猜你喜欢
    • 2015-11-24
    • 1970-01-01
    • 2015-09-05
    • 1970-01-01
    • 1970-01-01
    • 2018-04-21
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    相关资源
    最近更新 更多