Bounce ray casting recursion problem

Hello!

TLDR;
trying to add recursive bounces to a raycasting algorithm
first set of rays works, subsequent ones sort of work but are very buggy indeed.

I’m working on a 2D ray casting idea based on my hero Dan Schiffman’s coding train. His project was to emit rays and have them be blocked by “walls”, thus casting shadows. He did it in p5.js. I have got an equivalent thing working in regular processing.

I want to add bounces to the rays. I have it half working, here’s a video:

It looks quite cool but you may notice that when the light source is completely enclosed by boundaries, some rays still leak out. And if you reduce the number of rays significantly, it’s clear that it’s wigging out a lot.

I’ve rewritten most of it since then but I still can’t find the bug. I’m a beginner/intermediate python programmer and very novice with java. I’m sure there are many, many bad things about the way I’ve structured this…

Since it’s got 3 files here’s the full code as a zip:

The concept is thus:

An array list of Wall objects, which gets passed to:

A Ray class that gets a source position and a vector, searches for intersections with the walls along that vector, finds the closest one, and draws a line from the source to that intersection; ( this part ~works)

It then calculates the reflection vector of the incoming ray against the wall, and starting from the intersection point of the previous step, recursively creates a new Ray along that vector, until a maximum recursion depth limit is reached.

The rays are emitted in all directions from the mouse cursor with a given interval in degrees, which is a global variable in the main sketch.

I know the reflection math is working, because if I draw a simple line of arbitrary length from the intersection point along the reflection vector it works as expected.
22
The first set of ray objects behave as expected, and with no bounces it works perfectly.

However, when I emit a new reflected ray instead of a line, it goes a bit bananas. I’m really struggling to debug it.

Sorry for the super long question. Any help greatly appreciated, both in terms of this problem and any advice on how to structure things properly in java!

Thanks

If anyone ever comes across this issue in a search, the problem was that the new rays were emitting from inside the line they were supposed to be reflected from which was causing them to immediately detect intersection with their own point of origin. Solution was to move the point of reflection very slightly towards the original emission point.