Advertisement
GeneralGDA

Swizzling on D

Feb 24th, 2015
667
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.64 KB | None | 0 0
  1. module ru.nsk.sampler.math.vector;
  2.  
  3. //math stuff (sqrt, cos, sin)
  4. import std.math;
  5.  
  6. //'zip', 'repeat', 'take' lie here
  7. import std.range;
  8.  
  9. //'map' and 'reduce' lie here
  10. import std.algorithm;
  11.  
  12. //to make char upper case + 'format' - a sprintf-like function
  13. import std.string;
  14.  
  15. public static immutable X = 0;
  16. public static immutable Y = 1;
  17. public static immutable Z = 2;
  18. public static immutable W = 3;
  19.  
  20. public struct Vector4
  21. {
  22.     public
  23.     {
  24.  
  25.         static immutable DIMENSION = 4;
  26.  
  27.         this(Range)(Range coords) pure
  28.         {
  29.             auto i = 0u;
  30.             foreach (immutable coord; coords)
  31.             {
  32.                 this.coords[i] = coord;
  33.                 i++;
  34.             }
  35.         }
  36.  
  37.         this(in float x, in float y, in float z, in float w) pure nothrow
  38.         {
  39.             coords[X] = x;
  40.             coords[Y] = y;
  41.             coords[Z] = z;
  42.             coords[W] = w;
  43.         }
  44.  
  45.         this(in float x, in float y, in float z) pure nothrow
  46.         {
  47.             coords[X] = x;
  48.             coords[Y] = y;
  49.             coords[Z] = z;
  50.         }
  51.  
  52.         @property float[] get() pure nothrow
  53.         {
  54.             return coords;
  55.         }
  56.  
  57.         @property const (float[]) get() const pure nothrow
  58.         {
  59.             return coords;
  60.         }
  61.  
  62.         alias get this;
  63.  
  64.         @property auto opDispatch(const string swizzling)() const pure
  65.             if (swizzling.length == DIMENSION || swizzling.length == DIMENSION - 1)
  66.         {
  67.             immutable expression = "coords".repeat().take(swizzling.length).zip(swizzling)
  68.                 .map!( a => format("%s[%c]", a[0], a[1].toUpper()) ).reduce!((a,b) => a ~ "," ~ b);
  69.  
  70.             mixin( "return Vector4 (" ~ expression ~ ");" );
  71.         }
  72.  
  73.         auto opEquals(in Vector4 other) const pure nothrow
  74.         {
  75.             return this.coords == other.coords;
  76.         }
  77.  
  78.     }
  79.  
  80.     private
  81.     {
  82.         float[DIMENSION] coords = [0.0f, 0.0f, 0.0f, 1.0f,];
  83.     }
  84. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement