Tag Archives: three.js

Exploring Simple Noise and Clouds with Three.js

A while back I attempt writing a simple CloudShader for use in three.js scenes. Exploring the use of noise, it wasn’t difficult creating clouds which isn’t visually too bad looking. Another idea came to add Crepuscular rays (“God rays”) to make the scene more interesting. Failing to mix them correctly together on my first tries, I left these experiments abandoned. Until one fine day (or rather one night) I decided to give it another shot and finally got it to work so here’s the example.


(Now comes with sliders for clouds control!)

In this post, I would going to explain some of the ideas generating procedural clouds with noise (these topics frequently go hand in hand). While noise might be bread and butter in the world of computer graphics, but it did took me awhile to wrap my head around it.

Noise
Noise, could be described as a pseudo-random texture. Pseudo-random means that it might appear to be totally random, but being generated by the computer, it is not. Many might also refer to noise as Perlin noise (thanks to work by Ken Perlin), but there are really different form of noise, eg. Perlin noise, Simplex noise, Value noise, Wavelet noise, Gradient noise, Worley noise, Simulation noise.

The approach that I use for my clouds could be considered Value noise. Let’s start creating some random noise by creating a DataTexture of 256 by 256 pixels.


// Generate random noise texture
var noiseSize = 256;
var size = noiseSize * noiseSize;
var data = new Uint8Array( 4 * size );
for ( var i = 0; i < size * 4; i ++ ) {
    data[ i ] = Math.random() * 255 | 0;
}
var dt = new THREE.DataTexture( data, noiseSize, noiseSize, THREE.RGBAFormat );
dt.wrapS = THREE.RepeatWrapping;
dt.wrapT = THREE.RepeatWrapping;
dt.needsUpdate = true;

Now if we were to now render this texture, it would look really random (obviously) like a broken TV channel.

noisebw
(we set alpha to 255, and r=g=b to illustrate the example here)

Let’s say if we were to use the pixel values as a height map for a terrain (another use for noise), it is going to look really disjoint or random. One way to fix it is to interpolate the values from one point to another. This is becomes smooth noise. The nice thing about textures is that these interpolation can be done on the graphics unit automatically. By default, or by setting `.minFilter` and `.magFilter` properties of a THREE.Texture to `THREE.LinearMipMapLinearFilter`, you get almost free interpolation when you try to read a point on the texture between 2 pixels or more.

Still, this isn’t enough to look anything like clouds. The next step is to apply Fractional Brownian Motion, which is a summation of successive octaves of noise, each with higher frequency and lower amplitude. This generates Fractal noise which generates a more interesting and continuous texture. I’m doing this in the fragment shader with a a few lines of code…


float fnoise(vec2 uv) {
    float f = 0.;
    float scale = 1.;
    for (int i=0; i<5; i++) {
        scale *= 2.;
    f += texture2D(uv * scale).x / scale;
    }
    return f;
}

Given this my data texture has 4 channels (RGBA), one could pull out 4 or 3 components if needed, like


vec3 fNoise(vec2 uv) {
    vec3 f = vec3(0.);
    float scale = 1.;
    for (int i=0; i<5; i++) {
        scale *= 2.;
        f += texture2D(uv * scale).xyz / scale;
    }
    return f;
}

Now if you were to render this, it might look similar to the perlinNoise class in flash/actionscript or the cloud filter in photoshop.

Screenshot 2014-11-08 22.16.53

2D Clouds
Although we have a procedural cloud shader, how do we integrate it into a three.js scene? One way is to texture it over a sphere or a skybox, but the approach I use is to create a paraboloid shell generated with ParametricGeometry, similar to the approach Steven Wittens used to render Auroras in his demo “NeverSeenTheSky”. The code / formula I use is simply this


function SkyDome(i, j) {
    i -= 0.5;
    j -= 0.5;
    var r2 = i * i * 4 + j * j * 4;
    return new THREE.Vector3(
        i * 20000,
        (1 – r2) * 5000,
        j * 20000
    ).multiplyScalar(0.05);
};
var skyMesh = new THREE.Mesh(
    new THREE.ParametricGeometry(SkyDome, 5, 5),
    shaderMaterial
);

Now the remaining step, but its probably the most important step to simulate clouds is to make use and tweak the values from the fractal noise to obtain the kind of clouds you want. This is done in the fragment shader where you could decide what thresholds to apply, (eg. cutting off the high or low values) or apply a curve or a function to the signals. 2 articles which gave me ideas are Hugo Elias’s clouds and Iñigo Quilez’s dynamic 2d clouds. Apart from these, I added a function (where o is opacity) to reduce the clouds of the skies nearer the horizon to make it more illusion of clouds disappearing into the distant.


// applies more transparency to horizon for
// to create illusion of distant clouds
o = 1. – o * o * o * o;

Crepuscular rays
So I’m going a break explaining some of my ideas for producing the clouds. This might be disappointing if you’re expecting more advanced shading techniques, like ray-marching or volumetric rendering, but I am trying to see how far we could go with just the basic/easy stuff. Now if adding the crepuscular rays works, it would produce a more impressive effect that we can avoid complicated stuff at the moment.

So for the “God rays”, I started with the webgl_postprocessing_godrays example in three.js, implemented by @huwb using a similar technique used by Crytek. After some time debugging why my scene didn’t render correctly, I realized that my clouds shader (a ShaderMaterial) didn’t play well in the depth rendering step (which override the scene with the default MeshDepthMaterial), that was needed to compute occluded objects correctly. For that I manually override materials for the depth rendering step, and pass a uniform to the CloudShader to discard or write depth values based on the color and opacity of the clouds.

