nooshu - Matt Hobbs' Web Development Blog

Kneeling on the shoulders of giants

Debug Axes in three.js

Update: The code I had previously stopped working with the latest three.js API. I’ve updated and improved the code for the latest API.

I’ve been working on a couple of small projects using three.js recently; An issue I always seem to have when working with 3D is knowing the current orientation. To help me out I’ve put together a small snippet of JavaScript.

Creating a set of axis in three.js

{x: red, y: green, z: blue} It's not much to look at but the axes can be very useful.

The point where the lines cross is 0,0,0 as you’d expect, you can adjust the length of the line by changing the axisLength variable. I’ve uploaded a small demo so you can see the code used or copy / paste below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
var debugaxis = function(axisLength){
    //Shorten the vertex function
    function v(x,y,z){
            return new THREE.Vertex(new THREE.Vector3(x,y,z));
    }
   
    //Create axis (point1, point2, colour)
    function createAxis(p1, p2, color){
            var line, lineGeometry = new THREE.Geometry(),
            lineMat = new THREE.LineBasicMaterial({color: color, lineWidth: 1});
            lineGeometry.vertices.push(p1, p2);
            line = new THREE.Line(lineGeometry, lineMat);
            scene.add(line);
    }
   
    createAxis(v(-axisLength, 0, 0), v(axisLength, 0, 0), 0xFF0000);
    createAxis(v(0, -axisLength, 0), v(0, axisLength, 0), 0x00FF00);
    createAxis(v(0, 0, -axisLength), v(0, 0, axisLength), 0x0000FF);
};

//To use enter the axis length
debugaxis(100);

It’s not much to look at, but it can certainly help you get your bearing when starting a new project (or when things aren’t working!). Hopefully you find it useful.

The Sieve of Eratosthenes

I recently read Prime Obsession by John Derbyshire; a book all about prime numbers and one of the worlds greatest Mathematicians: Bernhard Riemann. The books main focus is on the Riemann Hypothesis which states that:

The real part of any non-trivial zero of the Riemann zeta function is 1/2.

I’d love to say that after reading the book I understand the Maths behind it but alas I do not. That’s not surprising though as it’s a problem that has yet to be solved, 159 years after Riemann paper on “On the Number of Primes Less Than a Given Magnitude”. It doesn’t look like it’s going to be solved any time soon either! If you’re interested it’s one of the Clay Mathematics Institutes Millennium Prize Problems in which you can earn yourself US$1,000,000.

While reading Prime Obsession it mentioned an interesting method for finding prime numbers called “Sieve of Eratosthenes” (pronounced air-a-TAWS-the-nEEss). Eratosthenes was a librarian at the great library of Alexandria around 230 B.C.E. It’s quite obvious how the method works once you know it, and easy to see why it’s called a sieve. The method goes like this:

  1. Write a list of numbers in which you wish to identify the primes, say 2 – 100 (exclude 1 as it isn’t required)
  2. Take the first number 2. Leaving 2 intact, remove every second number.
  3. Move onto the next number 3. Leave 3 intact and remove every third number
  4. Take the next number 5. Leave 5 intact and take away every fifth number
  5. Repeat until you get to the end of your list

The end result is the set of prime numbers up to your given number. Essentially all you are doing is removing any number that is divisible by the 1st, 2nd… Nth number. Clever stuff!

As a little side project I decided to implement this method using JavaScript, displaying the result in the browser. You can view the demo here. For fun I created two implementations, one relying heavily on the DOM, the other only using arrays. As you’d expect the DOM method is slow; looping through large tables multiple times doesn’t make for a quick execution time. The second method using a single JavaScript array is much quicker. I’ve added a stats panel to the right hand side of the page so it’s possible to compare results from both methods over different input values.

I’ve added a limit to the number you can enter into the input box (5000), I don’t want anyone blaming me for crashing their browser by entering 10 million! :) Feel free to copy the demo if you want to see what happens at higher values.

Sieve of Eratosthenes using JavaScript

The sieve in action showing prime numbers up to 500.

Thanks goes to John Resig for his very handy Array Remove method.It made removing non-primes from the numbers array very simple indeed.

Prime Obsession is a superb book but a word of warning, it contains a lot of higher level Mathematics, so may not be to everyone’s taste. It certainly made my brain hurt at times; not always what you need on that 8am commute to work! View the demo.

Creating 3D trees with some #CreativeJS

Random trees created using three.js and some creative JavaScript

Trees generated at random using some CreateiveJS and Three.js.

