cosmetix
[b2ld.git] / b2dlite / mathutils.d
blob4f27a200f2f14350e34f46946bfe2768b1585cfc
1 /*
2 * Copyright (c) 2006-2007 Erin Catto http://www.gphysics.com
4 * Permission to use, copy, modify, distribute and sell this software
5 * and its documentation for any purpose is hereby granted without fee,
6 * provided that the above copyright notice appear in all copies.
7 * Erin Catto makes no representations about the suitability
8 * of this software for any purpose.
9 * It is provided "as is" without express or implied warranty.
11 module b2dlite.mathutils;
13 import iv.vmath;
15 public alias Vec2 = VecN!(2, float);
16 public alias VFloat = Vec2.VFloat;
17 public alias VFloatNum = Vec2.VFloatNum;
20 public struct Mat22 {
21 pure nothrow @safe @nogc:
22 public:
23 Vec2 col1, col2;
25 public:
26 this (VFloat angle) {
27 pragma(inline, true);
28 import std.math : cos, sin;
29 immutable VFloat c = cos(angle), s = sin(angle);
30 col1.x = c; col1.y = s;
31 col2.x = -s; col2.y = c;
34 this() (in auto ref Vec2 acol1, in auto ref Vec2 acol2) { pragma(inline, true); col1 = acol1; col2 = acol2; }
36 Mat22 transpose () const { pragma(inline, true); return Mat22(Vec2(col1.x, col2.x), Vec2(col1.y, col2.y)); }
38 Mat22 invert () const {
39 pragma(inline, true);
40 immutable VFloat a = col1.x, b = col2.x, c = col1.y, d = col2.y;
41 Mat22 B;
42 VFloat det = a*d-b*c;
43 assert(det != VFloatNum!(0.0));
44 det = VFloatNum!(1.0)/det;
45 B.col1.x = det*d;
46 B.col2.x = -det*b;
47 B.col1.y = -det*c;
48 B.col2.y = det*a;
49 return B;
52 Vec2 opBinary(string op:"*") (in auto ref Vec2 v) const { pragma(inline, true); return Vec2(col1.x*v.x+col2.x*v.y, col1.y*v.x+col2.y*v.y); }
54 Mat22 opBinary(string op:"+") (in auto ref Mat22 B) const { pragma(inline, true); return Mat22(col1+B.col1, col2+B.col2); }
55 Mat22 opBinary(string op:"*") (in auto ref Mat22 B) const { pragma(inline, true); return Mat22(this*B.col1, this*B.col2); }
57 Mat22 abs() () { pragma(inline, true); return Mat22(col1.abs, col2.abs); }
61 //public VFloat cross() (in auto ref Vec2 a, in auto ref Vec2 b) { pragma(inline, true); return a.x*b.y-a.y*b.x; }
62 public Vec2 cross() (in auto ref Vec2 a, VFloat s) { pragma(inline, true); return Vec2(s*a.y, -s*a.x); }
63 public Vec2 cross() (VFloat s, in auto ref Vec2 a) { pragma(inline, true); return Vec2(-s*a.y, s*a.x); }
66 // Random number in range [-1,1]
67 public VFloat Random (void) {
68 pragma(inline, true);
69 import std.random : uniform;
70 return cast(VFloat)uniform!"[]"(-VFloatNum!(1.0), VFloatNum!(1.0));
73 public VFloat Random (VFloat lo, VFloat hi) {
74 pragma(inline, true);
75 import std.random : uniform;
76 return cast(VFloat)uniform!"[]"(lo, hi);