Conclusion
I hope I’ve introduce the ideas behind noise and how simple it could be for generating clouds. One way to get started with experimenting is to use Firefox, which now have a Shader Editor with its improved web developer tools that allows experimentation of the shaders in real time. Much is up to one’s imagination or creative, for example, turning the clouds into moving fog.

Clouds is also such common and an interesting topic which I believe there is much (advanced) literature on it (like websites, blogs and papers like this). As mentioned earlier, the links I found to be good starting point is by Hugo Elias and Iñigo Quilez. One website which I found explaining noise in an easy to understand fashion is http://lodev.org/cgtutor/randomnoise.html

Before ending, I would love to point out a couple other of realtime browser-based examples I love, implemented in in a very different or creative approaches.

1. mrdoob’s clouds which uses billboards sprites – http://mrdoob.com/lab/javascript/webgl/clouds/
2. Jaume Sánchez’s clouds which uses css – http://www.clicktorelease.com/code/css3dclouds/
3. IQ Clouds which uses some form of volumetric ray marching in a pixel shader! – https://www.shadertoy.com/view/XslGRr

So if you’re interested, read up and experiment as much as you can, for which there are never ending possibilities!

Free Birds

Earlier this year Google announced DevArt, a code and art collaboration with London’s Barbican Centre. Chinmay (a fellow geek in Singapore) and I decided to collaborate on a visual and aural entry for the competition.

As the competition attracted a number of quality works, the short story is that we didn’t win (the long story includes how my last git push failed before the deadline while tethering internet over my mobile in Nepal). This post is however about the stuff we explored, learned and created along the way. We also shared some of that at MeetupJS at the Singapore Microsoft office not long ago. Being open is actually one aspect of the DevArt event too, which is to share some of the source code, workflow and ideas around.

I wanted to reuse some of my work done with GPU flocking birds for the entry, while making it more interactive with a creative idea. We decided to have a little bird on an ipad which you could customize its colors and free it into a bigger canvas of freed birds.

Chinmay whose passionate about acoustics, took the opportunity to dabble more with the web audio api. (He previously created auralizr a really cool web app that transport you to another place using convolution filter). Based on the excellent bird call synthesis article, Chinmay created a javascript + web audio api library for generating synthesized bird calls.


Go ahead, try it, it’s interactive with a whole bunch of knobs and controls.

As for me, here’s some stuff I dabbled in for the entry

  1. Dug out my old library contact.js for some code node.js + websockets interaction.
  2. Mainly used code from three.js gpgpu flocking example, but upgraded it to use BufferedGeometry
  3. Explored GPGPU readback to javascript in order to get positional information of birds, to be feed into bird.js for positioning audio
  4. My first use of xgui.js, which uncovered and fixed some issues, but otherwise a really cool library for prototyping.
  5. Explored more post processing effects with Non-photo Realistic Rendering, unfortunately it wasn’t good enough during that time frame.

So that for the updates for now. Here are some links

Also, another entry of notable mention is Kuafu by yi-wen lin. I thought it shared a couple of similarities with our project, was more polished, but unfortunately didn’t made it to the first place.

WebGL, GPGPU & Flocking Birds – The 3rd Movement

This would be the final section of the 3 part-series covering the long journey of I’ve added the interactive WebGL GPGPU flocking bird example to three.js after a span of almost a year (no kidding, looking at some of the timestamps). Part 1 introduces to flocking, Part 2 talks about writing WebGL shaders for accelerated simulation, and Part 3 (this post) hopefully shows I’ve put things together.

(Ok, so I got to learn about a film about Birds after my tweet about the experiment late one night last year)

Just as it feel like forever to refine my flocking experiments, it feel just as long writing this. However, watching Robert Hodgin‘s (aka flight404) inspiring NVScene 2014 session: “Interactive Simulations (where nobody has to die)” (where he covered flocking too) was a motivation booster.

So much, I would recommend you watching that video (starting at 25:00 for flocking, or just watching the entire thing if you have the time) over reading this. So much I could relate in his talk like on flocking and the gpu, but so much more I could learn from. No doubt Robert have always been one of my inspirations.

Now back to my story, we were playing with simulated particles accelerated with GPGPU about 2 years ago in three.js.

With some pseudo code, here’s what is happening

/* Particle position vertex shader */
// As usual rendering a quad
/* Particle position fragment shader */
pos = readTexture(previousPositionTexture)
pos += velocity // update position the particle
color = pos // writing new position to framebuffer
/* Particle vertex shader */
pos = readTexture(currentPositionTexture)
gl_Position = pos
/* Particle fragment shader */
// As per usual.

One year later, I decided to experiment with particles interacting with each other (using the flocking algorithm).

For a simple GPGPU particle simulation, you need 2 textures (one for the currentPosition and one for the previous, since reading and writing to a same texture could cause corruption). In flocking simulation, 4 textures/render targets are used (currentPositions, previousPositions, currentVelocities, previousVelocities).

There would be one render pass for updating velocities (based on the flocking algorithm)

/* Velocities Update Fragment Shader */
currentPosition = readTexture(positionTexture)
currentVelocity = readTexture(velocityTexture)

for every other particle,
    otherPosition = readTexture(positionTexture)
    otherVelocity = readTexture(velocityTexture)
    if otherPosition is too close
        currentVelocity += oppositeDirection // Seperation
    if otherPosition is near
       currentVelocity += followDirection // Steer
    if otherPosition is far
       currentVelocity += towardsDirection // Cohesion

color = currentVelocity

Updating position is pretty simple (almost similar to the particle simulation)

/* Particle position fragment shader */
pos = readTexture(positionTexture)
pos += readTexture(velocityTexture) 
color = pos

