Three.js/GLSL - Convert Pixel Coordinate to World Coordinate

流过昼夜 提交于 2019-12-23 12:46:59

问题


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?



回答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>



来源:https://stackoverflow.com/questions/20307489/three-js-glsl-convert-pixel-coordinate-to-world-coordinate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!