# Generative Art in Swift

### 23 May 2020 ∞

For the past few days I’ve been working on my own Processing-like graphics library built in Swift. I got tired of working in JavaScript, and for lack of a better option, decided that writing my own library would be the way to go.

I didn’t want to simply port Processing into Swift, someone’s already done that. Instead I wanted to make a Swifty-er version that was more protocol and object oriented. Today I got it to a state where it’s functional and I’m happy with how it’s implemented.

One of the main reasons for wanting to build my own library was to make a nicer ray tracing system. I’d made a simple version in P5.js, but the idea of adding more features using JavaScript was… unappealing. After the basics (circles, rectangles) I wanted to add Fresnel lenses.

I tried several methods to figure out the angles. Initially I wanted to use vectors, but bailed on it (because I hadn’t implemented all of the vector math required for the operations) and decided that I should be able to use Pythagorean’s theorem to make a triangle from the line and calculate the angles. This initially worked, but ended up with far too many edge cases, everything from which way the line sloped, to horizontal and vertical lines.

Eventually I went back to the vector math. I knew that it was something that was possible, easy even, because of an example demonstrating non-orthogonal reflection from P5.js. After adding some more vector math operations I was able to reliable determine the angle perpendicular to the Fresnel lens line. This also gave the lens a single direction; it acts as a Fresnel from one side, and a collimating mirror from the other.