My hatred of C and C++ is world renown, or at least it should be. It's not that I hate the languages themselves, but the ancient build chain. A hack of compilers and #defines that have to be modified for every platform. Oh, and segfaults and memory leaks. The usual. Unfortunately, if you want to write fast graphics code you're pretty much going to be stuck with C or C++, and that's where Amino comes in.

Amino, my JavaScript library for OpenGL graphics on the Raspberry Pi (and other platforms), uses C++ code underneath. NodeJS binds to C++ fairly easily so I can hide the nasty parts, but the nasty is still there.

As the Amino codebase has developed the C++ bindings have gotten more and more complicated. This has caused a few problems.

3rd Party Libraries

First, Amino depends on several 3rd party libraries; libraries the user must already have installed. I can pretty much assume that OpenGL is installed, but most users don't have FreeType, libpng,or libjpeg. Even worse, most don't have GCC installed. While I don't have a solution for the GCC problem yet, I want to get rid of the libPNG and jpeg dependencies. I don't use most of what the libraries offer and they represent just one more thing to go wrong. Furthermore, there's no point is dealing with file paths on the C++ side when Node can work with files and streams very easily.

So, I ripped that code completely out. Now the native side can turn a Node buffer into a texture, regardless of where that buffer came from. Jpeg, PNG, or in-memory data are all treated the same. To decompress JPEG and PNGs I found two image libraries, NanoJPEG and uPNG, (each a single file!), to get the job done with minimal fuss. This code is now part of Amino so we have fewer dependencies and more flexibility.

I might move to pure JS for image decoding in the future, as I'm doing for my PureImage library but that might be very slow on the PI so we'll stick with native for now.

Shaders Debugging

GPU Shaders are powerful but hard to debug on a single platform, much less multiple platforms. As the shaders have developed I've found more differences between the Raspberry Pi and the Mac, even when I use ES 2.0 mode on the Mac. JavaScript is easier to change and debug than C++ (and faster to compile on the Pi), so I ripped out all of the shader init code and rewrote it in JavaScript.

The new JS code initializes the shaders from files on disk instead of inline strings, as before. This means I don't have to recompile the C++ side to make changes. This also means I can change the init code on a per platform basis at runtime rather than #defines in C++ code. For speed reasons the drawing code which uses the shaders is still in C++, but at least all of the nasty init code is in easier to maintain JS.

Input Events

Managing input events across platforms is a huge pain. The key codes vary by keyboard and particular locale. Further complicating matters GLFW, the Raspbian Linux Kernel, and the web browser also use different values for different keys, as well as mouse and scroll events. Over the years I've built key munging utilities over and over.

To solve this problem I started moving Amino's keyboard code into a new Node module: inputevents. It does not depend on Amino and will, eventually, be usable in plain browser code as well as on Mac, Raspberry PI, and wherever else we need it to go. Eventually it will support platform specific IMEs but that's a ways down the road.

Random Fixes and Improvements

Since I was in the code anyway, I fixed some alpha issues with dispmanx on the Pi, made opacity animatable, added more unit tests, turned clipping back on, built a new PixelView retained buffer for setting pixels under OpenGL (ex: software generation of fractals), and started using pre-node-gyp to make building the native parts easier.

I've also started on a new rich text editor toolkit for both Canvas and Amino. It's extremely beta right now, so don't use it yet unless you like 3rd degree burns.

That's it for now. Enjoy, folks.

Carthage and C++ must be destroyed.

I recently added the ability to set individual pixels in Amino, my Node JS based OpenGL scene graph for the Raspberry Pi. To test it out I thought I'd write a simple Mandlebrot generator. The challenge with CPU intensive work is that Node only has one thread. If you block that thread your UI stops. Dead. To solve this we need a background processing solution.

A Simple Background Processing Framework

While there are true threading libraries for Node, the simplest way to put something into the background is to start another Node process. It may seem like starting a process is heavyweight compared to a thread in other languages, but if you are doing something CPU intensive the cost of the exec() call is tiny compared to the rest of the work you are doing. It will be lost in the noise.

To be really useful, we don't want to just start a child process, but actually communicate with it to give it work. The childprocess module makes this very easy. childprocess.fork() takes the path to another script file and returns an event emitter. We can send messages to the child through this emitter and listen for responses. Here's a simple class I created called Workman to manage the process.

