Tuesday, 31 July 2012

Selfish genes and the meaning of life

Using selfish genes to ponder the meaning of life, and what the alternatives might be


Some time ago, I wrote about the meaning of life, and stated that while there doesn't seem to actually be one, that's the way I would prefer it: that any imposed meaning would detract from the wonder of the universe, and that the freedom to decide our own fate is the best of all possible alternatives.

However, that article missed out two fairly important points. First, what does science have to say about a possible meaning to life; and second, from whose point of view are we actually considering there to be a meaning? This post addresses both points.

All the major religions have some concept of a meaning to life, whether it be for our own personal enlightenment or the glorification of some ineffable higher being. These sufficed for a time, but as scientific understanding progressed humans began to ask the ultimate question in earnest: what are we here for? What is it all about? Attempting to answer such questions has driven many branches of science, in order to try and understand the world and our place in it - from a geological explanation of why the land on Earth is as it is, the physics of how the Earth, moon and sun came into being, to attempts to understand the origins of the universe itself.

However, these merely explain the backdrop, and it is to biology that we must turn to understand the origin or purpose of humanity. While explaining meaning and purpose can be considered rather lofty goals, I think that they are actually addressed quite satisfyingly by the explanation of how our species became to be, because in understanding how it happened, we get the answers to why it happened. The primary reason as to why we are here must be evolution: the process of adaptation, survival and selection that led to the emergence of our species over tens of millions of years. This provides a fairly succinct answer of why we are here: because our ancestors were here, and they were good at it.

But to find 'meaning' in this, we need to dig deeper. The mechanics of the process are well understood, but that is not quite the same as the reason it happens - that is, what ultimately drives evolution? Perhaps the best explanation of this is to consider it not from the point of view of species or organisms, but to take the gene's-eye-view of evolution: a perspective which was popularised in the 70s by Richard Dawkins's book The Selfish Gene, and draws on the work of many evolutionary biologists such as W.D. Hamilton and Robert Trivers. The basic idea is that genes are the fundamental unit of selection, and that good genes are ones which confer some advantage to their host, and so are more likely to be passed on to future generations.  This means there is no guiding hand on evolution, nor any sort of 'good-of-the-species' consideration - the only mechanism required is that genes are passed down through the generations, and the gradual development of their host organisms is a consequence. Complex life was never part of a 'plan'; but once the first primitive replicators, whatever form they may have taken, were forced to compete for resources against their neighbours, the race was on to survive.

This is quite important when considering a scientific answer to the meaning of life. The reason that humans, or any other animal, lives, is in order to propagate the genes it carries. If a species is not good at this, it will die out, while genes conferring improved survival are retained, leading to the vast array of incredibly complex survival machines we see today. To the extent that any organism can be seen to have a purpose, it is to reproduce and pass on its genetic material - anything that happens afterwards is largely irrelevant to its genetic legacy, and the diverse and bizarre behaviour of birds, bees, plants, and mammals can be explained by taking this gene-centric, rather than individual-centric, view of life.

But can it really be that the purpose of life is merely to pass it on? Doesn't this seem both self-serving and pointless? In a way, yes, but it is the only answer that makes sense. Genes are passed on simply because they are good replicators, and the evolution of complex life is nothing more than the best way of replicating genetic material. As Dawkins makes plain in his books, this is not because genes are conscious entities with a will to survive, but simply that they are sets of instructions which will be copied, and the best at being copied will be copied more. There is no need for any thought or intelligence in this, merely the mechanism for replication and a criteria (survival) by which fitness is defined; our own success, intelligence, creativity and technological accomplishments are just examples of successful strategies that genes have found to survive, much as claws, echolocation and venom are successful gene transportation mechanisms in other organisms.

Thus the meaning of life can be seen not even as a desire for our own reproduction, but rather as the propagation of genetic material, which is as invisible to us as we transport machines are to the genes themselves. The 'meaning' of all of this is that good genes will be passed on, and our 'purpose' is to facilitate this transfer. We no longer need to ascribe some divine or spiritual intent, or speculate endlessly about what it's all for, because science has provided the most succinct and plausible answer: we are here because it is convenient for genes.

