25ef94e7a3955c80f393618ab54d71d7fa2ae45f
[ipdf/code.git] / src / rect.h
1 #ifndef _RECT_H
2 #define _RECT_H
3
4 #include "common.h"
5 #include "real.h"
6
7 namespace IPDF
8 {
9         template <class T = IPDF::Real>
10         struct TRect
11         {
12                 T x; T y; T w; T h;
13                 //TRect() = default; // Needed so we can fread/fwrite this struct
14                 TRect(T _x=0, T _y=0, T _w=1, T _h=1) : x(_x), y(_y), w(_w), h(_h) {}
15                 
16                 std::string Str() const
17                 {
18                         std::stringstream s;
19                         // float conversion needed because it is fucking impossible to get ostreams working with template classes
20                         s << "{" << x << ", " << y << ", " << (x + w) << ", " << (y + h) << " (w: " << w <<", h: " << h <<")}";
21                         return s.str();
22                 }
23                 inline bool PointIn(T pt_x, T pt_y) const
24                 {
25                         if (pt_x <= x) return false;
26                         if (pt_y <= y) return false;
27                         if (pt_x >= x + w) return false;
28                         if (pt_y >= y + h) return false;
29                         return true;
30                 }
31
32                 inline bool Intersects(const TRect& other) const
33                 {
34                         if (x + w < other.x) return false;
35                         if (y + h < other.y) return false;
36                         if (x > other.x + other.w) return false;
37                         if (y > other.y + other.h) return false;
38                         return true;
39                 }
40                 
41                 template <class B> TRect<B> Convert() {return TRect<B>(B(x), B(y), B(w), B(h));}
42         };
43
44
45
46         template <class T = IPDF::Real>
47         inline TRect<T> TransformRectCoordinates(const TRect<T> & view, const TRect<T> & r)
48         {
49                 TRect<T> out;
50                 T w = (view.w == T(0))?T(1):view.w;
51                 T h = (view.h == T(0))?T(1):view.h;
52                 out.x = (r.x - view.x) / w; //r.x = out.x *w + view.x
53                 out.y = (r.y - view.y) / h; // r.y = out.y*h + view.y
54                 out.w = r.w / w; // r.w = out.w * w
55                 out.h = r.h / h; // r.h = out.h * h
56                 return out;
57         }
58
59
60         template <class T = IPDF::Real>
61         inline Vec2 TransformPointCoordinates(const TRect<T> & view, const Vec2& v)
62         {
63                 Vec2 out;
64                 out.x = (v.x - view.x) / view.w;
65                 out.y = (v.y - view.y) / view.h;
66                 return out;
67         }
68         
69         typedef TRect<Real> Rect;
70         
71
72 }
73
74 #endif //_RECT_H

UCC git Repository :: git.ucc.asn.au