|
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- |
|
2 * This Source Code Form is subject to the terms of the Mozilla Public |
|
3 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
5 |
|
6 #ifndef MOZILLA_GFX_BASEPOINT_H_ |
|
7 #define MOZILLA_GFX_BASEPOINT_H_ |
|
8 |
|
9 #include <cmath> |
|
10 #include "mozilla/Attributes.h" |
|
11 |
|
12 namespace mozilla { |
|
13 namespace gfx { |
|
14 |
|
15 /** |
|
16 * Do not use this class directly. Subclass it, pass that subclass as the |
|
17 * Sub parameter, and only use that subclass. This allows methods to safely |
|
18 * cast 'this' to 'Sub*'. |
|
19 */ |
|
20 template <class T, class Sub> |
|
21 struct BasePoint { |
|
22 T x, y; |
|
23 |
|
24 // Constructors |
|
25 MOZ_CONSTEXPR BasePoint() : x(0), y(0) {} |
|
26 MOZ_CONSTEXPR BasePoint(T aX, T aY) : x(aX), y(aY) {} |
|
27 |
|
28 void MoveTo(T aX, T aY) { x = aX; y = aY; } |
|
29 void MoveBy(T aDx, T aDy) { x += aDx; y += aDy; } |
|
30 |
|
31 // Note that '=' isn't defined so we'll get the |
|
32 // compiler generated default assignment operator |
|
33 |
|
34 bool operator==(const Sub& aPoint) const { |
|
35 return x == aPoint.x && y == aPoint.y; |
|
36 } |
|
37 bool operator!=(const Sub& aPoint) const { |
|
38 return x != aPoint.x || y != aPoint.y; |
|
39 } |
|
40 |
|
41 Sub operator+(const Sub& aPoint) const { |
|
42 return Sub(x + aPoint.x, y + aPoint.y); |
|
43 } |
|
44 Sub operator-(const Sub& aPoint) const { |
|
45 return Sub(x - aPoint.x, y - aPoint.y); |
|
46 } |
|
47 Sub& operator+=(const Sub& aPoint) { |
|
48 x += aPoint.x; |
|
49 y += aPoint.y; |
|
50 return *static_cast<Sub*>(this); |
|
51 } |
|
52 Sub& operator-=(const Sub& aPoint) { |
|
53 x -= aPoint.x; |
|
54 y -= aPoint.y; |
|
55 return *static_cast<Sub*>(this); |
|
56 } |
|
57 |
|
58 Sub operator*(T aScale) const { |
|
59 return Sub(x * aScale, y * aScale); |
|
60 } |
|
61 Sub operator/(T aScale) const { |
|
62 return Sub(x / aScale, y / aScale); |
|
63 } |
|
64 |
|
65 Sub operator-() const { |
|
66 return Sub(-x, -y); |
|
67 } |
|
68 |
|
69 // Round() is *not* rounding to nearest integer if the values are negative. |
|
70 // They are always rounding as floor(n + 0.5). |
|
71 // See https://bugzilla.mozilla.org/show_bug.cgi?id=410748#c14 |
|
72 Sub& Round() { |
|
73 x = static_cast<T>(floor(x + 0.5)); |
|
74 y = static_cast<T>(floor(y + 0.5)); |
|
75 return *static_cast<Sub*>(this); |
|
76 } |
|
77 |
|
78 }; |
|
79 |
|
80 } |
|
81 } |
|
82 |
|
83 #endif /* MOZILLA_GFX_BASEPOINT_H_ */ |