How good does this work? Pretty good actually, getting 60fps for 1024 particles. If we were to run the JS code (no rendering) of the three.js bird canvas example, here’s the kind of frame rates you might be getting (although it certainly could be optimized)

200 birds - 60fps
400 birds - 40fps
600 birds - 30fps
800 birds - 20fps
1000 birds - 10fps
2000 birds - 2fps

With the GPGPU version, I can get about 60fps for 4096 particles. Performance start dropping after that (depending on your graphics card too) without further tricks possibly due to the bottleneck of texture fetches.

The next challenge was trying to render something more than just billboarded particles. It was a feeble attempt at calculating the transformations so results weren’t great.

So I left the matter alone until half a year later when I suggested it was time to add a GPGPU example to three.js and I revisited the issue because of WestLangley persuasion.

Iñigo Quílez had also just written an article about avoiding trigonometry for orientating objects, but I failed to fully comprehend the rotation code and still ended up lost.

I decided finally I should try understanding and learning about matrices. The timing was also right because a really good talk “Making WebGL Dance” Steven Wittens gave at JSConfUS was made available online. Near the 12 minute mark, he gives a really good primer to Linear Algebra and Matrices. The take away is this – matrices can represent a rotation in orientation (,scale & translation), and matrices could be multiplied together.

With mrdoob’s pointer to how the rotations were done in canvas bird example, I managed to reconstruct the matrices to perform similar rotations with shader code and three.js code.

I’ve also learn’t along the way that matrices in glsl are a format from how it’s written typically mat3(col1, col2, col3) instead of mat3(row1, row2, row3).

And there we have it.

There was also one more final touch to the flocking shader which made things more interesting. To Robert’s credit again for writing the flocking simulation tutorial for cinder which I’ve decided to adopt his zone based flocking algorithm and easing functions. He covered this in his NVScene talk too.

Finally some nice words by Craig Reynold, the creator of the original “Boid” program in 1987, who seen the three.js gpgpu flocking experiment.

2014-02-24_222356

It has been a long journey, but certainly not the end of it. I’ve learn much along the way, and hopefully I have managed to share some. You may follow me on twitter for updates I have on flocking experiments.

WebGL, GPGPU & Flocking Birds Part II – Shaders

In the first part of “WebGL, GPGPU & Flocking Birds”, I introduced flocking. I mentioned briefly that simulating flocking can be a computationally intensive task.

The complexity of such simulations in Big O notation is O(n^2), that is since each bird or object has to be compared with every other object. For example, 10 objects requires 100 calculations, but 100 objects requires 10,000 calculations. You can quickly see how simulating even a couple thousand objects can quickly turn a fast modern machine to a crawl especially with just javascript alone.

It’s possible to speed this up using various tricks and techniques (eg with more efficient threading, data structures etc), but when one greed for more objects, yet another brick wall can be found quickly.

So in this second part, I’ll discuss the role of WebGL and GPGPU which i would use for my flocking birds experiments. It certainly may not be the best or fastest way to run a flocking simulation, but it was interesting experimenting with WebGL to do some of heavy lifting of the flocking calculations.

WebGL

WebGL can be seen as the cool “new kid on the block” (with its many interactive demos), and one may also consider WebGL as “just a 2d API“.

I think another way one can look at WebGL, is as an interface or a way to tap into your powerful graphics unit. Its like learning how to use a forklift to lift heavy loads for you.

Intro to GPUs and WebGL Shaders

For a long time, I understood computers had a graphics card or unit but never really understood what it is really until recently. Simply put, the GPU (Graphics Processing Unit) is a specialized piece of hardware for processing graphics efficiently and quickly. (More on Cuda parallel programming on Udacity, if you’re interested)

The design of a GPU is also slightly different from a CPU. For one, GPU can have thousands of cores compared to dozen that a CPU may have. While GPU cores may run at a lower clockrate, its massive parallel throughput may be higher than what a CPU can perform.

A GPU contains vertex and pixel processors. Shaders are code used to do to program them, to perform shading of course. That includes coloring, lighting, post-processing for images.

A shader program have a linked vertex shader and a pixel(aka fragment) shader. In a simple example to draw a triangle, a vertex shader calculates the coordinates of the 3 points of the triangle. The calculated area in between the triangle is passed on to the pixel shader where it paints each pixels in the triangle.

Some friends have asked me what language is used to program WebGL shaders. They are written in language call GLSL (Graphics Library Shading Language), a C like language also used for OpenGL shaders. At least, I think if you understand JS, GLSL shouldn’t be too difficult to be picked up.

Knowing that WebGL shaders are what used to run tasks on the GPUs, we have a basic key in unlocking powerful computation capabilities that GPUs have, even though it is primary for graphics. Moving on to the exciting GPGPU – “General-purpose computing on graphics processing units”.

Exploring GPGPU with WebGL

WebGL, instead of only rendering to the screen, has the ability to write to its own memory. These rendered bitmaps in memory or RAM is referred to Frame Buffer Objects (FBOs) and the process can sometimes be simply referred as a render-to-texture (RTT).

This may start to sound confusing, but what you need to know is that the output of shader can be a texture, and that texture can be an input for another shader. One example is an effect to rendering a scene inside a TV as part of a scene inside a room.

Frame buffers are also commonly use for post-processing effects. (Steven Wittens has a library for RTT with three.js)

Since these in-memory textures or FBOs is that they reside in the GPU’s memory, its nice to note that reading or writing to a texture within the GPU’s memory is way fast, compared to uploading a texture from the CPU’s memory in our context, javascript’s side.

Now how do we start making use or abusing this for GPGPU? First consider what would a Frame Buffer possibility represent. We know that a render texture is basically a quad / 2d array holding RGB(A) values, and we could decide that a texture could represent particles, and that we could represent each pixel as each particle’s position.

