Fast 2d geometry math: Vector2, Rectangle, Circle, Matrix2x3 (2D transformation), Circle, BoundingBox, Line2, Segment2, Intersections, Distances, Transitions (animation/tween), Noise, Random numbers.
So the objective is "Be fast"
- API completeness
- Testing
- did I miss anything useful?
- Avoid new
- Use arrays instead of objects, this is huge performance boost!
- Avoid creating unnecessary variables (reuse intermediate variables) only "create" & "clone" methods must instance new variables.
- Cache every function call to a single variable. example: Vec2.add -> vec2_add
- If access an multi-dimensional array in a loop, cache the array access. for(i...) carr=arr[i]; carr[X]
I'm sure I miss some of my own performance tips, PR if you find any error or find a better way!
See some performance test that prove it.
grunt dist
# creates:
# - dist/js-2dmath-browser.js
# - debug/js-2dmath-browser-debug.js
# - docs/*.markdown
Why there is a debug dist?
Debug distribution use falafel to add assertions based on the documentation.
Force to use valid sanitized inputs (Arrays, not NaN, not undefined, not null) to every function.
See some examples that we use as tests :)
- Angles
- Beizer
- Circle
- Intersections
- line2
- Matrix23
- Segment2
- Transitions
- Triangle
- Vec2 collisions
- Vec2
The documentation is autogenerated with falafel see dist.js for more fun! :)
How do i know a variable type?
You can't, there is no instanceof or anything like that, everything are numbers/arrays.
I choose to keep track of all types using meaningful naming or enclose the variable in an object like
var movable = {
body: Polygon.create(/*...*/), // could be a circle, change the type...
type: "polygon"
}