iosrecursionmetal

Recursion in Metal ios


Does Metal shading language support recursion? I have code :

 Intersection traceScene(Ray ray, int step) {
    Intersection retIntersection = Intersection();
    Intersection i1 = trianglePrism.intersect(ray);
    Intersection i2 = image.intersect(ray);
    if (i1.intersect) {
        Ray newRay = Ray(i1.position, Refract(ray.direction, trianglePrism.normal, 0.71));
        return traceScene(newRay, step + 1);
    } else {
        if (i2.intersect) {
            return i2;
        } else {
            return Intersection();
        }
    }
    return retIntersection;
}

But when i build kernel function which use it, it occur error. Any ideas?


Solution

  • Update

    Metal has supported recursive function calls in compute kernel contexts since Metal 2.4 released ~2021. Prior to that it did not support them. (Also note more recent versions are based on C++14 rather than C++11 from the original answer).

    Original answer

    The Metal shading language is based on C++ 11 but with some specific extensions and restrictions. One of the restrictions is that recursive function calls are not allowed so the short answer is no, you can't do this.

    I won't paste in the complete list of differences since I don't know how likely to change it is but they are covered in the section 'Metal and C++ 11' in Apple's Metal Shading Language Guide.