Over a month has passed since my last blog post and much has happened. We’ve had a wedding, a funeral at sea (maybe in bad taste!) and I’ve gone full-time freelance (yay!). I’ve had a little more time to work on a couple of personal projects so I’ve finished one that I started way back in January.

I had the pleasure of attending a Creative JavaScript course in Brighton, UK, hosted by Seb Lee-Delisle; a two-day course that covered a wealth of topics from Vanilla JavaScript to Three.js. If you’re looking for some inspiration I highly recommend looking out for one of Seb’s courses. Great fun and you get to meet some really nice people. Quick tip: You may want to brush up on a little Trigonometry before you go as it’s used numerous times. I knew that A-Level Mathematics course would come in useful one day :).

Seb produced a demo in Canvas that created ‘trees’ and it really caught my eye. The trees were in 2D so as I’ve had a bit of experience with Three.js I decided to create a 3D version! I’m quite happy with the result although I’ve had to restrict the number of branches rendered due to the lack of dedicated graphics card in my laptop; I get about 1fps when stopping at a branch length value of 10 (line 211) :(

The demo also allowed me to use the new request animation frame API which vendors have added to aid animations in browsers. The main advantage of using it is if you have the animation running in a tab that isn’t visible, the browser will know to stop the animation! Using the old setTimeout method, the animation still runs in the background and uses up precious CPU, memory and battery power (especially on a laptop). As with most new browser features the API isn’t set in stone (yet) but luckily Paul Irish has created a polyfill that falls back to setTimeout in older browsers.

View the demo here; reload for different trees. JavaScript finally seems to be coming of age!

Update: Original credit goes to Jean-No with his amazing OpenProcessing work! I’ll be bookmarking that link, some stunning work there. Thanks to Seb for pointing out who to credit :)

WordPress Stats broken? Grab yourself a Jetpack!

Last week one of my favourite WordPress plug-ins broke: WordPress Stats. For anyone who doesn’t use this fantastic plug-in it’s a very clean and simple way of viewing visitor statistics directly on your dashboard. It isn’t as extensive as Google Analytics and for that I’m grateful as it doesn’t need to be. I first thought it was a hosting issue but that turned out to be incorrect. The plug-in, in it’s current form has been discontinued as it has been rolled into a compilation of useful WordPress tools called Jetpack.

So what do you get in Jetpack? Well here are three of my favourites:

  • WordPress.com Stats – exactly what it says on the tin…
  • Shortcode Embeds – easily add media from YouTube, Vimeo and Slideshare.
  • LaTeX – need equations in a blog post? This ones for you then.

There are eight plug-ins currently available with more coming soon.

The last plug-in I mentioned, LaTeX may sound like it’s come straight from a .xxx domain name but bare with me; under that slightly suspect name is a powerful tool for anyone who needs to format equations in a post. Here’s a small demonstration:

e^{i\pi} + 1 = 0

LaTeX has allowed me to embed one of the most beautiful equations in all of mathematics; Euler’s Equation directly into my blog post. It links Real Numbers, Euler’s Number, Imaginary Numbers and Pi in a staggeringly simple equation. There’s a mass of information on LaTeX here with everything you’d ever need pretty much covered.

So if you’re looking to give your WordPress blog a bit of a boost (horrible pun I know), give Jetpack a whirl!

Fractal magic with WebGL

I’ve been so busy recently I haven’t had chance to work on any personal projects (bar a small amount of node.js, but that’s a future blog post); so I thought I do a quick post on a very impressive project that caught my eye last week: Fractal Lab.

Fractal Lab interactive examples

Pure mathematical worlds generated using Fractal Lab

Fractal Lab, as the name suggests, is a fractal rendering tool using OpenGL Shading Language (GLSL) by a very talented programmer called Tom Beddard. Now I’m not going to lie to you, the mathematics behind all this goes way over my head! OpenGL on the other hand is something I’ve read about with increasing frequency recently due to the WebGL explosion happening on the ‘net at the moment. Big thanks to all the developers of Firefox, Chrome (Webkit) and Opera for that! Internet Explorer 9 on the other hand isn’t planning on supporting it. Hopefully that will change in the future.

Fractal Lab allows you to render out 2D & 3D fractals directly to your browser and navigate through them in real time! Be warned though, this will push your browser and graphics card really hard. It mentions this on the site; it’s possible to lock-up your GPU with certain GLSL fractal shaders, so be careful (my poor laptops on-board graphics card did exactly that, so he’s not lying) :)

There’s hours of fun and experimentation to be had with this superb example or WebGL. Thank you to Tom for developing it.

Currently on page 4 of 23« First23456Last »