Help end child hunger

GLSL Core Tutorial – Statements and Functions

Prev: Data Types Next: Subroutines
 

Control Flow Statements

The available options are pretty much the same as in C. There are conditional statements, like if-else, iteration statements like for, while and do-while.

if (bool expression)
	...
else
	...

for (initialization; bool expression; loop expression)
	...

while (bool expression)
	...

do
	...
while (bool expression)

A few jumps are also defined:

  • continue – available in loops, causes a jump to the next iteration of the loop
  • break – available in loops, causes an exit of the loop
  • discard

The discard keyword can only be used in fragment shaders. It causes the termination of the shader for the current fragment without writing to the frame buffer, or depth.

Functions

As in C a shader can be structured in functions. Each type of shader must have one main function declared with the following syntax:

void main()

User defined functions may be written. As in C a function may have a return value, and should use the return statement to pass out its result. IN GLSL a function can also declare its parameters as outputs of the function. The return type can have any type, except an array.

The parameters of a function have the following qualifiers available:

  • in – for input parameters
  • out – for outputs of the function. The return statement is also an option for sending the result of a function.
  • inout – for parameters that are both input and output of a function

If no qualifier is specified, by default it is considered to be in.

A few final notes:

  • A function can be overloaded as long as the list of parameters is different.
  • Recursion behavior is undefined by specification.

An example of a function concludes this subsection.

vec4 toonify(in float intensity) {

	vec4 color;
	if (intensity > 0.98)
		color = vec4(0.8,0.8,0.8,1.0);
	else if (intensity > 0.5)
		color = vec4(0.4,0.4,0.8,1.0);
	else if (intensity > 0.25)
		color = vec4(0.2,0.2,0.4,1.0);
	else
		color = vec4(0.1,0.1,0.1,1.0);		

	return(color);
}

 

Prev: Data Types Next: Subroutines
 

Leave a Reply

(required)

(required)


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

© 2014 Lighthouse3d.com Suffusion theme by Sayontan Sinha