4

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?


gman
  • 100,619
  • 31
  • 269
  • 393
Dragonseer
  • 2,874
  • 7
  • 29
  • 42
  • 1
    See if this helps you: http://stackoverflow.com/questions/19776554/three-js-a-vertex-shader-to-color-based-on-location-of-pixel-on-screen/19781424#19781424 – WestLangley Dec 01 '13 at 01:21
  • @WestLangley: Your first Fiddle on the question is closer to what I'm looking to accomplish. I was able to derive the solution from it. See my answer below. Thanks! – Dragonseer Dec 01 '13 at 02:33

1 Answers1

1

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>

Dragonseer
  • 2,874
  • 7
  • 29
  • 42
  • 2
    That may be the answer you want but it is not an answer to the question you asked – gman Aug 27 '17 at 15:18