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>
24 #include <vg/openvg.h>
31 typedef std::vector<VGubyte> CmdList;
32 typedef std::vector<VGfloat> CoordList;
35 static const VGubyte shCoordsPerCommand[] = {
36 0, /* VG_CLOSE_PATH */
45 5, /* VG_SCCWARC_TO */
47 5, /* VG_LCCWARC_TO */
50 static const VGubyte shNumCommands = sizeof(shCoordsPerCommand)
51 / sizeof(shCoordsPerCommand[0]);
54 * Helper to split and convert comma/whitespace separated floating point
57 std::vector<float> splitAndConvert(const char del[], const std::string& str);
59 class Path::PathDrawable:
63 PathDrawable(Path* path):
65 _path(VG_INVALID_HANDLE),
66 _paint(VG_INVALID_HANDLE),
67 _paint_fill(VG_INVALID_HANDLE),
68 _attributes_dirty(~0),
70 _fill_rule(VG_EVEN_ODD),
72 _stroke_linecap(VG_CAP_BUTT)
74 setSupportsDisplayList(false);
75 setDataVariance(Object::DYNAMIC);
77 setUpdateCallback(new PathUpdateCallback());
80 virtual ~PathDrawable()
82 if( _path != VG_INVALID_HANDLE )
84 if( _paint != VG_INVALID_HANDLE )
85 vgDestroyPaint(_paint);
86 if( _paint_fill != VG_INVALID_HANDLE )
87 vgDestroyPaint(_paint_fill);
90 virtual const char* className() const { return "PathDrawable"; }
91 virtual osg::Object* cloneType() const { return new PathDrawable(_path_element); }
92 virtual osg::Object* clone(const osg::CopyOp&) const { return new PathDrawable(_path_element); }
95 * Replace the current path segments with the new ones
97 * @param cmds List of OpenVG path commands
98 * @param coords List of coordinates/parameters used by #cmds
100 void setSegments(const CmdList& cmds, const CoordList& coords)
105 _attributes_dirty |= (PATH | BOUNDING_BOX);
109 * Set path fill paint ("none" if not filled)
111 void setFill(const std::string& fill)
113 if( fill.empty() || fill == "none" )
115 _mode &= ~VG_FILL_PATH;
117 else if( parseColor(fill, _fill_color) )
119 _mode |= VG_FILL_PATH;
120 _attributes_dirty |= FILL_COLOR;
128 "canvas::Path Unknown fill: " << fill
134 * Set path fill rule ("pseudo-nonzero" or "evenodd")
136 * @warning As the current nonzero implementation causes sever artifacts
137 * for every concave path we call it pseudo-nonzero, so that
138 * everyone is warned that it won't work as expected :)
140 void setFillRule(const std::string& fill_rule)
142 if( fill_rule == "pseudo-nonzero" )
143 _fill_rule = VG_NON_ZERO;
144 else // if( fill_rule == "evenodd" )
145 _fill_rule = VG_EVEN_ODD;
149 * Set path stroke paint ("none" if no stroke)
151 void setStroke(const std::string& stroke)
153 if( stroke.empty() || stroke == "none" )
155 _mode &= ~VG_STROKE_PATH;
157 else if( parseColor(stroke, _stroke_color) )
159 _mode |= VG_STROKE_PATH;
160 _attributes_dirty |= STROKE_COLOR;
168 "canvas::Path Unknown stroke: " << stroke
176 void setStrokeWidth(float width)
178 _stroke_width = width;
179 _attributes_dirty |= BOUNDING_BOX;
183 * Set stroke dash (line stipple)
185 void setStrokeDashArray(const std::string& dash)
187 _stroke_dash = splitAndConvert(",\t\n ", dash);
193 * @see http://www.w3.org/TR/SVG/painting.html#StrokeLinecapProperty
195 void setStrokeLinecap(const std::string& linecap)
197 if( linecap == "round" )
198 _stroke_linecap = VG_CAP_ROUND;
199 else if( linecap == "square" )
200 _stroke_linecap = VG_CAP_SQUARE;
202 _stroke_linecap = VG_CAP_BUTT;
208 virtual void drawImplementation(osg::RenderInfo& renderInfo) const
210 if( _attributes_dirty & PATH )
213 osg::State* state = renderInfo.getState();
216 state->setActiveTextureUnit(0);
217 state->setClientActiveTextureUnit(0);
218 state->disableAllVertexArrays();
220 bool was_blend_enabled = state->getLastAppliedMode(GL_BLEND);
221 bool was_stencil_enabled = state->getLastAppliedMode(GL_STENCIL_TEST);
223 // Initialize/Update the paint
224 if( _attributes_dirty & STROKE_COLOR )
226 if( _paint == VG_INVALID_HANDLE )
227 _paint = vgCreatePaint();
229 vgSetParameterfv(_paint, VG_PAINT_COLOR, 4, _stroke_color._v);
231 _attributes_dirty &= ~STROKE_COLOR;
234 // Initialize/update fill paint
235 if( _attributes_dirty & FILL_COLOR )
237 if( _paint_fill == VG_INVALID_HANDLE )
238 _paint_fill = vgCreatePaint();
240 vgSetParameterfv(_paint_fill, VG_PAINT_COLOR, 4, _fill_color._v);
242 _attributes_dirty &= ~FILL_COLOR;
246 if( _mode & VG_STROKE_PATH )
248 vgSetPaint(_paint, VG_STROKE_PATH);
250 vgSetf(VG_STROKE_LINE_WIDTH, _stroke_width);
251 vgSeti(VG_STROKE_CAP_STYLE, _stroke_linecap);
252 vgSetfv( VG_STROKE_DASH_PATTERN,
254 _stroke_dash.empty() ? 0 : &_stroke_dash[0] );
256 if( _mode & VG_FILL_PATH )
258 vgSetPaint(_paint_fill, VG_FILL_PATH);
260 vgSeti(VG_FILL_RULE, _fill_rule);
263 // And finally draw the path
265 vgDrawPath(_path, _mode);
267 VGErrorCode err = vgGetError();
268 if( err != VG_NO_ERROR )
269 SG_LOG(SG_GL, SG_ALERT, "vgError: " << err);
271 if( was_blend_enabled ) glEnable(GL_BLEND);
272 if( was_stencil_enabled ) glEnable(GL_STENCIL_TEST);
275 osg::BoundingBox getTransformedBounds(const osg::Matrix& mat) const
279 osg::Vec2f cur(0, 0), // VG "Current point" (in local coordinates)
280 sub(0, 0); // beginning of current sub path
281 VGubyte cmd_index = 0;
282 for( size_t i = 0, ci = 0;
283 i < _cmds.size() && ci < _coords.size();
284 ++i, ci += shCoordsPerCommand[cmd_index] )
286 VGubyte rel = _cmds[i] & 1,
290 if( cmd_index >= shNumCommands )
291 return osg::BoundingBox();
293 const VGubyte max_coords = 3;
294 osg::Vec2f points[max_coords];
295 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]) );
357 cur = points[ num_coords - 1 ];
359 if( cmd == VG_MOVE_TO )
368 * Compute the bounding box
370 virtual osg::BoundingBox computeBound() const
372 if( _path == VG_INVALID_HANDLE || (_attributes_dirty & PATH) )
373 return osg::BoundingBox();
375 VGfloat min[2], size[2];
376 vgPathBounds(_path, &min[0], &min[1], &size[0], &size[1]);
378 _attributes_dirty &= ~BOUNDING_BOX;
380 // vgPathBounds doesn't take stroke width into account
381 float ext = 0.5 * _stroke_width;
383 return osg::BoundingBox
385 min[0] - ext, min[1] - ext, -0.1,
386 min[0] + size[0] + ext, min[1] + size[1] + ext, 0.1
395 STROKE_COLOR = PATH << 1,
396 FILL_COLOR = STROKE_COLOR << 1,
397 BOUNDING_BOX = FILL_COLOR << 1
402 mutable VGPath _path;
403 mutable VGPaint _paint;
404 mutable VGPaint _paint_fill;
405 mutable uint32_t _attributes_dirty;
411 osg::Vec4f _fill_color;
412 VGFillRule _fill_rule;
413 osg::Vec4f _stroke_color;
414 VGfloat _stroke_width;
415 std::vector<VGfloat> _stroke_dash;
416 VGCapStyle _stroke_linecap;
418 osg::Vec3f transformPoint( const osg::Matrix& m,
419 osg::Vec2f pos ) const
423 m(0, 0) * pos[0] + m(1, 0) * pos[1] + m(3, 0),
424 m(0, 1) * pos[0] + m(1, 1) * pos[1] + m(3, 1),
430 * Initialize/Update the OpenVG path
434 if( !vgHasContextSH() )
437 if( _attributes_dirty & PATH )
439 const VGbitfield caps = VG_PATH_CAPABILITY_APPEND_TO
440 | VG_PATH_CAPABILITY_MODIFY
441 | VG_PATH_CAPABILITY_PATH_BOUNDS;
443 if( _path == VG_INVALID_HANDLE )
444 _path = vgCreatePath(
445 VG_PATH_FORMAT_STANDARD,
447 1.f, 0.f, // scale,bias
448 _cmds.size(), _coords.size(),
452 vgClearPath(_path, caps);
454 if( !_cmds.empty() && !_coords.empty() )
455 vgAppendPathData(_path, _cmds.size(), &_cmds[0], &_coords[0]);
457 _attributes_dirty &= ~PATH;
458 _attributes_dirty |= BOUNDING_BOX;
461 if( _attributes_dirty & BOUNDING_BOX )
465 // Recalculate bounding box now (prevent race condition)
470 struct PathUpdateCallback:
471 public osg::Drawable::UpdateCallback
473 virtual void update(osg::NodeVisitor*, osg::Drawable* drawable)
475 static_cast<PathDrawable*>(drawable)->update();
480 //----------------------------------------------------------------------------
481 const std::string Path::TYPE_NAME = "path";
483 //----------------------------------------------------------------------------
484 void Path::staticInit()
489 PathDrawableRef Path::*path = &Path::_path;
491 addStyle("fill", "color", &PathDrawable::setFill, path);
492 addStyle("fill-rule", "", &PathDrawable::setFillRule, path);
493 addStyle("stroke", "color", &PathDrawable::setStroke, path);
494 addStyle("stroke-width", "numeric", &PathDrawable::setStrokeWidth, path);
495 addStyle("stroke-dasharray", "", &PathDrawable::setStrokeDashArray, path);
496 addStyle("stroke-linecap", "", &PathDrawable::setStrokeLinecap, path);
499 //----------------------------------------------------------------------------
500 Path::Path( const CanvasWeakPtr& canvas,
501 const SGPropertyNode_ptr& node,
502 const Style& parent_style,
504 Element(canvas, node, parent_style, parent),
505 _path( new PathDrawable(this) )
513 //----------------------------------------------------------------------------
519 //----------------------------------------------------------------------------
520 void Path::update(double dt)
522 if( _attributes_dirty & (CMDS | COORDS) )
526 _node->getChildValues<VGubyte, int>("cmd"),
527 _node->getChildValues<VGfloat, float>("coord")
530 _attributes_dirty &= ~(CMDS | COORDS);
536 //----------------------------------------------------------------------------
537 osg::BoundingBox Path::getTransformedBounds(const osg::Matrix& m) const
539 return _path->getTransformedBounds(m);
542 //----------------------------------------------------------------------------
543 Path& Path::moveTo(float x_abs, float y_abs)
545 return addSegment(VG_MOVE_TO_ABS, x_abs, y_abs);
548 //----------------------------------------------------------------------------
549 Path& Path::move(float x_rel, float y_rel)
551 return addSegment(VG_MOVE_TO_REL, x_rel, y_rel);
554 //----------------------------------------------------------------------------
555 Path& Path::lineTo(float x_abs, float y_abs)
557 return addSegment(VG_LINE_TO_ABS, x_abs, y_abs);
560 //----------------------------------------------------------------------------
561 Path& Path::line(float x_rel, float y_rel)
563 return addSegment(VG_LINE_TO_REL, x_rel, y_rel);
566 //----------------------------------------------------------------------------
567 Path& Path::horizTo(float x_abs)
569 return addSegment(VG_HLINE_TO_ABS, x_abs);
572 //----------------------------------------------------------------------------
573 Path& Path::horiz(float x_rel)
575 return addSegment(VG_HLINE_TO_REL, x_rel);
578 //----------------------------------------------------------------------------
579 Path& Path::vertTo(float y_abs)
581 return addSegment(VG_VLINE_TO_ABS, y_abs);
584 //----------------------------------------------------------------------------
585 Path& Path::vert(float y_rel)
587 return addSegment(VG_VLINE_TO_REL, y_rel);
590 //----------------------------------------------------------------------------
593 return addSegment(VG_CLOSE_PATH);
596 //----------------------------------------------------------------------------
597 void Path::childRemoved(SGPropertyNode* child)
602 //----------------------------------------------------------------------------
603 void Path::childChanged(SGPropertyNode* child)
605 if( child->getParent() != _node )
608 if( child->getNameString() == "cmd" )
609 _attributes_dirty |= CMDS;
610 else if( child->getNameString() == "coord" )
611 _attributes_dirty |= COORDS;
614 //----------------------------------------------------------------------------
615 std::vector<float> splitAndConvert(const char del[], const std::string& str)
617 std::vector<float> values;
621 pos = str.find_first_not_of(del, pos);
622 if( pos == std::string::npos )
626 float val = strtod(&str[pos], &end);
627 if( end == &str[pos] || !end )
630 values.push_back(val);
636 } // namespace canvas
637 } // namespace simgear