1 // An OpenVG path on the Canvas
3 // Copyright (C) 2012 Thomas Geymayer <tomgey@gmail.com>
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.
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.
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
19 #include "CanvasPath.hxx"
20 #include <simgear/scene/util/parse_color.hxx>
22 #include <osg/Drawable>
23 #include <osg/BlendFunc>
25 #include <vg/openvg.h>
32 typedef std::vector<VGubyte> CmdList;
33 typedef std::vector<VGfloat> CoordList;
36 static const VGubyte shCoordsPerCommand[] = {
37 0, /* VG_CLOSE_PATH */
46 5, /* VG_SCCWARC_TO */
48 5, /* VG_LCCWARC_TO */
51 static const VGubyte shNumCommands = sizeof(shCoordsPerCommand)
52 / sizeof(shCoordsPerCommand[0]);
55 * Helper to split and convert comma/whitespace separated floating point
58 std::vector<float> splitAndConvert(const char del[], const std::string& str);
60 class Path::PathDrawable:
64 PathDrawable(Path* path):
66 _path(VG_INVALID_HANDLE),
67 _paint(VG_INVALID_HANDLE),
68 _paint_fill(VG_INVALID_HANDLE),
69 _attributes_dirty(~0),
71 _fill_rule(VG_EVEN_ODD),
73 _stroke_linecap(VG_CAP_BUTT)
75 setSupportsDisplayList(false);
76 setDataVariance(Object::DYNAMIC);
78 setUpdateCallback(new PathUpdateCallback());
81 virtual ~PathDrawable()
83 if( _path != VG_INVALID_HANDLE )
85 if( _paint != VG_INVALID_HANDLE )
86 vgDestroyPaint(_paint);
87 if( _paint_fill != VG_INVALID_HANDLE )
88 vgDestroyPaint(_paint_fill);
91 virtual const char* className() const { return "PathDrawable"; }
92 virtual osg::Object* cloneType() const { return new PathDrawable(_path_element); }
93 virtual osg::Object* clone(const osg::CopyOp&) const { return new PathDrawable(_path_element); }
96 * Replace the current path segments with the new ones
98 * @param cmds List of OpenVG path commands
99 * @param coords List of coordinates/parameters used by #cmds
101 void setSegments(const CmdList& cmds, const CoordList& coords)
106 _attributes_dirty |= (PATH | BOUNDING_BOX);
110 * Set path fill paint ("none" if not filled)
112 void setFill(const std::string& fill)
116 _mode &= ~VG_FILL_PATH;
118 else if( parseColor(fill, _fill_color) )
120 _mode |= VG_FILL_PATH;
121 _attributes_dirty |= FILL_COLOR;
129 "canvas::Path Unknown fill: " << fill
135 * Set path fill rule ("pseudo-nonzero" or "evenodd")
137 * @warning As the current nonzero implementation causes sever artifacts
138 * for every concave path we call it pseudo-nonzero, so that
139 * everyone is warned that it won't work as expected :)
141 void setFillRule(const std::string& fill_rule)
143 if( fill_rule == "pseudo-nonzero" )
144 _fill_rule = VG_NON_ZERO;
145 else // if( fill_rule == "evenodd" )
146 _fill_rule = VG_EVEN_ODD;
150 * Set path stroke paint ("none" if no stroke)
152 void setStroke(const std::string& stroke)
154 if( stroke == "none" )
156 _mode &= ~VG_STROKE_PATH;
158 else if( parseColor(stroke, _stroke_color) )
160 _mode |= VG_STROKE_PATH;
161 _attributes_dirty |= STROKE_COLOR;
169 "canvas::Path Unknown stroke: " << stroke
177 void setStrokeWidth(float width)
179 _stroke_width = width;
180 _attributes_dirty |= BOUNDING_BOX;
184 * Set stroke dash (line stipple)
186 void setStrokeDashArray(const std::string& dash)
188 _stroke_dash = splitAndConvert(",\t\n ", dash);
194 * @see http://www.w3.org/TR/SVG/painting.html#StrokeLinecapProperty
196 void setStrokeLinecap(const std::string& linecap)
198 if( linecap == "round" )
199 _stroke_linecap = VG_CAP_ROUND;
200 else if( linecap == "square" )
201 _stroke_linecap = VG_CAP_SQUARE;
203 _stroke_linecap = VG_CAP_BUTT;
209 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
211 if( _attributes_dirty & PATH )
214 osg::State* state = renderInfo.getState();
217 state->setActiveTextureUnit(0);
218 state->setClientActiveTextureUnit(0);
219 state->disableAllVertexArrays();
221 glPushAttrib(~0u); // Don't use GL_ALL_ATTRIB_BITS as on my machine it
222 // eg. doesn't include GL_MULTISAMPLE_BIT
223 glPushClientAttrib(~0u);
225 // Initialize/Update the paint
226 if( _attributes_dirty & STROKE_COLOR )
228 if( _paint == VG_INVALID_HANDLE )
229 _paint = vgCreatePaint();
231 vgSetParameterfv(_paint, VG_PAINT_COLOR, 4, _stroke_color._v);
233 _attributes_dirty &= ~STROKE_COLOR;
236 // Initialize/update fill paint
237 if( _attributes_dirty & FILL_COLOR )
239 if( _paint_fill == VG_INVALID_HANDLE )
240 _paint_fill = vgCreatePaint();
242 vgSetParameterfv(_paint_fill, VG_PAINT_COLOR, 4, _fill_color._v);
244 _attributes_dirty &= ~FILL_COLOR;
248 if( _mode & VG_STROKE_PATH )
250 vgSetPaint(_paint, VG_STROKE_PATH);
252 vgSetf(VG_STROKE_LINE_WIDTH, _stroke_width);
253 vgSeti(VG_STROKE_CAP_STYLE, _stroke_linecap);
254 vgSetfv( VG_STROKE_DASH_PATTERN,
256 _stroke_dash.empty() ? 0 : &_stroke_dash[0] );
258 if( _mode & VG_FILL_PATH )
260 vgSetPaint(_paint_fill, VG_FILL_PATH);
262 vgSeti(VG_FILL_RULE, _fill_rule);
265 // And finally draw the path
267 vgDrawPath(_path, _mode);
269 VGErrorCode err = vgGetError();
270 if( err != VG_NO_ERROR )
271 SG_LOG(SG_GL, SG_ALERT, "vgError: " << err);
277 osg::BoundingBox getTransformedBounds(const osg::Matrix& mat) const
281 osg::Vec2f cur; // VG "Current point" (in local coordinates)
282 VGubyte cmd_index = 0;
283 for( size_t i = 0, ci = 0;
284 i < _cmds.size() && ci < _coords.size();
285 ++i, ci += shCoordsPerCommand[cmd_index] )
287 VGubyte rel = _cmds[i] & 1,
291 if( cmd_index >= shNumCommands )
292 return osg::BoundingBox();
294 const VGubyte max_coords = 3;
295 osg::Vec2f points[max_coords];
296 VGubyte num_coords = 0;
306 points[ num_coords++ ].set(_coords[ci], _coords[ci + 1]);
310 points[ num_coords++ ].set( _coords[ci] + (rel ? cur.x() : 0),
312 // We have handled rel/abs already, so no need to do it again...
317 points[ num_coords++ ].set( cur.x(),
318 _coords[ci] + (rel ? cur.y() : 0) );
319 // We have handled rel/abs already, so no need to do it again...
325 points[ num_coords++ ].set(_coords[ci ], _coords[ci + 1]);
326 points[ num_coords++ ].set(_coords[ci + 2], _coords[ci + 3]);
330 points[ num_coords++ ].set(_coords[ci ], _coords[ci + 1]);
331 points[ num_coords++ ].set(_coords[ci + 2], _coords[ci + 3]);
332 points[ num_coords++ ].set(_coords[ci + 4], _coords[ci + 5]);
339 points[ num_coords++ ].set(_coords[ci + 3], _coords[ci + 4]);
342 SG_LOG(SG_GL, SG_WARN, "Unknown VG command: " << (int)cmd);
343 return osg::BoundingBox();
346 assert(num_coords <= max_coords);
347 for(VGubyte i = 0; i < num_coords; ++i)
352 bb.expandBy( transformPoint(mat, points[i]) );
356 cur = points[ num_coords - 1 ];
363 * Compute the bounding box
365 virtual osg::BoundingBox computeBound() const
367 if( _path == VG_INVALID_HANDLE || (_attributes_dirty & PATH) )
368 return osg::BoundingBox();
370 VGfloat min[2], size[2];
371 vgPathBounds(_path, &min[0], &min[1], &size[0], &size[1]);
373 _attributes_dirty &= ~BOUNDING_BOX;
375 // vgPathBounds doesn't take stroke width into account
376 float ext = 0.5 * _stroke_width;
380 min[0] - ext, min[1] - ext, -0.1,
381 min[0] + size[0] + ext, min[1] + size[1] + ext, 0.1
383 _path_element->setBoundingBox(bb);
393 STROKE_COLOR = PATH << 1,
394 FILL_COLOR = STROKE_COLOR << 1,
395 BOUNDING_BOX = FILL_COLOR << 1
400 mutable VGPath _path;
401 mutable VGPaint _paint;
402 mutable VGPaint _paint_fill;
403 mutable uint32_t _attributes_dirty;
409 osg::Vec4f _fill_color;
410 VGFillRule _fill_rule;
411 osg::Vec4f _stroke_color;
412 VGfloat _stroke_width;
413 std::vector<VGfloat> _stroke_dash;
414 VGCapStyle _stroke_linecap;
416 osg::Vec3f transformPoint( const osg::Matrix& m,
417 osg::Vec2f pos ) const
421 m(0, 0) * pos[0] + m(1, 0) * pos[1] + m(3, 0),
422 m(0, 1) * pos[0] + m(1, 1) * pos[1] + m(3, 1),
428 * Initialize/Update the OpenVG path
432 if( _attributes_dirty & PATH )
434 const VGbitfield caps = VG_PATH_CAPABILITY_APPEND_TO
435 | VG_PATH_CAPABILITY_MODIFY
436 | VG_PATH_CAPABILITY_PATH_BOUNDS;
438 if( _path == VG_INVALID_HANDLE )
439 _path = vgCreatePath(
440 VG_PATH_FORMAT_STANDARD,
442 1.f, 0.f, // scale,bias
443 _cmds.size(), _coords.size(),
447 vgClearPath(_path, caps);
449 if( !_cmds.empty() && !_coords.empty() )
450 vgAppendPathData(_path, _cmds.size(), &_cmds[0], &_coords[0]);
452 _attributes_dirty &= ~PATH;
453 _attributes_dirty |= BOUNDING_BOX;
456 if( _attributes_dirty & BOUNDING_BOX )
460 struct PathUpdateCallback:
461 public osg::Drawable::UpdateCallback
463 virtual void update(osg::NodeVisitor*, osg::Drawable* drawable)
465 static_cast<PathDrawable*>(drawable)->update();
470 //----------------------------------------------------------------------------
471 Path::Path( const CanvasWeakPtr& canvas,
472 const SGPropertyNode_ptr& node,
473 const Style& parent_style,
475 Element(canvas, node, parent_style, parent),
476 _path( new PathDrawable(this) )
479 PathDrawable *path = _path.get();
481 addStyle("fill", &PathDrawable::setFill, path);
482 addStyle("fill-rule", &PathDrawable::setFillRule, path);
483 addStyle("stroke", &PathDrawable::setStroke, path);
484 addStyle("stroke-width", &PathDrawable::setStrokeWidth, path);
485 addStyle("stroke-dasharray", &PathDrawable::setStrokeDashArray, path);
486 addStyle("stroke-linecap", &PathDrawable::setStrokeLinecap, path);
491 //----------------------------------------------------------------------------
497 //----------------------------------------------------------------------------
498 void Path::update(double dt)
500 if( _attributes_dirty & (CMDS | COORDS) )
504 _node->getChildValues<VGubyte, int>("cmd"),
505 _node->getChildValues<VGfloat, float>("coord")
508 _attributes_dirty &= ~(CMDS | COORDS);
514 //----------------------------------------------------------------------------
515 osg::BoundingBox Path::getTransformedBounds(const osg::Matrix& m) const
517 return _path->getTransformedBounds(m);
520 //----------------------------------------------------------------------------
521 void Path::childRemoved(SGPropertyNode* child)
526 //----------------------------------------------------------------------------
527 void Path::childChanged(SGPropertyNode* child)
529 if( child->getParent() != _node )
532 if( child->getNameString() == "cmd" )
533 _attributes_dirty |= CMDS;
534 else if( child->getNameString() == "coord" )
535 _attributes_dirty |= COORDS;
538 //----------------------------------------------------------------------------
539 std::vector<float> splitAndConvert(const char del[], const std::string& str)
541 std::vector<float> values;
545 pos = str.find_first_not_of(del, pos);
546 if( pos == std::string::npos )
550 float val = strtod(&str[pos], &end);
551 if( end == &str[pos] || !end )
554 values.push_back(val);
560 } // namespace canvas
561 } // namespace simgear