For each pixel we can assign the RGB channels to the positional component (red=x position, green=y position, blue=z position). A color channel may only have a limited range of 0-255, but if we enable floating-point texture support, each channel goes from -infinity to infinity (though there’s still limited precision). Currently, some devices (like mobile) do not support floating-point texture support, so one should decide whether to drop support for those devices or pack a number over a few channels to simulate a value type of larger range.

Now we can simulate particle positions in the fragment shaders instead of simulating particles with Javascript. In such cases, a program may be more difficult to debug, but the number of particles can be much higher (like 1 Million) and CPU can be freed up.

The next step after the simulation phase is to display the gpu simulated particles on screen. The approach is to render particles like normal, however, the vertex shader then looks up its positional information stored in the texture. Its like adding just a little more code to your vertex shaders to read the position from the texture, and “hijacking” the position of the vertex you’re about to render. This requires an extension to lookup textures in the vertex shader but likely its supported when floating point textures are.

Hopefully by now, this gives a little idea on how “GPGPU” could be done in WebGL. Notice I mentioned with WebGL, because its likely that you can perform GPGPU in other ways(eg. with WebCL) in a different approach. (Well, someone wrote a library call WebCLGPU, a WebGL library which emulates some kind of WebCL interface, but I’ll leave you to explore that).

(Some trivial: In fact, this whole GPGPU with WebGL was really confusing to me at first and I did not know what its supposed to be called. While one of the earliest articles about GPGPU with Webgl referred to this technique as “FBO Simulations”, many still refer to as GPGPU.

What’s funny what that initially I thought GP-GPU (with its repetitive acronym) is used to describe “ping-pong”-ing of textures in the graphics card but well… there may be some truth in that. 2 textures are typically used and swapped for simulating positions because its not recommended to read and writing to the same textures at the same time.)

Exploration and Experiments

Lastly, one point about exploration and experiments.

Simulating particles GPGPU are getting common these days, (there are probably many on chrome experiments), and I’ve also worked on some in the past. Not to say that they are boring, (one project which i found interesting is the particle shader toy) but I think there are many more less explored and untapped areas of GPGPU. For example, it could be used for fluid, physics simulations and applications such as terrain sculpting, cloth, hair, cloth simulation etc.

As for me, I started playing around with flocking. More about it in the 3rd and final part of these series.

WebGL, GPGPU, and Flocking – Part 1

One of my latest contributions to three.js is a webgl bird flocking example simulated in the GPU. Initially I wanted to sum up my experiences in a blog post of “WebGL, GPGPU, and Flocking”, but that became too difficult to write, and possibly too much to read in a go. So I opt to split them into 3 parts, the first part of flocking in general, and second on WebGL and GPGPU, and the third part to put them all together. So for part 1, we’ll start with flocking.

So what is flocking behavior? From Wikipedia, it is

the behavior exhibited when a group of birds, called a flock, are foraging or in flight. There are parallels with the shoaling behavior of fish, the swarming behavior of insects, and herd behavior of land animals.

So why has flocking behavior has caught my attention along the way? It is an interesting topic technically – simulating such behavior may require intensive computation which poses interesting challenges and solutions. It is also interesting for it use of creating “artificial life” – in games or interactive media, flocking activity can be use to spice up liveliness of the environment. I love it for an additional reason – it exhibits the beauty found in nature. Even if I haven’t have the opportunity to enjoy such displays at lengths in real life, I could easily spend hours watching beautiful flocking videos on youtube or vimeo.

You may have noticed that I’ve used of flocking birds previously in “Boid n Buildings” demo. The code I use for that is based on the version included in the canvas flocking birds example of three.js (which was based on another processing example). A variant of that code which was probably also used for “the wilderness downtown” and “3 dreams of black”.

However, to get closer to the raw metal, one can try to get his hands dirty implementing the flocking algorithm. If you can write a simple particle system already (with attraction and repulsion), its not that difficult to learn about and add the 3 simple rules of flocking

  1. Separation – steer away from others who are too close
  2. Alignment – steer towards where others are moving to
  3. Cohesion – steer towards where others are

I usually find it useful to try something new to me in 2d rather than 3d. It’s easier to debug when things go wrong, and make sure that new concepts are understood. So I started writing a simple 2d implementation with Canvas.

See the Pen Flocking Test by zz85 (@zz85) on CodePen

With this 2d exercise done, it would be easier to extend to 3D, and then into the Shaders (GPGPU).

If you are instead looking for guide or tutorial to follow with, you might find that this post isn’t very helpful. Instead, there are many resources, code and tutorials you can probably find online on this topic. With this, I’ll end this part for now, and leave you with a couple of links you can learn more about flocking. The next part in this series would be on WebGL and GPGPU.

Links:
http://natureofcode.com/book/chapter-6-autonomous-agents/ Autonomous Agents from Nature of code book.
http://www.red3d.com/cwr/boids/ Craig Reynolds’s page on Boids. He’s responsible for the original program named “Boid” and his original paper from 1987 of “Flocks, Herds, and Schools: A Distributed Behavioral Model”.
http://icouzin.princeton.edu/iain-couzin-on-wnyc-radiolab/ A really nice talk (video) on collective animal behavior. This was recommended by Robert Hodgin who does fantastic work with flocking behavior too.
http://www.wired.com/wiredscience/2011/11/starling-flock/ An article on Wired if you just want something easy to read

Three.js Bokeh Shader

(TL;DR? – check out the new three.js webgl Bokeh Shader here)

