Three. js is a great open-source webgl library. It simplifies browser 3D programming and makes it much easier to create complex scenarios in the browser using JavaScript. I am excited and eager to try many webgl demos on Github. Because this library is still in the development stage, there is a shortage of materials. Fans have to read the source code of this library most of the time. I am also preparing to do this now.
This is the first note, starting with the most basic Core object.
Core: Vector2
This constructor is used to create an object that represents a two-dimensional vector.Copy codeThe Code is as follows: THREE. Vector2 = function (x, y ){
This. x = x | 0;
This. y = y | 0;
};
Functions of the Vector2 object are implemented by defining the prototype object of the constructor, such:Copy codeThe Code is as follows: THREE. Vector2.prototype = {
Constructor: THREE. Vector2,
Set: function (x, y ){
This. x = x;
This. y = y;
Return this;
},
Copy: function (v ){
This. x = v. x;
This. y = v. y;
Return this;
},
... // More functions
};
The set (x, y) function is used to specify the value of a vector. The x and y values of the caller are affected, and the method itself returns the caller itself. This is common, it is not described below. Functions that can clearly express functions do not reference source code any more, which is not described below.
Function copy (v) is used to copy vector v into the caller.
The add (a, B) and sub (a, B) functions represent the addition and subtraction of the pair vectors a and B respectively.
The addSelf (v) and subSelf (v) functions add or subtract vector v to or from the caller.
The multiplyScale (s) and divideScale (s) functions are used to multiply or divide the caller by s.
The lerpSelf (v, alpha) function rotates the alpha from the caller to the direction indicated by v. When alpha is 1, the caller is eventually equal to v, and when alpha is 0, the caller is equal to the original.Copy codeThe Code is as follows: lerpSelf: function (v, alpha ){
This. x + = (v. x-this. x) * alpha;
This. y + = (v. y-this. y) * alpha;
Return this;
},
The negate () function is used to reverse the caller.
The dot (v) function returns the point multiplication of the float type caller and the vector v.
The lengthSq () and length () functions return the square or length of the float type caller.
The normalize () function normalizes the caller.
The distanceToSquared (v) and distanceTo (v) functions return the distance between the caller and the vector v. The distance here is actually the distance between the end points when both vectors start at the origin point, that is, the length of the vector this-v.
The setLength (s) function scales the vector length to s without changing the direction.
The equals (v) function determines whether the caller and the vector v have the same value.
The isZero () function determines whether the caller is a zero vector.
The function clone () returns a new vector with the same value as the caller, which is equivalent to copying it out. Note the difference with copy (v.
Core: Vector3
This constructor creates an object that represents a 3D vector.Copy codeThe Code is as follows: THREE. Vector3 = function (x, y, z ){
This. x = x | 0;
This. y = y | 0;
This. z = z | 0;
};
3D vectors have many commonalities with 2D vectors, such as set, add, dot, length, and clone. Here, all values are omitted, and only some functions of 3D vectors that are more than 2D vectors are recorded.
The setX (x), setY (y), and setZ (z) functions are used to separately set the values of a certain component.
The functions cross (a, B) and crossSelf (v) change the caller to a, B, or the caller and v respectively. A cross-multiplication is a vector perpendicular to the two vectors involved in the cross-multiplication and is in the right-hand spiral law.
The getPositionFromMatrix (m), getRotationFromMatrix (m), and getScaleFromMatrix (m) functions extract the position, rotation, and scaling components from the 4× 4 model matrix. The model matrix represents the superposition of a series of translation, rotation, and scaling transformations. (Here, the second function appears in the document and is replaced by the other two functions in the source code. It may not be updated yet ).
The angleTo (v) function calculates the angle between the caller and the vector v.
Core: Vector4
This constructor creates an object that represents a four-dimensional vector.Copy codeThe Code is as follows: THREE. Vector4 = function (x, y, z, w ){
This. x = x | 0;
This. y = y | 0;
This. z = z | 0;
This. w = (w! = Undefined )? W: 1;
};
Four-Dimensional vectors are used to represent the homogeneous coordinates. Their functions overlap with functions in Vector2 and Vector3, and only one more component is required.
Core: Matrix3
This constructor creates an object that represents a 3x3 matrix.
THREE. Matrix3 = function (){
This. elements = new Float32Array (9 );
};
The 3 × 3 matrix has nine elements stored in the attribute elements of the matrix object. elements is an array.
The getInverse (m) function returns the inverse matrix of matrix m and changes the caller.
The transpose () function is transposed to the caller.
The transposeToArray (r) function redirects callers to the array r without changing itself. (The source code is incorrect. var m = this. m should be var m = this. elements .)
Core: Matrix4
This constructor creates an object that represents a 4x4 matrix. a 4x4 matrix is very important in 3D graphics. model matrix, view matrix, and projection matrix are all such matrices.Copy codeThe Code is as follows: THREE. matrix4 = function (n11, n12, n13, n14, n21, n22, n23, n24, n31, n32, n33, n34, n41, n42, n43, n44 ){
This. elements = new Float32Array (16 );
This. set (
(N11! = Undefined )? N11: 1, n12 | 0, n13 | 0, n14 | 0,
N21 | 0, (n22! = Undefined )? N22: 1, n23 | 0, n24 | 0,
N31 | 0, n32 | 0, (n33! = Undefined )? N33: 1, n34 | 0,
N41 | 0, n42 | 0, n43 | 0, (n44! = Undefined )? N44: 1
);
};
Several Functions in the Matrix3 object play the same role in Matrix4, which is also omitted here.
The Function identity () resets an object to a unit array.
The lookAt (eye, center, up) function sets an object as a view matrix. All parameters are Vector3 objects. This matrix only uses the relative positions of eye and center. This view matrix indicates that the camera is directed to the center at the eye position, and the upward vector (which will be explained later) is the view matrix at the up position. The view matrix can also be seen as the model matrix of the camera. Therefore, the matrix generated by this function can represent the following transformations: moving an object from the origin to the center-eye position, and then rotate it to the up vector as up. The up vector up is used to fix the camera. It can be imagined that when the camera is fixed at a point and the camera orientation is fixed, the up vector can still rotate freely in one dimension.Copy codeThe Code is as follows: lookAt: function (eye, target, up ){
Var te = this. elements;
Var x = THREE. Matrix4. _ v1; // empty Vector3 object, the same below
Var y = THREE. Matrix4. _ v2;
Var z = THREE. Matrix4. _ v3;
Z. sub (eye, target). normalize ();
If (z. length () === 0 ){
Z. z = 1;
}
X. cross (up, z). normalize ();
If (x. length () = 0 ){
Z. x + = 0.0001;
X. cross (up, z). normalize ();
}
Y. cross (z, x );
Te [0] = x. x; te [4] = y. x; te [8] = z. x;
Te [1] = x. y; te [5] = y. y; te [9] = z. y;
Te [2] = x. z; te [6] = y. z; te [10] = z. z;
Return this;
},
The multiply (a, B), multiplySelf (v) and multiplyToArray (a, B, r) functions multiply the two matrices.
The multiplyScale (s) function times all 16 elements of an object by s.
The multiplyVector3 (v) and multiplyVector4 (v) functions multiply the left side of the object matrix by the four-dimensional row vector and return the row vectors of the vector3 and vector4 types. If the object matrix is a model view matrix and the input vector is the point position information, the output vector is the position of the point relative to the camera after the model transformation and camera transformation. When a vector of the vector3 type is input, it is automatically filled with the homogeneous coordinates, and the fourth component is cut off as the normal coordinates when the return result is returned.
The rotateAxis (v) function uses the 3 × 3 sub-matrix in the upper left corner of the object matrix to obtain a new row vector and normalize it. This new row vector is returned. This function also updates the value of vector v. The 3×3 submatrix in the upper left corner of the model view matrix contains the rotation information in the model matrix. This submatrix is left multiplied by a vector, the new vector is actually obtained after the original vector is rotated (the rotation effect is derived from the model matrix. Therefore, this function is named rotateAxis.Copy codeThe Code is as follows: rotateAxis: function (v ){
Var te = this. elements;
Var vx = v. x, vy = v. y, vz = v. z;
V. x = vx * te [0] + vy * te [4] + vz * te [8];
V. y = vx * te [1] + vy * te [5] + vz * te [9];
V. z = vx * te [2] + vy * te [6] + vz * te [10];
V. normalize ();
Return v;
},
The function crossVector (v) calculates the cross multiplication of the matrix object (caller) and v, which is actually the left-side four-dimensional row vector v of the object matrix and returns the vector. I haven't figured out what this is.Copy codeThe Code is as follows: crossVector: function (){
Var te = this. elements;
Var v = new THREE. Vector4 ();
V. x = te [0] * a. x + te [4] * a. y + te [8] * a. z + te [12] * a. w;
V. y = te [1] * a. x + te [5] * a. y + te [9] * a. z + te [13] * a. w;
V. z = te [2] * a. x + te [6] * a. y + te [10] * a. z + te [14] * a. w;
V. w = (a. w )? Te [3] * a. x + te [7] * a. y + te [11] * a. z + te [15] * a. w: 1;
Return v;
},
The determinant () function is used to calculate the determining value of the matrix.
Functions flattenToArray (flat) and flattenToArrayOfset (flat, offset) convert the Matrix to a one-dimensional array. The previous function is stored from flat [0] to flat [15]. the next function allows you to specify the Storage Start location, from flat [offset] to flat [offset + 15].
The getPosition () and setPosition () functions are used to obtain or set the position component of a matrix object. Just as the rotating component is stored in the 3 × 3 sub-matrix in the upper left corner, the positional component is stored in the first three components of the fourth row, that is, element [12], element [13], element [14.
The getColumeX (), getColumeY (), and getColumeZ () functions extract the three columns of the 3x3 sub-matrix in the upper left corner.
Function compose (translate, rotation, scale) sets the object matrix to the transform matrix that combines the translation represented by the vector3 type translate object, the rotation represented by the matrix3 type rotation object, and the scaling represented by the vector3 Type scale object.. In fact, it is directly filled into the corresponding sub-spaces of the model matrix.
The decompose (translate, rotation, scale) function splits the matrix object into three objects, which is the opposite of the previous function.
The extractPosition (m) and extractRotation (m) functions extract the components in the matrix object m that indicate the position or rotation to the caller object. For example, two objects undergo multiple and different transformations, only the Model View matrix of one object extractRotation Model View matrix of another object is required, and the caller maintains the same rotation orientation as the other object.
The function translate (v) is one of the most basic transformations of the model matrix: Translation transformation, which refers to the object translation vector v that the model matrix belongs.
The rotateX (angle), rotateY (angle), and rotateZ (angle) functions rotate the angle of the X, Y, and Z axes of the objects affiliated to the model matrix respectively.
The rotateByAxis (axis, angle) function rotates an object affiliated to the model matrix around an arbitrary axis angle, this is the multiple superposition of the preceding two transformations (the superposition parameter is determined by the current position and the axis parameter). In Model View matrix and Projection Matrix: webgl note (1) this article discusses the issue of rotating around any axis.
Shouldn't there be a scale (s) function here? But I cannot find it in the source code.
Functions include makeTranslate (x, y, z), makeRotationX (theta), makeRotationY (theta), makeRotationZ (theta), makeRotationAxis (axis, angle), and makeScale (s) the function directly resets the object matrix to a matrix after a single translation, or rotating around an axis, or simply scaling. This function updates the value of the object, and the updated result is unrelated to the previous value of the object (this is also a feature of the make prefix function ).
Function makeFrustum (...), makePerspective (...), makeOrthographic (...) it is also used to initialize the new matrix. The specific meaning is discussed in the camera class. I think the camera class constructor will certainly call these functions.
Function clone () copies the matrix object and returns it.
Core: Face3
This function creates a triangle plane object.Copy codeThe Code is as follows: THREE. Face3 = function (a, B, c, normal, color, materialIndex ){
This. a =;
This. B = B;
This. c = c;
This. normal = normal instanceof THREE. Vector3? Normal: new THREE. Vector3 ();
This. vertexNormals = normal instanceof Array? Normal: [];
This. color = color instanceof THREE. Color? Color: new THREE. Color ();
This. vertexColors = color instanceof Array? Color: [];
This. vertexTangents = [];
This. materialIndex = materialIndex;
This. centroid = new THREE. Vector3 ();
};
The, B, and c values of the object are the indexes of the three vertices (as mentioned later, all vertices are stored as an array in the Mesh object). As the name suggests, normal is the normal, and color is the color; materialIndex is a vertex Material Index. These parameters can be imported into the vector3 type and the array type.
The clone (x) method returns a new object with the same value.
Core: Face4
This function creates a plane of four vertices, which is almost the same as Face3 and omitted.
Core: Math
THREE. Math is a "static class" and does not have constructor. Therefore, it does not need to be initialized using the new keyword. This class provides some necessary mathematical tools.
Function clamp (x, a, B) inserts x in the range [a, B. ClampBottom (x, a) works similarly, but only one side is clipped.
The mapLinear (x, a1, a2, b1, b2) function calculates a value y, so that the vertex (x, y) falls into (a1, a2) and (b1, b2) in a straight line.Copy codeThe Code is as follows: mapLinear: function (x, a1, a2, b1, b2 ){
Return b1 + (x-a1) * (b2-b1)/(a2-a1 );
},
The functions random16 (), randInt (low, high), randFloat (low, high), and randFloatSpread (range) generate 16 random floating point numbers in the range [0, 1], [low, high] interval random integer, [low, high] interval random floating point number, [-range/2, range/2] interval random floating point number.
The sigh (x) function returns + 1 or-1 Based on the x symbol.
Core: Clock
This constructor creates a clock (stopwatch) object.Copy codeThe Code is as follows: THREE. Clock = function (autoStart ){
This. autoStart = (autoStart! = Undefined )? AutoStart: true;
This. startTime = 0;
This. oldTime = 0;
This. elapsedTime = 0;
This. running = false;
};
The start () and stop () functions are used to start or stop timing.
The getDelta () function returns the length of time between the call of the function and the previous call of the function. If this function is called for the first time, the length of time from the start of time is returned. If the autoStart value is true, if the start () function is not called or the stop () function has been called when the getDelta () function is called, the time is automatically started and 0 is returned. If the autoStart () value is false, call getDelta () to return 0 before or after start () is called.
The getElapsedTime () function returns the time from the start time when the function is called.
Core: Color
This constructor constructs an object that represents colorCopy codeThe Code is as follows: THREE. Color = function (hex ){
If (hex! = Undefined) this. setHex (hex );
Return this;
};
The setHex (hex) function sets the r, g, and B attributes of an object in hexadecimal sequence. In fact, in the object, colors are stored based on these three attributes.Copy codeThe Code is as follows: setHex: function (hex ){
Hex = Math. floor (hex );
This. r = (hex> 16 & 255)/255;
This. g = (hex> 8 & 255)/255;
This. B = (hex & 255)/255;
Return this;
},
The setRGB (r, g, B) and setHSV (h, s, v) functions are used to set objects with RGB or HSV values.
The getHex () function returns the hexadecimal color value.
The copyGammaToLinear (color) and copyLinearToGamma (color) functions are used to assign the rgb values of color to the caller respectively by square or square.
The convertGammaToLinear () and convertLinearToGamma () functions are respectively open to the caller's own rgb values.