Saturday, July 30, 2016

WebGL terrain tutorial



Today I put together a quick tutorial on how to build a 3d terrain in Javascript, from setting up three.js to loading a heightmap and texture. More will be added later (controls and collision).

Each step is organized as a release in the Github repo so you can download them all individually or browse through the commit diffs to see each change being made.

The Github project is here: https://github.com/wybiral/terrain

And, if course, there's a demo of it here: https://wybiral.github.io/terrain/

Saturday, July 23, 2016

Procedural trees with Javascript

Here's another quick web experiment, this time exploring the use of particle systems to generate art.


You can watch it generate a random forest live here: https://wybiral.github.io/code-art/projects/trees/

Or if you're one of the cool kids you can clone the Git repo or browse the code here: https://github.com/wybiral/code-art

Each tree starts as a single particle representing the trunk and moves upward with a random chance of bending or splitting as it goes. The branches are rendered using a technique similar to the spray can from MS Paint to create a charcoal look. Random pixels are faded out as it runs to create a grainy fog effect.

Saturday, July 16, 2016

Audio synthesis in the browser with WebAudio

Audio synthesis with WebAudio is easy. To prove it I'll get straight to the point...

(If you don't want to follow along via blog post, a working example project with code broken up into logical commits and releases is available here: https://github.com/wybiral/webaudio-example)

The first thing you need is an instance of AudioContext:

var ctx = new AudioContext();
var node = ctx.createGain();
node.connect(ctx.destination);


The "node" object is actually a gain node that you can use to adjust the audio level but you can ignore that for now. All I did was connect it to the AudioContext destination (our ouput).

Now you need to create an audio buffer to stuff some samples into:

var duration = 1.0;
var rate = ctx.sampleRate;
var length = rate * duration;
var buffer = ctx.createBuffer(1, length, rate);
var data = buffer.getChannelData(0);

In case you're lost here, duration will be the length of our audio buffer in seconds. I've grabbed the sample rate from the audio context and used that to compute the length of the buffer. Now we have "data", which is a Float32Array that we can start adding samples to.

Let's fill that buffer with some noise (random noise in this case):

for (var i = 0; i < data.length; i++) {
    data[i] = Math.random() * 2 - 1;
}

Now all you have to do is play the buffer by creating an audio source and connecting it to the gain node.

var source = ctx.createBufferSource();
source.buffer = buffer;
source.connect(node);
source.start(0);

That's it. The Github code will show you how to turn this random noise into musical notes and goes into a bit more detail in the comments so go check it out!