如何做紋理混合?
方法是,定義多個QOpenGLTexture,然后在fragment shader中添加相應的變量,然后把texture bind到對應的uniform變量上。
廢話不多說
texture.frag
#version 400 core in vec3 ourColor; in vec2 TexCoord; out vec4 color; uniform sampler2D ourTexture; uniform sampler2D ourTexture1; void main() { color = mix(texture(ourTexture, TexCoord),texture(ourTexture1,TexCoord),0.3); }
最后的0.2是一個混合系數。如果設置為0,則表示完全使用第一個紋理;設置為1,則完全使用第二個紋理。
程序中:
初始化texture
texture = new QOpenGLTexture(QImage("./resources/texture/flower.jpg").mirrored()); texture->setMinificationFilter(QOpenGLTexture::Nearest); texture->setMagnificationFilter(QOpenGLTexture::Linear); texture->setWrapMode(QOpenGLTexture::Repeat); texture1 = new QOpenGLTexture(QImage("./resources/texture/DSCN4391.JPG").mirrored()); texture1->setMinificationFilter(QOpenGLTexture::Nearest); texture1->setMagnificationFilter(QOpenGLTexture::Linear); texture1->setWrapMode(QOpenGLTexture::Repeat);
paintGL中使用:
m_program->setUniformValue("ourTexture", 0); texture->bind(); m_program->setUniformValue("ourTexture1", 1); texture1->bind(1);
這里為ourTexture1指定了一個unit,然后使用bind來把texture賦到指定unit的變量上去。
如果只有一個紋理,那么bind不需要傳參數,默認是0;如果有多個紋理,則需要在bind的時候指定要把當前紋理放到哪個(uniform的)變量中,供fragment shader使用。
結果:
color = mix(texture(ourTexture, TexCoord),texture(ourTexture1,TexCoord),0.3);
原圖:
texture1
texture2
-- the end --