3D Vector arithmetic and THREE.Vector3

CS 493 Lecture, Dr. Lawlor

Vectors, dot, and cross products (warp-speed review)

You should know basic 2D and 3D vectors, including dot products and cross products. Vectors are basically all we ever deal with in computer graphics, so it's important to understand these pretty well.

In particular, you should know at least:

JavaScript and THREE.Vector3

There are several annoying things about doing 3D vector work in JavaScript:
One of the most frustrating things about doing high performance code in interpreted languages is the high cost of dynamic allocations with "new".  C++ makes extensive use of stack allocation, so "vec3 a=2.0;" gets inlined and transformed into registers or temporaries by the compiler.  By contrast, in interpreted languages, this is a memory allocation.  Thus the API contorts to avoid creating new objects, typically by providing interfaces that mostly mutate existing objects rather than creating new objects.  You can work around this by explicitly asking for new objects (e.g., ".clone()") when you'd prefer not to trash the old values. 

For example:
GLSL or "osl/vec3.h"
Vector addition
vec3 c=a+b;
var c=a.clone().addSelf(b);
Incremental addition
Vector scaling
vec3 s=a*0.5;
var s=a.clone().multiplyScalar(0.5);
Dot product
float x=dot(a,b);
var x=a.dot(b);
Cosine of angle between vectors
float cos_ang=dot(a,b) / (length(a)*length(b));
var cos_ang=a.dot(b) / (a.length()*b.length());
Make unit vector
vec3 d=normalize(p);
var d=p.clone().normalize();

For examples, see the calculations in the boundary planes demo or the boundary sphere demo.