At first glance this may appear somewhat bleak, but as I said before, the absence of any particular meaning is not a problem. If our lives are merely a by-product of low-level replicators, that should not matter: passing on genetic material may be what we are 'for', but it is not all that we can do. We are here, and we can do great things, and whether or not this benefits our genes does not have to matter to us, now that we have evolved the intelligence to comprehend it. Indeed, rather than being slaves to genetic determinism, we can actively work against our genes' best interest, via contraception, care for the weak and sick, life-preserving technologies and genetic engineering. The 'meaning' of our existence is the survival of genes but we have already shown that we can move so much beyond this, and decide our own future. Indeed, it is quite empowering to think of it this way: we have pulled ourselves up from amongst the animal kingdom and into the stars, even though it was never meant to be our purpose. That we have achieved so much without divine intervention or controlling factors is impressive, as I said before; that we did it even though our 'meaning' or 'reason for existing' are nothing to do with it is even better.


Even so, I can imagine some people being uncomfortable with this reductionist view of human existence. Assuming evolution is true (it is), does that mean we have to take the gene's-eye-view of life? Why does that mean we don't have another meaning assigned to our lives, and replication of genes was merely the mechanism by which it was implemented (implausible but worth considering). Does the selfish gene model have to be the only way to think of our purpose, or can there be others?

These questions are worth exploring, because they beg the question of who's point of view the 'meaning of life' is to be evaluated from. There has to be some perspective from which meaning is defined, otherwise it makes no sense as a concept. The universe does not care about us any more than it cares about the collision of rocks in space - and even then, that would be ascribing thought and intention to some abstract entity, even if it is 'the universe' as a whole. So the question of the meaning of life, if not yet answered satisfactorily, must address this: from who's point of view are we asking?

First, consider our own point of view. It is a valid question to ask, from our vantage point as intelligent beings, what our purpose is for being here (so not the scientific reason as above, but what it means to us). However, I would argue that trying to decide our own meaning of life for our own purposes, and having no a priori imposed meaning, are exactly the same, and is basically the situation I described before. So, the question of a meaning of life at this level is resolved in that it doesn't make sense to think that there can be one: we are free.

On the other hand, what other point of view could there be? As I mentioned at the beginning, one historically prevalent concept is that it is from the perspective of a supernatural being that this question must be considered. For example: the meaning of life is to be good, devout, pious, and subservient, from the point of view of God. That would make sense logically, since it is God, not humans, who decide the meaning, and so humans do have a meaning for their lives (even if it isn't a very nice one to think about). Or, to take another example: the meaning of life is to live humbly and compassionately, in order to be re-incarnated in a better situation in a future life from the point of view of whatever karma or divinity makes the decision. The problem with all of these ideas is that they invoke supernatural entities to be the source of meaning and judges of our actions - for this to be the meaning of life, they would need to actually exist. Obviously, no evidence exists for God or any other super-human intelligence, but that is not the point here: my point is that if anyone wants to advance any alternative candidate for the meaning of life, other than the make-it-up-for-ourselves model that I have outlined, based on the indifference of the underlying selfish genes, they must choose a point of view from which this meaning is defined, and provide evidence that it is real.

Image: Jeff Johnson, Hybrid Medical Animation, taken from linked site
So we are left with scientific explanations of the world, which as I said have made considerable progress in understanding why everything is here. To date, the most compelling and convincing explanation of why humans exist is the gene-centric model of evolution: root through all the scientific discoveries which tell us how the universe, this planet, or our species came into being, and this is the theory which goes furthest to tell us why we are here, and what the purpose of our continued existence really is. Given all the possible alternatives, all the variety of ways that meaning could have been assigned, I'm very glad we have one that gives us the option to choose for ourselves; and that we can choose to overrule our genetic programming and to do what we think is right. The selfish gene may be the meaning of life, but what we do with it is up to us.


Sunday, 29 July 2012

Foundation and Patriarchy


This post is about Isaac Asimov and the Foundation series. Before I go further I'll point out that I like Asimov, and greatly value what he has done for science fiction, as well as his contributions to science, science popularisation, skepticism and humanism. If I appear to become quite critical, bear that in mind. Also, Spoiler Alert, for anyone who has not read the Foundation trilogy. So, on with the rant...

I recently finished reading Isaac Asimov's Foundation trilogy, his epic galaxy-spanning tale of conquest, survival and rebellion after the decline and fall of the first galactic empire (I'm focusing on the three books of the original trilogy, not the sequels and prequels he wrote much later). In general, I found the series to be excellent, with many interesting concepts, both in terms of science and how people deal with it. It was fascinating the way that technology, in the first book, is turned into a kind of religion, in order to spread it to people without them being able to understand the science behind it, and then of using it to control those who revere its mystic qualities. There were interesting ideas in the third book concerning mind control, namely if someone was influencing your desires and altering your loyalties, would you be able to tell; and if your mind was compromised in such a way, would you still be the same you? One of the bigger themes, pervading the three books, was the way people might behave if they thought the future was pre-ordained, and the faith and complacency they feel when they believe they are destined to win no matter what.

