Jono Shields

Procedurally Generated Scenes

This week I saw a totally rad twitter bot that posts procedurally generates mountain skylines.

I saw this and was jealous, mainly because last year I tried to make something similar that ended up looking like this…

image

Mine is nice and animated but is not as nice as @muted_mountains creations.

So I figured that I would go ahead and revamp mine to look a bit nicer.

Let’s change those hills from generic looking curves(that kind of look like waves in the sea) to something that looks more like mountains.

In my original I use Perlin Noise to generate the mountain. Perlin Noise is an algorithm that generates random numbers that are close to each other, this means that you can create smooth transitions between numbers and generate all kinds of curves. If you want to know more about Perlin Noise, then I would highly recommend this article by adrian’s soapbox.

The issue I am facing now is that I am struggling to get both the big amplitudes of the rolling mountains as well as the finer details that mountains have, the cracks, crevices and smaller rocks. This can however be acheived by using multiple octaves of Perlin Noise.

This essentially means adding multiple scales of Perlin noise together.

Again, the above blogpost covers this really well and these images were taken from there too. I took the code straight from that article and changed the syntax to javascript, worked like a charm.

function octavePerlin(x, y, z, octaves, persistence) {
    var total = 0;
    var frequency = 1;
    var amplitude = 1;
    var maxValue = 0;  // Used for normalizing result to 0.0 - 1.0
    for(var i=0;i<octaves;i++) {
        total += perlin.noise(x * frequency, y * frequency, z * frequency) * amplitude;
        
        maxValue += amplitude;
        
        amplitude *= persistence;
        frequency *= 2;
    }
    
    return total/maxValue;
}

And bam! We have lovely looking mountains.

I was pretty happy with this and started showing people. My friend Ian(@dentudim) was pretty impressed (obviously) and showed me this picture that he was reminded of (courtesy of chrischernewych).

Gorgeous! I wonder if I could make trees like that?

Lets just make a lovely sawtooth wave.

Easy right? But how?

All my mountains are drawn using Perlin Noise, to do this all the functions take a horizontal location on the screen and spit out the height of that point.

I wanted to do the same thing for the trees, so essentially we need a mathematical function.

We want a line that goes up and down real pointy like. So I started with a sawtooth wave. I achieved this with the modulo function.

Something like height = xPosition%100 and this gives us something that looks pretty deadly.

Next thing was making the waves symmetrical, this could be done by subtracting the modulo number from half of my frequency and aways taking the answer as a positive number. This gives me height = Math.abs(50 - xPosition%100).

Sweet. Now just to get some variation, like the hills, because trees don’t just magically float level, they are on something. For now I just combine the spikes with the mountain function and bam!

And together with the mountains…

And by the time I reached this point, Ian had already sent me another picture of a mountain with lovely low lying clouds.

So that was next, something fluffy to take away from the harsh pointy rigidity of the mountains and trees.

Once again Math to the rescue!

What is round and curvy?

A SINE WAVE!

height = Math.sin(xPosition)

I guess it could be fluffier and less wave like. But what if we took the bottom bits and make them look more like top bits?

Awesome!

And to add some variation I did the same that I did with the trees and pretended they were mountains.

Put it all together and wow!

At this point I was super happy with it. I posted it to my local gamedev facebook page for screenshot saturday and got some awesome feedback.

Add gradients on the mountains!! Its like Bob Ross always says; “they are more distinct at the top than they are at the bottom.”
Sam Batty

Thanks Sam! Now I had more work to do! And I was absolutely sure that this would be more difficult than the other components.

But no need to fear. I figured I could just reuse the exact same mountain, make it bit darker and offset it a bit depending where it is relative to the sun.

This looked better…

But not very realistic, the shadows on mountains aren’t predictable and vary based on the mountains curves. Unfortunately my mountains are only two dimensional and it is impossible to predict how the shadows should fall.

So lets fake it, make it a bit random, and a little more realistic than the above pic.

Using bits and pieces I already had, I threw a sawtooth wave into the mix. I made its amplitude bigger than the trees and the frequency smaller, I also threw some more Perlin Noise in to help vary the sawtooth in the x axis.

And this gives me the final product (at the time of writing this post).

I have a live demo of it here that you can check out. Yes I am sure you can find the source code in my github, but trust me it is not worth looking at.

I have ideas for a game that makes use of something like this, so maybe more of this in the future.


Animated Favicons

So you want to make a super badass animated favicon?

…skip to the code

As per the W3 spec the browser looks for your favicon in the head of your HTML document. All major browsers support .ico and .png filetypes. The highest resolution combatible universally is 32x32 pixels.

This is generally what it will look like.

