Custom UV unwrapping for ShaderMaterial

Hi, I want to create a texture in a cube with custom UV unwrapping.

Starting from a cube with MeshStandardMaterial and custom UV in an imported GLTF model (built in Blender), I get the right unwrapping in threejs:

Captura de pantalla 2021-12-02 a las 10.11.25

Then, I replace MeshStandardMaterial by ShaderMaterial:

// MyJavascriptFile.js
createCube(texture)
{
    const mesh = new THREE.Mesh(
        this.geometry,
        new THREE.ShaderMaterial({
            vertexShader: vertexShader,
            fragmentShader: fragmentShader,
            uniforms:
            {
                uTexture: { value: texture }
            }
        })
    )
}

// vertex.glsl
varying vec2 vUv;

void main()
{
    gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1.0);
}

// fragment.glsl
uniform sampler2D uTexture;

varying vec2 vUv;

void main()
{
    vec4 textureColor = texture2D(uTexture, vUv);
    gl_FragColor = textureColor;
}

But the UV unwrapping is wrong:

As far as I know, the UV values are passed by default to vertex shader, right?
So, how do I pass the right UV from geometry to vertex shader?

Hi!
Are you sure that vertex and fragment shaders have to have the same code?

1 Like

Sorry, I copied the wrong code to the question. It is fixed now!

Try this in vertex shader:

void main()
{
    vUv = uv; // add this line
    gl_Position = projectionMatrix * viewMatrix * modelMatrix * vec4(position, 1.0);
}
2 Likes

Yes! I forgot it. Thank you a lot. There is a lot of things to remember… :sweat_smile:

You’re welcome :beers:

1 Like