Wednesday, May 9, 2018

Recursion and Stackoverflow

Hi all,

Just thought I'd share a little incident that happened while I was working on Particularly Wavy yesterday. I had a light source on the left, and two light splitters on the right. When I tried testing this level, as soon as the two light splitters were setup as in the picture below, my speakers would explode as they tried to play hundreds of sound effects at the same time. Then Unity would freeze just after giving me a stackoverflow exception error. I tried the same level several times before giving up because I had some errands to run.

As I was walking to the train station to run those errands, I finally figured out what was happening. The way that light splitters work is when light hits one, we check if the light ray has hit this splitter before. If it has, then we just update its children, which involves using a function called Emit. If it has not hit the splitter before, we create two children: one which passes through the splitter, and a second which reflects off the surface. After creating those two children, we run Emit on them. The kicker is that we use Emit to determine what type of object we have hit, so the HitSplitter function can be called from Emit.

If you haven't got what was happening, here it is: When light hits the first splitter, it creates two children, one of which passes through and hits the second splitter. This also creates two children, one of which passes through, while the other reflects back to hit the first splitter. Here, again, we create two children, one which bounces back to hit the second splitter. And I think that's enough. Basically, I had created a situation where light would bounce back and forth an infinite number of times, or as close to infinite as your computer can handle before crashing the program.

The solution to this is as simple creating the problem in the first place: I was already keeping track of the "depth" of the light ray, or how many times it had bounced or split from the light source, so just checking whether this number is less than a limit, say, 20, prevents infinite recursion.

In any case, I now have 75 puzzles set up and earlier this week created two new game mechanics, but they need more testing and debugging to make sure they work correctly.

No comments:

Post a Comment