File indexing completed on 2025-01-19 04:00:00

0001 export class Vector
0002 {
0003     constructor(...components)
0004     {
0005         if ( this.constructor._size && components.length == 0 )
0006             this.components = new Float32Array(this.constructor._size)
0007         else
0008             this.components = Float32Array.from(components);
0009     }
0010 
0011     length()
0012     {
0013         return Math.hypot(...this.components);
0014     }
0015 
0016     length_squared()
0017     {
0018         return this.components.reduce((a, b) => a*a + b*b);
0019     }
0020 
0021     normalize()
0022     {
0023         var len = this.length();
0024         this.components.forEach((v, i, arr) => arr[i] /= len);
0025         return this;
0026     }
0027 
0028     flip()
0029     {
0030         this.components.forEach((v, i, arr) => arr[i] = -v);
0031         return this;
0032     }
0033 
0034     subtract(other)
0035     {
0036         this.components.forEach((v, i, arr) => arr[i] -= other.components[i]);
0037         return this;
0038     }
0039 
0040     add(other)
0041     {
0042         this.components.forEach((v, i, arr) => arr[i] += other.components[i]);
0043         return this;
0044     }
0045 
0046     divide(scalar)
0047     {
0048         this.components.forEach((v, i, arr) => arr[i] /= scalar);
0049         return this;
0050     }
0051 
0052     multiply(scalar)
0053     {
0054         this.components.forEach((v, i, arr) => arr[i] *= scalar);
0055         return this;
0056     }
0057 
0058     clone()
0059     {
0060         return new this.constructor(...this.components);
0061     }
0062 
0063     static define_named_component(name, index)
0064     {
0065         Object.defineProperty(this.prototype, name, {
0066             configurable: false,
0067             enumerable: false,
0068             get: function(){return this.components[index];},
0069             set: function(v){return this.components[index] = v;},
0070         });
0071     }
0072 
0073     static define_size(size)
0074     {
0075         this._size = size;
0076     }
0077 
0078     dot(other)
0079     {
0080         return (
0081             this.components
0082             .map((v, i) => v * other.components[i])
0083             .reduce((a, b) => a+b)
0084         );
0085     }
0086 
0087     lerp(other, factor)
0088     {
0089         return this.multiply(1-factor).add(other.clone().multiply(factor));
0090     }
0091 }
0092