Bokeh is a word used by photographers to describe the aesthetic out of focus or blur properties of a lens or a photo. Depth-of-field (DOF) is the distance objects seems to be sharp in a photo. So while “dof” is more measurable and “bokeh” subjective, one might say there’s more bokeh in picture with a shallower dof, because the background and foreground (if there’s a subject) is usually de-emphasized by being blurred when thrown out of focus.

Bokeh seems to be derived from the Japanese word “boke” 暈け – apart from the meaning blur, it might also mean senile, stupid, unaware, or clueless. This is interesting because in Singlish (Singapore’s flavor of English), it has that same negative meaning when referring “blur” to a person (it probably comes from the literal meaning of the opposite of sharp”. And now you might now know non graphical meaning of the word blur in my twitter id (BlurSpline).

IMG_8537
Here’s a photo of the Kinetic Rain I took at Changi Airport Terminal 1. Especially if you like kinetic structures, you should check out the official videos here and here (in which there’s much use of bokeh too)

I remember the time I knew little about 3d programming when I first tried three.js 2 years ago. I wondered whether camera.near and camera.far were the ways of defining when objects in the scene gets blurred when they are at distances at the far or near points.

Turns out of course that I was really wrong, since these values are used for clipping – improving performance by not rendering objects out of the view port. I had that naive thinking three.js work like real life cameras that I was able to create cinematic like scenes. Some helpful one on three.js IRC channel then pointed me to the post-processing DOF example done by alteredqualia who ported the original bokeh shader written by Martins Upitis.

So fast forward to the present, we have seen that shader used in ROME, and Martins Upitis has updated his Bokeh Shader to make it more realistic, and I attempted to port it back to three.js/webgl.


With focus debug turned on


Testing it in a scene


The example added to three.js with glitters.

So to copy what martinsh say the new shader does, it has the flexibility to
• variable sample count to increase quality/performance
• option to blur depth buffer to reduce hard edges
• option to dither the samples with noise or pattern
• bokeh chromatic aberration/fringing
• bokeh bias to bring out bokeh edges
• image thresholding to bring out highlights when image is out of focus
• pentagonal bokeh shape (experimental)
• bokeh vignetting at screen edges

The new three.js example also demonstrates how object picking can be used and interpolated for the focal distance too. More detailed comments about the parameters were also written on github.

Of course the shader is not perfect, as DOF is something not that simple (there are quite a few in depth Graphics Gems articles on it). Much of it is post-processing smoke and mirrors, the way is usually done in rasterization, compared to Path tracing or so. Yet I think its great addition to have in WebGL, just as we have seen DOF used in the Crytech, Nvidia demos or in other high end games. (There was a also a cool video of a minecraft mod using that DOF shader – but now seemed removed as I recently looked for it).

I would love to see the tasteful use of bokeh sometime, not just because it feels cinematic or been been widely used in photography, i think its also more natural given that’s how our eyes work with our brains (more details here).

Finally it seems that the deadline for the current js1k contest is just hours away – this means I gotta head off to do some cranking and crunching, maybe more on that in a later post! 😀

Making of Boids and Buildings

Here’s my latest three.js webgl experiment called “Boids and Buildings”. Its an experimental 3d procedural city generator that will run in a form of a short demo. Turn up your volume and be prepared to overclock your CPU (& GPUs) a little.

Here’s the story – early last month I was in Japan for a little travelling. Perhaps one thing I found interesting was the architectural. The cities are large and are packed with buildings (Edo, now called Tokyo, was once the world’s largest city).


(the huge billboards are at the famous dotonbori in osaka, the bottom 2 photos were houses shot in kyoto).

Sometime ago, I saw mrdoob’s procedural city generator. We have thought about creating a 3d version of it, but only during the trip I decided I should try working on it. Some of the process was written in this Google+ post, but I’ll summarize it a little here.

Firstly, the city generator works by building a road which spins off more roads along the way. The roads stop when it intersects with another road or reaches the boundary of the land. Another way of looking at this is that the land is split into many “small lands” divided by the roads. My approach was that if I could extract the shape information of each divided land, I could run ExtrudeGeometry to create buildings to fill the shape of each land.

The original js implementation of road intersections was done looking up pixel data on the canvas. While I managed to write a version which detects faces base on pixels, detecting edges and vertices was more tedious than I thought, as if I could write or use another image processing library similar to potrace. Instead of doing that, I work on an alternative intersection detection based on mathematically calculating whether each all lines/road intersected. This is probably slower when it takes up too much memory, but points of intersections were retained.


(here this version denotes where the starting and ending points of each road with red and green dots).

However some serious information is still missing – which edges connects the points, and which edges belongs to each face/land. Instead of determining these information after processing everything, using half-edge data structures can elegantly compute them on the fly. Demoscene coders might have seen this technique for mesh generation.

Without going into an in-depth technical explanation, here’s an analogy to how half-edges is employed. Since every land is defined by the roads surrounding it, and you build fences around the perimeter of the land to enclose the area within. The enclosed area defines each face and each fence is like a half-edge. Since each road divides the land into 2 sides (left and right), 2 fences will be constructed and its denote the land belonging to both sides. If a road is build through an existing land, fences on the existing land has to be broken down to connect to each side of the new road fences. In code, each new road contains 2 half-edges, and connecting new roads requires creating new split edges and updating of linked half edge pointers.

With that a 2D version…
2d generator

… and a 3D version was done.
3D

(on some hindsight, it could be possible to use half-edges with the original pixel collision detection)

Now we’ve got 3d buildings, but it lacks the emotions and feelings that I was initially thinking of. I thought, perhaps I’ll need to simulate the view out of the train. But that might require me to simulate train rails, although the stored paths of roads could be used for the procedural motion. As I was already started to feel weary of this whole experiment, I had another idea – since there’s a examples of boids in three.js, why not try attaching a camera to the boid, not only you’ll get a bird’s eye view, but you’ll get camera animation for free! I did a quick mesh up and the effects seems to be rather pleasant.

Incidentally, mrdoob in his code named the roads Boids, and I thought the name “Boids and Buildings” would be a rather fitting theme.

Let me start jumping around on bits and pieces I can think of to write of.

Splash screen
I abstracted the map generator into a class call Land which takes in parameters, and it was reusable for the 2d and 3d version. In the splash screen, a css3d was used to translate and scale the map generator in the background.

Text fonts
I wanted to create some text animation in the splash page, with a little of the boid/map generation feeling. I use mrdoob’s line font used in Aaronetrope and experimented with various text animations.

Visual Direction
To simplify working with colors, and used random grey for buildings at the start and ended up with a “black&white” / greyscale direction. For post processing, I added just a film post-processing shader by alteredqualia found in three.js examples, with slightly high amount of noise.

Scene control and animation
Since most of the animation was procedural, so during development, much of it was by code. When it was time to have some timeline control, I used Director.js which I wrote for “itcameupon”. The Director class schedules time-based actions and tweens, and most of the random snippet of animation code was added to it. So more or less, the animation runs on a fix schedule except for randomized parts (eg. time when roads just building on lands).

Pseudorandomness
This experiment allowed me to deal with lot of randomness, but based on probability distribution, lots of randomness can actually give expect results. I used this fact to help in debugging too. For example, you would like quickly to dump values out to the control in the render loop but you’re afraid of crashing your devtools – you could do this (Math.random()<0.1) && console.log(bla); This means, take a sample of 10% of the values and spit out the results out to the console. If you are in Canary, you can even do (Math.random()<0.01) && console.clear(); to clear your debug messages ones in a while.

Buildings
Buildings height are randomized, but they follow certain rules to make it more realistic and cityscape like. If the area of land is big, the building height would be lower. If its a small area but not too small, then it could be a skyscraper.

Boid cams
The boid camera was simply to follow the first boid, based on its velocity, placed the camera position slightly higher and behind the bird. I wanted to try a spring-damper camera system but opt for this simpler implementation instead – move the camera, a factor k position closer to the target position every render. In simple code, targetX = (targetX – currentX) * k where k is a small factor eg. 0.1 – this creates a cheap damping/easing effect. This effect is apparent toward the end of the animation when the camera is slingshot to the birds as the camera mode changes to the boidcams.

Performance Hacks

Shape triangulation is probably one of the most expensive operations here. In “It came upon”, slow computers experienced a short sharp delay when text get triangulated the first time (before caching). Over here, its a greater problem due to potentially high number of triangulations. Apart from placing a limits to buildings, one way to prevent a big noticeable lag is to use web workers. However I opt to use the old trick of using setTimeouts instead. lets say there are 100 buildings to triangulate, instead of doing everything inside one event loop which would bring a big pause, I’ll do setTimeout(buildBuilding, Math.random() * 5000); – based on random probability, 100 buildings would be triangulated across 5 seconds, reducing the noticeable pauses. I supposed, this is somewhat like an incremental garbage collection technique newer javascript engines employ.

Another thing I did was to disable matrix calculations, using object.matrixAutoUpdate = false; once buildings are completed building and animating.

Music
Pretty awesome music from Walid Feghali. Nothing much else to add.

Audio
Added my Web Audio API experiment of creating wind sound to simulate wind sound during the boidcams. Wind can simply be created with random samples (white noise?), I added a lowpass filter and a delay. Aptitude of wind noise is generated by the vertical direction boids are flying at. Wanted to add a Low Frequency Oscillator to make more realistic sounding wind, but I haven’t figured that out.

Future Enhancements
Yes, there’s always inperfections. Edge handling could be better, same with triangulation. Boids could do building collision detection. Improve the wind algorithm. Create variety of buildings, or making some cool collapsing buildings (like in inception).

Conclusion
So the demo is online at http://jabtunes.com/labs/boidsnbuildings/, sources are unminified, you’re welcome to poke around.

Going back to the original idea, I still wonder if I managed to create the mood and feelings I originally thought in my head. Here are some photos I shot overseeing Osaka in Japan, maybe you can compared it with the demo and make a judgement – perhaps you might think the demo is closer to a Resident Evil scene instead. ;P

edit: after watching this short documentary on Hashima island (where a scene from skyfall was at), i think the demo could resemble hashima’s torn buildings too.




Nucleal, The Exploding Photo Experiment

Particles. Photos. Exploding motions. The outcome of experimentation of more particles done this year. Check out http://nucleal.com/


This might probably look better in motion

Without boring you with large amount of text, perhaps some pictures to help do some talking.

First you get to chose how much particles to run.


Most decent computers could do 262144 particles easily, even my 3 generation old 11″ macbook air can run 1 or 4 millions particles.

On the top bar, you get some options on how you may interact with the particles, or select which photo albums if connect to facebook.

At the bottom is a film strip which helps you view and select photos from the photo album.

Of course at the middle you view the photo particles. A trackball camera is used, so you could control the camera with the different buttons of your mouse, or press A, S or D while moving your mouse.

Instead of arranging the particles in a plane like a photo, you could assemble them as a sphere, cone, or even a “supershape”.

Static shapes by itself aren’t good, so physics forces could be applied the particle formation.

Instead of the default noise wave, you can use 3 invisible orbs to attract particles with intensity relating to its individual colors

Or do the opposite of attracting, repelling

My favorite physics motion is the “air brakes”.

This slows and stops the particles in their tracks, allow you to observe something like a “bullet time”.

While not every combinations always look good, it’s pretty fun to see how what the particles form after sometime, especially with air brakes between different combinations.

Oh btw noticed the colors are kind of greyscale? That’s the vintage photo effect I’m applying in real time to the photos.

And for the other photo effect I added, a cross-processing filter.

(this btw is my nephew, who allows me to spend less attention and time on twitter these days:)

So hopefully I’ve given you a satisfying walk-through of the Nucleal experiment, at least way simpler than the massive Higgs boson “god” particle experiment.

Of course some elements of this experiments are also not entirely new.

Before this myself have also enjoyed the particle experiments of
Kris Temmerman’s blowing up images
Ronny Welter’s video animation modification
Paul Lewis’s Photo Particles

Difference is now that brilliant idea of using photos to spawn particles can reach a new level of interactivity and particles massiveness, all done in the browser.

While I’m happy with the results, this is just the tip of the iceberg. Since this being an experiment, there’s much room for improvements in both artistic and technical areas.

A big thank you again to those involved in three.js, for which this was built on, to those adventurous who have explored GPGPU/FBO particles before me, to those who blog and share their knowledge about GLSL and graphics for which much knowledge was absorb to assemble this together, and not the least to Yvo Schaap who support me and this project.

Thank you also to others who are encouraging and make the internet a better place.

p.s. this is largely a non-technical post right? Stay tune for perhaps a more in-depth technical post about this experiment :)

