Visualizing electrostatic potentials using webgl, web workers and Coffeescript

Here is a webgl applet that draws the field lines and potentials of a distribution of positive and negative charges on a plane. There are two views. The 2D view draws a texture on the plane. The color of the texture at a point is determined by the value of the potential there. The 2D view also shows the lines of force of the field produced by the charges. The 3D view shows the potentials as a height map( I think that's what it is called).

Click on the screenshot below to try out the applet.

I have made an attempt to write this using the model-view design pattern. Actually, it's called the model-view-controller design pattern. But I couldn't find any real need in this case for a controller and so it became the model-view pattern.

The model stores the charge data: the position and sign of every charge placed on the plane. The model also stores the computed potentials and the field lines.

For simplicity, I have the 2D and 3D views as two modes of one logical view. Charges are placed using the mouse in the 2D mode. Every time a charge is placed, the charge information is relayed to the model.

The potential and lines of force calculations are carried out by the model using two web workers. This means that you can keep clicking away furiously and placing charges while the calculations continue in the background. The model notifies the view once the calculations are complete and the view gets updated.

One feature of web workers is that they do not share state with the main thread. Data has to be copied between a web worker and the main thread and all communication between them is through message passing. This means that you cannot interrupt a lengthy web worker calculation because the message handler in the worker thread will not execute until the function that does the lengthy calculation is completed. To work around this limitation, you will have to carry out the worker calculation in small steps and try interrupt it between the steps.

View the source to see the code which is in Coffeescript. The worker code in 'worker.js' was also generated from Coffeescript code.

Acknowledgements

This article for a clear and succinct introduction to the MVC pattern, and, the webgl resource, for almost all my knowledge about webgl.