var Workman = {
    count: 4,
    init: function(chpath, cb, count) {
        if(typeof count == 'number') this.count = count;
        console.log("using thread count", this.count);
        for(var i=0; i<this.count; i++) {
            this.chs[i] = child.fork(chpath);
    sendWork: function(msg) {

Workman creates count child processes, then saves them in the chs array. When you want to send some work to it, call the sendWork function. This will send the message to one of the children, round robin style.

Whenever a child sends an event back, the event will be handed to the callback passed to the workman.init() function.

Now that we can talk to the child processes it's time to do some drawing.

Parent Process

This is the code to actually talk to the screen. First the setup. pv is a new PixelView object. A PixelView is like an image view, but you can set pixel values directly instead of using a texture from disk. w and h are the width and height of the texture in the GPU.

var pv = new amino.PixelView().pw(500).w(500).ph(500).h(500);

var w =;
var h =;

Now let's create a Workman to schedule the work. We will submit work for each row of the image. When work comes back from the child process the handleRow function will handle it.

var workman = Workman;
var scale = 0.01;
for(var y=0; y<h; y++) {
    var py = (y-h/2)*scale;
    var msg = {
        iw: w,
Notice that the work message must contain all of the information the child needs to do it's work: the start and end values in the x direction, the y value, the length of the row, the index of the row, and the number of iterations to do (more iterations makes the fractal more accurate but slower). This message is the only communication the child has from the outside world. Unlike with threads, child processes do not share memory with the parent.

Here is the handleRow function which receives the completed work (an array of iteration counts) and draws the row into the PixelView. After updating the pixels we have to call updateTexture to push the changes to the GPU and screen. lookupColor converts the iteration counts into a color using a look up table.

function handleRow(m) {
    var y = m.iy;
    for(var x=0; x<m.row.length; x++) {
         var c = lookupColor(m.row[x]);
var lut = [];
for(var i=0; i<10; i++) {
    var s = (255/10)*i;
function lookupColor(iter) {
    return lut[iter%lut.length];

Child Process

Now let's look at the child process. This is where the actual fractal calculations are done. It's your basic Mandelbrot. For each pixel in the row it calculates a complex number until the value exceeds 2 or it hits the maximum number of iterations. Then it stores the iteration count for that pixel in the row array.

function lerp(a,b,t) {
    return a + t*(b-a);
process.on('message', function(m) {
    var row = [];
    for(var i=0; i<m.iw; i++) {
        var x0 = lerp(m.x0, m.x1, i/m.iw);
        var y0 = m.y;
        var x = 0.0;
        var y = 0.0;
        var iteration = 0;
        var max_iteration = m.iter;
        while(x*x + y*y < 2*2 && iteration < max_iteration) {
            xtemp = x*x - y*y + x0;
            y = 2*x*y + y0;
            x = xtemp;
            iteration = iteration + 1;
        row[i] = iteration;

After every pixel in the row is complete it sends the row back to the parent. Notice that it also sends an iy value. Since the children could complete their work in any order (if one row happens to take longer than another), the iy value lets the parent know which row this result is for so that it will be drawn in the right place.

Also notice that all of the calculation happens in the message event handler. This will be called every time the parent process sends some work. The child process just waits for the next message. The beauty of this scheme is that Node handles any overflow or underflow of the work queue. If the parent sends a lot of work requests at once they will stay in the queue until the child takes them out. If there is no work then the child will automatically wait until there is. Easy-peasy.

Here's what it looks like running on my Mac. Yes, Amino runs on Mac as well as Linux. I mainly talk about the Raspberry Pi because that's Amino's sweet spot, but it will run on almost anything. I chose Mac for this demo simply because I've got 4 cores there and only 1 on my Raspberry Pi. It just looks cooler to have for bars spiking up. :)


This code is now in the aminogfx repository under demos/pixels/mandle.js.

A post about Arthur Whitney and kOS made the rounds a few days ago. It concerns a text editor Arthur made with four lines of K code, and a complete operating system he’s working on. These were all built in K, a vector oriented programming language derived from APL. This reminded me that I really need to look at APL after all of the language ranting I’ve done recently.

Note: For the purposes of this post I’m lumping K, J, and the other APL derived languages in with APL itself, much as I’d refer to Scheme or Clojure as Lisps.

After reading up, I’m quite impressed with APL. I’ve always heard it can do complex tasks in a fraction of the code as other languages, and be super fast. It turns out this is very true. Bernard Legrand's APL – a Glimpse of Heaven provides a great overview of the language and why it’s interesting.

APL is not without it’s problems, however. The syntax is very hard to read. I’m sure it becomes easier once you get used to it, but I still spent a lot more time analyzing a single line of code than I would in any another language.

APL is fast and compact for some tasks, but not others. Fundamentally it’s a bunch of operations that work on arrays. If your problem can be phrased in terms of array operations then this is awesome. If it can’t then you start fighting the language and eventually it bites you.

I found anything with control structures to be cumbersome. This isn’t to say that APL can’t do things that require an if statement, but you don’t get the benefits. This code to compute a convex hull, for example, seems about as long as it would be in a more traditional language. With a factor of 2, at least. It doesn’t benefit much from APL’s strengths.

Another challenge is that the official syntax uses non-ASCII characters. I actually don’t see this as a problem. We are a decade and a half into the 21st century and can deal with non-ASCII characters quite easily. The challenge is that the symbols themselves to most people. I didn’t find it hard to pick up the basics after reading a half hour tutorial, so I think the real problem is that the syntax scares programmers away before they ever try it.

I also think enthusiasts focus on how much better APL is than other languages, rather than simply showing someone why they should spend the time to learn it. They need to show what it can do that is also practical. While it’s cool to be able to calculate all of the primes from 1 to N in just a few characters, that isn’t going to sell most developers because that’s not a task they actually need to accomplish very often.

APL seems ideal for solving mathematical problems, or at least a good subset of them. The problem for APL is that Mathematica, MathLab, and various other tools have sprung up to do that better.

Much like Lisp, APL seems stuck between the past and the future. The things it’s really good at it is too general for. More recent specialized tools to the job better. APL isn't general enough to be good as a general purpose language. And many general purpose languages have added array processing support (often through libraries) that make them good enough for the things APL is good at. Java 8 streams and lambda functions, for example. Thus it remains stuck in a few niches like high speed finance. This is not a bad niche to be in (highly profitable, I’m sure) but APL will never become widely used.

That said, I really like APL for the things it’s good at. I wish APL could be embedded in a more general purpose language, much like regular expressions are embedded in JavaScript. I love the concept of a small number of functions that can be combined to do amazing things with arrays. This is the most important part of APL — for me at least — but it’s hidden behind a difficult notation.

I buy the argument that any notation is hard to understand until you learn it, and with learning comes power. Certainly this is true for reading prose.

Humans are good pattern recognizers. We don’t read by parsing letters. Only children just learning to read go letter by letter. The letters form patterns, called words, that our brains recognize in their entirety. After a while children's brains pick up the patterns and process them whole. In fact our brains are so good at picking up patterns that we can read most English words with all of the letters scrambled as long as the first and last letters are correct.

I’m sure this principle of pattern recognition applies to an experienced APL programmer as well. They can probably look at this


and think: pick six random numbers from 1 to 40 and return them in ascending order.

After a time this mental processing would become natural. However, much like with writing, code needs spacing and punctuation to help the symbolic "letters" form words in the mind of the programmer. Simply pursuing compactness for the sake of "mad skillz props" doesn’t help anyone. It just makes for write-only code.

Were I to reinvent computing (in my fictional JoshTrek show where the computer understands all spoken words with 200% accuracy), I would replace the symbols with actual meaningful words, then separate them into chunks with punctuation, much like sentences.


would become
deal 6 of 1 to 40 => x, sort_ascending, index x

The symbols are replaced with words and the ordering swapped, left to right. It still takes some training to understand what it means, but far less. It’s not as compact but far easier to pick up.

So, in summary, APL is cool and has a lot to teach us, but I don’t think I’d ever use it in my daily work.


Since writing this essay I discovered Q, also by Arthur Whitney, that expands K’s terse syntax, but I still find it harder to read than it should be.

I am unhappy to announce the release of Electron 0.4 beta 3.

What's that? unhappy?! Well......

I haven't done a release quite some time. Part of this delay is from a complete refactoring of the user interface; but another big chunk of time comes from trying to build Electron with Atom Shell.

AtomShell is a tool that bundles WebKit/Chromium and NodeJS into a single app bundle. This means developers can download a single app with an icon instead of running Electron from the command line. It might even let us put it into the various app stores some day.

Unfortunately, the switch to AtomShell hasn't been as smooth as I would like. The Mac version builds okay but I have yet to get Windows to work. There seems to be some conflict between the version of Node that the native serial port module uses and the version of Node inside of AtomShell. While I'm sure these are solvable problems I don't want to hold back the rest of Electron. It's still useful even if you have to launch it from the command line. So...

Electron 0.4 beta 3

You can download a Mac .app bundle from here, or check out the source and run node electron to start it from the command line. The new file browser works as do the various dialogs. Compiler output shows up in the debug panel. You can upload through the serial port but the serial port console is still disabled (due to other bugs I'm still working through).

Undoubtedly many things are still broken during the transition from the old UI to the new. Please, please, please file issues on github. I'll get to them ASAP.

Thanks, Josh

I have a problem. Sometimes I get something into my head and it sticks there, taunting me, until I do something about it. Much like the stupid song stuck in your brain, you must play the song to be released from it's grasp. So it is with software.

Last week I had to spend a lot of time in Windows working on a port of Electron. This means lots of Node scripts and Git on the command line.

Windows Pains

It may sound like it sometimes, but I really don't hate Windows. It's a fine GUI operating system but the command shell sucks. Really, really bad. Powershell is an improvement but still pretty bad. There has to be something better. I don't want to hate myself and throw my laptop across the room while coding. It dampens productivity. This blog was the result of that rage face. I tiny birdy told me things will get a lot better in Windows 10. I sure hope so.

In the past I would have used Cygwin, which is a port of Bash and a bunch of unix utilities. Sadly it never worked very well (getting POSIX compliant apps to run on Windows is just a big ball of pain) and support has dwindled in recent years.

Then something happened. After pondering for a while I realized I didn't actually care about having standard Unix utilities. Really I just want the Bash interface. I want a command line interpreter that has a proper history, tab completion, and directory navigation. I want ls and more and cd. I don't actually care if they are spec compliant and can be used in Bash shell scripts. I don't really care about shell scripts at all, since I write everything in Node now. I just want the interface.

I could make a new shell, something simple that would get the job done. Node is already ported to Windows, it's built around streams, and NPM gives me access to endless existing modules. That's 90% of the work already done. I just need to stitch it together.


And so Photon was born.

Photon is about 250 lines of Javascript that give a command line with ls, cp, mv, rm, rmdir, mkdir, more, pwd, and the ability to call other programs like git. It has a very simple form of tab completion (rather buggy), and uses ANSI colors and tables for formatting. (For some reason there are approximately 4.8 billion ANSI color modules for Node).

All you need to do is npm install -g photonsh then photonsh to get this:

Photon Shell screenshot

Most features were trivial to implement. Here is the function for cp.

    cp: function(a,b) {
        if(!fs.existsSync(a))         return fileError("No such file: ",a);
        if(!fs.statSync(a).isFile())  return fileError("Not a file: ",a);
        var ip = fs.createReadStream(path.join(cwd,a));
        var op = fs.createWriteStream(path.join(cwd,b));

Pretty much exactly what you would expect. For the buffered editor with history I used Node's built in readline module which includes callbacks for tab completion.

The hard part

The grand irony here is that I wrote it because of my Windows pain but have yet to actually run it on Windows. I stopped that Windows porting effort for other reasons; so now I just have this program I randomly wrote. Rather than waste the man-months of effort (okay, it was really only about 3 hours), I figured something like this should be shared with the world so that others might learn from my mistakes.

Speaking of mistakes, Photon is horribly buggy and you probably shouldn't run it. No really, it could totally delete your hard drive and stuff. More importantly, Node TTY support is iffy. It turns out Unix shells are very hard to write because of lots of semi-documented assumptions. Go try to write Xterm sometime. There's a reason few people have done it.

In theory a unix shell is simple. You exec a program and pipe it's output to stdout until it's done. The same with input. But what about buffering? But what about ANSI codes? But what about raw keyboard input? Apparently there is a whole world of adhoc specs for how command line apps do 'interactive' things. Running grep from exec is easy. Running vim is not.

In the end I found pausing Node's own REPL interface then execing with the 'inherit' flag worked most of the time. I'm sure there's a better way to do it, but casual Googling with Bing hasn't found it yet.


So where does Photon go from here? I have no idea. There's tons of things you could do with it. Node can stream anything, so copying a remote URL to a local file should be trivial. Or you could build a text mode raytracer. Whatever. The choice is yours. Choose wisely. Or don't. The code will still be here (on github).