There was a problem in my code in my two js1k entries for this year (this and this). They weren’t showing the bee’s wings in latest Chrome - that I installed just today - and it was reported of having other problems in Firefox nightly. Note that by the time you read this, the organizer of js1k might have updated the code with my bug-fix and it might look right again.

So what was the problem? For js1k size coding, it is very common to try to save every single byte/character as possible, even if it results in ugly and/or unreadable code. One of the ways to do it is by placing code inside function calls without parameters, just to avoid the use an additional semicolon. So I had this:

a.fill( /* some code here */ );

With a being a Canvas 2D Context. So, why it is not working on the latest browsers right? The reason is simple: Canvas 2D Context spec is just a working draft, the draft changed and the new browsers are adapting to it.

Previous, the fill method had a single functionality, and no parameters. Now fill accepts an optional path parameter. Without parameters it works as previously, with parameters it doesn’t.

So, the bug-fix was easy; just to place the code inside fill outside it. I believe this problem will be happening in more than one js1k entries, as it is a very common size optimization.

For the latest editon of Js1k contest (a contest to create something cool with only 1 kilobyte of Javascript), I’ve submitted an entry with a furry bee with springy antennae and my tie. Check it here.

I’ve been pushing the limits of what is possible to render with canvas 2d. As a result, it renders at decent speed only in Chrome with a very fast computer. In case you don’t have one, check out this video capture:

Rendering fur

For rendering the fur, I’ve used the same method as I previously used in the Christmas Tree I made for a previous js1k edition.The basic idea is to create sprites that represent handfuls of fur, and then draw those sprites/brushes thousands of times to create the body of the bee.

For this entry I’ve enhanced and reduced in code size the sprite generation method used in the Christmas Tree, also making it better suited for fur. Now it generates multiple sprites with different sizes and colors.

Color palette

Creating a nice color palette with the 1kb limitations of js1k is not an easy task. I wanted to have nice gradients with colors switching hue from red/orange/brown to yellow for the bee’s body, and it is very expensive in size to do it with RGB color space. Fortunately, browsers support the HSL space, that makes much easier the generation of nice gradients.

This piece of code is generating the palette, including the grays needed for the tie:

‘hsla(’+[(j&15)*8-x,(j&15)*6+x+’%',(j<17)*60+(j&15)*7+’%',1]+’)’

Point cloud rendering

The spring in the antennae and the tie are rendered with a point cloud rendering method. It consists in representing 3d points in space as little dots (and/or pixels) in the screen. If they are dense enough in the screen, all space will be covered and it will look like a full surface.

Taking advantage of the same rendering code of the fur, and that I have little fur sprites available, I use them to render the point clouds without the need of additional code.

Clouds rendering

The image above is very descriptive of the process I’ve used for rendering the clouds. Again, the fur sprites are being reused to render clouds. I render 16 of those sprites with perspective transform, translating them in z, and recycling them when they are not visible anymore.

This results in the 3d cloudscape in the background. I have a gradient in the background from cyan to white. The clouds slowly move from top to the bottom, into the white area, and as they are white too, they seem to disappear. At this point is when I recycle them to create a new cloud.

Generating the sprite positions of the bee’s body

The body, stripes and eyes of the bee are non-uniformly scaled spheres. Fur sprites are drawn at multiple points in the surface of those spheres. So there is the need to generate those points in the surface of a sphere.

To make the fur look good, we need the points in the sphere to be well distributed. The ideal for render quality and rendering speed - due the need of less sprites - would be a Poisson disc sampling in a sphere, but it is too expensive, both in pre-computation time and in byte size. So I tried with the simpler uniform random sampling.

Generating uniform random sampling in a sphere surface, while it might sound simple, it is a world of its own with dozens or hundreds of different well known methods. I tried with a good amount of them, the shorter in byte size ones, and figured out the shorter is Normalize and Discard.

It consist in generating a random number between -1 and 1 for each x, y and z coordinate. That would set up uniform random point inside a cube with center at (0, 0, 0) and width=2. Then, we compute its vector magnitude, and discard the points for which magnitude is bigger than 1, that means only points inside a sphere radius 1 will remain. Finally, we normalize the vector (dividing x, y and z by its magnitude) and we project this way the point from the inside to the surface of the sphere.

It is both a very simple and short in size method. However, js1k is very restrictive in size, each byte counts, so I needed to shorten it. So I discarded the idea of a uniform random sampling and opted for just some random sampling.

