]> git.mxchange.org Git - simgear.git/blob - simgear/canvas/elements/CanvasImage.cxx
Move parseColor to scene/util
[simgear.git] / simgear / canvas / elements / CanvasImage.cxx
1 // An image on the Canvas
2 //
3 // Copyright (C) 2012  Thomas Geymayer <tomgey@gmail.com>
4 //
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Library General Public
7 // License as published by the Free Software Foundation; either
8 // version 2 of the License, or (at your option) any later version.
9 //
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // Library General Public License for more details.
14 //
15 // You should have received a copy of the GNU Library General Public
16 // License along with this library; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301, USA
18
19 #include "CanvasImage.hxx"
20
21 #include <simgear/canvas/Canvas.hxx>
22 #include <simgear/canvas/CanvasMgr.hxx>
23 #include <simgear/canvas/CanvasSystemAdapter.hxx>
24 #include <simgear/scene/util/parse_color.hxx>
25 #include <simgear/misc/sg_path.hxx>
26
27 #include <osg/Array>
28 #include <osg/Geometry>
29 #include <osg/PrimitiveSet>
30
31 #include <boost/algorithm/string/predicate.hpp>
32
33 namespace simgear
34 {
35 namespace canvas
36 {
37   /**
38    * Callback to enable/disable rendering of canvas displayed inside windows or
39    * other canvases.
40    */
41   class CullCallback:
42     public osg::Drawable::CullCallback
43   {
44     public:
45       CullCallback(const CanvasWeakPtr& canvas);
46
47     private:
48       CanvasWeakPtr _canvas;
49
50       virtual bool cull( osg::NodeVisitor* nv,
51                          osg::Drawable* drawable,
52                          osg::RenderInfo* renderInfo ) const;
53   };
54
55   //----------------------------------------------------------------------------
56   CullCallback::CullCallback(const CanvasWeakPtr& canvas):
57     _canvas( canvas )
58   {
59
60   }
61
62   //----------------------------------------------------------------------------
63   bool CullCallback::cull( osg::NodeVisitor* nv,
64                            osg::Drawable* drawable,
65                            osg::RenderInfo* renderInfo ) const
66   {
67     if( !_canvas.expired() )
68       _canvas.lock()->enableRendering();
69
70     // TODO check if window/image should be culled
71     return false;
72   }
73
74   //----------------------------------------------------------------------------
75   Image::Image( const CanvasWeakPtr& canvas,
76                 SGPropertyNode_ptr node,
77                 const Style& parent_style ):
78     Element(canvas, node, parent_style),
79     _texture(new osg::Texture2D),
80     _node_src_rect( node->getNode("source", 0, true) )
81   {
82     _geom = new osg::Geometry;
83     _geom->setUseDisplayList(false);
84
85     osg::StateSet *stateSet = _geom->getOrCreateStateSet();
86     stateSet->setTextureAttributeAndModes(0, _texture.get());
87     stateSet->setDataVariance(osg::Object::STATIC);
88
89     // allocate arrays for the image
90     _vertices = new osg::Vec3Array(4);
91     _vertices->setDataVariance(osg::Object::STATIC);
92     _geom->setVertexArray(_vertices);
93
94     _texCoords = new osg::Vec2Array(4);
95     _texCoords->setDataVariance(osg::Object::STATIC);
96     _geom->setTexCoordArray(0, _texCoords);
97
98     _colors = new osg::Vec4Array(4);
99     _colors->setDataVariance(osg::Object::STATIC);
100     _geom->setColorBinding(osg::Geometry::BIND_PER_VERTEX);
101     _geom->setColorArray(_colors);
102
103     osg::DrawArrays* prim = new osg::DrawArrays(osg::PrimitiveSet::QUADS);
104     prim->set(osg::PrimitiveSet::QUADS, 0, 4);
105     prim->setDataVariance(osg::Object::STATIC);
106     _geom->addPrimitiveSet(prim);
107
108     setDrawable(_geom);
109
110     addStyle("fill", &Image::setFill, this);
111     setFill("#ffffff"); // TODO how should we handle default values?
112
113     setupStyle();
114   }
115
116   //----------------------------------------------------------------------------
117   Image::~Image()
118   {
119
120   }
121
122   //----------------------------------------------------------------------------
123   void Image::update(double dt)
124   {
125     Element::update(dt);
126
127     if( _attributes_dirty & DEST_SIZE )
128     {
129       (*_vertices)[0].set(_region.l(), _region.t(), 0);
130       (*_vertices)[1].set(_region.r(), _region.t(), 0);
131       (*_vertices)[2].set(_region.r(), _region.b(), 0);
132       (*_vertices)[3].set(_region.l(), _region.b(), 0);
133       _vertices->dirty();
134
135       _attributes_dirty &= ~DEST_SIZE;
136       _geom->dirtyBound();
137       setBoundingBox(_geom->getBound());
138     }
139
140     if( _attributes_dirty & SRC_RECT )
141     {
142       double u0 = _src_rect.l(),
143              u1 = _src_rect.r(),
144              v0 = _src_rect.b(),
145              v1 = _src_rect.t();
146
147       if( !_node_src_rect->getBoolValue("normalized", true) )
148       {
149         const Rect<int>& tex_dim = getTextureDimensions();
150
151         u0 /= tex_dim.width();
152         u1 /= tex_dim.width();
153         v0 /= tex_dim.height();
154         v1 /= tex_dim.height();
155       }
156
157       (*_texCoords)[0].set(u0, v0);
158       (*_texCoords)[1].set(u1, v0);
159       (*_texCoords)[2].set(u1, v1);
160       (*_texCoords)[3].set(u0, v1);
161       _texCoords->dirty();
162
163       _attributes_dirty &= ~SRC_RECT;
164     }
165   }
166
167   //----------------------------------------------------------------------------
168   void Image::setSrcCanvas(CanvasPtr canvas)
169   {
170     if( !_src_canvas.expired() )
171       _src_canvas.lock()->removeDependentCanvas(_canvas);
172
173     _src_canvas = canvas;
174     _geom->getOrCreateStateSet()
175          ->setTextureAttribute(0, canvas ? canvas->getTexture() : 0);
176     _geom->setCullCallback(canvas ? new CullCallback(canvas) : 0);
177
178     if( !_src_canvas.expired() )
179     {
180       setupDefaultDimensions();
181       _src_canvas.lock()->addDependentCanvas(_canvas);
182     }
183   }
184
185   //----------------------------------------------------------------------------
186   CanvasWeakPtr Image::getSrcCanvas() const
187   {
188     return _src_canvas;
189   }
190
191   //----------------------------------------------------------------------------
192   void Image::setImage(osg::Image *img)
193   {
194     // remove canvas...
195     setSrcCanvas( CanvasPtr() );
196
197     _texture->setImage(img);
198     _geom->getOrCreateStateSet()
199          ->setTextureAttributeAndModes(0, _texture);
200
201     if( img )
202       setupDefaultDimensions();
203   }
204
205   //----------------------------------------------------------------------------
206   void Image::setFill(const std::string& fill)
207   {
208     osg::Vec4 color;
209     if( !parseColor(fill, color) )
210       return;
211
212     for( int i = 0; i < 4; ++i )
213       (*_colors)[i] = color;
214     _colors->dirty();
215   }
216
217   //----------------------------------------------------------------------------
218   const Rect<float>& Image::getRegion() const
219   {
220     return _region;
221   }
222
223   //----------------------------------------------------------------------------
224   void Image::childChanged(SGPropertyNode* child)
225   {
226     const std::string& name = child->getNameString();
227
228     if( child->getParent() == _node_src_rect )
229     {
230       _attributes_dirty |= SRC_RECT;
231
232       if(      name == "left" )
233         _src_rect.setLeft( child->getFloatValue() );
234       else if( name == "right" )
235         _src_rect.setRight( child->getFloatValue() );
236       else if( name == "top" )
237         _src_rect.setTop( child->getFloatValue() );
238       else if( name == "bottom" )
239         _src_rect.setBottom( child->getFloatValue() );
240
241       return;
242     }
243     else if( child->getParent() != _node )
244       return;
245
246     if( name == "x" )
247     {
248       _region.setX( child->getFloatValue() );
249       _attributes_dirty |= DEST_SIZE;
250     }
251     else if( name == "y" )
252     {
253       _region.setY( child->getFloatValue() );
254       _attributes_dirty |= DEST_SIZE;
255     }
256     else if( name == "size" )
257     {
258       if( child->getIndex() == 0 )
259         _region.setWidth( child->getFloatValue() );
260       else
261         _region.setHeight( child->getFloatValue() );
262
263       _attributes_dirty |= DEST_SIZE;
264     }
265     else if( name == "file" )
266     {
267       static const std::string CANVAS_PROTOCOL = "canvas://";
268       const std::string& path = child->getStringValue();
269
270       CanvasPtr canvas = _canvas.lock();
271       if( !canvas )
272       {
273         SG_LOG(SG_GL, SG_ALERT, "canvas::Image: No canvas available");
274         return;
275       }
276
277       if( boost::starts_with(path, CANVAS_PROTOCOL) )
278       {
279         CanvasMgr* canvas_mgr = canvas->getCanvasMgr();
280         if( !canvas_mgr )
281         {
282           SG_LOG(SG_GL, SG_ALERT, "canvas::Image: Failed to get CanvasMgr");
283           return;
284         }
285
286         const SGPropertyNode* canvas_node =
287           canvas_mgr->getPropertyRoot()
288                     ->getParent()
289                     ->getNode( path.substr(CANVAS_PROTOCOL.size()) );
290         if( !canvas_node )
291         {
292           SG_LOG(SG_GL, SG_ALERT, "canvas::Image: No such canvas: " << path);
293           return;
294         }
295
296         // TODO add support for other means of addressing canvases (eg. by
297         // name)
298         CanvasPtr src_canvas = canvas_mgr->getCanvas( canvas_node->getIndex() );
299         if( !src_canvas )
300         {
301           SG_LOG(SG_GL, SG_ALERT, "canvas::Image: Invalid canvas: " << path);
302           return;
303         }
304
305         setSrcCanvas(src_canvas);
306       }
307       else
308       {
309         setImage( canvas->getSystemAdapter()->getImage(path) );
310       }
311     }
312   }
313
314   //----------------------------------------------------------------------------
315   void Image::setupDefaultDimensions()
316   {
317     if( !_src_rect.width() || !_src_rect.height() )
318     {
319       const Rect<int>& tex_dim = getTextureDimensions();
320
321       _node_src_rect->setBoolValue("normalized", false);
322       _node_src_rect->setFloatValue("right", tex_dim.width());
323       _node_src_rect->setFloatValue("bottom", tex_dim.height());
324     }
325
326     if( !_region.width() || !_region.height() )
327     {
328       _node->setFloatValue("size[0]", _src_rect.width());
329       _node->setFloatValue("size[1]", _src_rect.height());
330     }
331   }
332
333   //----------------------------------------------------------------------------
334   Rect<int> Image::getTextureDimensions() const
335   {
336     osg::Texture2D *texture = !_src_canvas.expired()
337                             ? _src_canvas.lock()->getTexture()
338                             : _texture.get();
339
340     if( !texture )
341       return Rect<int>();
342
343     return Rect<int>
344     (
345       0,0,
346       texture->getTextureWidth(),
347       texture->getTextureHeight()
348     );
349   }
350
351 } // namespace canvas
352 } // namespace simgear