2017-05-10 31 views
0

這種金屬着色器是根據設在這裏如何在金屬片段着色器中動態渲染目標尺寸?

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

它把頁面上的第3圖像中看到的淡黃色和藍色漸變的教程。 enter image description here

我這個着色器的目標是得出這樣使用片段/頂點對,而不是計算着色器。

此着色器的結果是由MTKView的在MacOS的夫特遊樂場一個子類可見。

着色器代碼:

#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); 
} 

迅速頂點和索引代碼:

 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 
     ] 

最終圖像的尺寸被硬編碼的,400×400。有沒有辦法動態獲取渲染目標維度?

回答

1

我不知道一種方法來直接查詢渲染目標的尺寸從片段函數。

一種技術是通過緩衝區傳遞尺寸。應用程序代碼將使用渲染目標紋理的屬性填充該緩衝區。您已經爲您的timer參數有效地做到了這一點。你會擴大這個。例如:

struct params 
{ 
    float timer; 
    uint2 size; 
}; 

然後,params &params在函數的參數列表替換float &timer。將函數體中的timer的用法替換爲params.timer。使用params.size而不是resolution

您的應用程序代碼將,當然,要改變它是如何設置緩衝區0是合適的尺寸和佈局的結構,用定時器和渲染存儲到它的目標尺寸。

我想這也將努力在通過渲染目標的紋理作爲參數的函數(通過渲染指令編碼器的碎片質地表)。你的片段函數會聲明另一個參數,如texture2d<float, access::read> rt [[texture(0)]],以接收該紋理參數。然後,您可以撥打rt.get_width()rt.get_height()以獲取其尺寸。

+0

謝謝你......我想我會用紋理方法 –

相關問題