The first try was just to remove the discarding, and so leaving just the Normalize method. That would just project points from a cube to the surface of the sphere. Unfortunately the distribution is awful as you can see in the interactive illustration above, and it was clearly visible in the fur.

So the next idea, and the one finally used was to perform 2 Euler rotations. As advantages it is shorter in code size, the distribution of points is near 20% denser in the low density areas than Normalize and it has only 2 high density points at the poles.

Finally, I will leave to the reader the option to analyze why Math.cos(i * y) is a rough and low quality approximation of Math.cos(random() * Math.PI * 2), where random is an LCG.

Wings with artistic motion blur

To make the wings looks good (as any very fast moving object), there is a strong need for motion blur.

A real honey bee flaps its wings during flight more than 200 times per second, that should be enough to make them look fully motion blurred and seemingly static with solar light conditions. Well, I’ve to say this is just what I suspect, I’ve not tried to look at a real one; I’ve a strong entomophobia, so I’m sorry, real bees are not my friends. But I like honey. Anyway :P. Oh, and I really hope bees to recover soon from the colony collapse disorder making them disappear so fast in the latest years. Nature (us included) would have a really hard impact without them, it is both amazing and somewhat scaring how such a little animal is so important for the stability of the whole system.

I was writing about motion blur and wings, right? Ok, so… motion blur, motion blur… ah, yes! If I were to represent wings as they are in reality, they would not look as having movement at all, because they would have a full motion blur. That would not be cool at all. So the next option is to represent them with my artistic vision of the motion blur they should have.

It was about adjusting the motion blur to cause sensation of movement, but a movement not so fast it is it is distracting or even annoying. Doing it required a huge amount of trial, mostly because of the size limitations of the compo. It ended pretty close to my artistic vision, so I’m very happy with them.

From a technical stand-point, they are multiple filled cubic bezier curves drawn on top of each other with a very low opacity.

Size optimizations

Furbee was compressed with jscrush, and so a lot of size optimizations were targeted to it. Jscrush is specially effective if you repeat as often as possible, so I used a lot of different reusable patterns for that purpose.

Using the less as possible different keywords is really important with Jscrush, so I limited myself to a very limited subset:

I’m using the canvas context object as array to avoid the creation of a new variable and array and most of the common byte saving techniques, that are well described in this post from my good friend Claudio Cañete.

And finally, I use quantization for the bee’s body data. Well… to tell you the truth, I’m not even sure if quantization is the best word to describe it or not… but I’m going to call it like that. For the spheres that create body and eyes I have these parameters:

- Center x position of the sphere

- Center y

- Center z

- Brush size

- A flag to determine is the sphere is stripped or not

- Scale x

- Scale y

- Scale z

- Initial color for gradient

- Final color for gradient

- Gradient color dithering level

Eleven properties and a total of 6 spheres: body, stripes, 2 eyes and 2 pupils. So, 66 properties in total, thinking in clear numbers comma separated from 0 to 300, and averaging around 3 bytes per property, gives us a total of around 200 bytes of data.

A usual trick in js1k is to package data as string characters, that could reduce up to by half (depending on the data) the size, but in the case of that little amount of data as I had, the depackaging code was too big to compensate it.

So, I opted for quantization and lossy compression of it. As an example, suppose I have this code:

[33,11,66,121,22,77,88,55,132][i];

As all numbers are divisible by 11, I can safely do this:

[3,1,6,11,2,7,8,5,12][i]*11;

The size is lower, and the result is the same. Now, suppose I have instead of 132, that I have 133 in the last position:

[33,11,66,121,22,77,88,55,133][i];

Now, not all values are divisible by 11. But suppose that 133 value represents the width of the body sphere. Nobody will notice the difference between width 132 or 133, so this is the lossy compression part I’ve used. So, I end with the same quantization:

[3,1,6,11,2,7,8,5,12][i]*11;

I used this method carefully by hand tuning it to maintain the nice proportions and design of the bee while taking the less space as possible.

Rotation of the bee

The bee rotates with 2 degrees of freedom. Well… not. It just looks like that, but it is just a little trick. In fact it has a 1 degree of freedom for the y rotation axis and 1 degree of freedom for skew. For little angles, the skew is a reasonably good a approximation to rotation, so it does the trick. And it takes just 6 or 7 extra bytes.

Furbee inspector

My best friend Jan Carlo Mityorn has been really supportive during the development of this entry. He has been pushing me hard to make it better and better, and also he provided a lot of help testing it for performance on different computers. Thank you Jan!

