COIN-OR::LEMON - Graph Library

source: lemon-0.x/lemon/graph_to_eps.h @ 2184:05a5e48010ab

Last change on this file since 2184:05a5e48010ab was 2178:0d7c0f96a5ee, checked in by Alpar Juttner, 18 years ago
  • bezier.h went to lemon/bits/
  • new graphToEps() option: absolute/relative node size/link width scaling.
File size: 35.3 KB
Line 
1/* -*- C++ -*-
2 *
3 * This file is a part of LEMON, a generic C++ optimization library
4 *
5 * Copyright (C) 2003-2006
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 <sys/time.h>
23
24#ifdef WIN32
25#include <lemon/bits/mingw32_time.h>
26#endif
27
28#include<iostream>
29#include<fstream>
30#include<sstream>
31#include<algorithm>
32#include<vector>
33
34#include <ctime>
35#include <cmath>
36
37#include<lemon/bits/invalid.h>
38#include<lemon/xy.h>
39#include<lemon/maps.h>
40#include<lemon/color.h>
41#include<lemon/bits/bezier.h>
42
43
44///\ingroup eps_io
45///\file
46///\brief Simple graph drawer
47///
48///\author Alpar Juttner
49
50namespace lemon {
51
52template<class MT>
53class _NegY {
54public:
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///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.
68template<class G>
69struct 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  typedef ConstMap<typename Graph::Node,xy<double> > CoordsMapType;
85  CoordsMapType _coords;
86  ConstMap<typename Graph::Node,double > _nodeSizes;
87  ConstMap<typename Graph::Node,int > _nodeShapes;
88
89  ConstMap<typename Graph::Node,Color > _nodeColors;
90  ConstMap<typename Graph::Edge,Color > _edgeColors;
91
92  ConstMap<typename Graph::Edge,double > _edgeWidths;
93
94  double _edgeWidthScale;
95 
96  double _nodeScale;
97  double _xBorder, _yBorder;
98  double _scale;
99  double _nodeBorderQuotient;
100 
101  bool _drawArrows;
102  double _arrowLength, _arrowWidth;
103 
104  bool _showNodes, _showEdges;
105
106  bool _enableParallel;
107  double _parEdgeDist;
108
109  bool _showNodeText;
110  ConstMap<typename Graph::Node,bool > _nodeTexts; 
111  double _nodeTextSize;
112
113  bool _showNodePsText;
114  ConstMap<typename Graph::Node,bool > _nodePsTexts; 
115  char *_nodePsTextsPreamble;
116 
117  bool _undirected;
118
119  bool _pleaseRemoveOsStream;
120
121  bool _scaleToA4;
122
123  std::string _title;
124  std::string _copyright;
125
126  enum NodeTextColorType
127    { DIST_COL=0, DIST_BW=1, CUST_COL=2, SAME_COL=3 } _nodeTextColorType;
128  ConstMap<typename Graph::Node,Color > _nodeTextColors;
129
130  bool _autoNodeScale;
131  bool _autoEdgeWidthScale;
132
133  bool _absoluteNodeSizes;
134  bool _absoluteEdgeWidths;
135
136  bool _negY;
137  ///Constructor
138
139  ///Constructor
140  ///\param _g is a reference to the graph to be printed
141  ///\param _os is a reference to the output stream.
142  ///\param _os is a reference to the output stream.
143  ///\param _pros If it is \c true, then the \c ostream referenced by \c _os
144  ///will be explicitly deallocated by the destructor.
145  ///By default it is <tt>std::cout</tt>
146  DefaultGraphToEpsTraits(const G &_g,std::ostream& _os=std::cout,
147                          bool _pros=false) :
148    g(_g), os(_os),
149    _coords(xy<double>(1,1)), _nodeSizes(.01), _nodeShapes(0),
150    _nodeColors(WHITE), _edgeColors(BLACK),
151    _edgeWidths(1.0), _edgeWidthScale(0.003),
152    _nodeScale(1.0), _xBorder(10), _yBorder(10), _scale(1.0),
153    _nodeBorderQuotient(.1),
154    _drawArrows(false), _arrowLength(1), _arrowWidth(0.3),
155    _showNodes(true), _showEdges(true),
156    _enableParallel(false), _parEdgeDist(1),
157    _showNodeText(false), _nodeTexts(false), _nodeTextSize(1),
158    _showNodePsText(false), _nodePsTexts(false), _nodePsTextsPreamble(0),
159    _undirected(false),
160    _pleaseRemoveOsStream(_pros), _scaleToA4(false),
161    _nodeTextColorType(SAME_COL), _nodeTextColors(BLACK),
162    _autoNodeScale(false),
163    _autoEdgeWidthScale(false),
164    _absoluteNodeSizes(false),
165    _absoluteEdgeWidths(false),
166    _negY(false)
167  {}
168};
169
170///Helper class to implement the named parameters of \ref graphToEps()
171
172///Helper class to implement the named parameters of \ref graphToEps()
173///\todo Is 'helper class' a good name for this?
174///
175///\todo Follow PostScript's DSC.
176/// Use own dictionary.
177///\todo Useful new features.
178/// - Linestyles: dotted, dashed etc.
179/// - A second color and percent value for the lines.
180template<class T> class GraphToEps : public T
181{
182  // Can't believe it is required by the C++ standard
183  using T::g;
184  using T::os;
185
186  using T::_coords;
187  using T::_nodeSizes;
188  using T::_nodeShapes;
189  using T::_nodeColors;
190  using T::_edgeColors;
191  using T::_edgeWidths;
192
193  using T::_edgeWidthScale;
194  using T::_nodeScale;
195  using T::_xBorder;
196  using T::_yBorder;
197  using T::_scale;
198  using T::_nodeBorderQuotient;
199 
200  using T::_drawArrows;
201  using T::_arrowLength;
202  using T::_arrowWidth;
203 
204  using T::_showNodes;
205  using T::_showEdges;
206
207  using T::_enableParallel;
208  using T::_parEdgeDist;
209
210  using T::_showNodeText;
211  using T::_nodeTexts; 
212  using T::_nodeTextSize;
213
214  using T::_showNodePsText;
215  using T::_nodePsTexts; 
216  using T::_nodePsTextsPreamble;
217 
218  using T::_undirected;
219
220  using T::_pleaseRemoveOsStream;
221
222  using T::_scaleToA4;
223
224  using T::_title;
225  using T::_copyright;
226
227  using T::NodeTextColorType;
228  using T::CUST_COL;
229  using T::DIST_COL;
230  using T::DIST_BW;
231  using T::_nodeTextColorType;
232  using T::_nodeTextColors;
233
234  using T::_autoNodeScale;
235  using T::_autoEdgeWidthScale;
236
237  using T::_absoluteNodeSizes;
238  using T::_absoluteEdgeWidths;
239
240
241  using T::_negY;
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::Edge Edge;
249  typedef typename Graph::EdgeIt EdgeIt;
250  typedef typename Graph::InEdgeIt InEdgeIt;
251  typedef typename Graph::OutEdgeIt OutEdgeIt;
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 edgeLess {
294    const Graph &g;
295  public:
296    edgeLess(const Graph &_g) : g(_g) {}
297    bool operator()(Edge a,Edge 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(Edge e,Edge 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 xy<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 xy<double> or \ref xy "xy<int>" values.
341  template<class X> GraphToEps<CoordsTraits<X> > coords(const X &x) {
342    dontPrint=true;
343    return GraphToEps<CoordsTraits<X> >(CoordsTraits<X>(*this,x));
344  }
345  template<class X> struct NodeSizesTraits : public T {
346    const X &_nodeSizes;
347    NodeSizesTraits(const T &t,const X &x) : T(t), _nodeSizes(x) {}
348  };
349  ///Sets the map of the node sizes
350
351  ///Sets the map of the node sizes
352  ///\param x must be a node map with \c double (or convertible) values.
353  template<class X> GraphToEps<NodeSizesTraits<X> > nodeSizes(const X &x)
354  {
355    dontPrint=true;
356    return GraphToEps<NodeSizesTraits<X> >(NodeSizesTraits<X>(*this,x));
357  }
358  template<class X> struct NodeShapesTraits : public T {
359    const X &_nodeShapes;
360    NodeShapesTraits(const T &t,const X &x) : T(t), _nodeShapes(x) {}
361  };
362  ///Sets the map of the node shapes
363
364  ///Sets the map of the node shapes.
365  ///The availabe shape values
366  ///can be found in \ref NodeShapes "enum NodeShapes".
367  ///\param x must be a node map with \c int (or convertible) values.
368  ///\sa NodeShapes
369  template<class X> GraphToEps<NodeShapesTraits<X> > nodeShapes(const X &x)
370  {
371    dontPrint=true;
372    return GraphToEps<NodeShapesTraits<X> >(NodeShapesTraits<X>(*this,x));
373  }
374  template<class X> struct NodeTextsTraits : public T {
375    const X &_nodeTexts;
376    NodeTextsTraits(const T &t,const X &x) : T(t), _nodeTexts(x) {}
377  };
378  ///Sets the text printed on the nodes
379
380  ///Sets the text printed on the nodes
381  ///\param x must be a node map with type that can be pushed to a standard
382  ///ostream.
383  template<class X> GraphToEps<NodeTextsTraits<X> > nodeTexts(const X &x)
384  {
385    dontPrint=true;
386    _showNodeText=true;
387    return GraphToEps<NodeTextsTraits<X> >(NodeTextsTraits<X>(*this,x));
388  }
389  template<class X> struct NodePsTextsTraits : public T {
390    const X &_nodePsTexts;
391    NodePsTextsTraits(const T &t,const X &x) : T(t), _nodePsTexts(x) {}
392  };
393  ///Inserts a PostScript block to the nodes
394
395  ///With this command it is possible to insert a verbatim PostScript
396  ///block to the nodes.
397  ///The PS current point will be moved to the centre of the node before
398  ///the PostScript block inserted.
399  ///
400  ///Before and after the block a newline character is inserted so you
401  ///don't have to bother with the separators.
402  ///
403  ///\param x must be a node map with type that can be pushed to a standard
404  ///ostream.
405  ///
406  ///\sa nodePsTextsPreamble()
407  ///\todo Offer the choise not to move to the centre but pass the coordinates
408  ///to the Postscript block inserted.
409  template<class X> GraphToEps<NodePsTextsTraits<X> > nodePsTexts(const X &x)
410  {
411    dontPrint=true;
412    _showNodePsText=true;
413    return GraphToEps<NodePsTextsTraits<X> >(NodePsTextsTraits<X>(*this,x));
414  }
415  template<class X> struct EdgeWidthsTraits : public T {
416    const X &_edgeWidths;
417    EdgeWidthsTraits(const T &t,const X &x) : T(t), _edgeWidths(x) {}
418  };
419  ///Sets the map of the edge widths
420
421  ///Sets the map of the edge widths
422  ///\param x must be a edge map with \c double (or convertible) values.
423  template<class X> GraphToEps<EdgeWidthsTraits<X> > edgeWidths(const X &x)
424  {
425    dontPrint=true;
426    return GraphToEps<EdgeWidthsTraits<X> >(EdgeWidthsTraits<X>(*this,x));
427  }
428
429  template<class X> struct NodeColorsTraits : public T {
430    const X &_nodeColors;
431    NodeColorsTraits(const T &t,const X &x) : T(t), _nodeColors(x) {}
432  };
433  ///Sets the map of the node colors
434
435  ///Sets the map of the node colors
436  ///\param x must be a node map with \ref Color values.
437  ///
438  ///\sa Palette
439  template<class X> GraphToEps<NodeColorsTraits<X> >
440  nodeColors(const X &x)
441  {
442    dontPrint=true;
443    return GraphToEps<NodeColorsTraits<X> >(NodeColorsTraits<X>(*this,x));
444  }
445  template<class X> struct NodeTextColorsTraits : public T {
446    const X &_nodeTextColors;
447    NodeTextColorsTraits(const T &t,const X &x) : T(t), _nodeTextColors(x) {}
448  };
449  ///Sets the map of the node text colors
450
451  ///Sets the map of the node text colors
452  ///\param x must be a node map with \ref Color values.
453  ///
454  ///\sa Palette
455  template<class X> GraphToEps<NodeTextColorsTraits<X> >
456  nodeTextColors(const X &x)
457  {
458    dontPrint=true;
459    _nodeTextColorType=CUST_COL;
460    return GraphToEps<NodeTextColorsTraits<X> >
461      (NodeTextColorsTraits<X>(*this,x));
462  }
463  template<class X> struct EdgeColorsTraits : public T {
464    const X &_edgeColors;
465    EdgeColorsTraits(const T &t,const X &x) : T(t), _edgeColors(x) {}
466  };
467  ///Sets the map of the edge colors
468
469  ///Sets the map of the edge colors
470  ///\param x must be a edge map with \ref Color values.
471  ///
472  ///\sa Palette
473  template<class X> GraphToEps<EdgeColorsTraits<X> >
474  edgeColors(const X &x)
475  {
476    dontPrint=true;
477    return GraphToEps<EdgeColorsTraits<X> >(EdgeColorsTraits<X>(*this,x));
478  }
479  ///Sets a global scale factor for node sizes
480
481  ///Sets a global scale factor for node sizes.
482  ///
483  /// If nodeSizes() is not given, this function simply sets the node
484  /// sizes to \c d.  If nodeSizes() is given, but
485  /// autoNodeScale() is not, then the node size given by
486  /// nodeSizes() will be multiplied by the value \c d.
487  /// If both nodeSizes() and autoNodeScale() are used, then the
488  /// node sizes will be scaled in such a way that the greatest size will be
489  /// equal to \c d.
490  /// \sa nodeSizes()
491  /// \sa autoNodeScale()
492  GraphToEps<T> &nodeScale(double d) {_nodeScale=d;return *this;}
493  ///Turns on/off the automatic node width scaling.
494
495  ///Turns on/off the automatic node width scaling.
496  ///
497  ///\sa nodeScale()
498  ///
499  GraphToEps<T> &autoNodeScale(bool b=true) {
500    _autoNodeScale=b;return *this;
501  }
502
503  ///Turns on/off the absolutematic node width scaling.
504
505  ///Turns on/off the absolutematic node width scaling.
506  ///
507  ///\sa nodeScale()
508  ///
509  GraphToEps<T> &absoluteNodeSizes(bool b=true) {
510    _absoluteNodeSizes=b;return *this;
511  }
512
513  ///Negates the Y coordinates.
514
515  ///Negates the Y coordinates.
516  ///
517  ///\todo More docs.
518  ///
519  GraphToEps<T> &negateY(bool b=true) {
520    _negY=b;return *this;
521  }
522
523  ///Sets a global scale factor for edge widths
524
525  /// Sets a global scale factor for edge widths.
526  ///
527  /// If edgeWidths() is not given, this function simply sets the edge
528  /// widths to \c d.  If edgeWidths() is given, but
529  /// autoEdgeWidthScale() is not, then the edge withs given by
530  /// edgeWidths() will be multiplied by the value \c d.
531  /// If both edgeWidths() and autoEdgeWidthScale() are used, then the
532  /// edge withs will be scaled in such a way that the greatest width will be
533  /// equal to \c d.
534  GraphToEps<T> &edgeWidthScale(double d) {_edgeWidthScale=d;return *this;}
535  ///Turns on/off the automatic edge width scaling.
536
537  ///Turns on/off the automatic edge width scaling.
538  ///
539  ///\sa edgeWidthScale()
540  ///
541  GraphToEps<T> &autoEdgeWidthScale(bool b=true) {
542    _autoEdgeWidthScale=b;return *this;
543  }
544  ///Turns on/off the absolutematic edge width scaling.
545
546  ///Turns on/off the absolutematic edge width scaling.
547  ///
548  ///\sa edgeWidthScale()
549  ///
550  GraphToEps<T> &absoluteEdgeWidths(bool b=true) {
551    _absoluteEdgeWidths=b;return *this;
552  }
553  ///Sets a global scale factor for the whole picture
554
555  ///Sets a global scale factor for the whole picture
556  ///
557
558  GraphToEps<T> &scale(double d) {_scale=d;return *this;}
559  ///Sets the width of the border around the picture
560
561  ///Sets the width of the border around the picture
562  ///
563  GraphToEps<T> &border(double b) {_xBorder=_yBorder=b;return *this;}
564  ///Sets the width of the border around the picture
565
566  ///Sets the width of the border around the picture
567  ///
568  GraphToEps<T> &border(double x, double y) {
569    _xBorder=x;_yBorder=y;return *this;
570  }
571  ///Sets whether to draw arrows
572
573  ///Sets whether to draw arrows
574  ///
575  GraphToEps<T> &drawArrows(bool b=true) {_drawArrows=b;return *this;}
576  ///Sets the length of the arrowheads
577
578  ///Sets the length of the arrowheads
579  ///
580  GraphToEps<T> &arrowLength(double d) {_arrowLength*=d;return *this;}
581  ///Sets the width of the arrowheads
582
583  ///Sets the width of the arrowheads
584  ///
585  GraphToEps<T> &arrowWidth(double d) {_arrowWidth*=d;return *this;}
586 
587  ///Scales the drawing to fit to A4 page
588
589  ///Scales the drawing to fit to A4 page
590  ///
591  GraphToEps<T> &scaleToA4() {_scaleToA4=true;return *this;}
592 
593  ///Enables parallel edges
594
595  ///Enables parallel edges
596  GraphToEps<T> &enableParallel(bool b=true) {_enableParallel=b;return *this;}
597 
598  ///Sets the distance
599 
600  ///Sets the distance
601  ///
602  GraphToEps<T> &parEdgeDist(double d) {_parEdgeDist*=d;return *this;}
603 
604  ///Hides the edges
605 
606  ///Hides the edges
607  ///
608  GraphToEps<T> &hideEdges(bool b=true) {_showEdges=!b;return *this;}
609  ///Hides the nodes
610 
611  ///Hides the nodes
612  ///
613  GraphToEps<T> &hideNodes(bool b=true) {_showNodes=!b;return *this;}
614 
615  ///Sets the size of the node texts
616 
617  ///Sets the size of the node texts
618  ///
619  GraphToEps<T> &nodeTextSize(double d) {_nodeTextSize=d;return *this;}
620
621  ///Sets the color of the node texts to be different from the node color
622
623  ///Sets the color of the node texts to be as different from the node color
624  ///as it is possible
625  ///
626  GraphToEps<T> &distantColorNodeTexts()
627  {_nodeTextColorType=DIST_COL;return *this;}
628  ///Sets the color of the node texts to be black or white and always visible.
629
630  ///Sets the color of the node texts to be black or white according to
631  ///which is more
632  ///different from the node color
633  ///
634  GraphToEps<T> &distantBWNodeTexts()
635  {_nodeTextColorType=DIST_BW;return *this;}
636
637  ///Gives a preamble block for node Postscript block.
638 
639  ///Gives a preamble block for node Postscript block.
640  ///
641  ///\sa nodePsTexts()
642  GraphToEps<T> & nodePsTextsPreamble(const char *str) {
643    _nodePsTextsPreamble=str ;return *this;
644  }
645  ///Sets whether the the graph is undirected
646
647  ///Sets whether the the graph is undirected
648  ///
649  GraphToEps<T> &undirected(bool b=true) {_undirected=b;return *this;}
650
651  ///Sets whether the the graph is directed
652
653  ///Sets whether the the graph is directed.
654  ///Use it to show the undirected edges as a pair of directed ones.
655  GraphToEps<T> &bidir(bool b=true) {_undirected=!b;return *this;}
656
657  ///Sets the title.
658
659  ///Sets the title of the generated image,
660  ///namely it inserts a <tt>%%Title:</tt> DSC field to the header of
661  ///the EPS file.
662  GraphToEps<T> &title(const std::string &t) {_title=t;return *this;}
663  ///Sets the copyright statement.
664
665  ///Sets the copyright statement of the generated image,
666  ///namely it inserts a <tt>%%Copyright:</tt> DSC field to the header of
667  ///the EPS file.
668  ///\todo Multiline copyright notice could be supported.
669  GraphToEps<T> &copyright(const std::string &t) {_copyright=t;return *this;}
670
671protected:
672  bool isInsideNode(xy<double> p, double r,int t)
673  {
674    switch(t) {
675    case CIRCLE:
676    case MALE:
677    case FEMALE:
678      return p.normSquare()<=r*r;
679    case SQUARE:
680      return p.x<=r&&p.x>=-r&&p.y<=r&&p.y>=-r;
681    case DIAMOND:
682      return p.x+p.y<=r && p.x-p.y<=r && -p.x+p.y<=r && -p.x-p.y<=r;
683    }
684    return false;
685  }
686
687public:
688  ~GraphToEps() { }
689 
690  ///Draws the graph.
691
692  ///Like other functions using
693  ///\ref named-templ-func-param "named template parameters",
694  ///this function calles the algorithm itself, i.e. in this case
695  ///it draws the graph.
696  void run() {
697    ///\todo better 'epsilon' would be nice here.
698    const double EPSILON=1e-9;
699    if(dontPrint) return;
700   
701    _NegY<typename T::CoordsMapType> mycoords(_coords,_negY);
702
703    os << "%!PS-Adobe-2.0 EPSF-2.0\n";
704    if(_title.size()>0) os << "%%Title: " << _title << '\n';
705     if(_copyright.size()>0) os << "%%Copyright: " << _copyright << '\n';
706//        << "%%Copyright: XXXX\n"
707    os << "%%Creator: LEMON, graphToEps()\n";
708   
709    {
710      char cbuf[50];
711      timeval tv;
712      gettimeofday(&tv, 0);
713      ctime_r(&tv.tv_sec,cbuf);
714      os << "%%CreationDate: " << cbuf;
715    }
716
717    if (_autoEdgeWidthScale) {
718      double max_w=0;
719      for(EdgeIt e(g);e!=INVALID;++e)
720        max_w=std::max(double(_edgeWidths[e]),max_w);
721      ///\todo better 'epsilon' would be nice here.
722      if(max_w>EPSILON) {
723        _edgeWidthScale/=max_w;
724      }
725    }
726
727    if (_autoNodeScale) {
728      double max_s=0;
729      for(NodeIt n(g);n!=INVALID;++n)
730        max_s=std::max(double(_nodeSizes[n]),max_s);
731      ///\todo better 'epsilon' would be nice here.
732      if(max_s>EPSILON) {
733        _nodeScale/=max_s;
734      }
735    }
736
737    double diag_len = 1;
738    if(!(_absoluteNodeSizes&&_absoluteEdgeWidths)) {
739      BoundingBox<double> bb;
740      for(NodeIt n(g);n!=INVALID;++n) bb.add(mycoords[n]);
741      if (bb.empty()) {
742        bb = BoundingBox<double>(xy<double>(0,0));
743      }
744      diag_len = std::sqrt((bb.bottomLeft()-bb.topRight()).normSquare());
745      if(diag_len<EPSILON) diag_len = 1;
746      if(!_absoluteNodeSizes) _nodeScale*=diag_len;
747      if(!_absoluteEdgeWidths) _edgeWidthScale*=diag_len;
748    }
749   
750    BoundingBox<double> bb;
751    for(NodeIt n(g);n!=INVALID;++n) {
752      double ns=_nodeSizes[n]*_nodeScale;
753      xy<double> p(ns,ns);
754      switch(_nodeShapes[n]) {
755      case CIRCLE:
756      case SQUARE:
757      case DIAMOND:
758        bb.add(p+mycoords[n]);
759        bb.add(-p+mycoords[n]);
760        break;
761      case MALE:
762        bb.add(-p+mycoords[n]);
763        bb.add(xy<double>(1.5*ns,1.5*std::sqrt(3.0)*ns)+mycoords[n]);
764        break;
765      case FEMALE:
766        bb.add(p+mycoords[n]);
767        bb.add(xy<double>(-ns,-3.01*ns)+mycoords[n]);
768        break;
769      }
770    }
771    if (bb.empty()) {
772      bb = BoundingBox<double>(xy<double>(0,0));
773    }
774   
775    if(_scaleToA4)
776      os <<"%%BoundingBox: 0 0 596 842\n%%DocumentPaperSizes: a4\n";
777    else {
778      //Rescale so that BoundingBox won't be neither to big nor too small.
779      while(bb.height()*_scale>1000||bb.width()*_scale>1000) _scale/=10;
780      while(bb.height()*_scale<100||bb.width()*_scale<100) _scale*=10;
781   
782      os << "%%BoundingBox: "
783         << int(floor(bb.left()   * _scale - _xBorder)) << ' '
784         << int(floor(bb.bottom() * _scale - _yBorder)) << ' '
785         << int(ceil(bb.right()  * _scale + _xBorder)) << ' '
786         << int(ceil(bb.top()    * _scale + _yBorder)) << '\n';
787    }
788   
789    os << "%%EndComments\n";
790   
791    //x1 y1 x2 y2 x3 y3 cr cg cb w
792    os << "/lb { setlinewidth setrgbcolor newpath moveto\n"
793       << "      4 2 roll 1 index 1 index curveto stroke } bind def\n";
794    os << "/l { setlinewidth setrgbcolor newpath moveto lineto stroke } bind def\n";
795    //x y r
796    os << "/c { newpath dup 3 index add 2 index moveto 0 360 arc closepath } bind def\n";
797    //x y r
798    os << "/sq { newpath 2 index 1 index add 2 index 2 index add moveto\n"
799       << "      2 index 1 index sub 2 index 2 index add lineto\n"
800       << "      2 index 1 index sub 2 index 2 index sub lineto\n"
801       << "      2 index 1 index add 2 index 2 index sub lineto\n"
802       << "      closepath pop pop pop} bind def\n";
803    //x y r
804    os << "/di { newpath 2 index 1 index add 2 index moveto\n"
805       << "      2 index             2 index 2 index add lineto\n"
806       << "      2 index 1 index sub 2 index             lineto\n"
807       << "      2 index             2 index 2 index sub lineto\n"
808       << "      closepath pop pop pop} bind def\n";
809    // x y r cr cg cb
810    os << "/nc { 0 0 0 setrgbcolor 5 index 5 index 5 index c fill\n"
811       << "     setrgbcolor " << 1+_nodeBorderQuotient << " div c fill\n"
812       << "   } bind def\n";
813    os << "/nsq { 0 0 0 setrgbcolor 5 index 5 index 5 index sq fill\n"
814       << "     setrgbcolor " << 1+_nodeBorderQuotient << " div sq fill\n"
815       << "   } bind def\n";
816    os << "/ndi { 0 0 0 setrgbcolor 5 index 5 index 5 index di fill\n"
817       << "     setrgbcolor " << 1+_nodeBorderQuotient << " div di fill\n"
818       << "   } bind def\n";
819    os << "/nfemale { 0 0 0 setrgbcolor 3 index "
820       << _nodeBorderQuotient/(1+_nodeBorderQuotient)
821       << " 1.5 mul mul setlinewidth\n"
822       << "  newpath 5 index 5 index moveto "
823       << "5 index 5 index 5 index 3.01 mul sub\n"
824       << "  lineto 5 index 4 index .7 mul sub 5 index 5 index 2.2 mul sub moveto\n"
825       << "  5 index 4 index .7 mul add 5 index 5 index 2.2 mul sub lineto stroke\n"
826       << "  5 index 5 index 5 index c fill\n"
827       << "  setrgbcolor " << 1+_nodeBorderQuotient << " div c fill\n"
828       << "  } bind def\n";
829    os << "/nmale {\n"
830       << "  0 0 0 setrgbcolor 3 index "
831       << _nodeBorderQuotient/(1+_nodeBorderQuotient)
832       <<" 1.5 mul mul setlinewidth\n"
833       << "  newpath 5 index 5 index moveto\n"
834       << "  5 index 4 index 1 mul 1.5 mul add\n"
835       << "  5 index 5 index 3 sqrt 1.5 mul mul add\n"
836       << "  1 index 1 index lineto\n"
837       << "  1 index 1 index 7 index sub moveto\n"
838       << "  1 index 1 index lineto\n"
839       << "  exch 5 index 3 sqrt .5 mul mul sub exch 5 index .5 mul sub lineto\n"
840       << "  stroke\n"
841       << "  5 index 5 index 5 index c fill\n"
842       << "  setrgbcolor " << 1+_nodeBorderQuotient << " div c fill\n"
843       << "  } bind def\n";
844   
845
846    os << "/arrl " << _arrowLength << " def\n";
847    os << "/arrw " << _arrowWidth << " def\n";
848    // l dx_norm dy_norm
849    os << "/lrl { 2 index mul exch 2 index mul exch rlineto pop} bind def\n";
850    //len w dx_norm dy_norm x1 y1 cr cg cb
851    os << "/arr { setrgbcolor /y1 exch def /x1 exch def /dy exch def /dx exch def\n"
852       << "       /w exch def /len exch def\n"
853      //         << "       0.1 setlinewidth x1 y1 moveto dx len mul dy len mul rlineto stroke"
854       << "       newpath x1 dy w 2 div mul add y1 dx w 2 div mul sub moveto\n"
855       << "       len w sub arrl sub dx dy lrl\n"
856       << "       arrw dy dx neg lrl\n"
857       << "       dx arrl w add mul dy w 2 div arrw add mul sub\n"
858       << "       dy arrl w add mul dx w 2 div arrw add mul add rlineto\n"
859       << "       dx arrl w add mul neg dy w 2 div arrw add mul sub\n"
860       << "       dy arrl w add mul neg dx w 2 div arrw add mul add rlineto\n"
861       << "       arrw dy dx neg lrl\n"
862       << "       len w sub arrl sub neg dx dy lrl\n"
863       << "       closepath fill } bind def\n";
864    os << "/cshow { 2 index 2 index moveto dup stringwidth pop\n"
865       << "         neg 2 div fosi .35 mul neg rmoveto show pop pop} def\n";
866
867    os << "\ngsave\n";
868    if(_scaleToA4)
869      if(bb.height()>bb.width()) {
870        double sc= std::min((A4HEIGHT-2*A4BORDER)/bb.height(),
871                  (A4WIDTH-2*A4BORDER)/bb.width());
872        os << ((A4WIDTH -2*A4BORDER)-sc*bb.width())/2 + A4BORDER << ' '
873           << ((A4HEIGHT-2*A4BORDER)-sc*bb.height())/2 + A4BORDER << " translate\n"
874           << sc << " dup scale\n"
875           << -bb.left() << ' ' << -bb.bottom() << " translate\n";
876      }
877      else {
878        //\todo Verify centering
879        double sc= std::min((A4HEIGHT-2*A4BORDER)/bb.width(),
880                  (A4WIDTH-2*A4BORDER)/bb.height());
881        os << ((A4WIDTH -2*A4BORDER)-sc*bb.height())/2 + A4BORDER << ' '
882           << ((A4HEIGHT-2*A4BORDER)-sc*bb.width())/2 + A4BORDER  << " translate\n"
883           << sc << " dup scale\n90 rotate\n"
884           << -bb.left() << ' ' << -bb.top() << " translate\n";
885        }
886    else if(_scale!=1.0) os << _scale << " dup scale\n";
887   
888    if(_showEdges) {
889      os << "%Edges:\ngsave\n";     
890      if(_enableParallel) {
891        std::vector<Edge> el;
892        for(EdgeIt e(g);e!=INVALID;++e)
893          if((!_undirected||g.source(e)<g.target(e))&&_edgeWidths[e]>0
894             &&g.source(e)!=g.target(e))
895            el.push_back(e);
896        std::sort(el.begin(),el.end(),edgeLess(g));
897       
898        typename std::vector<Edge>::iterator j;
899        for(typename std::vector<Edge>::iterator i=el.begin();i!=el.end();i=j) {
900          for(j=i+1;j!=el.end()&&isParallel(*i,*j);++j) ;
901
902          double sw=0;
903          for(typename std::vector<Edge>::iterator e=i;e!=j;++e)
904            sw+=_edgeWidths[*e]*_edgeWidthScale+_parEdgeDist;
905          sw-=_parEdgeDist;
906          sw/=-2.0;
907          xy<double> 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          xy<double> d(dvec/std::max(l,EPSILON));
911          xy<double> m;
912//        m=xy<double>(mycoords[g.target(*i)]+mycoords[g.source(*i)])/2.0;
913
914//        m=xy<double>(mycoords[g.source(*i)])+
915//          dvec*(double(_nodeSizes[g.source(*i)])/
916//             (_nodeSizes[g.source(*i)]+_nodeSizes[g.target(*i)]));
917
918          m=xy<double>(mycoords[g.source(*i)])+
919            d*(l+_nodeSizes[g.source(*i)]-_nodeSizes[g.target(*i)])/2.0;
920
921          for(typename std::vector<Edge>::iterator e=i;e!=j;++e) {
922            sw+=_edgeWidths[*e]*_edgeWidthScale/2.0;
923            xy<double> mm=m+rot90(d)*sw/.75;
924            if(_drawArrows) {
925              int node_shape;
926              xy<double> s=mycoords[g.source(*e)];
927              xy<double> t=mycoords[g.target(*e)];
928              double rn=_nodeSizes[g.target(*e)]*_nodeScale;
929              node_shape=_nodeShapes[g.target(*e)];
930              Bezier3 bez(s,mm,mm,t);
931              double t1=0,t2=1;
932              for(int i=0;i<INTERPOL_PREC;++i)
933                if(isInsideNode(bez((t1+t2)/2)-t,rn,node_shape)) t2=(t1+t2)/2;
934                else t1=(t1+t2)/2;
935              xy<double> apoint=bez((t1+t2)/2);
936              rn = _arrowLength+_edgeWidths[*e]*_edgeWidthScale;
937              rn*=rn;
938              t2=(t1+t2)/2;t1=0;
939              for(int i=0;i<INTERPOL_PREC;++i)
940                if((bez((t1+t2)/2)-apoint).normSquare()>rn) t1=(t1+t2)/2;
941                else t2=(t1+t2)/2;
942              xy<double> linend=bez((t1+t2)/2);       
943              bez=bez.before((t1+t2)/2);
944//            rn=_nodeSizes[g.source(*e)]*_nodeScale;
945//            node_shape=_nodeShapes[g.source(*e)];
946//            t1=0;t2=1;
947//            for(int i=0;i<INTERPOL_PREC;++i)
948//              if(isInsideNode(bez((t1+t2)/2)-t,rn,node_shape)) t1=(t1+t2)/2;
949//              else t2=(t1+t2)/2;
950//            bez=bez.after((t1+t2)/2);
951              os << _edgeWidths[*e]*_edgeWidthScale << " setlinewidth "
952                 << _edgeColors[*e].red() << ' '
953                 << _edgeColors[*e].green() << ' '
954                 << _edgeColors[*e].blue() << " setrgbcolor newpath\n"
955                 << bez.p1.x << ' ' <<  bez.p1.y << " moveto\n"
956                 << bez.p2.x << ' ' << bez.p2.y << ' '
957                 << bez.p3.x << ' ' << bez.p3.y << ' '
958                 << bez.p4.x << ' ' << bez.p4.y << " curveto stroke\n";
959              xy<double> dd(rot90(linend-apoint));
960              dd*=(.5*_edgeWidths[*e]*_edgeWidthScale+_arrowWidth)/
961                std::sqrt(dd.normSquare());
962              os << "newpath " << psOut(apoint) << " moveto "
963                 << psOut(linend+dd) << " lineto "
964                 << psOut(linend-dd) << " lineto closepath fill\n";
965            }
966            else {
967              os << mycoords[g.source(*e)].x << ' '
968                 << mycoords[g.source(*e)].y << ' '
969                 << mm.x << ' ' << mm.y << ' '
970                 << mycoords[g.target(*e)].x << ' '
971                 << mycoords[g.target(*e)].y << ' '
972                 << _edgeColors[*e].red() << ' '
973                 << _edgeColors[*e].green() << ' '
974                 << _edgeColors[*e].blue() << ' '
975                 << _edgeWidths[*e]*_edgeWidthScale << " lb\n";
976            }
977            sw+=_edgeWidths[*e]*_edgeWidthScale/2.0+_parEdgeDist;
978          }
979        }
980      }
981      else for(EdgeIt e(g);e!=INVALID;++e)
982        if((!_undirected||g.source(e)<g.target(e))&&_edgeWidths[e]>0
983           &&g.source(e)!=g.target(e))
984          if(_drawArrows) {
985            xy<double> d(mycoords[g.target(e)]-mycoords[g.source(e)]);
986            double rn=_nodeSizes[g.target(e)]*_nodeScale;
987            int node_shape=_nodeShapes[g.target(e)];
988            double t1=0,t2=1;
989            for(int i=0;i<INTERPOL_PREC;++i)
990              if(isInsideNode((-(t1+t2)/2)*d,rn,node_shape)) t1=(t1+t2)/2;
991              else t2=(t1+t2)/2;
992            double l=std::sqrt(d.normSquare());
993            d/=l;
994           
995            os << l*(1-(t1+t2)/2) << ' '
996               << _edgeWidths[e]*_edgeWidthScale << ' '
997               << d.x << ' ' << d.y << ' '
998               << mycoords[g.source(e)].x << ' '
999               << mycoords[g.source(e)].y << ' '
1000               << _edgeColors[e].red() << ' '
1001               << _edgeColors[e].green() << ' '
1002               << _edgeColors[e].blue() << " arr\n";
1003          }
1004          else os << mycoords[g.source(e)].x << ' '
1005                  << mycoords[g.source(e)].y << ' '
1006                  << mycoords[g.target(e)].x << ' '
1007                  << mycoords[g.target(e)].y << ' '
1008                  << _edgeColors[e].red() << ' '
1009                  << _edgeColors[e].green() << ' '
1010                  << _edgeColors[e].blue() << ' '
1011                  << _edgeWidths[e]*_edgeWidthScale << " l\n";
1012      os << "grestore\n";
1013    }
1014    if(_showNodes) {
1015      os << "%Nodes:\ngsave\n";
1016      for(NodeIt n(g);n!=INVALID;++n) {
1017        os << mycoords[n].x << ' ' << mycoords[n].y << ' '
1018           << _nodeSizes[n]*_nodeScale << ' '
1019           << _nodeColors[n].red() << ' '
1020           << _nodeColors[n].green() << ' '
1021           << _nodeColors[n].blue() << ' ';
1022        switch(_nodeShapes[n]) {
1023        case CIRCLE:
1024          os<< "nc";break;
1025        case SQUARE:
1026          os<< "nsq";break;
1027        case DIAMOND:
1028          os<< "ndi";break;
1029        case MALE:
1030          os<< "nmale";break;
1031        case FEMALE:
1032          os<< "nfemale";break;
1033        }
1034        os<<'\n';
1035      }
1036      os << "grestore\n";
1037    }
1038    if(_showNodeText) {
1039      os << "%Node texts:\ngsave\n";
1040      os << "/fosi " << _nodeTextSize << " def\n";
1041      os << "(Helvetica) findfont fosi scalefont setfont\n";
1042      for(NodeIt n(g);n!=INVALID;++n) {
1043        switch(_nodeTextColorType) {
1044        case DIST_COL:
1045          os << psOut(distantColor(_nodeColors[n])) << " setrgbcolor\n";
1046          break;
1047        case DIST_BW:
1048          os << psOut(distantBW(_nodeColors[n])) << " setrgbcolor\n";
1049          break;
1050        case CUST_COL:
1051          os << psOut(distantColor(_nodeTextColors[n])) << " setrgbcolor\n";
1052          break;
1053        default:
1054          os << "0 0 0 setrgbcolor\n";
1055        }
1056        os << mycoords[n].x << ' ' << mycoords[n].y
1057           << " (" << _nodeTexts[n] << ") cshow\n";
1058      }
1059      os << "grestore\n";
1060    }
1061    if(_showNodePsText) {
1062      os << "%Node PS blocks:\ngsave\n";
1063      for(NodeIt n(g);n!=INVALID;++n)
1064        os << mycoords[n].x << ' ' << mycoords[n].y
1065           << " moveto\n" << _nodePsTexts[n] << "\n";
1066      os << "grestore\n";
1067    }
1068   
1069    os << "grestore\nshowpage\n";
1070
1071    //CleanUp:
1072    if(_pleaseRemoveOsStream) {delete &os;}
1073  }
1074};
1075
1076template<class T>
1077const int GraphToEps<T>::INTERPOL_PREC = 20;
1078template<class T>
1079const double GraphToEps<T>::A4HEIGHT = 841.8897637795276;
1080template<class T>
1081const double GraphToEps<T>::A4WIDTH  = 595.275590551181;
1082template<class T>
1083const double GraphToEps<T>::A4BORDER = 15;
1084
1085
1086///Generates an EPS file from a graph
1087
1088///\ingroup eps_io
1089///Generates an EPS file from a graph.
1090///\param g is a reference to the graph to be printed
1091///\param os is a reference to the output stream.
1092///By default it is <tt>std::cout</tt>
1093///
1094///This function also has a lot of
1095///\ref named-templ-func-param "named parameters",
1096///they are declared as the members of class \ref GraphToEps. The following
1097///example shows how to use these parameters.
1098///\code
1099/// graphToEps(g,os).scale(10).coords(coords)
1100///              .nodeScale(2).nodeSizes(sizes)
1101///              .edgeWidthScale(.4).run();
1102///\endcode
1103///\warning Don't forget to put the \ref GraphToEps::run() "run()"
1104///to the end of the parameter list.
1105///\sa GraphToEps
1106///\sa graphToEps(G &g, const char *file_name)
1107template<class G>
1108GraphToEps<DefaultGraphToEpsTraits<G> >
1109graphToEps(G &g, std::ostream& os=std::cout)
1110{
1111  return
1112    GraphToEps<DefaultGraphToEpsTraits<G> >(DefaultGraphToEpsTraits<G>(g,os));
1113}
1114 
1115///Generates an EPS file from a graph
1116
1117///\ingroup eps_io
1118///This function does the same as
1119///\ref graphToEps(G &g,std::ostream& os)
1120///but it writes its output into the file \c file_name
1121///instead of a stream.
1122///\sa graphToEps(G &g, std::ostream& os)
1123template<class G>
1124GraphToEps<DefaultGraphToEpsTraits<G> >
1125graphToEps(G &g,const char *file_name)
1126{
1127  return GraphToEps<DefaultGraphToEpsTraits<G> >
1128    (DefaultGraphToEpsTraits<G>(g,*new std::ofstream(file_name),true));
1129}
1130
1131///Generates an EPS file from a graph
1132
1133///\ingroup eps_io
1134///This function does the same as
1135///\ref graphToEps(G &g,std::ostream& os)
1136///but it writes its output into the file \c file_name
1137///instead of a stream.
1138///\sa graphToEps(G &g, std::ostream& os)
1139template<class G>
1140GraphToEps<DefaultGraphToEpsTraits<G> >
1141graphToEps(G &g,const std::string& file_name)
1142{
1143  return GraphToEps<DefaultGraphToEpsTraits<G> >
1144    (DefaultGraphToEpsTraits<G>(g,*new std::ofstream(file_name.c_str()),true));
1145}
1146
1147} //END OF NAMESPACE LEMON
1148
1149#endif // LEMON_GRAPH_TO_EPS_H
Note: See TracBrowser for help on using the repository browser.