Advertisement
Guest User

vec2.d

a guest
Apr 23rd, 2014
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.57 KB | None | 0 0
  1. module util.vec2;
  2.  
  3. import std.string;
  4. import std.stdio;
  5.  
  6. class Vec2
  7. {
  8.     public:
  9.     double x = 0;
  10.     double y = 0;
  11.  
  12.     unittest {
  13.         assert(new Vec2(2, 2) == new Vec2(2, 2));
  14.         assert(new Vec2(0, 0) != new Vec2(2, 2));
  15.  
  16.         Vec2 testVec = new Vec2(2, 1);
  17.  
  18.         Vec2 testVecMod = -testVec;
  19.         assert(testVecMod == new Vec2(-2, -1));
  20.  
  21.         testVecMod = +testVec;
  22.         assert(testVecMod == testVec);
  23.  
  24.         assert(!new Vec2(double.nan, double.nan).valid);
  25.         assert(!new Vec2(double.nan, 0).valid);
  26.         assert(new Vec2(0, 0).valid);
  27.  
  28.         testVec += testVecMod;
  29.         assert(testVec.x == 4 && testVec.y == 2);
  30.  
  31.         Vec2 assign = [1.0, 2.0];
  32.     }
  33.  
  34.     this() {
  35.     }
  36.  
  37.     this(double x1, double y1) {
  38.         x = x1;
  39.         y = y1;
  40.     }
  41.  
  42.     public Vec2 opUnary(string s)() if (s == "-") {
  43.         assert(valid);
  44.  
  45.         return new Vec2(-x, -y);
  46.     }
  47.  
  48.     public Vec2 opUnary(string s)() if (s == "+") {
  49.         assert(valid);
  50.  
  51.         return new Vec2(x, y);
  52.     }
  53.    
  54.     public override bool opEquals(Object b) {
  55.         Vec2 bVec = cast(Vec2)b;
  56.         return x == bVec.x && y == bVec.y;
  57.     }
  58.  
  59.     public void opAssign(double[] vecArr) {
  60.         assert(vecArr.length == 2);
  61.  
  62.         x = vecArr[0];
  63.         y = vecArr[1];
  64.     }
  65.  
  66.     void opOpAssign(string op)(Vec2 vec2)
  67.     {
  68.         mixin("x " ~ op ~ "= vec2.x;");
  69.         mixin("y " ~ op ~ "= vec2.y;");
  70.     }
  71.  
  72.     void opOpAssign(string op)(double[] vecArr)
  73.     {
  74.         assert(vecArr.length == 2);
  75.  
  76.         mixin("x " ~ op ~ "= vecArr[0];");
  77.         mixin("y " ~ op ~ "= vecArr[1];");
  78.     }
  79.  
  80.     override string toString() {
  81.         return format("[x = %f, y = %f]", x, y);
  82.     }
  83.  
  84.     @property {
  85.         bool valid() {
  86.             return !(x is x.nan) && !(y is y.nan);
  87.         }
  88.     }
  89. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement