]> git.donarmstrong.com Git - lilypond.git/blob - lily/lookup.cc
Issue 4550 (1/2) Avoid "using namespace std;" in included files
[lilypond.git] / lily / lookup.cc
1 /*
2   This file is part of LilyPond, the GNU music typesetter.
3
4   Copyright (C) 1997--2015 Han-Wen Nienhuys <hanwen@xs4all.nl>
5
6   Jan Nieuwenhuizen <janneke@gnu.org>
7
8   LilyPond is free software: you can redistribute it and/or modify
9   it under the terms of the GNU General Public License as published by
10   the Free Software Foundation, either version 3 of the License, or
11   (at your option) any later version.
12
13   LilyPond is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "lookup.hh"
23
24 #include <cmath>
25 #include <cctype>
26 using namespace std;
27
28 #include "line-interface.hh"
29 #include "warn.hh"
30 #include "international.hh"
31 #include "dimensions.hh"
32 #include "bezier.hh"
33 #include "file-path.hh"
34 #include "main.hh"
35 #include "lily-guile.hh"
36
37 using std::vector;
38
39 Stencil
40 Lookup::beam (Real slope, Real width, Real thick, Real blot)
41 {
42   Box b;
43
44   Offset p;
45
46   p = Offset (0, thick / 2);
47   b.add_point (p);
48   p += Offset (1, -1) * (blot / 2);
49
50   SCM points = SCM_EOL;
51
52   points = scm_cons (scm_from_double (p[X_AXIS]),
53                      scm_cons (scm_from_double (p[Y_AXIS]),
54                                points));
55
56   p = Offset (0, -thick / 2);
57   b.add_point (p);
58   p += Offset (1, 1) * (blot / 2);
59
60   points = scm_cons (scm_from_double (p[X_AXIS]),
61                      scm_cons (scm_from_double (p[Y_AXIS]),
62                                points));
63
64   p = Offset (width, width * slope - thick / 2);
65   b.add_point (p);
66   p += Offset (-1, 1) * (blot / 2);
67
68   points = scm_cons (scm_from_double (p[X_AXIS]),
69                      scm_cons (scm_from_double (p[Y_AXIS]),
70                                points));
71
72   p = Offset (width, width * slope + thick / 2);
73   b.add_point (p);
74   p += Offset (-1, -1) * (blot / 2);
75
76   points = scm_cons (scm_from_double (p[X_AXIS]),
77                      scm_cons (scm_from_double (p[Y_AXIS]),
78                                points));
79
80   SCM expr = scm_list_n (ly_symbol2scm ("polygon"),
81                          ly_quote_scm (points),
82                          scm_from_double (blot),
83                          SCM_BOOL_T,
84                          SCM_UNDEFINED);
85
86   return Stencil (b, expr);
87 }
88
89 Stencil
90 Lookup::rotated_box (Real slope, Real width, Real thick, Real blot)
91 {
92   vector<Offset> pts;
93   Offset rot = Offset (1, slope).direction ();
94
95   pts.push_back (Offset (0, -thick / 2) * rot);
96   pts.push_back (Offset (width, -thick / 2) * rot);
97   pts.push_back (Offset (width, thick / 2) * rot);
98   pts.push_back (Offset (0, thick / 2) * rot);
99   return Lookup::round_filled_polygon (pts, blot);
100 }
101
102 Stencil
103 Lookup::horizontal_line (Interval w, Real th)
104 {
105   SCM at = scm_list_n (ly_symbol2scm ("draw-line"),
106                        scm_from_double (th),
107                        scm_from_double (w[LEFT]),
108                        scm_from_double (0),
109                        scm_from_double (w[RIGHT]),
110                        scm_from_double (0),
111                        SCM_UNDEFINED);
112
113   Box box;
114   box[X_AXIS] = w;
115   box[Y_AXIS] = Interval (-th / 2, th / 2);
116
117   return Stencil (box, at);
118 }
119
120 Stencil
121 Lookup::blank (Box b)
122 {
123   return Stencil (b, scm_string (SCM_EOL));
124 }
125
126 Stencil
127 Lookup::circle (Real rad, Real thick, bool filled)
128 {
129   Box b (Interval (-rad, rad), Interval (-rad, rad));
130   return Stencil (b, scm_list_4 (ly_symbol2scm ("circle"),
131                                  scm_from_double (rad),
132                                  scm_from_double (thick),
133                                  scm_from_bool (filled)));
134 }
135
136 Stencil
137 Lookup::filled_box (Box b)
138 {
139   return round_filled_box (b, 0.0);
140 }
141
142 /*
143  * round filled box:
144  *
145  *   __________________________________
146  *  /     \  ^           /     \      ^
147  * |         |blot              |     |
148  * |       | |dia       |       |     |
149  * |         |meter             |     |
150  * |\ _ _ /  v           \ _ _ /|     |
151  * |                            |     |
152  * |                            |     | Box
153  * |                    <------>|     | extent
154  * |                      blot  |     | (Y_AXIS)
155  * |                    diameter|     |
156  * |                            |     |
157  * |  _ _                  _ _  |     |
158  * |/     \              /     \|     |
159  * |                            |     |
160  * |       |            |       |     |
161  * |                            |     |
162  * x\_____/______________\_____/|_____v
163  * |(0, 0)                       |
164  * |                            |
165  * |                            |
166  * |<-------------------------->|
167  *       Box extent (X_AXIS)
168  */
169 Stencil
170 Lookup::round_filled_box (Box b, Real blotdiameter)
171 {
172   Real width = b.x ().delta ();
173   blotdiameter = min (blotdiameter, width);
174   Real height = b.y ().delta ();
175   blotdiameter = min (blotdiameter, height);
176
177   if (blotdiameter < 0.0)
178     {
179       if (!isinf (blotdiameter))
180         warning (_f ("Not drawing a box with negative dimension, %.2f by %.2f.",
181                      width, height));
182       return Stencil (b, SCM_EOL);
183     }
184
185   SCM at = (scm_list_n (ly_symbol2scm ("round-filled-box"),
186                         scm_from_double (-b[X_AXIS][LEFT]),
187                         scm_from_double (b[X_AXIS][RIGHT]),
188                         scm_from_double (-b[Y_AXIS][DOWN]),
189                         scm_from_double (b[Y_AXIS][UP]),
190                         scm_from_double (blotdiameter),
191                         SCM_UNDEFINED));
192
193   return Stencil (b, at);
194 }
195
196 /*
197  * Create Stencil that represents a filled polygon with round edges.
198  *
199  * LIMITATIONS:
200  *
201  * (a) Only outer (convex) edges are rounded.
202  *
203  * (b) This algorithm works as expected only for polygons whose edges
204  * do not intersect.  For example, the polygon ((0, 0), (q, 0), (0,
205  * q), (q, q)) has an intersection at point (q/2, q/2) and therefore
206  * will give a strange result.  Even non-adjacent edges that just
207  * touch each other will in general not work as expected for non-null
208  * blotdiameter.
209  *
210  * (c) Given a polygon ((x0, y0), (x1, y1), ... , (x (n-1), y (n-1))),
211  * if there is a natural number k such that blotdiameter is greater
212  * than the maximum of { | (x (k mod n), y (k mod n)) - (x ((k+1) mod n),
213  * y ((k+1) mod n)) |, | (x (k mod n), y (k mod n)) - (x ((k+2) mod n),
214  * y ((k+2) mod n)) |, | (x ((k+1) mod n), y ((k+1) mod n)) - (x ((k+2)
215  * mod n), y ((k+2) mod n)) | }, then the outline of the rounded
216  * polygon will exceed the outline of the core polygon.  In other
217  * words: Do not draw rounded polygons that have a leg smaller or
218  * thinner than blotdiameter (or set blotdiameter to a sufficiently
219  * small value -- maybe even 0.0)!
220  *
221  * NOTE: Limitations (b) and (c) arise from the fact that round edges
222  * are made by moulding sharp edges to round ones rather than adding
223  * to a core filled polygon.  For details of these two different
224  * approaches, see the thread upon the ledger lines patch that started
225  * on March 25, 2002 on the devel mailing list.  The below version of
226  * round_filled_polygon () sticks to the moulding model, which the
227  * majority of the list participants finally voted for.  This,
228  * however, results in the above limitations and a much increased
229  * complexity of the algorithm, since it has to compute a shrinked
230  * polygon -- which is not trivial define precisely and unambigously.
231  * With the other approach, one simply could move a circle of size
232  * blotdiameter along all edges of the polygon (which is what the
233  * postscript routine in the backend effectively does, but on the
234  * shrinked polygon). --jr
235  *
236  * An extra parameter "extroversion" has been added since staying just
237  * inside of a polygon will reduce its visual size when tracing a
238  * rounded path.  If extroversion is zero, the polygon is just traced
239  * as-is.  If it is -1 (the default) the drawing will stay just within
240  * the given polygon.  If it is 1, the traced line will stay just
241  * outside of the given polygon.
242  */
243 Stencil
244 Lookup::round_filled_polygon (vector<Offset> const &points,
245                               Real blotdiameter,
246                               Real extroversion)
247 {
248   /* TODO: Maybe print a warning if one of the above limitations
249      applies to the given polygon.  However, this is quite complicated
250      to check. */
251
252   const Real epsilon = 0.01;
253
254 #ifdef DEBUG
255   /* remove consecutive duplicate points */
256   for (vsize i = 0; i < points.size (); i++)
257     {
258       int next = (i + 1) % points.size ();
259       Real d = (points[i] - points[next]).length ();
260       if (d < epsilon)
261         programming_error ("Polygon should not have duplicate points");
262     }
263 #endif
264
265   /* special cases: degenerated polygons */
266   if (points.size () == 0)
267     return Stencil ();
268   if (points.size () == 1)
269     {
270       Stencil circ = circle (0.5 * (1.0 + extroversion) * blotdiameter, 0, true);
271       circ.translate (points[0]);
272       return circ;
273     }
274   if (points.size () == 2)
275     return Line_interface::make_line ((1.0 + extroversion) * blotdiameter, points[0], points[1]);
276
277   vector<Offset> shrunk_points;
278
279   if (extroversion == 0.0)
280     {
281       shrunk_points = points;
282     }
283   else
284     {
285       /* shrink polygon in size by 0.5 * blotdiameter */
286
287       // first we need to determine the orientation of the polygon in
288       // order to decide whether shrinking means moving the polygon to the
289       // left or to the right of the outline.  We do that by calculating
290       // (double) the oriented area of the polygon.  We first determine the
291       // center and do the area calculations relative to it.
292       // Mathematically, the result is not affected by this shift, but
293       // numerically a lot of cancellation is going on and this keeps its
294       // effects in check.
295
296       Offset center;
297       for (vsize i = 0; i < points.size (); i++)
298         center += points[i];
299       center /= points.size ();
300
301       Real area = 0.0;
302       Offset last = points.back () - center;
303
304       for (vsize i = 0; i < points.size (); i++)
305         {
306           Offset here = points[i] - center;
307           area += cross_product (last, here);
308           last = here;
309         }
310
311       bool ccw = area >= 0.0;  // true if whole shape is counterclockwise oriented
312
313       shrunk_points.resize (points.size ());
314
315       for (vsize i = 0; i < points.size (); i++)
316         {
317           int i0 = i;
318           int i1 = (i + 1) % points.size ();
319           int i2 = (i + 2) % points.size ();
320           Offset p0 = points[i0];
321           Offset p1 = points[i1];
322           Offset p2 = points[i2];
323           Offset p01 = p1 - p0;
324           Offset p12 = p2 - p1;
325           Offset inward0 = Offset(-p01[Y_AXIS], p01[X_AXIS]).direction ();
326           Offset inward2 = Offset(-p12[Y_AXIS], p12[X_AXIS]).direction ();
327
328           if (!ccw)
329             {
330               inward0 = -inward0;
331               inward2 = -inward2;
332             }
333
334           Offset middle = 0.5*(inward0 + inward2);
335
336           // "middle" now is a vector in the right direction for the
337           // shrinkage.  Its size needs to be large enough that the
338           // projection on either of the inward vectors has a size of 1.
339
340           Real proj = dot_product (middle, inward0);
341
342           // What's the size of proj?  Assuming that we have a corner
343           // angle of phi where 0 corresponds to a continuing line, the
344           // length of middle is 0.5 |(1+cos phi, sin phi)| = cos (phi/2),
345           // so its projection has length
346           // cos^2 (phi/2) = 0.5 + 0.5 cos (phi).
347           // We don't really want to move inwards more than 3 blob
348           // diameters corresponding to 6 blob radii.  So
349           // cos (phi/2) = 1/6 gives phi ~ 161, meaning that a 20 degree
350           // corner necessitates moving 3 blob diameters from the corner
351           // in order to stay inside the lines.  Ruler and circle agree.
352           // 0.03 is close enough to 1/36.  Basically we want to keep the
353           // shape from inverting from pulling too far inward.
354           // 3 diameters is pretty much a handwaving guess.
355
356           if (abs (proj) < 0.03)
357             proj = proj < 0 ? -0.03 : 0.03;
358
359           shrunk_points[i1] = p1 - (0.5 * blotdiameter / proj) * middle
360                           * extroversion;
361         }
362     }
363
364   /* build scm expression and bounding box */
365   SCM shrunk_points_scm = SCM_EOL;
366   Box box;
367   Box shrunk_box;
368   for (vsize i = 0; i < shrunk_points.size (); i++)
369     {
370       SCM x = scm_from_double (shrunk_points[i][X_AXIS]);
371       SCM y = scm_from_double (shrunk_points[i][Y_AXIS]);
372       shrunk_points_scm = scm_cons (x, scm_cons (y, shrunk_points_scm));
373       box.add_point (points[i]);
374       shrunk_box.add_point (shrunk_points[i]);
375     }
376   shrunk_box.widen (0.5*blotdiameter, 0.5*blotdiameter);
377   box.unite (shrunk_box);
378   SCM polygon_scm = scm_list_n (ly_symbol2scm ("polygon"),
379                                 ly_quote_scm (shrunk_points_scm),
380                                 scm_from_double (blotdiameter),
381                                 SCM_BOOL_T,
382                                 SCM_UNDEFINED);
383
384   Stencil polygon = Stencil (box, polygon_scm);
385   return polygon;
386 }
387
388 /*
389   TODO: deprecate?
390 */
391 Stencil
392 Lookup::frame (Box b, Real thick, Real blot)
393 {
394   Stencil m;
395   for (Axis a = X_AXIS; a < NO_AXES; a = Axis (a + 1))
396     {
397       Axis o = Axis ((a + 1) % NO_AXES);
398       for (LEFT_and_RIGHT (d))
399         {
400           Box edges;
401           edges[a] = b[a][d] + 0.5 * thick * Interval (-1, 1);
402           edges[o][DOWN] = b[o][DOWN] - thick / 2;
403           edges[o][UP] = b[o][UP] + thick / 2;
404
405           m.add_stencil (round_filled_box (edges, blot));
406         }
407     }
408   return m;
409 }
410
411 /*
412   Make a smooth curve along the points
413 */
414 Stencil
415 Lookup::slur (Bezier curve, Real curvethick, Real linethick,
416               SCM dash_details)
417 {
418   Stencil return_value;
419
420   /*
421       calculate the offset for the two beziers that make the sandwich
422       for the slur
423   */
424   Real alpha = (curve.control_[3] - curve.control_[0]).arg ();
425   Bezier back = curve;
426   Offset perp = curvethick * complex_exp (Offset (0, alpha + M_PI / 2)) * 0.5;
427   back.control_[1] += perp;
428   back.control_[2] += perp;
429
430   curve.control_[1] -= perp;
431   curve.control_[2] -= perp;
432
433   if (!scm_is_pair (dash_details))
434     {
435       /* solid slur  */
436       return_value = bezier_sandwich (back, curve, linethick);
437     }
438   else
439     {
440       /* dashed or combination slur */
441       int num_segments = scm_to_int (scm_length (dash_details));
442       for (int i = 0; i < num_segments; i++)
443         {
444           SCM dash_pattern = scm_list_ref (dash_details, scm_from_int (i));
445           Real t_min = robust_scm2double (scm_car (dash_pattern), 0);
446           Real t_max = robust_scm2double (scm_cadr (dash_pattern), 1.0);
447           Real dash_fraction
448             = robust_scm2double (scm_caddr (dash_pattern), 1.0);
449           Real dash_period
450             = robust_scm2double (scm_cadddr (dash_pattern), 0.75);
451           Bezier back_segment = back.extract (t_min, t_max);
452           Bezier curve_segment = curve.extract (t_min, t_max);
453           if (dash_fraction == 1.0)
454             return_value.add_stencil (bezier_sandwich (back_segment,
455                                                        curve_segment,
456                                                        linethick));
457           else
458             {
459               Bezier back_dash, curve_dash;
460               Real seg_length = (back_segment.control_[3]
461                                  - back_segment.control_[0]).length ();
462               int pattern_count = (int) (seg_length / dash_period);
463               Real pattern_length = 1.0 / (pattern_count + dash_fraction);
464               Real start_t, end_t;
465               for (int p = 0; p <= pattern_count; p++)
466                 {
467                   start_t = p * pattern_length;
468                   end_t = (p + dash_fraction) * pattern_length;
469                   back_dash
470                     = back_segment.extract (start_t, end_t);
471                   curve_dash
472                     = curve_segment.extract (start_t, end_t);
473                   return_value.add_stencil (bezier_sandwich (back_dash,
474                                                              curve_dash,
475                                                              linethick));
476                 }
477             }
478         }
479     }
480   return return_value;
481 }
482
483 /*
484  * Bezier Sandwich:
485  *
486  *                               .|
487  *                        .       |
488  *              top .             |
489  *              . curve           |
490  *          .                     |
491  *       .                        |
492  *     .                          |
493  *    |                           |
494  *    |                          .|
495  *    |                     .
496  *    |         bottom .
497  *    |            . curve
498  *    |         .
499  *    |      .
500  *    |   .
501  *    | .
502  *    |.
503  *    |
504  *
505  */
506 Stencil
507 Lookup::bezier_sandwich (Bezier top_curve, Bezier bottom_curve, Real thickness)
508 {
509   SCM commands = scm_list_n (ly_symbol2scm ("moveto"),
510                              scm_from_double (top_curve.control_[0][X_AXIS]),
511                              scm_from_double (top_curve.control_[0][Y_AXIS]),
512                              ly_symbol2scm ("curveto"),
513                              scm_from_double (top_curve.control_[1][X_AXIS]),
514                              scm_from_double (top_curve.control_[1][Y_AXIS]),
515                              scm_from_double (top_curve.control_[2][X_AXIS]),
516                              scm_from_double (top_curve.control_[2][Y_AXIS]),
517                              scm_from_double (top_curve.control_[3][X_AXIS]),
518                              scm_from_double (top_curve.control_[3][Y_AXIS]),
519                              ly_symbol2scm ("lineto"),
520                              scm_from_double (bottom_curve.control_[3][X_AXIS]),
521                              scm_from_double (bottom_curve.control_[3][Y_AXIS]),
522                              ly_symbol2scm ("curveto"),
523                              scm_from_double (bottom_curve.control_[2][X_AXIS]),
524                              scm_from_double (bottom_curve.control_[2][Y_AXIS]),
525                              scm_from_double (bottom_curve.control_[1][X_AXIS]),
526                              scm_from_double (bottom_curve.control_[1][Y_AXIS]),
527                              scm_from_double (bottom_curve.control_[0][X_AXIS]),
528                              scm_from_double (bottom_curve.control_[0][Y_AXIS]),
529                              ly_symbol2scm ("closepath"),
530                              SCM_UNDEFINED);
531
532   SCM horizontal_bend = scm_list_n (ly_symbol2scm ("path"),
533                                     scm_from_double (thickness),
534                                     ly_quote_scm (commands),
535                                     ly_quote_scm (ly_symbol2scm ("round")),
536                                     ly_quote_scm (ly_symbol2scm ("round")),
537                                     SCM_BOOL_T,
538                                     SCM_UNDEFINED);
539
540   Interval x_extent = top_curve.extent (X_AXIS);
541   x_extent.unite (bottom_curve.extent (X_AXIS));
542   Interval y_extent = top_curve.extent (Y_AXIS);
543   y_extent.unite (bottom_curve.extent (Y_AXIS));
544   Box b (x_extent, y_extent);
545
546   b.widen (0.5 * thickness, 0.5 * thickness);
547   return Stencil (b, horizontal_bend);
548 }
549
550 Stencil
551 Lookup::repeat_slash (Real w, Real s, Real t)
552 {
553
554   Real x_width = sqrt ((t * t) + ((t / s) * (t / s)));
555   Real height = w * s;
556
557   SCM controls = scm_list_n (ly_symbol2scm ("moveto"),
558                              scm_from_double (0),
559                              scm_from_double (0),
560                              ly_symbol2scm ("rlineto"),
561                              scm_from_double (x_width),
562                              scm_from_double (0),
563                              ly_symbol2scm ("rlineto"),
564                              scm_from_double (w),
565                              scm_from_double (height),
566                              ly_symbol2scm ("rlineto"),
567                              scm_from_double (-x_width),
568                              scm_from_double (0),
569                              ly_symbol2scm ("closepath"),
570                              SCM_UNDEFINED);
571
572   SCM slashnodot = scm_list_n (ly_symbol2scm ("path"),
573                                scm_from_double (0),
574                                ly_quote_scm (controls),
575                                ly_quote_scm (ly_symbol2scm ("round")),
576                                ly_quote_scm (ly_symbol2scm ("round")),
577                                SCM_BOOL_T,
578                                SCM_UNDEFINED);
579
580   Box b (Interval (0, w + sqrt (sqr (t / s) + sqr (t))),
581          Interval (0, w * s));
582
583   return Stencil (b, slashnodot); //  http://slashnodot.org
584 }
585
586 Stencil
587 Lookup::bracket (Axis a, Interval iv, Real thick, Real protrude, Real blot)
588 {
589   Box b;
590   Axis other = Axis ((a + 1) % 2);
591   b[a] = iv;
592   b[other] = Interval (-1, 1) * thick * 0.5;
593
594   Stencil m = round_filled_box (b, blot);
595
596   b[a] = Interval (iv[UP] - thick, iv[UP]);
597   Interval oi = Interval (-thick / 2, thick / 2 + fabs (protrude));
598   oi *= sign (protrude);
599   b[other] = oi;
600   m.add_stencil (round_filled_box (b, blot));
601   b[a] = Interval (iv[DOWN], iv[DOWN] + thick);
602   m.add_stencil (round_filled_box (b, blot));
603
604   return m;
605 }
606
607 Stencil
608 Lookup::triangle (Interval iv, Real thick, Real protrude)
609 {
610   Box b;
611   b[X_AXIS] = Interval (0, iv.length ());
612   b[Y_AXIS] = Interval (min (0., protrude), max (0.0, protrude));
613
614   vector<Offset> points;
615   points.push_back (Offset (iv[LEFT], 0));
616   points.push_back (Offset (iv[RIGHT], 0));
617   points.push_back (Offset (iv.center (), protrude));
618   points.push_back (Offset (iv[LEFT], 0));  // close triangle
619
620   return points_to_line_stencil (thick, points);
621
622 }
623
624 Stencil
625 Lookup::points_to_line_stencil (Real thick, vector<Offset> const &points)
626 {
627   Stencil ret;
628   for (vsize i = 1; i < points.size (); i++)
629     {
630       if (points[i - 1].is_sane () && points[i].is_sane ())
631         {
632           Stencil line
633             = Line_interface::make_line (thick, points[i - 1], points[i]);
634           ret.add_stencil (line);
635         }
636     }
637   return ret;
638 }