Part of the Khronos Group
OpenGL.org

The Industry's Foundation for High Performance Graphics

from games to virtual reality, mobile phones to supercomputers

Results 1 to 3 of 3

Thread: If command not working in the fragment shader

Hybrid View

  1. #1
    Newbie Newbie
    Join Date
    Nov 2012
    Posts
    2

    If command not working in the fragment shader

    I'm fairly new to GLSL but all seems to work except one if. I'm trying to use the following code in the fragment shader:

    [some code here]
    void main (void)
    {
    if (enablelighting) {

    [some code here]

    for (int i=0; i<numused; i++)
    {
    if (lightposn[i].w != 0.0) {vec3 position = lightposn[i].xyz / lightposn[i].w ;}
    vec3 direction = normalize (position - mypos) ;

    [some code here]
    }
    } else {
    [some code here]
    }
    }

    Since it is a homework I'm not allowed to post complete codes, so I cut out the parts, which are not so important.
    If I try to run it I get the "0:70(39): error: `position' undeclared" error (though I'm sure lightposn[i].w is not zero). If I put "if (true)" I still get the same error What is really strange is that I have an if at the beggining which works perfectly. I also tried if (enablelighting) inside the for loop and still have the same error.

    If I delete the if command the code works perfectly (but I need it, because I have to deal with lights having zero w component).

    Why the if command works at the beggining at the code but not inside the for?

  2. #2
    Member Regular Contributor
    Join Date
    Aug 2008
    Posts
    450
    It's a scope issue, you would get the same problem with:
    Code :
    {vec3 position = vec3(1,0,0);}
    vec3 direction = normalize (position - mypos);
    because "position" is only visible inside the code block surrounded by "{"+"}".
    To be able to access "position" you need to declare it before the brackets:
    Code :
    vec3 position;
    if (...) {position = ...;} else {position = ...;}
    vec3 direction = normalize (position - mypos)

  3. #3
    Newbie Newbie
    Join Date
    Nov 2012
    Posts
    2
    Thanks a lot!
    Now my code works perfectly.

    (I indeed got the same problem with only the brackets which should have made me think a little bit harder...)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •