3D transform calculations ported from this three.js demo.