# Simulating Lightning on a Computer

I wrote a lightning simulator this week. To get the gif, I generated frames with modified code and merged the frames with Gimp -program. This post describes how to generate such images. Please note that this is unoptimized implementation. It runs very slow.

To understand it, you need to understand first what is it simulating. Lightning bolt is a momentary, conductive channel of plasma. It's a result of a potential difference strong enough to heat the air into plasma and resolving itself via that channel. Single lightning usually contains multiple 'strokes' that each go slightly different path.

The phenomena is continuous and a fractal. Small piece of the bolt is just a copy of the larger piece of the bolt. For computer to simulate it, it needs to be discretized. I implemented the algorithm in two dimensions so I computed it in a grid. The grid cells contains following information:

- Charge at the point
- Is the cell part of the bolt, is it plasma?
- The 'permeability' or 'boundary' at this point.

The bolt is simulated by calculating the charges, picking cells adjacent to the plasma cells and activating one by random, using the charge as the weight:

`cells, totalCharge = plasmaAdjacents()`

`n = random()*totalCharge`

`for cell in cells`

`n -= cell.charge`

`activate cell and return if n < 0`

Once a stroke has reached a ground, the permeability is increased in places where there's plasma, and the simulation is recalculated for the subsequent strokes.

## Laplace's equation

The charges are calculated with Laplace's equation. It was the hardest part to understand in the algorithm yet there are various ways to solve this equation.

To get an approximation, you can run every pixel through this kind of function some hundreds of times:

`updateCharge = (x, y) ->`

`if x, y is plasma`

`charge at this point is 0`

`if x, y is ground`

`charge at this point is 1`

`a = charge x-1, y`

`b = charge x+1, y`

`c = charge x, y-1`

`d = charge x, y+1`

`B = boundary x, y`

`charge at this point (B + a + b + c + d) / 4`

References: