COIN-OR::LEMON - Graph Library

source: lemon-0.x/src/lemon/graph_to_eps.h @ 1178:3c176c65d33b

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