Wednesday, January 7, 2009

And easy way to make for loops unrollable

Cg will let you use for loops in your shaders, but only if they can be unrolled. Though it loses you the performance benefits of loop unrolling, you can make a for loop unrollable by moving the guard (or "are we done yet?" check) into the loop body.

For example:

int arr[] = {2, 1, 3};
for (int i = 1; i < arr[0]; i ++) {
doStuff(arr[i]);
}

That snippet gives an error like this when you try to compile it:
frag.cg(71) : error C5013: profile does not support "for" statements and "for" could not be unrolled.

Instead, try the following:

int arr[] = {2, 1, 3};
for (int i = 1; i < MAX_LEN; i ++) {
doStuff(arr[i]);
if (i == arr[0])
break;
}


EDIT:
Or better yet, just do this:

int arr[] = {2, 1, 3};
for (int i = 1; i < MAX_LEN && i < arr[0]; i ++) {
doStuff(arr[i]);
if (i == arr[0])
break;
}


Note that I found order to be important (it didn't like arr[0] before MAX_LEN).

1 comment:

Jérémie St-Amand said...

Holy shit you saved my life.