COIN-OR::LEMON - Graph Library

source: lemon-main/lemon/graph_to_eps.h @ 210:81cfc04531e8

Last change on this file since 210:81cfc04531e8 was 210:81cfc04531e8, checked in by Alpar Juttner <alpar@…>, 16 years ago

Remove long lines (from all but one file)

File size: 38.3 KB
Line 
1/* -*- mode: C++; indent-tabs-mode: nil; -*-
2 *
3 * This file is a part of LEMON, a generic C++ optimization library.
4 *
5 * Copyright (C) 2003-2008
6 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
7 * (Egervary Research Group on Combinatorial Optimization, EGRES).
8 *
9 * Permission to use, modify and distribute this software is granted
10 * provided that this copyright notice appears in all copies. For
11 * precise terms see the accompanying LICENSE file.
12 *
13 * This software is provided "AS IS" with no warranty of any kind,
14 * express or implied, and with no claim as to its suitability for any
15 * purpose.
16 *
17 */
18
19#ifndef LEMON_GRAPH_TO_EPS_H
20#define LEMON_GRAPH_TO_EPS_H
21
22#include<iostream>
23#include<fstream>
24#include<sstream>
25#include<algorithm>
26#include<vector>
27
28#ifndef WIN32
29#include<sys/time.h>
30#include<ctime>
31#else
32#define WIN32_LEAN_AND_MEAN
33#define NOMINMAX
34#include<windows.h>
35#endif
36
37#include<lemon/math.h>
38#include<lemon/bits/invalid.h>
39#include<lemon/dim2.h>
40#include<lemon/maps.h>
41#include<lemon/color.h>
42#include<lemon/bits/bezier.h>
43
44
45///\ingroup eps_io
46///\file
47///\brief A well configurable tool for visualizing graphs
48
49namespace lemon {
50
51  namespace _graph_to_eps_bits {
52    template<class MT>
53    class _NegY {
54    public:
55      typedef typename MT::Key Key;
56      typedef typename MT::Value Value;
57      const MT &map;
58      int yscale;
59      _NegY(const MT &m,bool b) : map(m), yscale(1-b*2) {}
60      Value operator[](Key n) { return Value(map[n].x,map[n].y*yscale);}
61    };
62  }
63
64///Default traits class of \ref GraphToEps
65
66///Default traits class of \ref GraphToEps.
67///
68///\c G is the type of the underlying graph.
69template<class G>
70struct DefaultGraphToEpsTraits
71{
72  typedef G Graph;
73  typedef typename Graph::Node Node;
74  typedef typename Graph::NodeIt NodeIt;
75  typedef typename Graph::Arc Arc;
76  typedef typename Graph::ArcIt ArcIt;
77  typedef typename Graph::InArcIt InArcIt;
78  typedef typename Graph::OutArcIt OutArcIt;
79
80
81  const Graph &g;
82
83  std::ostream& os;
84
85  typedef ConstMap<typename Graph::Node,dim2::Point<double> > CoordsMapType;
86  CoordsMapType _coords;
87  ConstMap<typename Graph::Node,double > _nodeSizes;
88  ConstMap<typename Graph::Node,int > _nodeShapes;
89
90  ConstMap<typename Graph::Node,Color > _nodeColors;
91  ConstMap<typename Graph::Arc,Color > _arcColors;
92
93  ConstMap<typename Graph::Arc,double > _arcWidths;
94
95  double _arcWidthScale;
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, _showArcs;
106
107  bool _enableParallel;
108  double _parArcDist;
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 _undirected;
119
120  bool _pleaseRemoveOsStream;
121
122  bool _scaleToA4;
123
124  std::string _title;
125  std::string _copyright;
126
127  enum NodeTextColorType
128    { DIST_COL=0, DIST_BW=1, CUST_COL=2, SAME_COL=3 } _nodeTextColorType;
129  ConstMap<typename Graph::Node,Color > _nodeTextColors;
130
131  bool _autoNodeScale;
132  bool _autoArcWidthScale;
133
134  bool _absoluteNodeSizes;
135  bool _absoluteArcWidths;
136
137  bool _negY;
138
139  bool _preScale;
140  ///Constructor
141
142  ///Constructor
143  ///\param _g  Reference to the graph to be printed.
144  ///\param _os Reference to the output stream.
145  ///\param _os Reference to the output stream.
146  ///By default it is <tt>std::cout</tt>.
147  ///\param _pros If it is \c true, then the \c ostream referenced by \c _os
148  ///will be explicitly deallocated by the destructor.
149  DefaultGraphToEpsTraits(const G &_g,std::ostream& _os=std::cout,
150                          bool _pros=false) :
151    g(_g), os(_os),
152    _coords(dim2::Point<double>(1,1)), _nodeSizes(1), _nodeShapes(0),
153    _nodeColors(WHITE), _arcColors(BLACK),
154    _arcWidths(1.0), _arcWidthScale(0.003),
155    _nodeScale(.01), _xBorder(10), _yBorder(10), _scale(1.0),
156    _nodeBorderQuotient(.1),
157    _drawArrows(false), _arrowLength(1), _arrowWidth(0.3),
158    _showNodes(true), _showArcs(true),
159    _enableParallel(false), _parArcDist(1),
160    _showNodeText(false), _nodeTexts(false), _nodeTextSize(1),
161    _showNodePsText(false), _nodePsTexts(false), _nodePsTextsPreamble(0),
162    _undirected(lemon::UndirectedTagIndicator<G>::value),
163    _pleaseRemoveOsStream(_pros), _scaleToA4(false),
164    _nodeTextColorType(SAME_COL), _nodeTextColors(BLACK),
165    _autoNodeScale(false),
166    _autoArcWidthScale(false),
167    _absoluteNodeSizes(false),
168    _absoluteArcWidths(false),
169    _negY(false),
170    _preScale(true)
171  {}
172};
173
174///Auxiliary class to implement the named parameters of \ref graphToEps()
175
176///Auxiliary class to implement the named parameters of \ref graphToEps().
177///
178///For detailed examples see the \ref graph_to_eps_demo.cc demo file.
179template<class T> class GraphToEps : public T
180{
181  // Can't believe it is required by the C++ standard
182  using T::g;
183  using T::os;
184
185  using T::_coords;
186  using T::_nodeSizes;
187  using T::_nodeShapes;
188  using T::_nodeColors;
189  using T::_arcColors;
190  using T::_arcWidths;
191
192  using T::_arcWidthScale;
193  using T::_nodeScale;
194  using T::_xBorder;
195  using T::_yBorder;
196  using T::_scale;
197  using T::_nodeBorderQuotient;
198
199  using T::_drawArrows;
200  using T::_arrowLength;
201  using T::_arrowWidth;
202
203  using T::_showNodes;
204  using T::_showArcs;
205
206  using T::_enableParallel;
207  using T::_parArcDist;
208
209  using T::_showNodeText;
210  using T::_nodeTexts;
211  using T::_nodeTextSize;
212
213  using T::_showNodePsText;
214  using T::_nodePsTexts;
215  using T::_nodePsTextsPreamble;
216
217  using T::_undirected;
218
219  using T::_pleaseRemoveOsStream;
220
221  using T::_scaleToA4;
222
223  using T::_title;
224  using T::_copyright;
225
226  using T::NodeTextColorType;
227  using T::CUST_COL;
228  using T::DIST_COL;
229  using T::DIST_BW;
230  using T::_nodeTextColorType;
231  using T::_nodeTextColors;
232
233  using T::_autoNodeScale;
234  using T::_autoArcWidthScale;
235
236  using T::_absoluteNodeSizes;
237  using T::_absoluteArcWidths;
238
239
240  using T::_negY;
241  using T::_preScale;
242
243  // dradnats ++C eht yb deriuqer si ti eveileb t'naC
244
245  typedef typename T::Graph Graph;
246  typedef typename Graph::Node Node;
247  typedef typename Graph::NodeIt NodeIt;
248  typedef typename Graph::Arc Arc;
249  typedef typename Graph::ArcIt ArcIt;
250  typedef typename Graph::InArcIt InArcIt;
251  typedef typename Graph::OutArcIt OutArcIt;
252
253  static const int INTERPOL_PREC;
254  static const double A4HEIGHT;
255  static const double A4WIDTH;
256  static const double A4BORDER;
257
258  bool dontPrint;
259
260public:
261  ///Node shapes
262
263  ///Node shapes.
264  ///
265  enum NodeShapes {
266    /// = 0
267    ///\image html nodeshape_0.png
268    ///\image latex nodeshape_0.eps "CIRCLE shape (0)" width=2cm
269    CIRCLE=0,
270    /// = 1
271    ///\image html nodeshape_1.png
272    ///\image latex nodeshape_1.eps "SQUARE shape (1)" width=2cm
273    ///
274    SQUARE=1,
275    /// = 2
276    ///\image html nodeshape_2.png
277    ///\image latex nodeshape_2.eps "DIAMOND shape (2)" width=2cm
278    ///
279    DIAMOND=2,
280    /// = 3
281    ///\image html nodeshape_3.png
282    ///\image latex nodeshape_2.eps "MALE shape (4)" width=2cm
283    ///
284    MALE=3,
285    /// = 4
286    ///\image html nodeshape_4.png
287    ///\image latex nodeshape_2.eps "FEMALE shape (4)" width=2cm
288    ///
289    FEMALE=4
290  };
291
292private:
293  class arcLess {
294    const Graph &g;
295  public:
296    arcLess(const Graph &_g) : g(_g) {}
297    bool operator()(Arc a,Arc b) const
298    {
299      Node ai=std::min(g.source(a),g.target(a));
300      Node aa=std::max(g.source(a),g.target(a));
301      Node bi=std::min(g.source(b),g.target(b));
302      Node ba=std::max(g.source(b),g.target(b));
303      return ai<bi ||
304        (ai==bi && (aa < ba ||
305                    (aa==ba && ai==g.source(a) && bi==g.target(b))));
306    }
307  };
308  bool isParallel(Arc e,Arc f) const
309  {
310    return (g.source(e)==g.source(f)&&
311            g.target(e)==g.target(f)) ||
312      (g.source(e)==g.target(f)&&
313       g.target(e)==g.source(f));
314  }
315  template<class TT>
316  static std::string psOut(const dim2::Point<TT> &p)
317    {
318      std::ostringstream os;
319      os << p.x << ' ' << p.y;
320      return os.str();
321    }
322  static std::string psOut(const Color &c)
323    {
324      std::ostringstream os;
325      os << c.red() << ' ' << c.green() << ' ' << c.blue();
326      return os.str();
327    }
328
329public:
330  GraphToEps(const T &t) : T(t), dontPrint(false) {};
331
332  template<class X> struct CoordsTraits : public T {
333  typedef X CoordsMapType;
334    const X &_coords;
335    CoordsTraits(const T &t,const X &x) : T(t), _coords(x) {}
336  };
337  ///Sets the map of the node coordinates
338
339  ///Sets the map of the node coordinates.
340  ///\param x must be a node map with \ref dim2::Point "dim2::Point<double>" or
341  ///\ref dim2::Point "dim2::Point<int>" values.
342  template<class X> GraphToEps<CoordsTraits<X> > coords(const X &x) {
343    dontPrint=true;
344    return GraphToEps<CoordsTraits<X> >(CoordsTraits<X>(*this,x));
345  }
346  template<class X> struct NodeSizesTraits : public T {
347    const X &_nodeSizes;
348    NodeSizesTraits(const T &t,const X &x) : T(t), _nodeSizes(x) {}
349  };
350  ///Sets the map of the node sizes
351
352  ///Sets the map of the node sizes.
353  ///\param x must be a node map with \c double (or convertible) values.
354  template<class X> GraphToEps<NodeSizesTraits<X> > nodeSizes(const X &x)
355  {
356    dontPrint=true;
357    return GraphToEps<NodeSizesTraits<X> >(NodeSizesTraits<X>(*this,x));
358  }
359  template<class X> struct NodeShapesTraits : public T {
360    const X &_nodeShapes;
361    NodeShapesTraits(const T &t,const X &x) : T(t), _nodeShapes(x) {}
362  };
363  ///Sets the map of the node shapes
364
365  ///Sets the map of the node shapes.
366  ///The available shape values
367  ///can be found in \ref NodeShapes "enum NodeShapes".
368  ///\param x must be a node map with \c int (or convertible) values.
369  ///\sa NodeShapes
370  template<class X> GraphToEps<NodeShapesTraits<X> > nodeShapes(const X &x)
371  {
372    dontPrint=true;
373    return GraphToEps<NodeShapesTraits<X> >(NodeShapesTraits<X>(*this,x));
374  }
375  template<class X> struct NodeTextsTraits : public T {
376    const X &_nodeTexts;
377    NodeTextsTraits(const T &t,const X &x) : T(t), _nodeTexts(x) {}
378  };
379  ///Sets the text printed on the nodes
380
381  ///Sets the text printed on the nodes.
382  ///\param x must be a node map with type that can be pushed to a standard
383  ///\c ostream.
384  template<class X> GraphToEps<NodeTextsTraits<X> > nodeTexts(const X &x)
385  {
386    dontPrint=true;
387    _showNodeText=true;
388    return GraphToEps<NodeTextsTraits<X> >(NodeTextsTraits<X>(*this,x));
389  }
390  template<class X> struct NodePsTextsTraits : public T {
391    const X &_nodePsTexts;
392    NodePsTextsTraits(const T &t,const X &x) : T(t), _nodePsTexts(x) {}
393  };
394  ///Inserts a PostScript block to the nodes
395
396  ///With this command it is possible to insert a verbatim PostScript
397  ///block to the nodes.
398  ///The PS current point will be moved to the center of the node before
399  ///the PostScript block inserted.
400  ///
401  ///Before and after the block a newline character is inserted so you
402  ///don't have to bother with the separators.
403  ///
404  ///\param x must be a node map with type that can be pushed to a standard
405  ///\c ostream.
406  ///
407  ///\sa nodePsTextsPreamble()
408  template<class X> GraphToEps<NodePsTextsTraits<X> > nodePsTexts(const X &x)
409  {
410    dontPrint=true;
411    _showNodePsText=true;
412    return GraphToEps<NodePsTextsTraits<X> >(NodePsTextsTraits<X>(*this,x));
413  }
414  template<class X> struct ArcWidthsTraits : public T {
415    const X &_arcWidths;
416    ArcWidthsTraits(const T &t,const X &x) : T(t), _arcWidths(x) {}
417  };
418  ///Sets the map of the arc widths
419
420  ///Sets the map of the arc widths.
421  ///\param x must be an arc map with \c double (or convertible) values.
422  template<class X> GraphToEps<ArcWidthsTraits<X> > arcWidths(const X &x)
423  {
424    dontPrint=true;
425    return GraphToEps<ArcWidthsTraits<X> >(ArcWidthsTraits<X>(*this,x));
426  }
427
428  template<class X> struct NodeColorsTraits : public T {
429    const X &_nodeColors;
430    NodeColorsTraits(const T &t,const X &x) : T(t), _nodeColors(x) {}
431  };
432  ///Sets the map of the node colors
433
434  ///Sets the map of the node colors.
435  ///\param x must be a node map with \ref Color values.
436  ///
437  ///\sa Palette
438  template<class X> GraphToEps<NodeColorsTraits<X> >
439  nodeColors(const X &x)
440  {
441    dontPrint=true;
442    return GraphToEps<NodeColorsTraits<X> >(NodeColorsTraits<X>(*this,x));
443  }
444  template<class X> struct NodeTextColorsTraits : public T {
445    const X &_nodeTextColors;
446    NodeTextColorsTraits(const T &t,const X &x) : T(t), _nodeTextColors(x) {}
447  };
448  ///Sets the map of the node text colors
449
450  ///Sets the map of the node text colors.
451  ///\param x must be a node map with \ref Color values.
452  ///
453  ///\sa Palette
454  template<class X> GraphToEps<NodeTextColorsTraits<X> >
455  nodeTextColors(const X &x)
456  {
457    dontPrint=true;
458    _nodeTextColorType=CUST_COL;
459    return GraphToEps<NodeTextColorsTraits<X> >
460      (NodeTextColorsTraits<X>(*this,x));
461  }
462  template<class X> struct ArcColorsTraits : public T {
463    const X &_arcColors;
464    ArcColorsTraits(const T &t,const X &x) : T(t), _arcColors(x) {}
465  };
466  ///Sets the map of the arc colors
467
468  ///Sets the map of the arc colors.
469  ///\param x must be an arc map with \ref Color values.
470  ///
471  ///\sa Palette
472  template<class X> GraphToEps<ArcColorsTraits<X> >
473  arcColors(const X &x)
474  {
475    dontPrint=true;
476    return GraphToEps<ArcColorsTraits<X> >(ArcColorsTraits<X>(*this,x));
477  }
478  ///Sets a global scale factor for node sizes
479
480  ///Sets a global scale factor for node sizes.
481  ///
482  /// If nodeSizes() is not given, this function simply sets the node
483  /// sizes to \c d.  If nodeSizes() is given, but
484  /// autoNodeScale() is not, then the node size given by
485  /// nodeSizes() will be multiplied by the value \c d.
486  /// If both nodeSizes() and autoNodeScale() are used, then the
487  /// node sizes will be scaled in such a way that the greatest size will be
488  /// equal to \c d.
489  /// \sa nodeSizes()
490  /// \sa autoNodeScale()
491  GraphToEps<T> &nodeScale(double d=.01) {_nodeScale=d;return *this;}
492  ///Turns on/off the automatic node size scaling.
493
494  ///Turns on/off the automatic node size scaling.
495  ///
496  ///\sa nodeScale()
497  ///
498  GraphToEps<T> &autoNodeScale(bool b=true) {
499    _autoNodeScale=b;return *this;
500  }
501
502  ///Turns on/off the absolutematic node size scaling.
503
504  ///Turns on/off the absolutematic node size scaling.
505  ///
506  ///\sa nodeScale()
507  ///
508  GraphToEps<T> &absoluteNodeSizes(bool b=true) {
509    _absoluteNodeSizes=b;return *this;
510  }
511
512  ///Negates the Y coordinates.
513  GraphToEps<T> &negateY(bool b=true) {
514    _negY=b;return *this;
515  }
516
517  ///Turn on/off pre-scaling
518
519  ///By default graphToEps() rescales the whole image in order to avoid
520  ///very big or very small bounding boxes.
521  ///
522  ///This (p)rescaling can be turned off with this function.
523  ///
524  GraphToEps<T> &preScale(bool b=true) {
525    _preScale=b;return *this;
526  }
527
528  ///Sets a global scale factor for arc widths
529
530  /// Sets a global scale factor for arc widths.
531  ///
532  /// If arcWidths() is not given, this function simply sets the arc
533  /// widths to \c d.  If arcWidths() is given, but
534  /// autoArcWidthScale() is not, then the arc withs given by
535  /// arcWidths() will be multiplied by the value \c d.
536  /// If both arcWidths() and autoArcWidthScale() are used, then the
537  /// arc withs will be scaled in such a way that the greatest width will be
538  /// equal to \c d.
539  GraphToEps<T> &arcWidthScale(double d=.003) {_arcWidthScale=d;return *this;}
540  ///Turns on/off the automatic arc width scaling.
541
542  ///Turns on/off the automatic arc width scaling.
543  ///
544  ///\sa arcWidthScale()
545  ///
546  GraphToEps<T> &autoArcWidthScale(bool b=true) {
547    _autoArcWidthScale=b;return *this;
548  }
549  ///Turns on/off the absolutematic arc width scaling.
550
551  ///Turns on/off the absolutematic arc width scaling.
552  ///
553  ///\sa arcWidthScale()
554  ///
555  GraphToEps<T> &absoluteArcWidths(bool b=true) {
556    _absoluteArcWidths=b;return *this;
557  }
558  ///Sets a global scale factor for the whole picture
559  GraphToEps<T> &scale(double d) {_scale=d;return *this;}
560  ///Sets the width of the border around the picture
561  GraphToEps<T> &border(double b=10) {_xBorder=_yBorder=b;return *this;}
562  ///Sets the width of the border around the picture
563  GraphToEps<T> &border(double x, double y) {
564    _xBorder=x;_yBorder=y;return *this;
565  }
566  ///Sets whether to draw arrows
567  GraphToEps<T> &drawArrows(bool b=true) {_drawArrows=b;return *this;}
568  ///Sets the length of the arrowheads
569  GraphToEps<T> &arrowLength(double d=1.0) {_arrowLength*=d;return *this;}
570  ///Sets the width of the arrowheads
571  GraphToEps<T> &arrowWidth(double d=.3) {_arrowWidth*=d;return *this;}
572
573  ///Scales the drawing to fit to A4 page
574  GraphToEps<T> &scaleToA4() {_scaleToA4=true;return *this;}
575
576  ///Enables parallel arcs
577  GraphToEps<T> &enableParallel(bool b=true) {_enableParallel=b;return *this;}
578
579  ///Sets the distance between parallel arcs
580  GraphToEps<T> &parArcDist(double d) {_parArcDist*=d;return *this;}
581
582  ///Hides the arcs
583  GraphToEps<T> &hideArcs(bool b=true) {_showArcs=!b;return *this;}
584  ///Hides the nodes
585  GraphToEps<T> &hideNodes(bool b=true) {_showNodes=!b;return *this;}
586
587  ///Sets the size of the node texts
588  GraphToEps<T> &nodeTextSize(double d) {_nodeTextSize=d;return *this;}
589
590  ///Sets the color of the node texts to be different from the node color
591
592  ///Sets the color of the node texts to be as different from the node color
593  ///as it is possible.
594  GraphToEps<T> &distantColorNodeTexts()
595  {_nodeTextColorType=DIST_COL;return *this;}
596  ///Sets the color of the node texts to be black or white and always visible.
597
598  ///Sets the color of the node texts to be black or white according to
599  ///which is more different from the node color.
600  GraphToEps<T> &distantBWNodeTexts()
601  {_nodeTextColorType=DIST_BW;return *this;}
602
603  ///Gives a preamble block for node Postscript block.
604
605  ///Gives a preamble block for node Postscript block.
606  ///
607  ///\sa nodePsTexts()
608  GraphToEps<T> & nodePsTextsPreamble(const char *str) {
609    _nodePsTextsPreamble=str ;return *this;
610  }
611  ///Sets whether the graph is undirected
612
613  ///Sets whether the graph is undirected.
614  ///
615  ///This setting is the default for undirected graphs.
616  ///
617  ///\sa directed()
618   GraphToEps<T> &undirected(bool b=true) {_undirected=b;return *this;}
619
620  ///Sets whether the graph is directed
621
622  ///Sets whether the graph is directed.
623  ///Use it to show the edges as a pair of directed ones.
624  ///
625  ///This setting is the default for digraphs.
626  ///
627  ///\sa undirected()
628  GraphToEps<T> &directed(bool b=true) {_undirected=!b;return *this;}
629
630  ///Sets the title.
631
632  ///Sets the title of the generated image,
633  ///namely it inserts a <tt>%%Title:</tt> DSC field to the header of
634  ///the EPS file.
635  GraphToEps<T> &title(const std::string &t) {_title=t;return *this;}
636  ///Sets the copyright statement.
637
638  ///Sets the copyright statement of the generated image,
639  ///namely it inserts a <tt>%%Copyright:</tt> DSC field to the header of
640  ///the EPS file.
641  GraphToEps<T> &copyright(const std::string &t) {_copyright=t;return *this;}
642
643protected:
644  bool isInsideNode(dim2::Point<double> p, double r,int t)
645  {
646    switch(t) {
647    case CIRCLE:
648    case MALE:
649    case FEMALE:
650      return p.normSquare()<=r*r;
651    case SQUARE:
652      return p.x<=r&&p.x>=-r&&p.y<=r&&p.y>=-r;
653    case DIAMOND:
654      return p.x+p.y<=r && p.x-p.y<=r && -p.x+p.y<=r && -p.x-p.y<=r;
655    }
656    return false;
657  }
658
659public:
660  ~GraphToEps() { }
661
662  ///Draws the graph.
663
664  ///Like other functions using
665  ///\ref named-templ-func-param "named template parameters",
666  ///this function calls the algorithm itself, i.e. in this case
667  ///it draws the graph.
668  void run() {
669    //\todo better 'epsilon' would be nice here.
670    const double EPSILON=1e-9;
671    if(dontPrint) return;
672
673    _graph_to_eps_bits::_NegY<typename T::CoordsMapType>
674      mycoords(_coords,_negY);
675
676    os << "%!PS-Adobe-2.0 EPSF-2.0\n";
677    if(_title.size()>0) os << "%%Title: " << _title << '\n';
678     if(_copyright.size()>0) os << "%%Copyright: " << _copyright << '\n';
679    os << "%%Creator: LEMON, graphToEps()\n";
680
681    {
682#ifndef WIN32
683      timeval tv;
684      gettimeofday(&tv, 0);
685
686      char cbuf[26];
687      ctime_r(&tv.tv_sec,cbuf);
688      os << "%%CreationDate: " << cbuf;
689#else
690      SYSTEMTIME time;
691      char buf1[11], buf2[9], buf3[5];
692
693      GetSystemTime(&time);
694      if (GetDateFormat(LOCALE_USER_DEFAULT, 0, &time,
695                        "ddd MMM dd", buf1, 11) &&
696          GetTimeFormat(LOCALE_USER_DEFAULT, 0, &time,
697                        "HH':'mm':'ss", buf2, 9) &&
698          GetDateFormat(LOCALE_USER_DEFAULT, 0, &time,
699                                "yyyy", buf3, 5)) {
700        os << "%%CreationDate: " << buf1 << ' '
701           << buf2 << ' ' << buf3 << std::endl;
702      }
703#endif
704    }
705
706    if (_autoArcWidthScale) {
707      double max_w=0;
708      for(ArcIt e(g);e!=INVALID;++e)
709        max_w=std::max(double(_arcWidths[e]),max_w);
710      //\todo better 'epsilon' would be nice here.
711      if(max_w>EPSILON) {
712        _arcWidthScale/=max_w;
713      }
714    }
715
716    if (_autoNodeScale) {
717      double max_s=0;
718      for(NodeIt n(g);n!=INVALID;++n)
719        max_s=std::max(double(_nodeSizes[n]),max_s);
720      //\todo better 'epsilon' would be nice here.
721      if(max_s>EPSILON) {
722        _nodeScale/=max_s;
723      }
724    }
725
726    double diag_len = 1;
727    if(!(_absoluteNodeSizes&&_absoluteArcWidths)) {
728      dim2::BoundingBox<double> bb;
729      for(NodeIt n(g);n!=INVALID;++n) bb.add(mycoords[n]);
730      if (bb.empty()) {
731        bb = dim2::BoundingBox<double>(dim2::Point<double>(0,0));
732      }
733      diag_len = std::sqrt((bb.bottomLeft()-bb.topRight()).normSquare());
734      if(diag_len<EPSILON) diag_len = 1;
735      if(!_absoluteNodeSizes) _nodeScale*=diag_len;
736      if(!_absoluteArcWidths) _arcWidthScale*=diag_len;
737    }
738
739    dim2::BoundingBox<double> bb;
740    for(NodeIt n(g);n!=INVALID;++n) {
741      double ns=_nodeSizes[n]*_nodeScale;
742      dim2::Point<double> p(ns,ns);
743      switch(_nodeShapes[n]) {
744      case CIRCLE:
745      case SQUARE:
746      case DIAMOND:
747        bb.add(p+mycoords[n]);
748        bb.add(-p+mycoords[n]);
749        break;
750      case MALE:
751        bb.add(-p+mycoords[n]);
752        bb.add(dim2::Point<double>(1.5*ns,1.5*std::sqrt(3.0)*ns)+mycoords[n]);
753        break;
754      case FEMALE:
755        bb.add(p+mycoords[n]);
756        bb.add(dim2::Point<double>(-ns,-3.01*ns)+mycoords[n]);
757        break;
758      }
759    }
760    if (bb.empty()) {
761      bb = dim2::BoundingBox<double>(dim2::Point<double>(0,0));
762    }
763
764    if(_scaleToA4)
765      os <<"%%BoundingBox: 0 0 596 842\n%%DocumentPaperSizes: a4\n";
766    else {
767      if(_preScale) {
768        //Rescale so that BoundingBox won't be neither to big nor too small.
769        while(bb.height()*_scale>1000||bb.width()*_scale>1000) _scale/=10;
770        while(bb.height()*_scale<100||bb.width()*_scale<100) _scale*=10;
771      }
772
773      os << "%%BoundingBox: "
774         << int(floor(bb.left()   * _scale - _xBorder)) << ' '
775         << int(floor(bb.bottom() * _scale - _yBorder)) << ' '
776         << int(ceil(bb.right()  * _scale + _xBorder)) << ' '
777         << int(ceil(bb.top()    * _scale + _yBorder)) << '\n';
778    }
779
780    os << "%%EndComments\n";
781
782    //x1 y1 x2 y2 x3 y3 cr cg cb w
783    os << "/lb { setlinewidth setrgbcolor newpath moveto\n"
784       << "      4 2 roll 1 index 1 index curveto stroke } bind def\n";
785    os << "/l { setlinewidth setrgbcolor newpath moveto lineto stroke }"
786       << " bind def\n";
787    //x y r
788    os << "/c { newpath dup 3 index add 2 index moveto 0 360 arc closepath }"
789       << " bind def\n";
790    //x y r
791    os << "/sq { newpath 2 index 1 index add 2 index 2 index add moveto\n"
792       << "      2 index 1 index sub 2 index 2 index add lineto\n"
793       << "      2 index 1 index sub 2 index 2 index sub lineto\n"
794       << "      2 index 1 index add 2 index 2 index sub lineto\n"
795       << "      closepath pop pop pop} bind def\n";
796    //x y r
797    os << "/di { newpath 2 index 1 index add 2 index moveto\n"
798       << "      2 index             2 index 2 index add lineto\n"
799       << "      2 index 1 index sub 2 index             lineto\n"
800       << "      2 index             2 index 2 index sub lineto\n"
801       << "      closepath pop pop pop} bind def\n";
802    // x y r cr cg cb
803    os << "/nc { 0 0 0 setrgbcolor 5 index 5 index 5 index c fill\n"
804       << "     setrgbcolor " << 1+_nodeBorderQuotient << " div c fill\n"
805       << "   } bind def\n";
806    os << "/nsq { 0 0 0 setrgbcolor 5 index 5 index 5 index sq fill\n"
807       << "     setrgbcolor " << 1+_nodeBorderQuotient << " div sq fill\n"
808       << "   } bind def\n";
809    os << "/ndi { 0 0 0 setrgbcolor 5 index 5 index 5 index di fill\n"
810       << "     setrgbcolor " << 1+_nodeBorderQuotient << " div di fill\n"
811       << "   } bind def\n";
812    os << "/nfemale { 0 0 0 setrgbcolor 3 index "
813       << _nodeBorderQuotient/(1+_nodeBorderQuotient)
814       << " 1.5 mul mul setlinewidth\n"
815       << "  newpath 5 index 5 index moveto "
816       << "5 index 5 index 5 index 3.01 mul sub\n"
817       << "  lineto 5 index 4 index .7 mul sub 5 index 5 index 2.2 mul sub"
818       << " moveto\n"
819       << "  5 index 4 index .7 mul add 5 index 5 index 2.2 mul sub lineto "
820       << "stroke\n"
821       << "  5 index 5 index 5 index c fill\n"
822       << "  setrgbcolor " << 1+_nodeBorderQuotient << " div c fill\n"
823       << "  } bind def\n";
824    os << "/nmale {\n"
825       << "  0 0 0 setrgbcolor 3 index "
826       << _nodeBorderQuotient/(1+_nodeBorderQuotient)
827       <<" 1.5 mul mul setlinewidth\n"
828       << "  newpath 5 index 5 index moveto\n"
829       << "  5 index 4 index 1 mul 1.5 mul add\n"
830       << "  5 index 5 index 3 sqrt 1.5 mul mul add\n"
831       << "  1 index 1 index lineto\n"
832       << "  1 index 1 index 7 index sub moveto\n"
833       << "  1 index 1 index lineto\n"
834       << "  exch 5 index 3 sqrt .5 mul mul sub exch 5 index .5 mul sub"
835       << " lineto\n"
836       << "  stroke\n"
837       << "  5 index 5 index 5 index c fill\n"
838       << "  setrgbcolor " << 1+_nodeBorderQuotient << " div c fill\n"
839       << "  } bind def\n";
840
841
842    os << "/arrl " << _arrowLength << " def\n";
843    os << "/arrw " << _arrowWidth << " def\n";
844    // l dx_norm dy_norm
845    os << "/lrl { 2 index mul exch 2 index mul exch rlineto pop} bind def\n";
846    //len w dx_norm dy_norm x1 y1 cr cg cb
847    os << "/arr { setrgbcolor /y1 exch def /x1 exch def /dy exch def /dx "
848       << "exch def\n"
849       << "       /w exch def /len exch def\n"
850      //<< "0.1 setlinewidth x1 y1 moveto dx len mul dy len mul rlineto stroke"
851       << "       newpath x1 dy w 2 div mul add y1 dx w 2 div mul sub moveto\n"
852       << "       len w sub arrl sub dx dy lrl\n"
853       << "       arrw dy dx neg lrl\n"
854       << "       dx arrl w add mul dy w 2 div arrw add mul sub\n"
855       << "       dy arrl w add mul dx w 2 div arrw add mul add rlineto\n"
856       << "       dx arrl w add mul neg dy w 2 div arrw add mul sub\n"
857       << "       dy arrl w add mul neg dx w 2 div arrw add mul add rlineto\n"
858       << "       arrw dy dx neg lrl\n"
859       << "       len w sub arrl sub neg dx dy lrl\n"
860       << "       closepath fill } bind def\n";
861    os << "/cshow { 2 index 2 index moveto dup stringwidth pop\n"
862       << "         neg 2 div fosi .35 mul neg rmoveto show pop pop} def\n";
863
864    os << "\ngsave\n";
865    if(_scaleToA4)
866      if(bb.height()>bb.width()) {
867        double sc= std::min((A4HEIGHT-2*A4BORDER)/bb.height(),
868                  (A4WIDTH-2*A4BORDER)/bb.width());
869        os << ((A4WIDTH -2*A4BORDER)-sc*bb.width())/2 + A4BORDER << ' '
870           << ((A4HEIGHT-2*A4BORDER)-sc*bb.height())/2 + A4BORDER
871           << " translate\n"
872           << sc << " dup scale\n"
873           << -bb.left() << ' ' << -bb.bottom() << " translate\n";
874      }
875      else {
876        //\todo Verify centering
877        double sc= std::min((A4HEIGHT-2*A4BORDER)/bb.width(),
878                  (A4WIDTH-2*A4BORDER)/bb.height());
879        os << ((A4WIDTH -2*A4BORDER)-sc*bb.height())/2 + A4BORDER << ' '
880           << ((A4HEIGHT-2*A4BORDER)-sc*bb.width())/2 + A4BORDER
881           << " translate\n"
882           << sc << " dup scale\n90 rotate\n"
883           << -bb.left() << ' ' << -bb.top() << " translate\n";
884        }
885    else if(_scale!=1.0) os << _scale << " dup scale\n";
886
887    if(_showArcs) {
888      os << "%Arcs:\ngsave\n";
889      if(_enableParallel) {
890        std::vector<Arc> el;
891        for(ArcIt e(g);e!=INVALID;++e)
892          if((!_undirected||g.source(e)<g.target(e))&&_arcWidths[e]>0
893             &&g.source(e)!=g.target(e))
894            el.push_back(e);
895        std::sort(el.begin(),el.end(),arcLess(g));
896
897        typename std::vector<Arc>::iterator j;
898        for(typename std::vector<Arc>::iterator i=el.begin();i!=el.end();i=j) {
899          for(j=i+1;j!=el.end()&&isParallel(*i,*j);++j) ;
900
901          double sw=0;
902          for(typename std::vector<Arc>::iterator e=i;e!=j;++e)
903            sw+=_arcWidths[*e]*_arcWidthScale+_parArcDist;
904          sw-=_parArcDist;
905          sw/=-2.0;
906          dim2::Point<double>
907            dvec(mycoords[g.target(*i)]-mycoords[g.source(*i)]);
908          double l=std::sqrt(dvec.normSquare());
909          //\todo better 'epsilon' would be nice here.
910          dim2::Point<double> d(dvec/std::max(l,EPSILON));
911           dim2::Point<double> m;
912//           m=dim2::Point<double>(mycoords[g.target(*i)]+
913//                                 mycoords[g.source(*i)])/2.0;
914
915//            m=dim2::Point<double>(mycoords[g.source(*i)])+
916//             dvec*(double(_nodeSizes[g.source(*i)])/
917//                (_nodeSizes[g.source(*i)]+_nodeSizes[g.target(*i)]));
918
919           m=dim2::Point<double>(mycoords[g.source(*i)])+
920            d*(l+_nodeSizes[g.source(*i)]-_nodeSizes[g.target(*i)])/2.0;
921
922          for(typename std::vector<Arc>::iterator e=i;e!=j;++e) {
923            sw+=_arcWidths[*e]*_arcWidthScale/2.0;
924            dim2::Point<double> mm=m+rot90(d)*sw/.75;
925            if(_drawArrows) {
926              int node_shape;
927              dim2::Point<double> s=mycoords[g.source(*e)];
928              dim2::Point<double> t=mycoords[g.target(*e)];
929              double rn=_nodeSizes[g.target(*e)]*_nodeScale;
930              node_shape=_nodeShapes[g.target(*e)];
931              dim2::Bezier3 bez(s,mm,mm,t);
932              double t1=0,t2=1;
933              for(int ii=0;ii<INTERPOL_PREC;++ii)
934                if(isInsideNode(bez((t1+t2)/2)-t,rn,node_shape)) t2=(t1+t2)/2;
935                else t1=(t1+t2)/2;
936              dim2::Point<double> apoint=bez((t1+t2)/2);
937              rn = _arrowLength+_arcWidths[*e]*_arcWidthScale;
938              rn*=rn;
939              t2=(t1+t2)/2;t1=0;
940              for(int ii=0;ii<INTERPOL_PREC;++ii)
941                if((bez((t1+t2)/2)-apoint).normSquare()>rn) t1=(t1+t2)/2;
942                else t2=(t1+t2)/2;
943              dim2::Point<double> linend=bez((t1+t2)/2);
944              bez=bez.before((t1+t2)/2);
945//               rn=_nodeSizes[g.source(*e)]*_nodeScale;
946//               node_shape=_nodeShapes[g.source(*e)];
947//               t1=0;t2=1;
948//               for(int i=0;i<INTERPOL_PREC;++i)
949//                 if(isInsideNode(bez((t1+t2)/2)-t,rn,node_shape))
950//                   t1=(t1+t2)/2;
951//                 else t2=(t1+t2)/2;
952//               bez=bez.after((t1+t2)/2);
953              os << _arcWidths[*e]*_arcWidthScale << " setlinewidth "
954                 << _arcColors[*e].red() << ' '
955                 << _arcColors[*e].green() << ' '
956                 << _arcColors[*e].blue() << " setrgbcolor newpath\n"
957                 << bez.p1.x << ' ' <<  bez.p1.y << " moveto\n"
958                 << bez.p2.x << ' ' << bez.p2.y << ' '
959                 << bez.p3.x << ' ' << bez.p3.y << ' '
960                 << bez.p4.x << ' ' << bez.p4.y << " curveto stroke\n";
961              dim2::Point<double> dd(rot90(linend-apoint));
962              dd*=(.5*_arcWidths[*e]*_arcWidthScale+_arrowWidth)/
963                std::sqrt(dd.normSquare());
964              os << "newpath " << psOut(apoint) << " moveto "
965                 << psOut(linend+dd) << " lineto "
966                 << psOut(linend-dd) << " lineto closepath fill\n";
967            }
968            else {
969              os << mycoords[g.source(*e)].x << ' '
970                 << mycoords[g.source(*e)].y << ' '
971                 << mm.x << ' ' << mm.y << ' '
972                 << mycoords[g.target(*e)].x << ' '
973                 << mycoords[g.target(*e)].y << ' '
974                 << _arcColors[*e].red() << ' '
975                 << _arcColors[*e].green() << ' '
976                 << _arcColors[*e].blue() << ' '
977                 << _arcWidths[*e]*_arcWidthScale << " lb\n";
978            }
979            sw+=_arcWidths[*e]*_arcWidthScale/2.0+_parArcDist;
980          }
981        }
982      }
983      else for(ArcIt e(g);e!=INVALID;++e)
984        if((!_undirected||g.source(e)<g.target(e))&&_arcWidths[e]>0
985           &&g.source(e)!=g.target(e)) {
986          if(_drawArrows) {
987            dim2::Point<double> d(mycoords[g.target(e)]-mycoords[g.source(e)]);
988            double rn=_nodeSizes[g.target(e)]*_nodeScale;
989            int node_shape=_nodeShapes[g.target(e)];
990            double t1=0,t2=1;
991            for(int i=0;i<INTERPOL_PREC;++i)
992              if(isInsideNode((-(t1+t2)/2)*d,rn,node_shape)) t1=(t1+t2)/2;
993              else t2=(t1+t2)/2;
994            double l=std::sqrt(d.normSquare());
995            d/=l;
996
997            os << l*(1-(t1+t2)/2) << ' '
998               << _arcWidths[e]*_arcWidthScale << ' '
999               << d.x << ' ' << d.y << ' '
1000               << mycoords[g.source(e)].x << ' '
1001               << mycoords[g.source(e)].y << ' '
1002               << _arcColors[e].red() << ' '
1003               << _arcColors[e].green() << ' '
1004               << _arcColors[e].blue() << " arr\n";
1005          }
1006          else os << mycoords[g.source(e)].x << ' '
1007                  << mycoords[g.source(e)].y << ' '
1008                  << mycoords[g.target(e)].x << ' '
1009                  << mycoords[g.target(e)].y << ' '
1010                  << _arcColors[e].red() << ' '
1011                  << _arcColors[e].green() << ' '
1012                  << _arcColors[e].blue() << ' '
1013                  << _arcWidths[e]*_arcWidthScale << " l\n";
1014        }
1015      os << "grestore\n";
1016    }
1017    if(_showNodes) {
1018      os << "%Nodes:\ngsave\n";
1019      for(NodeIt n(g);n!=INVALID;++n) {
1020        os << mycoords[n].x << ' ' << mycoords[n].y << ' '
1021           << _nodeSizes[n]*_nodeScale << ' '
1022           << _nodeColors[n].red() << ' '
1023           << _nodeColors[n].green() << ' '
1024           << _nodeColors[n].blue() << ' ';
1025        switch(_nodeShapes[n]) {
1026        case CIRCLE:
1027          os<< "nc";break;
1028        case SQUARE:
1029          os<< "nsq";break;
1030        case DIAMOND:
1031          os<< "ndi";break;
1032        case MALE:
1033          os<< "nmale";break;
1034        case FEMALE:
1035          os<< "nfemale";break;
1036        }
1037        os<<'\n';
1038      }
1039      os << "grestore\n";
1040    }
1041    if(_showNodeText) {
1042      os << "%Node texts:\ngsave\n";
1043      os << "/fosi " << _nodeTextSize << " def\n";
1044      os << "(Helvetica) findfont fosi scalefont setfont\n";
1045      for(NodeIt n(g);n!=INVALID;++n) {
1046        switch(_nodeTextColorType) {
1047        case DIST_COL:
1048          os << psOut(distantColor(_nodeColors[n])) << " setrgbcolor\n";
1049          break;
1050        case DIST_BW:
1051          os << psOut(distantBW(_nodeColors[n])) << " setrgbcolor\n";
1052          break;
1053        case CUST_COL:
1054          os << psOut(distantColor(_nodeTextColors[n])) << " setrgbcolor\n";
1055          break;
1056        default:
1057          os << "0 0 0 setrgbcolor\n";
1058        }
1059        os << mycoords[n].x << ' ' << mycoords[n].y
1060           << " (" << _nodeTexts[n] << ") cshow\n";
1061      }
1062      os << "grestore\n";
1063    }
1064    if(_showNodePsText) {
1065      os << "%Node PS blocks:\ngsave\n";
1066      for(NodeIt n(g);n!=INVALID;++n)
1067        os << mycoords[n].x << ' ' << mycoords[n].y
1068           << " moveto\n" << _nodePsTexts[n] << "\n";
1069      os << "grestore\n";
1070    }
1071
1072    os << "grestore\nshowpage\n";
1073
1074    //CleanUp:
1075    if(_pleaseRemoveOsStream) {delete &os;}
1076  }
1077
1078  ///\name Aliases
1079  ///These are just some aliases to other parameter setting functions.
1080
1081  ///@{
1082
1083  ///An alias for arcWidths()
1084  template<class X> GraphToEps<ArcWidthsTraits<X> > edgeWidths(const X &x)
1085  {
1086    return arcWidths(x);
1087  }
1088
1089  ///An alias for arcColors()
1090  template<class X> GraphToEps<ArcColorsTraits<X> >
1091  edgeColors(const X &x)
1092  {
1093    return arcColors(x);
1094  }
1095
1096  ///An alias for arcWidthScale()
1097  GraphToEps<T> &edgeWidthScale(double d) {return arcWidthScale(d);}
1098
1099  ///An alias for autoArcWidthScale()
1100  GraphToEps<T> &autoEdgeWidthScale(bool b=true)
1101  {
1102    return autoArcWidthScale(b);
1103  }
1104
1105  ///An alias for absoluteArcWidths()
1106  GraphToEps<T> &absoluteEdgeWidths(bool b=true)
1107  {
1108    return absoluteArcWidths(b);
1109  }
1110
1111  ///An alias for parArcDist()
1112  GraphToEps<T> &parEdgeDist(double d) {return parArcDist(d);}
1113
1114  ///An alias for hideArcs()
1115  GraphToEps<T> &hideEdges(bool b=true) {return hideArcs(b);}
1116
1117  ///@}
1118};
1119
1120template<class T>
1121const int GraphToEps<T>::INTERPOL_PREC = 20;
1122template<class T>
1123const double GraphToEps<T>::A4HEIGHT = 841.8897637795276;
1124template<class T>
1125const double GraphToEps<T>::A4WIDTH  = 595.275590551181;
1126template<class T>
1127const double GraphToEps<T>::A4BORDER = 15;
1128
1129
1130///Generates an EPS file from a graph
1131
1132///\ingroup eps_io
1133///Generates an EPS file from a graph.
1134///\param g Reference to the graph to be printed.
1135///\param os Reference to the output stream.
1136///By default it is <tt>std::cout</tt>.
1137///
1138///This function also has a lot of
1139///\ref named-templ-func-param "named parameters",
1140///they are declared as the members of class \ref GraphToEps. The following
1141///example shows how to use these parameters.
1142///\code
1143/// graphToEps(g,os).scale(10).coords(coords)
1144///              .nodeScale(2).nodeSizes(sizes)
1145///              .arcWidthScale(.4).run();
1146///\endcode
1147///
1148///For more detailed examples see the \ref graph_to_eps_demo.cc demo file.
1149///
1150///\warning Don't forget to put the \ref GraphToEps::run() "run()"
1151///to the end of the parameter list.
1152///\sa GraphToEps
1153///\sa graphToEps(G &g, const char *file_name)
1154template<class G>
1155GraphToEps<DefaultGraphToEpsTraits<G> >
1156graphToEps(G &g, std::ostream& os=std::cout)
1157{
1158  return
1159    GraphToEps<DefaultGraphToEpsTraits<G> >(DefaultGraphToEpsTraits<G>(g,os));
1160}
1161
1162///Generates an EPS file from a graph
1163
1164///\ingroup eps_io
1165///This function does the same as
1166///\ref graphToEps(G &g,std::ostream& os)
1167///but it writes its output into the file \c file_name
1168///instead of a stream.
1169///\sa graphToEps(G &g, std::ostream& os)
1170template<class G>
1171GraphToEps<DefaultGraphToEpsTraits<G> >
1172graphToEps(G &g,const char *file_name)
1173{
1174  return GraphToEps<DefaultGraphToEpsTraits<G> >
1175    (DefaultGraphToEpsTraits<G>(g,*new std::ofstream(file_name),true));
1176}
1177
1178///Generates an EPS file from a graph
1179
1180///\ingroup eps_io
1181///This function does the same as
1182///\ref graphToEps(G &g,std::ostream& os)
1183///but it writes its output into the file \c file_name
1184///instead of a stream.
1185///\sa graphToEps(G &g, std::ostream& os)
1186template<class G>
1187GraphToEps<DefaultGraphToEpsTraits<G> >
1188graphToEps(G &g,const std::string& file_name)
1189{
1190  return GraphToEps<DefaultGraphToEpsTraits<G> >
1191    (DefaultGraphToEpsTraits<G>(g,*new std::ofstream(file_name.c_str()),true));
1192}
1193
1194} //END OF NAMESPACE LEMON
1195
1196#endif // LEMON_GRAPH_TO_EPS_H
Note: See TracBrowser for help on using the repository browser.