However, it became obvious mid-way through the first book ('Foundation') that every single one of the characters was male. Not only all of the lead characters, such as the rulers of the Foundation or their adversaries, and the rogueish merchant traders, but pretty much anyone they deal with. In a whole galaxy, that seems a bit lop-sided. There are two exceptions, whose appearance was conspicuous given the obvious omission so far. One of these is the wife of a planetary ruler, acquired for diplomatic purposes, being the daughter of a neighbouring warlord; whose entire dialogue (her existence spans only a few pages) seems to consist solely of nagging at, moaning about, or generally belittling her husband, in some kind of clich├ęd 50s stereotype. The other female character's presence is even more fleeting, her entire purpose being to go "ooh shiny!" when some heroic space-trader presents her with a high-tech necklace. In all, not a particularly flattering or considered portrayal of half the population of the galaxy; and the perception of space as a massive boys' playground was wearing rather thin by the end of the book. Not that any of the men had particularly deep or developed characters though, each being rather single-minded and flat: but that's partly down to the way the book is written, consisting of a series of short segments of the Foundation's history, spaced decades apart.

Things seem to get somewhat better in the second instalment though ('Foundation and Empire'), with the introduction of Bayta Darell (see - I can actually remember her name). She is one of the main characters of the book, albeit primarily because she happens to be the wife of a figure involved in the democratic rebellion. She's a reasonably strong character, though much of her purpose revolves around being the understanding, compassionate, fragile, weak-but-caring trope. Her actions are pivotal to the end of the novel (really, spoiler alert), where her quick thinking (after a few chapters of muddling along) in shooting the old psycho-historian, just on the brink of the big reveal, is pivotal in the development of the whole story arc. So while her actions consist mostly of following her husband from planet to planet and being all wifey, she is at least a female character that exists, with some importance to plot - or so it at least seems, but we'll get to that...


