1

I'm trying to write a ray tracer in julia but my main function returns StackOverFlowError. Below is my main function:

function trace(ray::Ray, surfaces::Array{Any, 1}, depth::Int64, maxDepth::Int64)
    material, t = findIntersection(ray, surfaces, Inf)
    if typeof(material) == Empty
        Vec3(0,0,0)
    end
    if depth > maxDepth
        Vec3(0,0,0)
    end
    if material.isLight == true
        material.emittance
    end
    normal = material.normal
    ρ = material.reflectance
    BRDF = ρ/3.14159
    R = randHemi(normal)
    cosθ = dot(R,normal)
    newRay = Ray(ray.s + t*ray.d, R)
    In = trace(newRay, surfaces, depth+1, maxDepth)
    2.0*3.14159*BRDF*In
end

And here is my intersection function:

function findIntersection(ray::Ray, surfaces::Array{Any, 1}, tmin::Float64)
    hitSurface = Empty(Vec3(0,0,0), Vec3(0,0,0), Vec3(0,0,0), false)
    for surface in surfaces
        t = intersect(surface, ray)
        if t < tmin
            hitSurface = surface
            tmin = t
        end
    end
    return hitSurface, tmin       
end

But I receive this error:

StackOverflowError:

Stacktrace:
 [1] findIntersection(::Ray, ::Array{Any,1}, ::Float64) at .\In[31]:10
 [2] trace(::Ray, ::Array{Any,1}, ::Int64, ::Int64) at .\In[33]:2
 [3] trace(::Ray, ::Array{Any,1}, ::Int64, ::Int64) at .\In[33]:18 (repeats 
 14493 times)
 [4] top-level scope at In[35]:1

What is the cause of error?

Oscar Smith
  • 5,766
  • 1
  • 20
  • 34
bitWise
  • 699
  • 5
  • 11

2 Answers2

3

Your problem is that you missed a return. What you meant to have was

if depth > maxDepth
    return Vec3(0,0,0)
end

Without the return, that line just allocates a Vec3, and the code continues looping.

Oscar Smith
  • 5,766
  • 1
  • 20
  • 34
0

Stackoverflow error usually occurs when there are too many recursive calls. In a nutshell, in most programming languages there is a limit on how many recursive calls you can make.

In your example, the trace functions calls itself recursively and it can cause an stack overflow. You have a parameters maxDepth that can limit that. Setting it to a lower value will probably solve this particular issue.

Isaac
  • 2,332
  • 6
  • 33
  • 59
  • It's strange because maxdepth = 3 and depth = 0, but I received this error. Sorry for my English. – bitWise Sep 25 '19 at 14:36