A vector math package for 2D and 3D applications

Overview

CI Coverage Status

Introduction

A Vector math library for 2D and 3D applications.

Features

  • 2D, 3D, and 4D vector and matrix types.
  • Quaternion type for animating rotations.
  • Collision detection: AABB, rays, spheres, ...
  • Utilities like color and common rendering related operations
  • Flexible getters and setters, for example, position.xwz = color.grb;.
  • Fully documented.
  • Well tested.
  • Heavily optimized.

Libraries using vector_math

Examples

1. Using the GLSL getter and setter syntax.

import 'package:vector_math/vector_math.dart';

void main() {
  Vector3 x = new Vector3.zero(); // Zero vector
  Vector4 y = new Vector4.all(4.0); // Vector with 4.0 in all lanes
  x.zyx = y.xzz; // Sets z,y,x the values in x,z,z
}

2. Transforming a vector.

import 'dart:math';
import 'package:vector_math/vector_math.dart';

void main() {
  // Rotation of PI/2 degrees around the Y axis followed by a
  // translation of (5.0, 2.0, 3.0).
  Matrix4 T = new Matrix4.rotationY(PI * 0.5)..translate(5.0, 2.0, 3.0);
  // A point.
  Vector3 position = new Vector3(1.0, 1.0, 1.0);
  // Transform position by T.
  T.transform3(position);
}

3. Invert a matrix

import 'dart:math';
import 'package:vector_math/vector_math.dart';

void main() {
  // Rotation of 90 degrees around the Y axis followed by a
  // translation of (5.0, 2.0, 3.0).
  Matrix4 T = new Matrix4.rotationY(PI * 0.5)..translate(5.0, 2.0, 3.0);
  // Invert T.
  T.invert();
  // Invert just the rotation in T.
  T.invertRotation();
}

4. Rotate a vector using a quaternion

import 'dart:math';
import 'package:vector_math/vector_math.dart';

void main() {
  // The X axis.
  Vector3 axis = new Vector3(1.0, 0.0, 0.0);
  // 90 degrees.
  double angle = PI / 2.0;
  // Quaternion encoding a 90 degree rotation along the X axis.
  Quaternion q = new Quaternion.axisAngle(axis, angle);
  // A point.
  Vector3 point = new Vector3(1.0, 1.0, 1.0);
  // Rotate point by q.
  q.rotate(point);
}

5. Check if two axis aligned bounding boxes intersect

import 'package:vector_math/vector_math.dart';

void main() {
  // Define the first box with a minimum and a maximum.
  Aabb2 aabbOne = new Aabb2.minMax(new Vector2.zero(), new Vector2(4.0, 4.0));
  // Define the second box
  Aabb2 aabbTwo =
      new Aabb2.minMax(new Vector2(5.0, 5.0), new Vector2(6.0, 6.0));
  // Extend the second box to contain a point
  aabbTwo.hullPoint(new Vector2(3.0, 3.0));
  // Check if the two boxes intersect, returns true in this case.
  bool intersect = aabbOne.intersectsWithAabb2(aabbTwo);
}

6. Check where a ray and a sphere intersect

import 'package:vector_math/vector_math.dart';

void main() {
  // Define a ray starting at the origin and going into positive x-direction.
  Ray ray = new Ray.originDirection(new Vector3.zero(), new Vector3(1.0, 0.0, 0.0));
  // Defines a sphere with the center (5.0 0.0 0.0) and a radius of 2.
  Sphere sphere = new Sphere.centerRadius(new Vector3(5.0, 0.0, 0.0), 2.0);
  // Checks if the ray intersect with the sphere and returns the distance of the
  // intersection from the origin of the ray. Would return null if no intersection
  // is found.
  double distanceFromOrigin = ray.intersectsWithSphere(sphere);
  // Evaluate the position of the intersection, in this case (3.0 0.0 0.0).
  Vector3 position = ray.at(distanceFromOrigin);
}

7. Work with colors

import 'package:vector_math/vector_math.dart';

void main() {
  // Access a build-in color, colors are stored in 4-dimensional vectors.
  Vector4 red = Colors.red;
  Vector4 gray = new Vector4.zero();
  // Convert the red color to a grayscaled color.
  Colors.toGrayscale(red, gray);
  // Parse a blue color from a hex string.
  Vector4 blue = new Vector4.zero();
  Colors.fromHexString('#0000FF', blue);
  // Convert the blue color from RGB to HSL.
  Colors.rgbToHsl(blue, blue);
  // Reduce the lightness of the color by 50%.
  blue.z *= 0.5;
  // Convert the HSL color back to RGB.
  Colors.hslToRgb(blue, blue);
}

