Search code examples
loopsrecursiondirectcompute

How to unwrap this recursive function into a loop?


I'm writing a simple diffuse path tracer in DirectCompute for education. DirectCompute doesn't allow recursive functions, so I need to figure out how to turn this recursive statement into a loop:

intersectCode() {

    // ... intersection code 

    if(hit an object)
        return objectHit.diffuse * (intersectCode() + objectHit.emittance);
}

Generic pseudo-code or C example would be really appreciated


Solution

  • object = initialObject;
    objectStack = new ObjectStack();
    do {
        objectStack.push(object);
        // get new intersected object as object
    
    } while (object);
    
    result = 0;
    while (object = objectStack.pop()) {
        result = object.diffuse * (result + object.emittance);
    }
    
    return result;
    

    You might want to adjust that, because all details are not known - for example, maybe initObject does not have to be in stack?