The third book ('Second Foundation'), for the most part, continues in a similar vein, with good old space men zipping around the galaxy being all daring and wise, or plotting their cunning treachery as the plot gets ever more complex, never quite knowing who the good guys are (actually, for most of the book I was convinced there were none). Here is perhaps the best potential for a strong female character, where Arcadia (14 year old daughter of a prominent scientist and grand-daughter of the above-mentioned Bayta) shows some actual courage and determination, eager to be part of the action and basically have an adventure. She goes as far as managing to acquire high-tech listening equipment (in the time-honoured method of flirting with the nerdy kid) to find out what her father and his mysterious associates are up to, then stows away on a ship to see for herself, and to be part of the action. It seems that the female hero has finally arrived, albeit with rather a lot of being scared, followed by pretty much running away to a quiet corner of the galaxy until everything is alright (admittedly she has fairly sound reasons for doing so, but still). She still manages to be quite pro-active in achieving what she needs - namely, getting a message across the galaxy to her father, without knowing who she can trust or who might be under the influence of the mysterious Second Foundation (achieved by profiteering in a massive war, incidentally, but that's fairly standard by now), and so basically saved the day, or so it would appear.

But all this cunning and bravery can't be natural, right? The girls and women can't really be that clever and daring, can they? Indeed, no: and this is the point at which I got properly annoyed about the whole lack-of-actual-women-in-the-whole-of-space thing. It turns out that Arcadia, and Bayta before her, were acting as they did because they too had been under the subtle influence of the Second Foundation. Yes: they only actually showed any initiative, bravery, aggression, or sense to run away because they were being mind-controlled by a conspiracy of psychologists on another planet in order to maintain the thousand-year plan for the next empire. OK, that's all valid plot-wise, and the long time-scale over which the grand plans unfold is a major (and fascinating) theme of the books - but this also gives the impression that Asimov considers women to be pretty much incapable of anything noteworthy, unless they happen to be made artificially heroic by not-entirely-explained psychological manipulation. This third book actually lessens the regard which I had for characters in the second book, when things started to be looking up.

I should mention for completeness that there are a few other women in the third book - the one that is not a fairy bland housewife / maid is the clingy, needy, pathetic mistress of the ruler of a strategically important planet. Her purpose seemed to be to annoy her man with inappropriate pet names and be chastised for it, and desperately latch onto any form of contact with another female. Or so it seemed, for it turned out she was an agent of the Second Foundation, merely playing the part of a pathetic weak-willed hanger-on - her identity is revealed when her disguise slips momentarily, since she considers Arcadia too stupid to notice. So at least women are capable of being lying and manipulative members of this secret and highly advanced gang of psycho-historians.


So in all, the trilogy doesn't paint a very good picture of the author's consideration of women (I'm not saying he hated women, or was fundamentally misogynistic - just that he didn't deem it necessary to actually write any decent ones into these books). Now, obviously, this trilogy was written in the 1950s, so we perhaps shouldn't have too high expectations; it is pretty much contemporaneous with The Lord of the Rings, that other epic trilogy in which women, for the most part, are content with being wives, queens and signposts. But still, this is science fiction, set thousands of years into mankind's (oh, I mean humanity, how did I forget...) future - so the thing which I find most odd is that Asimov, while capable of thinking up the most fantastic vision of the future of the human race, as it spreads out amongst the stars with an array of fabulous technology, assumes that societal organisation will remain totally unchanged. Without exception, all of the societies in the Foundation trilogy, on innumerable planets through five hundred years of history, are modelled in the same patriarchal way as a 50s nuclear family, or worse as dynastic monarchies typical of medieval history and fantasy epics.  Again, this has to be seen in its historical context, but even so there had been vast progress in women's liberation and rights in the decades preceding these books, with women's suffrage, the right to actually be considered human, and the rise of second-wave feminism being reasonably recent occurrences, with progress showing no signs of slowing down by the mid 50s - so I am confused as to why Asimov did not extrapolate this further, or even play with the ideas in the various future cultures he invokes. In fact, Asimov considered himself a feminist, and regarded the education of women as a key need for society, in part in order to reduce the rapidly growing population - so it's not as if he would have been alien to such ideas.

Of course, the above is based entirely upon the three books of the Foundation trilogy. I've not read much else of his work, so it might not be a particularly fair sampling. Indeed, the other three books in the series - added many years later - may redress the imbalance; and I can't vouch for the content of his hour hundred or so other novels. However, it's worth noting that the Foundation trilogy is his best known work, and the books he wrote during that period generally remain his most popular.

One of the only other books by Asimov I've read is The Stars Like Dust, which has quite a similarly disappointing portrayal of women. One of the main characters (I forget her name) is a princess-like daughter of one of the main planetary rulers. As important as her actions may be to the plot, her main purpose seems to be as a love interest to the protagonist, and to tag along on his adventure. From what I recall she isn't portrayed in a particularly enlightening way, with plenty of "oh you know what women are like" moments. The main things I remember about her is that at one point it's necessary to attach a separate living pod onto their tiny spaceship to house her (while being on the run, or on a secretive mission, or generally in a bit of a rush), lest she have to be indecently close to the males present, and because she needs a lot of space because... well, woman stuff, or something. I read Stars Like Dust a few years before Foundation (twice actually, without realising), and remember back then being struck by his less than egalitarian portrayal of the major characters; and so this further bolsters my impression of Asimov's writing having a disappointingly misogynist slant.

Again, this was written about sixty years ago, and so are very much a product of their time - so I don't hold it against Asimov particularly. Then again, as I alluded to above, while his writing, being science fiction, is predominantly about futuristic technology and its consequences (and perhaps can't be expected to do the whole social justice thing as well), science fiction has always really been about people and society; so when quite a large aspect of society is assumed to be completely static, it is quite an obvious omission.