Virtual Rendering 1,000,000 Items Efficiently

You probably haven’t heard from me for a while, and probably some reasons, and one could well be attributed to my dark periods of un-productivity.


Link to the Demo. Recommended that you’re run it with Chrome.

But if you are hearing from me now, that’s because there’s some progress I would like to share on a small experiment, which is an attempt to render large amount of data using html, javascript in the browser efficiently.

Here’s the problem: Let’s say you have a million rows of data, and to simply create a million Divs and placing them to your html document’s body is a good way to freeze or crash your browser, that’s after chewing up large amount of RAM and CPU. That doesn’t only to browser applications, because many text editors are pretty incapable of opening large files.

One example of how I encountered this problem was running three.js inspector with a particle scene, and I realized attempting that the couple thousand or even hundred elements representing them was locking up the browser. One motivation for this experiment was also to try creating new UI components for a more efficient three.js scene inspector.

Solution: Placing objects in memory are way faster than placed in the dom or rendered. In the case of huge list in a scroll panel, the trick is to hide all objects and render only the items in view. Though this isn’t super simple, it isn’t totally new, and a couple of good libraries have already utilized such techniques. CodeMirror, the extensible and powerful browser based code editor, uses handles large amount of code in this manner. Slickgrid, a powerful open source grid/spreadsheet library created by a Google employee, is built on this technique to allow large rows of data. Sites that implement the “infinity” scrolling interface (eg. Pinterest, Facebook timeline) utilizes a similar technique to reduce huge memory footprint (twitter, I’m looking at you).

