3D Vectors, vec3, and THREE.Vector3

CS 482 Lecture, Dr. Lawlor

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, but this adds more syntactic overhead.

For example:
GLSL or "osl/vec4.h"
Vector addition
vec3 c=a+b;
var c=a.p(b);
var c=a.clone().addSelf(b);
Incremental addition
Vector scaling
vec3 s=a*0.5;
var s=a.t(0.5);
var s=a.clone().multiplyScalar(0.5);
Vector average
vec3 c=(a+b)*0.5;
var c=a.p(b).t(0.5);
var c=a.clone().add(b).multiplyScalar(0.5);
Dot product
float x=dot(a,b);
    - same ->
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());
Cross product
vec3 d=cross(a,b);

var d=a.clone().cross(b); // make new vector
d.crossVectors(a,b); // assign old vector
Make unit vector
vec3 d=normalize(p);

var d=p.clone().normalize();

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:
Try out the PixAnvil vec3 demo!