]> git.tdb.fi Git - libs/gltk.git/blob - source/part.cpp
Cache widget parts in meshes
[libs/gltk.git] / source / part.cpp
1 #include <msp/gl/meshbuilder.h>
2 #include "geometry.h"
3 #include "part.h"
4 #include "partcache.h"
5 #include "resources.h"
6
7 using namespace std;
8
9 namespace Msp {
10 namespace GLtk {
11
12 Part::Part(const string &n):
13         name(n)
14 {
15         for(unsigned i=0; i<N_STATES_; ++i)
16                 graphic[i] = 0;
17 }
18
19 const Graphic *Part::get_graphic(State state) const
20 {
21         if(state>N_STATES_)
22                 throw invalid_argument("Part::get_graphic");
23
24         return graphic[state];
25 }
26
27 void Part::build(const Geometry &parent, State state, CachedPart &cache) const
28 {
29         if(!graphic[state])
30         {
31                 cache.texture = 0;
32                 return;
33         }
34
35         cache.texture = graphic[state]->get_texture();
36         cache.clear_mesh();
37
38         Geometry rgeom = geom;
39         align.apply(rgeom, parent, margin);
40         GL::MeshBuilder bld(*cache.mesh);
41         bld.matrix() *= GL::Matrix::translation(rgeom.x, rgeom.y, 0);
42         graphic[state]->build(rgeom.w, rgeom.h, bld);
43 }
44
45
46 Part::Loader::Loader(Part &p, Resources &r):
47         DataFile::CollectionObjectLoader<Part>(p, &r)
48 {
49         add("graphic", &Loader::graphic);
50         add("align",   &Loader::align);
51         add("fill",    &Loader::fill);
52         add("margin",  &Loader::margin);
53         add("size",    &Loader::size);
54 }
55
56 Part::Loader::~Loader()
57 {
58         for(unsigned i=0; i<N_STATES_; ++i)
59                 if(obj.graphic[i])
60                 {
61                         const Graphic &grph = *obj.graphic[i];
62                         const Sides &shadow = grph.get_shadow();
63                         obj.geom.w = max(obj.geom.w, grph.get_width()-shadow.left-shadow.right);
64                         obj.geom.h = max(obj.geom.h, grph.get_height()-shadow.bottom-shadow.top);
65                 }
66 }
67
68 void Part::Loader::graphic(State s, const string &n)
69 {
70         Graphic *grph = &get_collection().get<Graphic>(n);
71         for(int i=0; i<N_STATES_; ++i)
72                 if((i&s)==s)
73                         obj.graphic[i] = grph;
74 }
75
76 void Part::Loader::align(float x, float y)
77 {
78         obj.align.x = x;
79         obj.align.y = y;
80 }
81
82 void Part::Loader::fill(float w, float h)
83 {
84         obj.align.w = w;
85         obj.align.h = h;
86 }
87
88 void Part::Loader::margin()
89 {
90         load_sub(obj.margin);
91 }
92
93 void Part::Loader::size(unsigned w, unsigned h)
94 {
95         obj.geom.w = w;
96         obj.geom.h = h;
97 }
98
99 } // namespace GLtk
100 } // namespace Msp