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