<link rel="icon" 
      type="image/png" 
      href="http://example.com/myicon.png">

Fantastic! So my initial idea was just to change the href attribute of the link element using javascript.

This had two downfalls though…

  • Each new image had to be loaded first and the page would show the loading icon until each image frame of the animation had played.
  • A request is made for every frame of the animation even if it has already loaded it once. The browser doesn’t try to cache them.

So we get something that looks like this…

This isn’t very efficient, unless your intention is to slowly suck at your viewers data plan.

But there is another way to do it. I took inspiration from DEFENDER OF THE FAVICON, a game played entirely in the favicon of the webpage.

They render the game to a 16x16 pixel HTML5 canvas element then export each frame as a data: URI. A data: URI is the same data that makes up a png file, but base64 encoded and stored as a string.

Using a data: URI means that a request doesn’t need to be made because the information is already there. Depending on how complex your animation is, this might be a good solution for you. But since mine was two frames it was much easier to just convert them and stick them straight in the header.

There are a few online tools that can do this, and they are just a quick google away. Or you can render them in a canvas element and call the .toDataURL() method to fetch them.

Code

<link id="animated-favicon" rel="icon" type="image/png" href="">
<script>
    var currentIcon = false;
    function swapIcon(){
        var link = document.getElementById('animated-favicon');
        if(currentIcon){
            link.href = "data:image/png;base64,iVBORw0KGgoAAA.....";
        } else {
            link.href = "data:image/png;base64,iVBORw0KGgo.....";
        }
        currentIcon = !currentIcon;
    }
    setInterval(swapIcon, 1000);
</script>

But should we?

The unwritten rules of the internet declare visual or auditory effects without user consent a big no no. Pop up boxes, autoplaying videos and big splash pages are generally considered to be very annoying.

So where does this stand amongst all that. In my opinion in depends on the context and the site’s intention. Definitely think long and hard about why if you are considering animating your favicon.

PS. I am fully aware how annoying a low battery symbol is as a favicon. Enjoy!


Self Taught

Jono’s experiences with self learning

So.

I make a bunch of things.

My Github report card says that last year I made 372 commits across 28 repos in 5 languages. People ask me why I do it, spend 40 hours coding at work then go home and do more. It’s because I love it. Sure I could watch TV, play video games, hang out with friends or even go outside. It’s not like I don’t do these things though, but maybe less than others.

So passion is pretty key for me. It gives me the motivation I need to do this. But sometimes even when I want to do something the motivation isn’t always there.

A long time ago I worked in retail.

It was a job.

In my first year as we prepared for holiday period my manager gave this super inspirational speech…

Enthusiasm is one of the most powerful engines of success. When you do a thing, do it with all your might. Put your whole soul into it. Stamp it with your personality. Be active, be energetic and faithful and you will accomplish your goal. Nothing great was ever achieved without enthusiasm. - Ralph Waldo Emerson

This was the whiteboard in our lunch room 6 years ago.

It stuck with me ever since. It is hard for me to find motivation, sometimes even with things that I love. But going head first at 110% is something I find easier to do. It’s hard to be passionate about everything, especially the more tedious parts of a project. But you know what they say?

Honestly just try it. I was cynical at first too. But it works.

Just don’t make the same mistake I did, look after yourself. I was going all out when I felt inspired and when I didn’t, which is pretty much all the time in the day.

Sweet.

Motivation. Tick. Enthusiasm. Tick.

This is the bit where I got lost

Right now I am certain that if something has enough documentation then I can learn it or at least give it a decent go. But I am not sure how I got to this point. It is like all of a sudden some time ago a confidence switch turned on in my brain. I know I can solve problems and find answers.

So what is that?

How to learn how to learn?

I volunteer at codeclub every week with 10-12 year olds. I love it more than anything else I do because I get to share what I am passionate about with others. I want to help them get to the stage where they don’t need me anymore. So last year when they asked me for help I started replying with “Did you Google it?” and encouraging them to look for their own solutions first.

It is tough holding back the answers, especially when I am so keen to share them. But I want to foster initiative and self learning.

So this is where I am right now. Most still don’t do a google search before asking for help. I am suspicious that it’s because they haven’t done it before and are not confident in their own ability to find the solution. I worry that it’s a fear of failure.

But I don’t want to push them too far, I don’t want them to stop enjoying it.

It is almost like we need an codeclub tutorial that forces kids to google to find the answers.

HAHHAHAHAHAH LAUGHS MANIACALLY!!! AHAAHA

Okay I might actually do this. Write an exercise or something. Also talk about your downfalls more Jono, mistakes are a key part of learning and I make a hell of a lot of them.

Toodles.