Approach: So why did I try to do this myself? Similar to reasons why one would write a library is to have more understanding and control over your own code, while experimenting on stuff you otherwise wouldn’t have ever try. In this experiment, I got to attempt skinning my own scrollbar, as well as to experiment and benchmark a DOM versus a Canvas implementation of Virtual Rendering. In this post, we would look at the DOM approach, which is similar to how CodeMirror and Slickgrid do it.

If you take a look at the source, there 4 simple classes.

1. SimpleEvent
A minimalistic approach to do the observer patten in the style of Signals.

For example usage,

2. ScrollBar
This is a UI component that displays a scrolltrack and slider, that fires some scroll events when scrollbar is clicked or dragged via .onScroll. Its 2 public interfaces are .setLength() for defining the size of the slider block in percentage, while .setPosition() moves the slider according to the document viewport’s position by a fraction.

(See bottom for more UI/UX notes on the scrollbar)

3. RowItem
The row item is responsible for storing its own data and rendering its dom representation when it comes into view. Here, it simply stores a string for its text data.

For visual representation, its needs to store its x, y, width and height to be activated and positioned correctly for rendering.

4. ScrollPane
This is class which integrates all the above into this Virtual Rendering component. Firstly, it needs to be represented as a div element to be inserted to the dom. ScrollPane tracks the items, and keeps the total virtual area it contains. Based on its dimension, it calls ScrollPane to update its visual elements. The ScrollPane listens to its component for mousewheel events and listens to the ScrollBar for scroll events.

On any request to update its viewport, ScrollPane iterates over its item, quickly find which RowItem are in view and calls draw(). RowItem would create dom objects on demand, and position it. Upon another update, dom objects found visible in the previous render would be reused and those elements scrolled out of view would be remove from dom and destroyed to free memory.

Results: While this has only been tested and ran in Chrome, I’m pretty satisfied with the results of this hack. At a million objects (I’ve tested up to 6 million objects), scrolling is pretty responsive, initially loading it takes ~2 seconds to load, each repaint takes ~25ms, and the heap memory footprint stays below 100Mb. Apart from requiring more refactoring, i think its has quite minimal javascript and css.

Applications: Apart of my planned usage for a revamp three.js inspector, there are perhaps a few mini usages for this widget. For example, the developer’s console can choke up when displaying huge amount of data (now chrome devtools splits them up into small sub chunks, so it works but not the best way imho), and such could be a solution to this problem.

So hopefully this little experiment would find itself some nice usage. Until you hear from me again, continue reading for more side thoughts when I was playing around on the scrollbar. And the link to the demo if you didn’t see it earlier.

