Question

I have a simple shader in my Three.js application that colors the screen red. However, I want to color all pixels to the right of a given world position to to a different color.

I have seen some answers that suggest using varying vec4 worldCoord = gl_ModelViewMatrix * gl_Vertex;, but since WebGL using GLSLES, variables like gl_Vertex are not available to me.


Vertex Shader

<script type="x-shader/x-vertex" id="vertexshader">
    #ifdef GL_ES
    precision highp float;
    #endif

    void main()
    {
        gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
    }
</script>

Fragment Shader

<script type="x-shader/x-fragment" id="fragmentshader">
    #ifdef GL_ES
    precision highp float;
    #endif

    float worldX = 10.0; //Or some other position in the WebGL world

    void main()
    {
        if(gl_FragCoord.x > worldX) //FragCoord gives me coordinates relative to the screen
        {
            gl_FragColor = vec4(0.0, 1.0, 0.0, 1);
        }

        else
        {
            gl_FragColor = vec4(1.0, 0.0, 0.0, 1);
        }
    }
</script>

Q: How do I convert the position of a pixel to it's world position in WebGL using Three.js?


Was it helpful?

Solution

Answer derived from WestLangley's Fiddle here: http://jsfiddle.net/ST4aM/2/.


Vertex Shader

<script type="x-shader/x-vertex" id="vertexshader">
    #ifdef GL_ES
    precision highp float;
    #endif

    varying float x;
    varying float y;
    void main()
    {
        gl_Position = projectionMatrix * modelViewMatrix * vec4(position,1.0);
        x = position.x;
        y = position.y;
    }
</script>

Fragment Shader

<script type="x-shader/x-fragment" id="fragmentshader">
    #ifdef GL_ES
    precision highp float;
    #endif

    varying float x;
    varying float y;

    void main()
    {
        if(x > somePosition)
        {
            gl_FragColor = vec4(0.0, 1.0, 0.0, 1);
        }

        else
        {
            gl_FragColor = vec4(1.0, 0.0, 0.0, 1);
        }
    }
</script>

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top