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