UI/UX notes on the scrollbar.
While working on the Scrollbar implementation, I observed that clicking in the track outside the slider has a same effect of “page up” and “page down” both in mac and windows. Instead of moving the slider to the clicked position (as I thought was the correct behavior initially), it fires onScroll event to a controller listener. While it seems that Mac Lion “un-obstructive” scrollbars are “in”, evidenced by sites like Facebook that imitate that, I’m however not a fan of it. Somehow I find those scrollbars ugly for applications that have a non-white background, so I’ve tried to style my scrollbars in the dark gradient colors after Sublime Editor instead.

Another challenge is that the slider would not be able to size proportionally as it would result in thinner than a pixel height for huge list. Therefore the scrollbar has an minimal size which makes it more practical for dragging. There’s probably more tweaks that can be done here, and there are alternative UI designs that eliminates the scrollbar in large lists (eg. your iphone contact list).

The Ascii Effect

Brief: Sometime ago, I decided to try what happens if the three.js renders ascii. Originally called the AsciiRenderer, it has been renamed to AsciiEffect and included with three.js examples.

**since this screenshot is displayed in ascii format**


                       *++==---::::::.                      
                    %**+++====--..                          
                  @%**++++-----.....                        
                 @@###++++------.....                       
                @@%###+++++-----:.....                      
               @@@####+++++-=====......     .               
               @@%%%%%*****=======......  ...               
               @@@%%%%******======-....::....               
               @@@%%%%******======+::::::....               
               @@@%%%%***###*++++++=:::::..--               
                @@@@@@@######+++++++::::=---                
                 @@@@@@#######++++++=====--                 
                  %%@@@@###%%@******+====*                  
                    %@@@@@@@@@@******###                    
                       %%%@@@@@%%%%%#                       
                     ..................                     
                    ....................                    
                  ........................                  
                 ..........................                 
                ............................                
               ..............................               
              ................................              
             ..................................             
                                                            
58 FPS (58-58)

Demo link: http://jabtunes.com/labs/3d/canvas_ascii_effects.html

I can’t really remember what triggered the thought process, but I thinking of that while being in the shower. Isn’t bathrooms quite a source of inspiration, like the Archimedes’ “Eureka!” story? While I’m not really an ASCII fanatic, I think I can appreciate some creative use of them. Some sites dedicated to these Ascii art are pretty interesting, such as 16 colors which utilises the javascript library escapes.js.

Some other ASCII effects I have found interesting includes a fluid solver, javascript raytracers, and a morphing animations! So much for the ASCII influence, that’s there even a text based category in the demoscene.

Moving to some implementation details:

1. JS Ascii Libraries
Originally I ambitiously wanted to complete the proof of concept in 15 minutes, so the first thing was to look existing ascii libraries in JS out there. Turns out there were a few libraries out there such as this and this, but I decided on nihilogic’s jsascii library which seems to provide a little more options despite being written a longer time before.

2. Extracting Image Data
Since jsascii and the similar libraries uses images as an input, the first integration approach extract the base64 encoded image data via the Canvas’s toDataURL() from CanvasRenderer, and import the image to the library and pull the Ascii output. Doesn’t take too long to realize its pretty silly wasting cycles when we could process the image data directly without encoding and decoding the image data by using canvas.getImageData().

So I started modifying jascii library to tap straight into the domElement of CanvasRenderer. I worked but performance was still horrible, so I being more tweakings, particularly the text resolution. By having a lower resolution, a larger font size would be use, resulting greater performance but less clarity. After making these adjustments, I found there certain ratios where there was good performance with reasonable clarity. In fact, the framerates were also on par or sometimes faster than rendering the canvas to screen. It ran well on Chrome, and ran even faster in Firefox.

3. Swapping WebGLRender with CanvasRenderer
The next little experiment was to use WebGLRenderer instead of CanvasRender for rasterizing the scene. Turns out that rendering ASCII with WebGLRenderer was slower than the CanvasRenderer. Alteredq suggest that it was probably more expensive to pull data out of the webgl context. Perhaps gl.readPixels might be a more efficient way of extracting data, but I haven’t tried that yet.

4. More Settings
Here’s another area to explore for the adventurous. JSAscii supports various options like enabling colors, inverting them, using blocks, and its pretty interesting to see some of these effects although some of these options have a big penalty on performance.

At the least, the reader might want to have some fun and try custom character sets. The ASCII library works by converting a pixel block into text by measuring its brightness and using an ascii character which represents that brightness. One could also try looking up and utilize unicode characters. In my experiments, I realized the use of even really simple pallets, for example one made of different sizes of dots, are interesting and effective too. (for example: start with something simple like ” .*%”)

5. Ascii Renderer -> Effects
In r49, the previously Anaglyph, Crosseyed, ParallaxBarrier Renderers were refactored to Effects, and are located in /examples/js/effects. AsciiRenderer follows the style and gets refactored to AsciiEffect. In r50dev, mrdoob works on several new software renderers, I did a couple of tests of the AsciiEffect with the new rasterizers, and they work too. Now in theory, with some modifications to the software renderer and ascii effect, one can effectively render a three.js scene in old non-canvas supported browsers, such as IE6, using ASCII output.

Finally, to throw out more ideas, one could create ASCII stereogram, combining the styles of Crosseyed and Ascii effect. ASCII stereograms may look like they would give a big headache, but they’re pretty cool!

Summing up, I hope the additional of the Ascii Effect provides a really simple way to do interesting 3d scenes and animation in Ascii, and probably a good way to relax when you get tired of writing glsl shaders.

Who knows if I’ll be writing up more text experiments again, but till then, it’d be interesting what else you may come up with!

ps. on a somewhat unrelated theme, I recently came across the demoscene production “the Butterfly Effect” by ASD and turns out that its a demo I really like…