New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

@thi.ng/vectors

Package Overview
Dependencies
Maintainers
1
Versions
298
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@thi.ng/vectors

Vector algebra for fixed & variable sizes, memory mapped, flexible layouts

  • 0.1.2
  • Source
  • npm
  • Socket score

Version published
Weekly downloads
4.9K
decreased by-22.04%
Maintainers
1
Weekly downloads
 
Created
Source

@thi.ng/vectors

npm (scoped)

This project is part of the @thi.ng/umbrella monorepo.

About

This package provides vector and matrix operations as plain functions and class wrappers with fluid interface. All functions support any array / typed array storage, incl. mapped views of larger buffers (e.g. for WebGL / WASM interop, pixel buffers). Additionally, vectors support flexible data layouts, incl. AOS / SOA, striped, interleaved, aligned etc.

Vectors

In addition to arbitrary sized vectors, the library provides these optimized fixed-sized versions:

Supported operations

Note: Most functions are provided in different (optimized) versions, depending on vector size. E.g. add performs vector addition for arbitrary sizes, add2 for 2D vectors, add3 for 3D, add4 for 4D...

All vector operations (regardless of size) operate on any array-like buffer and accept optional start indices and component strides (number of elements (+1) between individual vector components). This allows for zero-copy vector operations on sections of larger buffers. The default start index is 0, default stride 1. See examples below and tests.

OperationGVecVec2Vec3Vec4
Get vector (dense copy)getget2get3get4
Set vector components (vector)setset2set3set4
Set vector components (uniform)setNsetN2setN3setN4
Set vector components (scalars)setS2setS3setS4
Swizzle vector componentsswizzle2swizzle3swizzle4
Equality (w/ epsilon)eqDeltaeqDelta2eqDelta3eqDelta4
Vector additionaddadd2add3add4
Vector subtractionsubsub2sub3sub4
Vector multiplicationmulmul2mul3mul4
Vector divisiondivdiv2div3div4
Uniform scalar additionaddNaddN2addN3addN4
Uniform scalar subtractionsubNsubN2subN3subN4
Uniform scalar multiplymulNmulN2mulN3mulN4
Uniform scalar multiplydivNdivN2divN3divN4
Vector negationnegneg2neg3neg4
Multiply-add vectorsmaddmadd2madd3madd4
Multiply-add scalarmaddNmaddN2maddN3maddN4
Linear interpolation (vector)mixmix2mix3mix4
Linear interpolation (uniform)mixNmixN2mixN3mixN4
Dot productdotdot2dot3dot4
Cross productcross2cross3
Magnitudemagmag2mag3mag4
Magnitude (squared)magSqmagSq2magSq3magSq4
Normalize (w/ opt length)normalizenormalize2normalize3normalize4
Limit to lengthlimit2limit3limit4
Distancedistdist2dist3dist4
Distance (squared)distSqdistSq2distSq3distSq4
Manhattan distancedistManhattan2distManhattan3distManhattan4
Chebyshev distancedistChebyshev2distChebyshev3distChebyshev4
Reflectionreflect2reflect3reflect4
RotationXrotateX3
RotationYrotateY3
RotationZrotate2rotateZ3
Heading XYheading2headingXY3
Heading XZheadingXZ3
Heading YZheadingYZ3
Cartesian -> PolartoPolar2toSpherical3
Polar -> CartesiantoCartesian2toCartesian3
Minor axisminorAxis2minorAxis3minorAxis4
Major axismajorAxis2majorAxis3majorAxis4
Minimumminmin2min3min4
Maximummaxmax2max3max4
Range clampingclampclamp2clamp3clamp4
Step (like GLSL)stepstep2step3step4
SmoothStep (like GLSL)smoothStepsmoothStep2smoothStep3smoothStep4
Absolute valueabsabs2abs3abs4
Sign (w/ opt epsilon)signsign2sign3sign4
Round downfloorfloor2floor3floor4
Round upceilceil2ceil3ceil4
Square rootsqrtsqrt2sqrt3sqrt4
Power (vector)powpow2pow3pow4
Power (uniform)powNpowN2powN3powN4

Matrices

All matrix types are in WebGL layout (column major) and densely packed (stride always 1).

