COIN-OR::LEMON - Graph Library

source: lemon-0.x/src/lemon/graph_to_eps.h @ 1106:0a7d604a9763

Last change on this file since 1106:0a7d604a9763 was 1103:f196dc4f1b31, checked in by Alpar Juttner, 17 years ago

Add a 'scaleToA4()' function.

File size: 24.2 KB
Line 
1/* -*- C++ -*-
2 * src/lemon/graph_to_eps.h - Part of LEMON, a generic C++ optimization library
3 *
4 * Copyright (C) 2004 Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
5 * (Egervary Combinatorial Optimization Research Group, EGRES).
6 *
7 * Permission to use, modify and distribute this software is granted
8 * provided that this copyright notice appears in all copies. For
9 * precise terms see the accompanying LICENSE file.
10 *
11 * This software is provided "AS IS" with no warranty of any kind,
12 * express or implied, and with no claim as to its suitability for any
13 * purpose.
14 *
15 */
16
17#ifndef LEMON_GRAPH_TO_EPS_H
18#define LEMON_GRAPH_TO_EPS_H
19
20#include<iostream>
21#include<fstream>
22#include<sstream>
23#include<algorithm>
24#include<vector>
25
26#include<lemon/xy.h>
27#include<lemon/maps.h>
28#include<lemon/bezier.h>
29
30///\ingroup misc
31///\file
32///\brief Simple graph drawer
33///
34///\author Alpar Juttner
35
36namespace lemon {
37
38///Data structure representing RGB colors.
39
40///Data structure representing RGB colors.
41///\ingroup misc
42class Color
43{
44  double _r,_g,_b;
45public:
46  ///Default constructor
47  Color() {}
48  ///Constructor
49  Color(double r,double g,double b) :_r(r),_g(g),_b(b) {};
50  ///Returns the red component
51  double getR() {return _r;}
52  ///Returns the green component
53  double getG() {return _g;}
54  ///Returns the blue component
55  double getB() {return _b;}
56  ///Set the color components
57  void set(double r,double g,double b) { _r=r;_g=g;_b=b; };
58};
59 
60///Default traits class of \ref GraphToEps
61
62///Default traits class of \ref GraphToEps
63///
64///\c G is the type of the underlying graph.
65template<class G>
66struct DefaultGraphToEpsTraits
67{
68  typedef G Graph;
69  typedef typename Graph::Node Node;
70  typedef typename Graph::NodeIt NodeIt;
71  typedef typename Graph::Edge Edge;
72  typedef typename Graph::EdgeIt EdgeIt;
73  typedef typename Graph::InEdgeIt InEdgeIt;
74  typedef typename Graph::OutEdgeIt OutEdgeIt;
75 
76
77  const Graph &g;
78
79  std::ostream& os;
80 
81  ConstMap<typename Graph::Node,xy<double> > _coords;
82  ConstMap<typename Graph::Node,double > _nodeSizes;
83  ConstMap<typename Graph::Node,int > _nodeShapes;
84
85  ConstMap<typename Graph::Node,Color > _nodeColors;
86  ConstMap<typename Graph::Edge,Color > _edgeColors;
87
88  ConstMap<typename Graph::Edge,double > _edgeWidths;
89
90  static const double A4HEIGHT = 841.8897637795276;
91  static const double A4WIDTH  = 595.275590551181;
92  static const double A4BORDER = 15;
93
94 
95  double _edgeWidthScale;
96 
97  double _nodeScale;
98  double _xBorder, _yBorder;
99  double _scale;
100  double _nodeBorderQuotient;
101 
102  bool _drawArrows;
103  double _arrowLength, _arrowWidth;
104 
105  bool _showNodes, _showEdges;
106
107  bool _enableParallel;
108  double _parEdgeDist;
109
110  bool _showNodeText;
111  ConstMap<typename Graph::Node,bool > _nodeTexts; 
112  double _nodeTextSize;
113
114  bool _showNodePsText;
115  ConstMap<typename Graph::Node,bool > _nodePsTexts; 
116  char *_nodePsTextsPreamble;
117 
118  bool _undir;
119  bool _pleaseRemoveOsStream;
120
121  bool _scaleToA4;
122 
123  ///Constructor
124
125  ///Constructor
126  ///\param _g is a reference to the graph to be printed
127  ///\param _os is a reference to the output stream.
128  ///\param _os is a reference to the output stream.
129  ///\param _pros If it is \c true, then the \c ostream referenced by \c _os
130  ///will be explicitly deallocated by the destructor.
131  ///By default it is <tt>std::cout</tt>
132  DefaultGraphToEpsTraits(const G &_g,std::ostream& _os=std::cout,
133                          bool _pros=false) :
134    g(_g), os(_os),
135    _coords(xy<double>(1,1)), _nodeSizes(1.0), _nodeShapes(0),
136    _nodeColors(Color(1,1,1)), _edgeColors(Color(0,0,0)),
137    _edgeWidths(1), _edgeWidthScale(0.3),
138    _nodeScale(1.0), _xBorder(10), _yBorder(10), _scale(1.0),
139    _nodeBorderQuotient(.1),
140    _drawArrows(false), _arrowLength(1), _arrowWidth(0.3),
141    _showNodes(true), _showEdges(true),
142    _enableParallel(false), _parEdgeDist(1),
143    _showNodeText(false), _nodeTexts(false), _nodeTextSize(1),
144    _showNodePsText(false), _nodePsTexts(false), _nodePsTextsPreamble(0),
145    _undir(false),
146    _pleaseRemoveOsStream(_pros), _scaleToA4(false) {}
147};
148
149///Helper class to implement the named parameters of \ref graphToEps()
150
151///Helper class to implement the named parameters of \ref graphToEps()
152///\todo Is 'helper class' a good name for this?
153///
154///\todo Follow PostScript's DSC.
155///\todo Use own dictionary.
156template<class T> class GraphToEps : public T
157{
158  typedef typename T::Graph Graph;
159  typedef typename Graph::Node Node;
160  typedef typename Graph::NodeIt NodeIt;
161  typedef typename Graph::Edge Edge;
162  typedef typename Graph::EdgeIt EdgeIt;
163  typedef typename Graph::InEdgeIt InEdgeIt;
164  typedef typename Graph::OutEdgeIt OutEdgeIt;
165
166  static const int INTERPOL_PREC=20;
167
168  bool dontPrint;
169
170  enum NodeShapes { CIRCLE=0, SQUARE=1, DIAMOND=2 };
171                   
172  class edgeLess {
173    const Graph &g;
174  public:
175    edgeLess(const Graph &_g) : g(_g) {}
176    bool operator()(Edge a,Edge b) const
177    {
178      Node ai=min(g.source(a),g.target(a));
179      Node aa=max(g.source(a),g.target(a));
180      Node bi=min(g.source(b),g.target(b));
181      Node ba=max(g.source(b),g.target(b));
182      return ai<bi ||
183        (ai==bi && (aa < ba ||
184                    (aa==ba && ai==g.source(a) && bi==g.target(b))));
185    }
186  };
187  bool isParallel(Edge e,Edge f) const
188  {
189    return (g.source(e)==g.source(f)&&g.target(e)==g.target(f))||
190      (g.source(e)==g.target(f)&&g.target(e)==g.source(f));
191  }
192  static xy<double> rot(xy<double> v)
193  {
194    return xy<double>(v.y,-v.x);
195  }
196  template<class xy>
197  static std::string psOut(const xy &p)
198    {
199      std::ostringstream os;   
200      os << p.x << ' ' << p.y;
201      return os.str();
202    }
203 
204public:
205  GraphToEps(const T &t) : T(t), dontPrint(false) {};
206 
207  template<class X> struct CoordsTraits : public T {
208    const X &_coords;
209    CoordsTraits(const T &t,const X &x) : T(t), _coords(x) {}
210  };
211  ///Sets the map of the node coordinates
212
213  ///Sets the map of the node coordinates.
214  ///\param x must be a node map with xy<double> or \ref xy "xy<int>" values.
215  template<class X> GraphToEps<CoordsTraits<X> > coords(const X &x) {
216    dontPrint=true;
217    return GraphToEps<CoordsTraits<X> >(CoordsTraits<X>(*this,x));
218  }
219  template<class X> struct NodeSizesTraits : public T {
220    const X &_nodeSizes;
221    NodeSizesTraits(const T &t,const X &x) : T(t), _nodeSizes(x) {}
222  };
223  ///Sets the map of the node sizes
224
225  ///Sets the map of the node sizes
226  ///\param x must be a node map with \c double (or convertible) values.
227  template<class X> GraphToEps<NodeSizesTraits<X> > nodeSizes(const X &x)
228  {
229    dontPrint=true;
230    return GraphToEps<NodeSizesTraits<X> >(NodeSizesTraits<X>(*this,x));
231  }
232  template<class X> struct NodeShapesTraits : public T {
233    const X &_nodeShapes;
234    NodeShapesTraits(const T &t,const X &x) : T(t), _nodeShapes(x) {}
235  };
236  ///Sets the map of the node shapes
237
238  ///Sets the map of the node shapes
239  ///\param x must be a node map with \c int (or convertible) values.
240  ///\todo Incomplete doc.
241  template<class X> GraphToEps<NodeShapesTraits<X> > nodeShapes(const X &x)
242  {
243    dontPrint=true;
244    return GraphToEps<NodeShapesTraits<X> >(NodeShapesTraits<X>(*this,x));
245  }
246  template<class X> struct NodeTextsTraits : public T {
247    const X &_nodeTexts;
248    NodeTextsTraits(const T &t,const X &x) : T(t), _nodeTexts(x) {}
249  };
250  ///Sets the text printed on the nodes
251
252  ///Sets the text printed on the nodes
253  ///\param x must be a node map with type that can be pushed to a standard
254  ///ostream.
255  template<class X> GraphToEps<NodeTextsTraits<X> > nodeTexts(const X &x)
256  {
257    dontPrint=true;
258    _showNodeText=true;
259    return GraphToEps<NodeTextsTraits<X> >(NodeTextsTraits<X>(*this,x));
260  }
261  template<class X> struct NodePsTextsTraits : public T {
262    const X &_nodePsTexts;
263    NodePsTextsTraits(const T &t,const X &x) : T(t), _nodePsTexts(x) {}
264  };
265  ///Inserts a PostScript block to the nodes
266
267  ///With this command it is possible to insert a verbatim PostScript
268  ///block to the nodes.
269  ///The PS current point will be moved to the centre of the node before
270  ///the PostScript block inserted.
271  ///
272  ///Before and after the block a newline character is inserted to you
273  ///don't have to bother with the separators.
274  ///
275  ///\param x must be a node map with type that can be pushed to a standard
276  ///ostream.
277  ///
278  ///\sa nodePsTextsPreamble()
279  ///\todo Offer the choise not to move to the centre but pass the coordinates
280  ///to the Postscript block inserted.
281  template<class X> GraphToEps<NodePsTextsTraits<X> > nodePsTexts(const X &x)
282  {
283    dontPrint=true;
284    _showNodePsText=true;
285    return GraphToEps<NodePsTextsTraits<X> >(NodePsTextsTraits<X>(*this,x));
286  }
287  template<class X> struct EdgeWidthsTraits : public T {
288    const X &_edgeWidths;
289    EdgeWidthsTraits(const T &t,const X &x) : T(t), _edgeWidths(x) {}
290  };
291  ///Sets the map of the edge widths
292
293  ///Sets the map of the edge widths
294  ///\param x must be a edge map with \c double (or convertible) values.
295  template<class X> GraphToEps<EdgeWidthsTraits<X> > edgeWidths(const X &x)
296  {
297    dontPrint=true;
298    return GraphToEps<EdgeWidthsTraits<X> >(EdgeWidthsTraits<X>(*this,x));
299  }
300
301  template<class X> struct NodeColorsTraits : public T {
302    const X &_nodeColors;
303    NodeColorsTraits(const T &t,const X &x) : T(t), _nodeColors(x) {}
304  };
305  ///Sets the map of the node colors
306
307  ///Sets the map of the node colors
308  ///\param x must be a node map with \ref Color values.
309  template<class X> GraphToEps<NodeColorsTraits<X> >
310  nodeColors(const X &x)
311  {
312    dontPrint=true;
313    return GraphToEps<NodeColorsTraits<X> >(NodeColorsTraits<X>(*this,x));
314  }
315  template<class X> struct EdgeColorsTraits : public T {
316    const X &_edgeColors;
317    EdgeColorsTraits(const T &t,const X &x) : T(t), _edgeColors(x) {}
318  };
319  ///Sets the map of the edge colors
320
321  ///Sets the map of the edge colors
322  ///\param x must be a edge map with \ref Color values.
323  template<class X> GraphToEps<EdgeColorsTraits<X> >
324  edgeColors(const X &x)
325  {
326    dontPrint=true;
327    return GraphToEps<EdgeColorsTraits<X> >(EdgeColorsTraits<X>(*this,x));
328  }
329  ///Sets a global scale factor for node sizes
330
331  ///Sets a global scale factor for node sizes
332  ///
333  GraphToEps<T> &nodeScale(double d) {_nodeScale=d;return *this;}
334  ///Sets a global scale factor for edge widths
335
336  ///Sets a global scale factor for edge widths
337  ///
338  GraphToEps<T> &edgeWidthScale(double d) {_edgeWidthScale=d;return *this;}
339  ///Sets a global scale factor for the whole picture
340
341  ///Sets a global scale factor for the whole picture
342  ///
343  GraphToEps<T> &scale(double d) {_scale=d;return *this;}
344  ///Sets the width of the border around the picture
345
346  ///Sets the width of the border around the picture
347  ///
348  GraphToEps<T> &border(double b) {_xBorder=_yBorder=b;return *this;}
349  ///Sets the width of the border around the picture
350
351  ///Sets the width of the border around the picture
352  ///
353  GraphToEps<T> &border(double x, double y) {
354    _xBorder=x;_yBorder=y;return *this;
355  }
356  ///Sets whether to draw arrows
357
358  ///Sets whether to draw arrows
359  ///
360  GraphToEps<T> &drawArrows(bool b=true) {_drawArrows=b;return *this;}
361  ///Sets the length of the arrowheads
362
363  ///Sets the length of the arrowheads
364  ///
365  GraphToEps<T> &arrowLength(double d) {_arrowLength*=d;return *this;}
366  ///Sets the width of the arrowheads
367
368  ///Sets the width of the arrowheads
369  ///
370  GraphToEps<T> &arrowWidth(double d) {_arrowWidth*=d;return *this;}
371 
372  ///Scales the drawing to fit to A4 page
373
374  ///Scales the drawing to fit to A4 page
375  ///
376  GraphToEps<T> &scaleToA4() {_scaleToA4=true;return *this;}
377 
378  ///Enables parallel edges
379
380  ///Enables parallel edges
381  ///\todo Partially implemented
382  GraphToEps<T> &enableParallel(bool b=true) {_enableParallel=b;return *this;}
383 
384  ///Sets the distance
385 
386  ///Sets the distance
387  ///
388  GraphToEps<T> &parEdgeDist(double d) {_parEdgeDist*=d;return *this;}
389 
390  ///Hides the edges
391 
392  ///Hides the edges
393  ///
394  GraphToEps<T> &hideEdges(bool b=true) {_showEdges=!b;return *this;}
395  ///Hides the nodes
396 
397  ///Hides the nodes
398  ///
399  GraphToEps<T> &hideNodes(bool b=true) {_showNodes=!b;return *this;}
400 
401  ///Sets the size of the node texts
402 
403  ///Sets the size of the node texts
404  ///
405  GraphToEps<T> &nodeTextSize(double d) {_nodeTextSize=d;return *this;}
406  ///Gives a preamble block for node Postscript block.
407 
408  ///Gives a preamble block for node Postscript block.
409  ///
410  ///\sa nodePsTexts()
411  GraphToEps<T> & nodePsTextsPreamble(const char *str) {
412    _nodePsTextsPreamble=s ;return *this;
413  }
414  ///Sets whether the the graph is undirected
415
416  ///Sets whether the the graph is undirected
417  ///
418  GraphToEps<T> &undir(bool b=true) {_undir=b;return *this;}
419  ///Sets whether the the graph is directed
420
421  ///Sets whether the the graph is directed.
422  ///Use it to show the undirected edges as a pair of directed ones.
423  GraphToEps<T> &bidir(bool b=true) {_undir=!b;return *this;}
424
425protected:
426  bool isInsideNode(xy<double> p, double r,int t)
427  {
428    switch(t) {
429    case CIRCLE:
430      return p.normSquare()<=r*r;
431    case SQUARE:
432      return p.x<=r&&p.x>=-r&&p.y<=r&&p.y>=-r;
433    case DIAMOND:
434      return p.x+p.y<=r && p.x-p.y<=r && -p.x+p.y<=r && -p.x-p.y<=r;
435    }
436    return false;
437  }
438
439public:
440  ~GraphToEps() { }
441 
442  ///Draws the graph.
443
444  ///Like other functions using
445  ///\ref named-templ-func-param "named template parameters",
446  ///this function calles the algorithm itself, i.e. in this case
447  ///it draws the graph.
448  void run() {
449    if(dontPrint) return;
450   
451    os << "%!PS-Adobe-2.0 EPSF-2.0\n";
452    //\todo: Chech whether the graph is empty.
453    BoundingBox<double> bb;
454    for(NodeIt n(g);n!=INVALID;++n) {
455      double ns=_nodeSizes[n]*_nodeScale;
456      xy<double> p(ns,ns);
457      bb+=p+_coords[n];
458      bb+=-p+_coords[n];
459      }
460    if(!_scaleToA4) os << "%%BoundingBox: "
461                      << bb.left()*  _scale-_xBorder << ' '
462                      << bb.bottom()*_scale-_yBorder << ' '
463                      << bb.right()* _scale+_xBorder << ' '
464                      << bb.top()*   _scale+_yBorder << '\n';
465    //x1 y1 x2 y2 x3 y3 cr cg cb w
466    os << "/lb { setlinewidth setrgbcolor newpath moveto\n"
467       << "      4 2 roll 1 index 1 index curveto stroke } bind def\n";
468    os << "/l { setlinewidth setrgbcolor newpath moveto lineto stroke } bind def\n";
469    //x y r
470    os << "/c { newpath dup 3 index add 2 index moveto 0 360 arc closepath } bind def\n";
471    //x y r
472    os << "/sq { newpath 2 index 1 index add 2 index 2 index add moveto\n"
473       << "      2 index 1 index sub 2 index 2 index add lineto\n"
474       << "      2 index 1 index sub 2 index 2 index sub lineto\n"
475       << "      2 index 1 index add 2 index 2 index sub lineto\n"
476       << "      closepath pop pop pop} bind def\n";
477    //x y r
478    os << "/di { newpath 2 index 1 index add 2 index moveto\n"
479       << "      2 index             2 index 2 index add lineto\n"
480       << "      2 index 1 index sub 2 index             lineto\n"
481       << "      2 index             2 index 2 index sub lineto\n"
482       << "      closepath pop pop pop} bind def\n";
483    // x y r cr cg cb
484    os << "/nc { 0 0 0 setrgbcolor 5 index 5 index 5 index c fill\n"
485       << "     setrgbcolor " << 1+_nodeBorderQuotient << " div c fill\n"
486       << "   } bind def\n";
487    os << "/nsq { 0 0 0 setrgbcolor 5 index 5 index 5 index sq fill\n"
488       << "     setrgbcolor " << 1+_nodeBorderQuotient << " div sq fill\n"
489       << "   } bind def\n";
490    os << "/ndi { 0 0 0 setrgbcolor 5 index 5 index 5 index di fill\n"
491       << "     setrgbcolor " << 1+_nodeBorderQuotient << " div di fill\n"
492       << "   } bind def\n";
493    os << "/arrl " << _arrowLength << " def\n";
494    os << "/arrw " << _arrowWidth << " def\n";
495    // l dx_norm dy_norm
496    os << "/lrl { 2 index mul exch 2 index mul exch rlineto pop} bind def\n";
497    //len w dx_norm dy_norm x1 y1 cr cg cb
498    os << "/arr { setrgbcolor /y1 exch def /x1 exch def /dy exch def /dx exch def\n"
499       << "       /w exch def /len exch def\n"
500      //         << "       0.1 setlinewidth x1 y1 moveto dx len mul dy len mul rlineto stroke"
501       << "       newpath x1 dy w 2 div mul add y1 dx w 2 div mul sub moveto\n"
502       << "       len w sub arrl sub dx dy lrl\n"
503       << "       arrw dy dx neg lrl\n"
504       << "       dx arrl w add mul dy w 2 div arrw add mul sub\n"
505       << "       dy arrl w add mul dx w 2 div arrw add mul add rlineto\n"
506       << "       dx arrl w add mul neg dy w 2 div arrw add mul sub\n"
507       << "       dy arrl w add mul neg dx w 2 div arrw add mul add rlineto\n"
508       << "       arrw dy dx neg lrl\n"
509       << "       len w sub arrl sub neg dx dy lrl\n"
510       << "       closepath fill } bind def\n";
511    os << "/cshow { 2 index 2 index moveto dup stringwidth pop\n"
512       << "         neg 2 div fosi .35 mul neg rmoveto show pop pop} def\n";
513
514    os << "\ngsave\n";
515    if(_scaleToA4)
516      if(bb.height()>bb.width()) {
517        double sc= min((A4HEIGHT-2*A4BORDER)/bb.height(),
518                  (A4WIDTH-2*A4BORDER)/bb.width());
519        os << ((A4WIDTH -2*A4BORDER)-sc*bb.width())/2 + A4BORDER << ' '
520           << ((A4HEIGHT-2*A4BORDER)-sc*bb.height())/2 + A4BORDER << " translate\n"
521           << sc << " dup scale\n"
522           << -bb.left() << ' ' << -bb.bottom() << " translate\n";
523      }
524      else {
525        //\todo Verify centering
526        double sc= min((A4HEIGHT-2*A4BORDER)/bb.width(),
527                  (A4WIDTH-2*A4BORDER)/bb.height());
528        os << ((A4WIDTH -2*A4BORDER)-sc*bb.height())/2 + A4BORDER << ' '
529           << ((A4HEIGHT-2*A4BORDER)-sc*bb.width())/2 + A4BORDER  << " translate\n"
530           << sc << " dup scale\n90 rotate\n"
531           << -bb.left() << ' ' << -bb.top() << " translate\n";
532        }
533    else if(_scale!=1.0) os << _scale << " dup scale\n";
534   
535    if(_showEdges) {
536      os << "%Edges:\ngsave\n";     
537      if(_enableParallel) {
538        std::vector<Edge> el;
539        for(EdgeIt e(g);e!=INVALID;++e)
540          if(!_undir||g.source(e)<g.target(e)) el.push_back(e);
541        sort(el.begin(),el.end(),edgeLess(g));
542       
543        typename std::vector<Edge>::iterator j;
544        for(typename std::vector<Edge>::iterator i=el.begin();i!=el.end();i=j) {
545          for(j=i+1;j!=el.end()&&isParallel(*i,*j);++j) ;
546
547          double sw=0;
548          for(typename std::vector<Edge>::iterator e=i;e!=j;++e)
549            sw+=_edgeWidths[*e]*_edgeWidthScale+_parEdgeDist;
550          sw-=_parEdgeDist;
551          sw/=-2.0;
552          xy<double> dvec(_coords[g.target(*i)]-_coords[g.source(*i)]);
553          double l=sqrt(dvec.normSquare());
554          xy<double> d(dvec/l);
555          xy<double> m;
556//        m=xy<double>(_coords[g.target(*i)]+_coords[g.source(*i)])/2.0;
557
558//        m=xy<double>(_coords[g.source(*i)])+
559//          dvec*(double(_nodeSizes[g.source(*i)])/
560//             (_nodeSizes[g.source(*i)]+_nodeSizes[g.target(*i)]));
561
562          m=xy<double>(_coords[g.source(*i)])+
563            d*(l+_nodeSizes[g.source(*i)]-_nodeSizes[g.target(*i)])/2.0;
564
565          for(typename std::vector<Edge>::iterator e=i;e!=j;++e) {
566            sw+=_edgeWidths[*e]*_edgeWidthScale/2.0;
567            xy<double> mm=m+rot(d)*sw/.75;
568            if(_drawArrows) {
569              int node_shape;
570              xy<double> s=_coords[g.source(*e)];
571              xy<double> t=_coords[g.target(*e)];
572              double rn=_nodeSizes[g.target(*e)]*_nodeScale;
573              node_shape=_nodeShapes[g.target(*e)];
574              Bezier3 bez(s,mm,mm,t);
575              double t1=0,t2=1;
576              for(int i=0;i<INTERPOL_PREC;++i)
577                if(isInsideNode(bez((t1+t2)/2)-t,rn,node_shape)) t2=(t1+t2)/2;
578                else t1=(t1+t2)/2;
579              xy<double> apoint=bez((t1+t2)/2);
580              rn = _arrowLength+_edgeWidths[*e]*_edgeWidthScale;
581              rn*=rn;
582              t2=(t1+t2)/2;t1=0;
583              for(int i=0;i<INTERPOL_PREC;++i)
584                if((bez((t1+t2)/2)-apoint).normSquare()>rn) t1=(t1+t2)/2;
585                else t2=(t1+t2)/2;
586              xy<double> linend=bez((t1+t2)/2);       
587              bez=bez.before((t1+t2)/2);
588//            rn=_nodeSizes[g.source(*e)]*_nodeScale;
589//            node_shape=_nodeShapes[g.source(*e)];
590//            t1=0;t2=1;
591//            for(int i=0;i<INTERPOL_PREC;++i)
592//              if(isInsideNode(bez((t1+t2)/2)-t,rn,node_shape)) t1=(t1+t2)/2;
593//              else t2=(t1+t2)/2;
594//            bez=bez.after((t1+t2)/2);
595              os << _edgeWidths[*e]*_edgeWidthScale << " setlinewidth "
596                 << _edgeColors[*e].getR() << ' '
597                 << _edgeColors[*e].getG() << ' '
598                 << _edgeColors[*e].getB() << " setrgbcolor newpath\n"
599                 << bez.p1.x << ' ' <<  bez.p1.y << " moveto\n"
600                 << bez.p2.x << ' ' << bez.p2.y << ' '
601                 << bez.p3.x << ' ' << bez.p3.y << ' '
602                 << bez.p4.x << ' ' << bez.p4.y << " curveto stroke\n";
603              xy<double> dd(rot(linend-apoint));
604              dd*=(.5*_edgeWidths[*e]*_edgeWidthScale+_arrowWidth)/
605                sqrt(dd.normSquare());
606              os << "newpath " << psOut(apoint) << " moveto "
607                 << psOut(linend+dd) << " lineto "
608                 << psOut(linend-dd) << " lineto closepath fill\n";
609            }
610            else {
611              os << _coords[g.source(*e)].x << ' '
612                 << _coords[g.source(*e)].y << ' '
613                 << mm.x << ' ' << mm.y << ' '
614                 << _coords[g.target(*e)].x << ' '
615                 << _coords[g.target(*e)].y << ' '
616                 << _edgeColors[*e].getR() << ' '
617                 << _edgeColors[*e].getG() << ' '
618                 << _edgeColors[*e].getB() << ' '
619                 << _edgeWidths[*e]*_edgeWidthScale << " lb\n";
620            }
621            sw+=_edgeWidths[*e]*_edgeWidthScale/2.0+_parEdgeDist;
622          }
623        }
624      }
625      else for(EdgeIt e(g);e!=INVALID;++e)
626        if(!_undir||g.source(e)<g.target(e))
627          if(_drawArrows) {
628            xy<double> d(_coords[g.target(e)]-_coords[g.source(e)]);
629            double rn=_nodeSizes[g.target(e)]*_nodeScale;
630            int node_shape=_nodeShapes[g.target(e)];
631            double t1=0,t2=1;
632            for(int i=0;i<INTERPOL_PREC;++i)
633              if(isInsideNode((-(t1+t2)/2)*d,rn,node_shape)) t1=(t1+t2)/2;
634              else t2=(t1+t2)/2;
635            double l=sqrt(d.normSquare());
636            d/=l;
637           
638            os << l*(1-(t1+t2)/2) << ' '
639               << _edgeWidths[e]*_edgeWidthScale << ' '
640               << d.x << ' ' << d.y << ' '
641               << _coords[g.source(e)].x << ' '
642               << _coords[g.source(e)].y << ' '
643               << _edgeColors[e].getR() << ' '
644               << _edgeColors[e].getG() << ' '
645               << _edgeColors[e].getB() << " arr\n";
646          }
647          else os << _coords[g.source(e)].x << ' '
648                  << _coords[g.source(e)].y << ' '
649                  << _coords[g.target(e)].x << ' '
650                  << _coords[g.target(e)].y << ' '
651                  << _edgeColors[e].getR() << ' '
652                  << _edgeColors[e].getG() << ' '
653                  << _edgeColors[e].getB() << ' '
654                  << _edgeWidths[e]*_edgeWidthScale << " l\n";
655      os << "grestore\n";
656    }
657    if(_showNodes) {
658      os << "%Nodes:\ngsave\n";
659      for(NodeIt n(g);n!=INVALID;++n) {
660        os << _coords[n].x << ' ' << _coords[n].y << ' '
661           << _nodeSizes[n]*_nodeScale << ' '
662           << _nodeColors[n].getR() << ' '
663           << _nodeColors[n].getG() << ' '
664           << _nodeColors[n].getB() << ' ';
665        switch(_nodeShapes[n]) {
666        case CIRCLE:
667          os<< "nc";break;
668        case SQUARE:
669          os<< "nsq";break;
670        case DIAMOND:
671          os<< "ndi";break;
672        }
673        os<<'\n';
674      }
675      os << "grestore\n";
676    }
677    if(_showNodeText) {
678      os << "%Node texts:\ngsave\n";
679      os << "/fosi " << _nodeTextSize << " def\n";
680      os << "(Helvetica) findfont fosi scalefont setfont\n";
681      os << "0 0 0 setrgbcolor\n";
682      for(NodeIt n(g);n!=INVALID;++n)
683        os << _coords[n].x << ' ' << _coords[n].y
684           << " (" << _nodeTexts[n] << ") cshow\n";
685      os << "grestore\n";
686    }
687    if(_showNodePsText) {
688      os << "%Node PS blocks:\ngsave\n";
689      for(NodeIt n(g);n!=INVALID;++n)
690        os << _coords[n].x << ' ' << _coords[n].y
691           << " moveto\n" << _nodePsTexts[n] << "\n";
692      os << "grestore\n";
693    }
694   
695    os << "grestore\nshowpage\n";
696
697    //CleanUp:
698    if(_pleaseRemoveOsStream) {delete &os;}
699  }
700};
701
702
703///Generates an EPS file from a graph
704
705///\ingroup misc
706///Generates an EPS file from a graph.
707///\param g is a reference to the graph to be printed
708///\param os is a reference to the output stream.
709///By default it is <tt>std::cout</tt>
710///
711///This function also has a lot of
712///\ref named-templ-func-param "named parameters",
713///they are declared as the members of class \ref GraphToEps. The following
714///example shows how to use these parameters.
715///\code
716/// graphToEps(g).scale(10).coords(coords)
717///              .nodeScale(2).nodeSizes(sizes)
718///              .edgeWidthScale(.4).run();
719///\endcode
720///\warning Don't forget to put the \ref GraphToEps::run() "run()"
721///to the end of the parameter list.
722///\sa GraphToEps
723///\sa graphToEps(G &g, char *file_name)
724template<class G>
725GraphToEps<DefaultGraphToEpsTraits<G> >
726graphToEps(G &g, std::ostream& os=std::cout)
727{
728  return
729    GraphToEps<DefaultGraphToEpsTraits<G> >(DefaultGraphToEpsTraits<G>(g,os));
730}
731 
732///Generates an EPS file from a graph
733
734///\ingroup misc
735///This function does the same as
736///\ref graphToEps(G &g,std::ostream& os)
737///but it writes its output into the file \c file_name
738///instead of a stream.
739///\sa graphToEps(G &g, std::ostream& os)
740template<class G>
741GraphToEps<DefaultGraphToEpsTraits<G> >
742graphToEps(G &g,char *file_name)
743{
744  return GraphToEps<DefaultGraphToEpsTraits<G> >
745    (DefaultGraphToEpsTraits<G>(g,*new std::ofstream(file_name),true));
746}
747
748} //END OF NAMESPACE LEMON
749
750#endif // LEMON_GRAPH_TO_EPS_H
Note: See TracBrowser for help on using the repository browser.