So, he asked me for a bee where he could see the wireframe, rotate and play a bit with it. I’ve coded a special version of the bee without size limitations, that renders several times faster than the original so Jan Carlo is able to play in his old computer, so here it is:

If you are reading this post, you probably know about the love themed js1k competition. I tried to submit a new entry before the deadline on March 14th, but I failed to do it.

I was able to complete it on time, but I noticed a couple of problems during the last minute, so I told Kuvos, organizer of js1k to cancel its release.

The first and most notable problem was speed. I developed the thing on my recently bought high-end PC, and I had the error of not testing it on any older machine during development. In the new PC everything was fast and full framerate, but then I tested in my other machines, I noticed it was overkill, unacceptably slow and totally killing the visual effect.

Be warned that even the low res version might be too much for some old computers and for some browsers. And note it is a bit over 1kb, but it fits in less than 1kb after using JSCrush by aivopaas.

Ok, now I’m going to try to describe a bit what I did:

Making a texture

Perlin noise is specially well suited for clouds, as the own Ken Perlin explains in this presentation (a totally recommended read). Just to summarize how to go from Perlin noise to something resembling clouds:

The only problem with Perlin noise for js1k entries is that a perlin noise implementation is a bit too big for 1kb. It fits in 1kb, but it would not leave too much room for other code.

So I tried to make a texture similar to Perlin noise but by other method: a random walk. In the Wikipedia article about it you will find nice animations showing how it works. The only difference in my implementation, is that I don’t fill a full pixel at each position the walk traverses, but I just a bit, just like if I were using a non-full opacity brush, and this way it ends pretty similar to Perlin.

Random walk implementation details

The random walk needs a PRNG (pseudorandom number generator). As I wanted to create a cloud scene being always the same, I needed a PRNG with the ability to set its seed, and this way creating always on each run the same serie of (pseudo) random numbers.

Now a little problem was that Javascript’s Math.random doesn’t have the possibility to set the seed (not to mention each Math.random implementation would probably produce different results even with the same seed). So, I needed to implement my own PRNG, and to maintain it as little as possible… in js1k each byte counts.

This was my first implementation of the random walk with its own PRNG in 74 bytes:

It takes 11 bytes more up to 85, and we would not have set Math.cos in a single letter variable for posterior use as in the previous example, so in the end it is like occuping around 20 bytes more (a lot in js1k size terms). But it always renders this exact same result across all browsers:

Please note that the PRNG I created here is of extremely low quality, so while it is valid for my purpose it is not recommended for use in anything else. Search for high quality Javascript implementations of PRNGs with configurable seed - like Mersenne twister - if you need one for your own projects.

I use the noise texture again to decide where to paint a cloud brush. If the texture at (x, y) is above a threshold level, I paint the brush at a position determined by x and y.

I consider y determine how far are the clouds. Further brushes are painted first so nearer are painted on top. To add a perspective sensation, further clouds are painted littler than nearer ones.

Finally, since I’m using only one brush, if it is repeated along a totally straight line it would be very noticeable the repetition causing visible linear patterns. What I do is to use again the noise texture to offset a bit the final positionto paint the brush, and this way I avoid those visual artifacts.

Parallax displacement

Drawing the clouds scene takes almost all the time in the precomputation process, several seconds in the high resolution version even in a high end computer, so it is not possible to render it realtime with canvas right now.

What I did was to pre-render it into several layers (multiple canvases). I used 22 in the high res version, 11 in the low res version. Each layer contains a big amount of brushes painted on it, grouped by the distance to the camera:

Moving the layers at different speeds, as I explained it in the CSS 3D Meninas post, cause the parallax 3d effect.

Heart-shaped rainbow

Could I have been more kitsch? Not sure, but it fits the love theme of the competition.

What I did was to draw multiple bezier curves, all with very few opacity and some displacement to cause the blurry effect common in rainbows and I used a canvas lighter composite operation to enhance its realism.

I’ve participated in the love themed 4th edition of js1k. My submission is a static image, a procedurally generated 3d rose. You can take a look of it here.

It is made by Monte Carlo sampling of explicit piecewise 3d surfaces. I’m going to try to explain all a bit in this article.

A short note on Monte Carlo methods

Monte Carlo methods are incredible powerful tools. I use them all the time, for a lot of kinds of function optimization and sampling problems, and they are almost like magic when you have more CPU time than time for designing and coding algorithms. In the case of the rose, it was very useful for code size optimization.