OperationMat23Mat33Mat44
Set identityidentity23identity33identity44
Get matrix components (dense copy)get23get33get44
Set matrix components (matrix)set23set33set44
Set matrix components (scalars)setS23setS33setS44
Create rotation matrixrotationX33rotationX44
rotationY33rotationY44
rotation23rotationZ33rotationZ44
rotationAroundPoint23
Create scale matrix (vector)scaleV23scaleV33scaleV44
Create scale matrix (uniform)scaleN23scaleN33scaleN44
Create scale matrix (scalars)scaleS23scaleS33scaleS44
scaleWithCenter23scaleWithCenter44
Create translation matrix (vector)translationV23translationV44
Create translation matrix (scalars)translationS23translationS44
Create skew matrixskewX23 / shearX23
skewY23 / shearY23
Create projection matrixprojection
ortho
frustum
Create camera matrixlookAt
Matrix multiplymul23mul33mul44
Matrix concatenation (multiple)concat23concat33concat44
Matrix vector multiplymulV23mulV33mulV44 (Vec4)
mulV344 (Vec3)
Determinantdet23det33det44
Matrix inversioninvert23invert33invert44
Matrix transposetranspose33transpose44

Installation

yarn add @thi.ng/vectors

Usage examples

Basics

import * as v from "@thi.ng/vectors";

// raw vector addition
v.add4([1, 2, 3, 4], [10, 20, 30, 40]);
// [ 11, 22, 33, 44 ]

// with custom layout
// here 3x 3D vectors in SOA layout:
//       [x, x, x, y, y, y, z, z, z]
points = [1, 4, 7, 2, 5, 8, 3, 6, 9];

// specify start indices and stride lengths
// update 1st vector
v.add3(points, [100, 200, 300], 0, 0, 3, 1);
// [ 101, 4, 7, 202, 5, 8, 303, 6, 9 ]

// update 2nd vector
v.add3(points, [100, 200, 300], 1, 0, 3, 1);
// [ 101, 104, 7, 202, 205, 8, 303, 306, 9 ]

// update 3rd vector
v.add3(points, [100, 200, 300], 2, 0, 3, 1);
// [ 101, 104, 107, 202, 205, 208, 303, 306, 309 ]

// add 1st and 3rd vector and extract result
v.get3(v.add3(points, points, 0, 2, 3, 3), 0, 3);
// [ 208, 410, 612 ]

// re-arrange vector components into new vector
// the last 4 args define component order:

// YXWZ
v.swizzle4([], [10, 20, 30, 40], 1, 0, 3, 2);
// [ 20, 10, 40, 30 ]

// XXZZ
v.swizzle4([], [10, 20, 30, 40], 0, 0, 2, 2);
// [ 10, 10, 30, 30 ]

// arbitrary length vectors
norm = v.normalize([1, 2, 3, 4, 5, 6, 7, 8, 6, 4]);
// [ 0.0625, 0.125, 0.1875, 0.25, 0.3125, 0.375, 0.4375, 0.5, 0.375, 0.25 ]

v.mag(norm);
// 1

Vector classes & interleaved vectors in large buffer

// element stride 3 + 2 + 4 = 9
buf = [
    // pos     uv   color (rgba)
    0,0,0,     0,0, 1,0,0,1,
    100,0,0,   1,0, 1,1,0,1,
    100,100,0, 1,1, 1,0,1,1,
    0,100,0,   0,1, 0,1,1,1,
];

// create memory mapped vector instances (using Vec3 class)
pos = v.Vec3.mapBuffer(buf, 4, 0, 1, 9); // offset = 0
uv = v.Vec2.mapBuffer(buf, 4, 3, 1, 9);  // offset = 3
col = v.Vec4.mapBuffer(buf, 4, 5, 1, 9); // offset = 5

console.log(`pos: ${pos[1]}, uv: ${uv[1]}, color: ${col[1]}`);
// pos: [100, 0, 0], uv: [1, 0], color: [1, 1, 0, 1]

// compute centroid
centroid = pos.reduce((c, p) => c.add(p), v.vec3()).divN(pos.length);
// Vec3 { buf: [ 50, 50, 0 ], i: 0, s: 1 }

// build matrix to transform geometry
tx = v.Mat44.concat(
    v.Mat44.scale(0.01),
    v.Mat44.translation(centroid.copy().neg()),
    v.Mat44.rotationZ(v.rad(90)),
);

// apply transform to all positions
pos.forEach((p) => tx.mulV3(p));

Image RGB grayscale conversion

canvas = document.getElementById("main");
img = canvas.getContext("2d").getImageData(0,0, canvas.width, canvas.height);

v.transformVectors1(
    // multiply each RGB vector w/ weights
    // then use result for all 3 color channels
    (a, b, ia, ib, sa, sb) =>
        v.setN3(a, v.dot3(a, b, ia, ib, sa, sb), ia, sa),
    // pixel buffer
    img,
    // RGB weight coefficients
    [0.29, 0.6, 0.11],
    // num pixels (RGBA vectors)
    canvas.width * canvas.height,
    // start indices
    0, 0,
    // component strides
    1, 1,
    // pixel stride
    4
);

Authors

  • Karsten Schmidt

License

© 2016 - 2018 Karsten Schmidt // Apache Software License 2.0

Keywords

FAQs

Package last updated on 30 Jul 2018

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc