2011-04-23 75 views
6

在決定嘗試使用現代OpenGL進行編程之後,我留下了固定功能管道,並且我不完全確定要獲得與之前相同的功能。使用現代OpenGL進行像素完美紋理映射

我想紋理地圖四邊形像素完美大小,匹配紋理大小。例如,128x128紋理映射到四邊形128x128的大小。

這是我的頂點着色器。

 

    #version 110 
    uniform float xpos; 
    uniform float ypos; 
    uniform float tw; // texture width in pixels 
    uniform float th; // texture height in pixels 
    attribute vec4 position; 
    varying vec2 texcoord;   
void main() 
    { 
    mat4 projectionMatrix = mat4(2.0/600.0, 0.0, 0.0, -1.0, 
            0.0, 2.0/800.0, 0.0, -1.0, 
            0.0, 0.0, -1.0, 0.0, 
            0.0, 0.0, 0.0, 1.0); 

    gl_Position = position * projectionMatrix; 
    texcoord = (gl_Position.xy); 
    } 
 

這是我的片段着色器:

 

    #version 110 
    uniform float fade_factor;  
    uniform sampler2D textures[1]; 
    varying vec2 texcoord; 

    void main() 
    { 
     gl_FragColor = texture2D(textures[0], texcoord); 
    } 
 

我的頂點數據作爲這樣的,其中w和h是紋理的寬度和高度。

 

    [ 
    0, 0, 
    w, 0, 
    w, h, 
    0, h 
    ] 
 

我打開一個128x128的質地和與這些着色器我看到圖像重複4次:http://i.stack.imgur.com/UY7Ts.jpg

可以在正確的道路的人提供建議,以便能夠翻譯和規模給予TW日,XPOS ,xpos制服?

+0

Hello,Lefty!歡迎來到StackOverflow。請記住一些事項 - 請使用四個空格(或使用「{}」圖標)縮進代碼,以便格式正確。另外,當在OpenGL標籤中發佈時,在指定OpenGL版本時很有幫助。特別是因爲你的代碼樣本聽起來像OpenGL 2.0,這確實有用,但今天不是「現代」。 :) – Kos 2011-04-23 13:17:28

+0

感謝您的答覆。這是現代的OpenGL(> = 3?),因爲我沒有使用固定功能流水線,我的頂點數據是以數組形式提供的,紋理採樣是使用着色器完成的。這就是說,我還是比較新的這個,所以糾正我,如果我錯了:) – Lefty 2011-04-23 13:22:55

+0

相關http://stackoverflow.com/questions/7922526/opengl-deterministic-rendering-between-gpu-vendor – 2016-07-13 12:50:34

回答

6

有一個問題是:

mat4 projectionMatrix = mat4(2.0/600.0, 0.0, 0.0, -1.0, 
            0.0, 2.0/800.0, 0.0, -1.0, 
            0.0, 0.0, -1.0, 0.0, 
            0.0, 0.0, 0.0, 1.0); 

gl_Position = position * projectionMatrix; 

轉型matices是右關聯的,即你應該乘相反的順序。您通常也不會在着色器中指定投影矩陣,而是將其作爲統一進行傳遞。 OpenGL爲您提供了投影和模型視圖的準備工作。在OpenGL-3核心中,您可以重新使用統一名稱來保持兼容。

// predefined by OpenGL version < 3 core: 
#if __VERSION__ < 400 
uniform mat4 gl_ProjectionMatrix; 
uniform mat4 gl_ModelviewMatrx; 
uniform mat4 gl_ModelviewProjectionMatrix; // premultiplied gl_ProjectionMatrix * gl_ModelviewMatrix 
uniform mat4 gl_ModelviewInverseTranspose; // needed for transformin normals 

attribute vec4 gl_Vertex; 

varying vec4 gl_TexCoord[]; 
#endif 

void main() 
{ 
    gl_Position = gl_ModelviewProjectionMatrix * gl_Vertex; 
} 

接下來你必須明白,紋理座標不解決紋理像素(紋理元素),但質地應被理解爲與給定的採樣點的插值功能;紋理座標0或1不會撞擊紋理元素的中心,但恰好位於環繞之間,因此模糊。只要屏幕尺寸的四邊形與紋理尺寸完全一致,這就好了。但是,只要你想展示一個子圖像,事情就會變得有趣(我將它作爲練習讓讀者弄清楚確切的映射;提示:你將擁有0.5 /維和(維 - 1)/維在解決方案中)

+0

這可能是這個問題http://stackoverflow.com/questions/34952184/pixel-perfect-shader-in-unity對你來說很簡單,DW! :o – Fattie 2016-01-22 17:04:54