It's interesting to compare Asimov to other science fiction writers of the time. I recently read The Drowned World by J.G. Ballard, and the level of misogyny there was appalling, with the sole female character being generally described as listless, unreasonable, hysterical and generally incapable (often referred to simply as "the girl"). This would have been even more striking if it weren't for the bizarre neuroscience woo pervading the book, and the horrendous levels of blatant, unjustified racism - and so things could definitely be worse. My limited experience of reading Brian Aldiss and Ursula K. Le Guin hinted at some better things, with a sprinkling of key female characters, with no particularly memorable instances of sexism to complain about. Arthur C. Clarke's books (the Odyssey series in particular) fared rather better, with there being plenty of characters involved in the plot, who just happened to be female. This is especially pronounced in the later books (though these were written decades later), set in the near and distant future, where women are spaceship captains, engineers, scientists and so on, without that being a particularly remarkable thing - just as one would hope society would develop, given its trajectory so far.

Even though Asimov's Foundation books were written quite some time ago, and we can perhaps forgive him for merely reflecting the prevailing views of the times, I still think it's something worth mentioning. This is classic science fiction, and has had a big impact on a lot that followed, both in books and film, so it's important to realise what it got wrong as well as what it got right. Given the sexism, racism, and classist attitudes prevalent in many books of the time, and earlier (both in science fiction and in literature in general - I'm looking at you Conrad and Doyle) things could have been worse, but when trying to imagine the far distant future, things could have been better. It's always worth bearing such issues in mind when considering the genre often called 'hard' sci-fi: while it may well appear as scientifically rigorous as possible, it isn't always so thorough in other matters.

Friday, 27 July 2012

Fractal distraction


It seems I've not got around to much writing recently. This is partly because I've been quite busy at work (conference paper - yey), but also because I had something else to get distracted with. Recently, there has been a lot of interesting distraction in my lab with people making fractals, and various other patterns, so I had a lot of fun getting involved with all that - here are some of the results.

It all started when my friend Jack, in a bout of epic procrastination, created a rotating fern-like fractal. We all spent ages gazing in wonder at it - it's mesmerising, especially once he altered it so that its acceleration changed randomly, meaning its was smooth but still totally unpredictable. There are videos of it here.



The problem was that this is written in C++, and uses the OpenCV software library for drawing, so isn't exactly portable to everybody's machines - and while you do get to watch the video, it's the same every time. This is where I came in, with the plan of making it available to anyone: so I re-implemented it in javascript (a browser-based scripting language). This was a bit tricky, since I'd not done any javascript in years, and that was just to flip some images around on links on websites. Fortunately, once I got the hang of drawing a line, it was reasonably straightforward to translate (except for some odd properties of javascript and the way error reporting consists of it simply not working).  My initial implementation can be seen here, from before I worked out how to have lines of different colours (I haven't bothered with the random acceleration, so motion is a bit more jerky as speed randomly changes). [Note - all these examples work in chrome, and maybe newer versions of firefox... anything else, I can't guarantee]


So, a bit of background to how this works: it's a recursive drawing algorithm, which basically means that at each stage, the algorithm does something, then calls itself, and so on indefinitely (up to a certain limit). The basic step is to "draw two branches", where to draw a branch, it draws two more branches. The interesting patterns result from the angle between subsequent branches being passed down the levels, at each level being relative to the one before, which is what leads to the curling effect. It's quite interesting to play with the different parameters, such as the ratio by which the lines get shorter at each level (turns out a scaling of 0.7 is almost always the best; yes we tried the golden ratio.)

Stacks and colours

It's a well-known fact that any recursive algorithm (one that achieves its aim by repeatedly calling itself) can be implemented instead as an iterative algorithm - that is, a more 'normal' one where the instructions are layed out entirely within one function. Obviously, it's not possible to write it all out explicitly (well, it would be very tedious), since it isn't generally known how far deep to go - but this can be achieved using a structure like a queue to store the future branches that need to be explored. So, basically as a programming exercise, this is what I did. Javascript isn't exactly bursting with sophisticated data structures, but I managed to implement it as a stack, where each item in the stack holds the starting position, angle, length, and the depth of the current branch. It can be strange to imagine how an iterative algorithm can produce patterns like this - but basically, the first branch is put onto the stack; then at each iteration of a loop, the last thing on the stack is read off, drawn, and replaced with its two child branches, and so on until the deepest allowed level. Sometimes iterative algorithms can be (much) more efficient than their recursive equivalents - that might be the case here but I've not checked.

In re-writing it I played with a few other things too. Now the speed of the two main branches vary according to sinusoidal functions, so they reliably speed up, slow down, and change direction. This means there's actually no randomness at all, and yet complex and seemingly unpredictable patterns emerge, and you'd have to watch for a long time until it repeats. Mmmm complexity. The main thing that makes this version look nicer is the colours: the colour of each branch is now determined by its angle, by mapping it to a hue wheel. (Briefly: colour can be represented by hue, saturation, and lightness, where hue is a value that cycles from red, through yellow, green etc, finally via purple back to red. Saturation controls how intense the colour is, and lightness is where it sits between black and full colour).

The great thing about writing in javascript is that not only can anyone with a suitable browser see these, but you can also see the code (right click, view source). So feel free to copy it and have a play around; it may not be the most elegantly written piece of code but hopefully should be reasonably self-explanatory.

Clocks

At some point someone mentioned that the two branches rotating around each other at different speeds are a bit like the hands of a clock... and this gave me an idea. Could it be turned into a clock? Well, first it would need three hands, to do it properly and actually see the motion - fortunately this is pretty easy, and in fact the number of branches at each level was just a parameter in the original code. Generally more than two branches just looked a mess though, so for the clock version I altered the length scaling to thin it out. Secondly, the hands on a clock are different thicknesses and different widths - this required a few more parameters to be passed down the levels, to change length and width of the three branches independently (and to make the lines thinner as they get shorter, lest it become a big mess of overlapping lines). That, plus the hour-ticks, and the Fractal Clock is born:



It gets the current time via a javascript function, so it should always be the correct time wherever you are. The motion of each hand is smoothed by getting the exact, fractional number of hours, minutes and seconds, otherwise the hands tick (you can turn this on/off to see it, but I think the smooth version is nicer). You can read the clock pretty much as a normal clock, by basically just looking at the three main arms coming from the centre (the fractal ends don't point to anything in particular) - but if you look closely, at each junction there is another mini-clock, at some other orientation, and so on down the branches.

Again, in this clock, the colours are determined by the angles, where red is up (so the wheel shown above is rotated, but that's because having red=0 at the top makes sense on a clock face). In fact, this means you could tell the time simply from the colours of the three main hands, without bothering to look at their orientation... and this leads inevitably to this, the Hue Clock:


Yes, you can really tell the time from it. Imagine the hue wheel - red corresponds to straight up, so if the hour panel (the left-most) is red, it means it's midnight (or mid day, it's a 12 hour clock). If the second panel is greeny-yellow, it's quarter past the hour; and the third panel goes all the way around the hue wheel once per minute. Now we can finally tell the time with ease! (As I write this it's lawn green past cyan - that image was taken at orange past cyan, earlier in the hour)

