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