Development

To run test cases:

~/src/vector_math/> pub run test:test

To automatically generate the latest version of vector_math_64:

~/src/vector_math/> dart tool/generate_vector_math_64.dart
Comments
  • Feature/cleanup

    Feature/cleanup

    I started this pull request with the goal to remove call chaining (#59) but I also took a look at "some" other things:

    • Remove call chaining (breaking change, but the Dart Editor gives very good guidance here!)
    • Rename some parts to match the Dart Style guide (constants, constructors, ...) (I only deprecated them)
    • Removed some methods that didn't provide a real benefit (e.g. Sphere.copyOriginDirection)
    • Formatting
    • Analyser warnings
    • Remove duplicate code (e.g. the plus operator of a vector can share the same code as VectorN.add)
    • Add more documentation comments (especially for the collision detection objects)
    • Improve code in a way that dart2js can generate better code. I took these suggestions as a start. Here is a example of dart2js code that changed, the old code:
    dot$1: [function(other) {
          var t1, t2, t3, t4, t5, t6, t7;
          t1 = this.storage;
          t2 = t1[0];
          t3 = other.get$storage();
          t4 = t3.length;
          if (0 >= t4)
            return H.ioore(t3, 0);
          t5 = t3[0];
          t6 = t1[1];
          if (1 >= t4)
            return H.ioore(t3, 1);
          t7 = t3[1];
          t1 = t1[2];
          if (2 >= t4)
            return H.ioore(t3, 2);
          return t2 * t5 + t6 * t7 + t1 * t3[2];
        }, "call$1", "get$dot", 2, 0, null, 109, []],
    

    and the new code:

        dot$1: [function(other) {
          var otherStorage, t1;
          otherStorage = other.get$_storage();
          t1 = this._storage;
          return t1[0] * otherStorage[0] + t1[1] * otherStorage[1] + t1[2] * otherStorage[2];
        }, "call$1", "get$dot", 2, 0, null, 109, []],
    

    In this case range checks could be removed, in other cases less calls to getters are made. It also has a small influence on code size, but I don't think that these are significant. For the future it would be nice to have a test bench to compare the performance of changes in both the DartVM and Dart2Js. Not sure what to choose as a benchmark here, maybe some sort of simulation?

    opened by Fox32 22
  • Vector*.random constuctor

    Vector*.random constuctor

    See #170 The code generation tool has added some code to the 64bit float library that did not exists before (someone forgot to run it?). The formatting of some parts is also altered since I ran dartfmt.

    opened by bergwerf 13
  • More collision objects

    More collision objects

    I need some objects for collision detection. I implemented only the features, like intersection tests and other methods, that I need. But I hope that others users of the library add the features that they are missing. I will probably later add some more features, but at the moment I don't need more.

    Summary:

    • AabbN
      • More intersection tests
        • Point
        • Triangle
      • Renamed contains and intersectsWith to containsAabb and intersectsWithAabb to allow a better naming scheme. This is a breaking change =/ not sure about it.
    • Sphere
      • Sphere
      • Point
    • Ray
      • at method
      • intersectsWithSphere
      • intersectsWithTriangle
    • Triangle
    • Plane
    • Frustum
    • VectorN
      • distanceTo / distanceToSquared

    Any comment are welcome =D

    opened by Fox32 13
  • [WIP] Add Aabb2

    [WIP] Add Aabb2

    This adds an Aabb2 class to the library.

    Currently it has no transform and rotate methods because I am not quite sure what exactly the difference between absoluteRotate and transform are and why the Aabb3 class takes an Matrix4 instead of Matrix3.

    But the Aabb2 class has the following three methods, which could also be added to the Aabb3 class: void setFromCombination(Aabb2 a, Aabb2 b) bool contains(Aabb2 other) bool intersectsWith(Aabb2 other)

    opened by laszlokorte 11
  • Reuse Matrix3, Matrix4 and Vector3 in decompose

    Reuse Matrix3, Matrix4 and Vector3 in decompose

    The reduction in allocations improves the performance of the Matrix4Tween benchmarks by roughly 20%

    JIT VM Matrix4TweenBenchmark1(RunTime): 6488.954692556635 us. Matrix4TweenBenchmark2(RunTime): 4512.9009009009005 us. Matrix4TweenBenchmark3(RunTime): 4744.867298578199 us. ---> Matrix4TweenBenchmark1(RunTime): 5072.906329113924 us. Matrix4TweenBenchmark2(RunTime): 3204.7952 us. Matrix4TweenBenchmark3(RunTime): 3394.628813559322 us.

    JSC: Matrix4TweenBenchmark1(RunTime): 12300.613496932516 us. Matrix4TweenBenchmark2(RunTime): 9578.947368421053 us. Matrix4TweenBenchmark3(RunTime): 7347.985347985348 us. ---> Matrix4TweenBenchmark1(RunTime): 10287.179487179486 us. Matrix4TweenBenchmark2(RunTime): 7948.412698412699 us. Matrix4TweenBenchmark3(RunTime): 5717.142857142857 us.

    Chrome 74: Chrome has a serious performance problem with allocating Float64Array(9) and Float64Array(16). This makes the Chrome impact of the allocation reductions much higher. This is V8 issue 9199 Matrix4TweenBenchmark1(RunTime): 66481.45161290323 us. Matrix4TweenBenchmark2(RunTime): 63572.8125 us. Matrix4TweenBenchmark3(RunTime): 60984.666666666664 us. ---> Matrix4TweenBenchmark1(RunTime): 30604.090909090908 us. Matrix4TweenBenchmark2(RunTime): 26960.68 us. Matrix4TweenBenchmark3(RunTime): 19803.663366336634 us.

    opened by rakudrama 9
  • hashCode for Vector3 etc do not work well

    hashCode for Vector3 etc do not work well

    If two vectors are close to zero they will map to "0" in the current hashCode implementation. A better approach would be something like this:

    int hashVector3(VM.Vector3 v) { int h = 0; for (int i in v.storage.buffer.asInt32List()) { h ^= i; } return h; }

    opened by robertmuth 9
  • Colors

    Colors

    Vector4 is designed to hold color values, too. What I'm missing are methods to convert colors to and from other formats like:

    • RGB(A)
    • Hex RGB String (like CSS color)
    • (HSV)

    A colors class with definition of some known colors would be nice for fast prototyping, like:

    colors.red => new Vector4(1.0, 0.0, 0.0, 1.0)
    colors.green => new Vector4(0.0, 1.0, 0.0, 1.0)
    ...
    colors.all => [colors.red, colors.green, ...] // Allows to choose a random color if needed
    

    I could implement this. But the question is, is this more a vector_math or spectre related thing? Or is a own color class, like three.js has, the way to go?

    opened by Fox32 9
  • Matrix/Vector methods

    Matrix/Vector methods

    Ok, so I added some more methods from three.js. I only found tests for compose/decompose, so If you think some tests are in order, I would need some help with that. Also, I feel that maybe Matrix4.compose should be a constructor instead of a method. What do you think?

    opened by brason 8
  • Call chaining support

    Call chaining support

    I think call/method chaining is a nice feature and even better, Dart comes with support for that! So how about dropping the call chaining support in vector_math?

    Pro:

    • Why adding something that is already supported?
    • Better distinction between methods that return itself for chaining and methods that really return a new instance: For example, normalize vs normalized. I know that there is already the naming convention, but it could be easier.

    Cons:

    • BREAKING CHANGE
    • Typing one more '.'?
    • Work, programmers are lazy (but I could do it, if we decide to go this way)

    I'm not sure about the performance influence of this change. This is something for a person with in-depth knowledge. Maybe there was a good reasons forthe decision to implement call chaining (or Dart doesn't supported it back then).

    opened by Fox32 8
  • Aabb2 rotation broken

    Aabb2 rotation broken

    Aabb2 z = new Aabb2.minMax(new Vector2(1.0, 1.0), new Vector2(2.0, 2.0));
    
    print(z.min); // [1.0,1.0]
    print(z.max); // [2.0,2.0]
    
    z.rotate(new Matrix3.rotationZ((PI/2))); // Rotate 90 degrees
    
    print(z.min); // still [1.0,1.0]
    print(z.max); // still [2.0,2.0]
    

    I believe this is because an absolute rotation is being applied to min and max separately.

    opened by ArgentiApparatus 7
  • Modified the Aabb2 class to be based on center + half vectors

    Modified the Aabb2 class to be based on center + half vectors

    Modified the Aabb2 class to be based on center + half vectors instead of min + max. This makes some common operations a bit faster and avoids unnecessary allocations in certain operations.

    The API remains the same, except for two methods added:

    • setMinMax
    • copyMinMax

    These are useful when you need to get min/max vectors.

    This branch fixes part of #82. I will push another pull request with the necessary changes for Aabb3.

    opened by ceronman 7
  • Bump actions/checkout from 3.0.2 to 3.2.0

    Bump actions/checkout from 3.0.2 to 3.2.0

    Bumps actions/checkout from 3.0.2 to 3.2.0.

    Release notes

    Sourced from actions/checkout's releases.

    v3.2.0

    What's Changed

    New Contributors

    Full Changelog: https://github.com/actions/checkout/compare/v3...v3.2.0

    v3.1.0

    What's Changed

    New Contributors

    Full Changelog: https://github.com/actions/checkout/compare/v3.0.2...v3.1.0

    Changelog

    Sourced from actions/checkout's changelog.

    Changelog

    v3.1.0

    v3.0.2

    v3.0.1

    v3.0.0

    v2.3.1

    v2.3.0

    v2.2.0

    v2.1.1

    • Changes to support GHES (here and here)

    v2.1.0

    v2.0.0

    ... (truncated)

    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    dependencies 
    opened by dependabot[bot] 1
  • Quaternion unary - takes the conjugate instead of memberwise negation

    Quaternion unary - takes the conjugate instead of memberwise negation

    Currently quaternion negation takes the conjugate rather than scaling by -1, which was surprising to me and doesn't seem consistent with binary operator -, which indeed subtracts memberwise.

    This seems to be a regression introduced many years ago at https://github.com/google/vector_math.dart/commit/e7bf99e668fd680d2c0deba9b5b61d406868abd3#diff-f11831298dd6e7900532989a327b8f1934d513eb3e33faa366c68c1a44227c5eR377

    This applies to both vector_math and vector_math_64.

    opened by AsturaPhoenix 0
  • Axis calculation of quaternions from small angles

    Axis calculation of quaternions from small angles

    This pull request suggests lowering the 0-angle rotation denominator threshold in the axis calculation of a quaternion to get axis from smaller rotations.

    Previously, creating a quaternion from axis angle with axis [0, 0, 1] and angle =< 2.56 degrees would result in a zero vector axis on the quaternion. I found that this was due to a threshold added in another pull request. #149.

    opened by JKris95 1
  • Deprecate and remove the `SimplexNoise` classes

    Deprecate and remove the `SimplexNoise` classes

    We plan to deprecate and remove the SimplexNoise classes (both the vector_math and vector_math_64 library versions). Some details and discussion are here: https://github.com/google/vector_math.dart/issues/269.

    From investigation, we believe there's little to no use of this API (we couldn't find any existing uses). For people who had been using this API however, it could be worth investigating whether the https://pub.dev/packages/fast_noise package could serve as a replacement.

    The deprecation will happen shortly, in this current major version of vector_math. We'd then follow-up with the removal; that could either happen in the current major version (2.0.0) or in a rev'd version (3.0.0), depending on which we determine is least breaking to the ecosystem.

    opened by devoncarew 3
  • Remove bundled dependencies

    Remove bundled dependencies

    https://github.com/google/vector_math.dart/tree/master/lib/src/vector_math/third_party https://github.com/google/vector_math.dart/tree/master/lib/src/vector_math_64/third_party

    We should strip out these dependencies and import them individually from a separately package. This package may already exist.

    Bundled dependencies make it difficult to properly import packages into other repositories (such as Google's) due to potential licensing issues. Bundled dependencies can also represent potential security concerns, for example if a vulnerable older version of a library is bundled.

    opened by tvolkert 9
  • feat: included Matrix value setters

    feat: included Matrix value setters

    STATUS: Draft

    Description

    Adds setters r0c0, r0c1, r1c0 and r1c1 to Matrix2, Matrix3 and Matrix4.

    final m = Matrix2.zero()..r0c0 = 2;
    
    /*
    [ 2, 0 ]
    [ 0, 0 ]
    */
    

    Why?

    Sometimes it is very inconvenient and verbose to create Matrices.

    The value setters aim to improve the developer experience.

    // Before:
    Matrix4(2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
    
    /// After:
    Matrix4.zero()..r0c0 = 2;
    

    Additional Context

    #265 https://github.com/google/vector_math.dart/pull/265#discussion_r891894677 https://github.com/google/vector_math.dart/pull/265#issuecomment-1149507992

    opened by alestiago 0
Releases(2.0.8)
Owner
Google
Google ❤️ Open Source
Google
Boris Gautier 1 Jan 31, 2022
Beautiful and accessible math in all browsers

MathJax Beautiful math in all browsers MathJax is an open-source JavaScript display engine for LaTeX, MathML, and AsciiMath notation that works in all

MathJax 9.2k Jan 9, 2023
This is Math-Puzzle game made in flutter and available on Playstore & AppStore

Math Matrix : Train Your Brain, Improve Math Skill Train Your Brain · Report Bug · Request Feature Math Matrix is a Math Game that tries improvise you

Jay Savsani 182 Dec 30, 2022
A Mobile application developed with Flutter and Dart to do math operations with binary numbers.

Math operations with Binary Numbers Readme PT About this Project Mobile application developed with Flutter and Dart to do math operations as sum, subt

Manoel Ribeiro 3 Nov 3, 2020
Fast math TeX renderer for Flutter written in Dart.

CaTeX is a Flutter package that outputs TeX equations (like LaTeX, KaTeX, MathJax, etc.) inline using a widget and Flutter only - no plugins, no web v

simpleclub 56 Nov 14, 2022
MathTraining - A mobile application for training mental math skills

Math Training app A mobile application for training mental math skills. The app

null 34 Oct 5, 2022
MathCanvas - Graphical Math Equation Editor made by Flutter

Graphical Math Equation Editor made by Flutter. My goal is to provide a keyboard typing experience like a calculator. Test Web Page: https:

GongBJ 3 Jun 3, 2022
This is a repository for Flutter Focused Menu, an easy to implement package for adding Focused Long Press Menu to Flutter Applications

Focused Menu This is an easy to implement package for adding Focused Long Press Menu to Flutter Applications Current Features Add Focused Menu to Any

Paras Jain 160 Dec 26, 2022
This is an easy to use Flutter Package for adding Fancy Foldable Sidebar to your Flutter Applications.

Foldable Sidebar An easy to implement Foldable Sidebar Navigation Drawer for Flutter Applications. Current Features Initial Release for Foldable Navig

Paras Jain 87 Nov 26, 2022
An enterprise-class package of Flutter components for mobile applications.

Bruno 一套企业级移动端 Flutter 组件库 简体中文 | English ✨ 特性 提炼自企业级移动端产品的交互和视觉风格 开箱即用的高质量 Flutter 组件 提供满足业务差异的主题定制能力 设计工具赋能开发全链路 Demo 下载 适配 Flutter 版本 Bruno 版本 Flut

Ke Technologies 2.2k Jan 2, 2023
Emanuel Braz 27 Dec 22, 2022
flutter_thrio makes it easy and fast to add flutter to existing mobile applications, and provide a simple and consistent navigator APIs.

中文文档 英文文档 问题集 原仓库不再维护,代码已经很老了 最近版本更新会很快,主要是增加新特性,涉及到混合栈的稳定性的问题应该不多,可放心升级,发现问题加 QQ 群号码:1014085473,我会尽快解决。 不打算好好看看源码的使用者可以放弃这个库了,因为很多设定是比较死的,而我本人不打算花时间写

null 290 Dec 29, 2022
flutter_thrio makes it easy and fast to add flutter to existing mobile applications, and provide a simple and consistent navigator APIs.

本仓库不再维护,可移步新仓库 https://github.com/flutter-thrio/flutter_thrio 中文文档 问题集 QQ 群号码:1014085473 The Navigator for iOS, Android, Flutter. Version 0.2.2 requir

Hellobike 732 Dec 5, 2022
This is an applications for fetching pokemon data from API and showed in Listview with infinity scrolling

pokedex This is an applications for fetching pokemon data from API and showed in Listview with infinity scrolling #Author Created by Yusril Rapsanjani

Yusril Rapsanjani 9 Dec 13, 2019
Another way to build Flutter applications for mobile, web and desktop using the powerful of MVC Design Pattern.

Karee Another way to build Flutter applications for mobile, web and desktop using the powerful of MVC Design Pattern. + = About Karee Karee is a frame

@LeCode 44 Sep 29, 2022
Hyakunin Isshu 1 Jan 11, 2022
The typesafe, reactive, and lightweight SQLite abstraction for your Flutter applications

See the project's website for the full documentation. Floor provides a neat SQLite abstraction for your Flutter applications inspired by the Room pers

Vitus 786 Dec 28, 2022