As you can see, as you sample more and more dense, points get closer and closer, up to the density when the distance from a point to their neighbours is littler than a pixel, and the surface is fully filled on screen (see 0.01). After that, making it more dense doesn’t cause much visual difference, as you will be just drawing on top of areas that are already filled (compare results of 0.01 and 0.001).

Ok, now lets redefine the surface function to draw a circle. There are multiple ways to do it, but I will use this formula: (x-x0)^2 + (y-y0)^2 < radius^2 where (x0, y0) is the center of the circle:

As I said, there are different ways to define a circle, and some of them doesn’t need rejection in the sampling. I’m going to show one way, but just as a note; I will not keep using it later in the article:

Ok, now this looks much more like the shape of a petal of a rose. I suggest you to play a bit with deformations. You can use any imaginable math function you want, add, subtract, multiply, divide, sin, cos, pow… anything. Just experiment a bit modifying the function, and lots of shapes will appear (some more interesting, some less).

Now I want to add some color to it, so I’m going to add color data to the surface:

I will place my camera at (0, 0, cameraZ), I will call “perspective” to the distance from the camera to the canvas. I will consider my canvas is in the x/y plane, centered at (0, 0, cameraZ + perspective). Now, each sampled point will be projected into the canvas:

A z-buffer is a pretty common technique in computer graphics, useful to paint points closer to the camera on top of points that have been painted further to it. It works by maintaining an array with the closer z drawn per pixel of an image.

This is the visualized z-buffer of the rose, with black as far to the camera, white close to it.

I’ve been using during the article interval based sampling. It requires the setting of a proper interval for each surface. If the interval is big, it render fast but it can end with holes in the surface that has not been filled. On the other hand, if the interval is too little, the time for rendering increments up to prohibitive quantities.

Now, a and b parameters are set as 2 random values. Sampling enough points, the surface will be complete filled this way. I’m drawing 10,000 points each time and then letting the screen update thanks to the interval.

As a side note, the full filling of a surface is only ensured if the pseudorandom number generator is of good quality. In some browsers, Math.random is implemented with a linear congruential generator, and this may lead to problems with some surfaces. If you are in the need of a good PRNG for sampling, you can use high quality ones like Mersenne Twister (there are JS implementations for it), or the cryptographic random generators available in some browsers. It is also very advisable to use low-discrepancy sequences.

Final notes

To complete the rose, each part of the rose, each surface, is rendered at the same time. I added a third parameter for the function that selects the part of the rose to return a point from. Mathematically it is a piecewise function, where each piece represents a part of the rose. In the case of the petals, I used rotations and streching/deformation to create all the petals. Everything is done with by mixing the concepts exposed in the article.

While sampling explicit surfaces by sampling is a very well known method, and one of the oldest methods for 3d graphics, my approach of piecewise/Monte Carlo/z-buffer has been probably very few times used for artistical purposes the way I did. Not exactly very innovative, and not useful in real life scenarios, but it fits very good in the context of js1k where simplicity and minimal size are desirable.

With this article I really hope to inspire readers interested in computer graphics to experiment and have fun with different rendering methods. There is a whole world in graphics, and it is amazing to research and play on it.

I’ve decided to sell this blog, domain and content. It is a very personal blog, as it contains my surnames (Roman Cortes), but it is already popular and it would be perfect for SEO purposes. I’ve PR5 and PR6 blog posts, and a good amount of visitors per day.Since it is so personal, I’m selling also, as a pack, my Twitter account, my Gmail account, Facebook account, my Spanish ID and my passport.The starting price is $1 USD. If you are interested, please write a comment here and/or send me a message to my contact form. I could sell you also some of my clothes and anything you would need to assume my personality.

Several of Motorola Mobility engineering teams will be at the Mobile World Congress in Barcelona from February 14 to 17 for a recruiting event. We are looking for passionate and very high profile web developers. Send CV to TalentAcquisition@Motorola.com for consideration.

EDIT: After some commentaries, I’ve found that the idea exposed in this post was already developed. Being ashamed by futility and stupidity of the post, I’m now changing it and publishing something else: one of the very first drawings I’ve saved from my childhood:

I did it when I was 3 years old, and I was definitely and completely obsessed with the tiny home computer. It was drawn at school, and it made my teacher to ask my mother what it was - in 1984 computers were not a very common thing.

Ok, let’s try to add something more to distract from the fact the previous content of this post was ridiculous:

Look at this beatiful Magi King! At Spain, it is not only Santa Claus who brings gifts to good children, but mostly the Three Kings. They take a bit more to reach children houses (January 6th), and I suppose it is mostly because their camel based ground way of transport.

JS1k is a really nice contest for coding tiny 1 kb Javascript programs and try to do something nice in that few available space. In its second edition, all the entries must be Christmas themed.

My contribution to the contest has been a 3D Christmas tree (note it doesn’t work in IE, and works slow in any current browser except in Chrome). I’m really lazy to write articles explaining how I do my visual effects, but in this case a lot of people are asking me to do it, so let’s try it in a visual way:

Finally, some size optimization tricks

I used several tricks to make the code fit in 1 kb. The most of them are the usual tricks for reducing Javascript code size, like renaming variables to single character names, removing white spaces, unnecesary semi-colons and so on.

It is also very common to assign functions you use more than one time to variables to avoid the repetition. For example, if I do r=Math.random;, I can call r() each time I need a random number.

I used some few math tricks, like using cos(angle+11) to approximate sin(angle) and modular arithmetic.

Finally, I’ve used some other tricks like reusing functions. A function does different things depending on if it received parameters or not. This saves some few bytes from writing again “function”.

Writing code for limited size competitions is mostly like a puzzle or logical game. In the most of the cases there is not a common rule to do it, but just thinking and trying different ways to achieve the same goal in less space. It is usually possible to fit 5 or 6 kb of normal code in 1 kb if you try it and don’t give up.

Inspired by the research of Paul Debevec on photographic relighting, I’ve created this Flash experiment showing a real-time relighted scene of my girlfriend with her netbook. Watch it here. Please note it requires a fast computer to run at full framerate.

The scene has been captured without any special hardware, just a common reflex camera (Nikon D70) with its remote, a tripod and the netbook as the only light source. The time for shooting all the photos required for the relighting process was about 3-4 minutes, where Silvia — the Spanish for Sylvia — stayed amazingly static for the purpose.

I’ve really enjoyed the development of this experiment because it mixes the most of my hobbies: photography, art, coding, technology, and also it has been a great opportunity to involve my girlfriend in any of my experiments.

Few months ago I was invited to Merz Akademy by Olia Lialina to teach a CSS3 workshop for a week in June. I accepted, and it has been not only my first time visiting Germany but an amazing experience.

The Workshop at Merz

First I have to say that Merz Akademy installations are excellent. The best place to study I’ve ever seen. During a week each semester, they invite 8 to 10 expert guests in different fields — music, film, graphic design… — to teach workshops to their students. The students are free to choose in which workshop they want to participate.

My workshop was about web coding with standars and an overview of CSS3. There were 17 students, all of them really nice people, it was a pleasure to work with them. A message to them: Hello! Come to visit me at Málaga, you have a free room here!

We spent the first two days on learning a bit of semantic html, a review of CSS1/2 positioning, CSS sprites… The next two days were spent in experimenting with CSS3 and making something artistical with it.

The last day, projection and presentation of the projects from all the workshops.

Our workshop: CSS3 Guernica by Picasso

In my opinion, one of the better ways to learn is by free playing an experimenting, so after the first days of good coding practices and real life web design examples, we started to play in an artistical and free way with CSS3 — just the same as I usually do with my blog CSS experiments. So, our project was not meant to be useful or applicable to real world web design, but an artistical experiment.

We cutted the painting Guernica in parts, one for each student, and we animated it with CSS3 transitions. You can see the result here:

If you are a common reader of this blog, I suppose there is no need to explain that Smashing Magazine is one of the most important web magazines on web design and development. Since it was at only 2-3 hours by car from Merz Akademy, I went to visit their office with one of the students (Hello Candogan!).

We met Vitaly Friedman, editor-in-chief of Smashing Magazine. He is a really nice person and it was a pleasure to meet him and talk to him in person.

Vitaly gave us signed copies of the Smashing Book (Vitaly, thanks again for the book!). I’ve fully read it right now, and I’ve to say that it is really a good book. If you are into web design/development and you are searching for a good book, I can’t recommend you anything better than this. It is easy to read, well designed in its content, structure and visually, and very complete. I would have like to have a book like this when I was learning web development, it took me years to achieve all the knowledge that is condensed in this single book.

Conclusion

It has been an amazing and intense trip and experience. I would like to thank everybody I’ve met and Merz Akademy for making it possible.