Where next for the clock? Is this as minimalist as it can be? Not quite... see, the 'coordinates' of the current time (hour,minute,second), requires three variables. A colour, in the red-green-blue colour space (which is what's used to specify all the colours), needs three variables... you can see where this is going. So here it is, the RGB clock.

Admittedly, it's slightly harder to read the time off it. Basically, the redder it is, the closer it is to midnight (or mid day); the green component gradually increases over the hour, flipping back to no green at :00 (unlike hue, channel brightness is not cyclic); and if you watch it over the course of a minute, the blue component will gradually increase, before going back to 0 at the start of the next minute.

Now that I'd made pretty much the most minimalist clock possible, I moved back to other uses of the fractal. Well, it could have just been a single pixel, but that wouldn't look so good. I probably should have just made it the web page background and got rid of the canvas tag... I'm sure someone else can do that if they want.

The third dimension

The thing that seemed obvious to me with the original fractal is that it's only in two dimensions... and I do like to generalise things. So, my intention since the beginning was to adapt it to 3D. For this, I need some sort of 3D display environment, but didn't want to give up javascript, which doesn't have any sort of 3D environment. So I built one.

The can be done fairly easily because all you actually need to make a 3D environment is the ability to project a point from some 3D coordinate system, to 2D coordinates on the screen. That essentially defines the virtual camera with which you view the world, so you can see things in proper perspective, and freely move around the environment, just by changing the camera parameters. Dealing with the perspective projection of a pin-hole camera is something I've dealt with extensively in my work (it's a rather fundamental concept in computer vision), so now I just needed to use it the other way around, to create a 3D environment as seen from a 2D one. I'd actually done something quite similar before when I implemented a 3D environment with SDL (a basic 2D drawing library), using only a line drawing routine, in pure C (basically to see if I could) - so repeating this in javascript only took a couple of evenings. The biggest job when writing it with SDL one was to write a simple matrix library from scratch, to do all the necessary matrix-vector multiplications... but I realised I this was not strictly necessary, since it was quicker just to hard-code the relevant equations for projection and camera motion.

(Yes, I know I could have used VRML or something, or found some extension for javascript that renders in 3D, or at least matrix algebra; or used some 3D Java in an applet - but I like a challenge, and most of the fun was in proving I could make a 3D environment using only a line-drawing function and no matrix library in pure javascript... that's just the sort of thing I do).

Here's the 3D environment. Basically you can walk around the grid, see some simple, static fractal trees, and play with some particle effects (easy and fun!).


It's quite tempting to turn this into some sort of 3D shooter. Not now.

The simplest thing is to simply put the 2D fractal into some plane in this space - which is quite nice in itself, since then you can walk around and behind it and view it edge-on (this is still possible in the full implementation below).

The next step was to generalise the fern fractal to 3D. This actually required only a few changes: the main one is that the 2D version needs one joint angle per branch, while in 3D, it needs 2 (angle in the plane, and angle out of the plane, is one way to think of it). These two angles define a vector in 3D, which along with a length, specifies the start and end of each line in 3D space. This means that the fern is now fully in 3D, branching out into a volume of a (hemi)sphere, not just a circle. It looks a lot more complicated (it's still completely deterministic), and it's harder to understand what's happening from one view, so it helps to walk around. Controls are explained on the web page, allowing you to change the colour and speed (since there are two angles, one maps to hue, the other to saturation, giving each 3D line a unique colour).


So this is the kind of fun stuff that's been going on in our lab for the last few weeks (I love my lab). What's interesting is that after I ported it to Javascript, we each picked a language to see if we could write it with that - C# was done (that looked very nice); then Visual Basic for Applications (embedded in Microsoft Excel!) was surprising but actually looks great; there was even a cut-down Matlab implementation. It would be fun to try in something a bit more unusual, maybe Lisp, Haskell or assembler. It's a nice way to learn a language, a sort of visual Hello World - I've learned a ton of javascript by doing this, that I'll probably not use again.

That's basically it for the fractals and clocks - I think I've taken them as far as I want to for now (I do actually have work, see). Play with the code and see what you can do. People running Windows can set these to the desktop background (as the active desktop) - having the fractal or hue clocks as the background would be kind of awesome, if not a bit CPU hungry. Android coders might want to make a Hue Clock widget for a phone. It should also be possible to turn these into screensavers, using OpenGL in Linux (my first though on seeing Jack's fractal was "screensaver!" but I don't have the time to get into it right now). Then there's the potential for other types of fractal, or even more dimensions. I'd be interested to know if anyone gets some other adaptations running...