1 /*
2   This file is part of LilyPond, the GNU music typesetter.
3 
4   Copyright (C) 1997--2021 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 "lily-guile.hh"
31 
32 #include <cctype>
33 #include <cmath>
34 
35 using std::vector;
36 
37 Stencil
beam(Real slope,Real width,Real thick,Real blot)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 (to_scm (p[X_AXIS]),
51                      scm_cons (to_scm (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 (to_scm (p[X_AXIS]),
59                      scm_cons (to_scm (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 (to_scm (p[X_AXIS]),
67                      scm_cons (to_scm (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 (to_scm (p[X_AXIS]),
75                      scm_cons (to_scm (p[Y_AXIS]),
76                                points));
77 
78   SCM expr
79     = scm_list_4 (ly_symbol2scm ("polygon"), points, to_scm (blot), SCM_BOOL_T);
80 
81   return Stencil (b, expr);
82 }
83 
84 Stencil
rotated_box(Real slope,Real width,Real thick,Real blot)85 Lookup::rotated_box (Real slope, Real width, Real thick, Real blot)
86 {
87   vector<Offset> pts;
88   Offset rot = Offset (1, slope).direction ();
89 
90   pts.push_back (Offset (0, -thick / 2) * rot);
91   pts.push_back (Offset (width, -thick / 2) * rot);
92   pts.push_back (Offset (width, thick / 2) * rot);
93   pts.push_back (Offset (0, thick / 2) * rot);
94   return Lookup::round_polygon (pts, blot, -1.0, true);
95 }
96 
97 Stencil
horizontal_line(Interval w,Real th)98 Lookup::horizontal_line (Interval w, Real th)
99 {
100   SCM at = scm_list_n (ly_symbol2scm ("draw-line"),
101                        to_scm (th),
102                        to_scm (w[LEFT]),
103                        to_scm (0),
104                        to_scm (w[RIGHT]),
105                        to_scm (0),
106                        SCM_UNDEFINED);
107 
108   Box box;
109   box[X_AXIS] = w;
110   box[Y_AXIS] = Interval (-th / 2, th / 2);
111 
112   return Stencil (box, at);
113 }
114 
115 Stencil
blank(Box b)116 Lookup::blank (Box b)
117 {
118   return Stencil (b, scm_string (SCM_EOL));
119 }
120 
121 Stencil
circle(Real rad,Real thick,bool filled)122 Lookup::circle (Real rad, Real thick, bool filled)
123 {
124   Box b (Interval (-rad, rad), Interval (-rad, rad));
125   return Stencil (b, scm_list_4 (ly_symbol2scm ("circle"),
126                                  to_scm (rad),
127                                  to_scm (thick),
128                                  scm_from_bool (filled)));
129 }
130 
131 Stencil
filled_box(Box b)132 Lookup::filled_box (Box b)
133 {
134   return round_filled_box (b, 0.0);
135 }
136 
137 /*
138  * round filled box:
139  *
140  *   __________________________________
141  *  /     \  ^           /     \      ^
142  * |         |blot              |     |
143  * |       | |dia       |       |     |
144  * |         |meter             |     |
145  * |\ _ _ /  v           \ _ _ /|     |
146  * |                            |     |
147  * |                            |     | Box
148  * |                    <------>|     | extent
149  * |                      blot  |     | (Y_AXIS)
150  * |                    diameter|     |
151  * |                            |     |
152  * |  _ _                  _ _  |     |
153  * |/     \              /     \|     |
154  * |                            |     |
155  * |       |            |       |     |
156  * |                            |     |
157  * x\_____/______________\_____/|_____v
158  * |(0, 0)                       |
159  * |                            |
160  * |                            |
161  * |<-------------------------->|
162  *       Box extent (X_AXIS)
163  */
164 Stencil
round_filled_box(Box b,Real blotdiameter)165 Lookup::round_filled_box (Box b, Real blotdiameter)
166 {
167   Real width = b.x ().length ();
168   blotdiameter = std::min (blotdiameter, width);
169   Real height = b.y ().length ();
170   blotdiameter = std::min (blotdiameter, height);
171 
172   if (blotdiameter < 0.0)
173     {
174       if (!std::isinf (blotdiameter))
175         warning (_f ("Not drawing a box with negative dimension, %.2f by %.2f.",
176                      width, height));
177       return Stencil (b, SCM_EOL);
178     }
179 
180   SCM at = (scm_list_n (ly_symbol2scm ("round-filled-box"),
181                         to_scm (-b[X_AXIS][LEFT]),
182                         to_scm (b[X_AXIS][RIGHT]),
183                         to_scm (-b[Y_AXIS][DOWN]),
184                         to_scm (b[Y_AXIS][UP]),
185                         to_scm (blotdiameter),
186                         SCM_UNDEFINED));
187 
188   return Stencil (b, at);
189 }
190 
191 /*
192  * Create Stencil that represents a polygon with round edges.
193  *
194  * LIMITATIONS:
195  *
196  * (a) Only outer (convex) edges are rounded.
197  *
198  * (b) This algorithm works as expected only for polygons whose edges
199  * do not intersect.  For example, the polygon ((0, 0), (q, 0), (0,
200  * q), (q, q)) has an intersection at point (q/2, q/2) and therefore
201  * will give a strange result.  Even non-adjacent edges that just
202  * touch each other will in general not work as expected for non-null
203  * blotdiameter.
204  *
205  * (c) Given a polygon ((x0, y0), (x1, y1), ... , (x (n-1), y (n-1))),
206  * if there is a natural number k such that blotdiameter is greater
207  * than the maximum of { | (x (k mod n), y (k mod n)) - (x ((k+1) mod n),
208  * y ((k+1) mod n)) |, | (x (k mod n), y (k mod n)) - (x ((k+2) mod n),
209  * y ((k+2) mod n)) |, | (x ((k+1) mod n), y ((k+1) mod n)) - (x ((k+2)
210  * mod n), y ((k+2) mod n)) | }, then the outline of the rounded
211  * polygon will exceed the outline of the core polygon.  In other
212  * words: Do not draw rounded polygons that have a leg smaller or
213  * thinner than blotdiameter (or set blotdiameter to a sufficiently
214  * small value -- maybe even 0.0)!
215  *
216  * NOTE: Limitations (b) and (c) arise from the fact that round edges
217  * are made by moulding sharp edges to round ones rather than adding
218  * to a core polygon.  For details of these two different
219  * approaches, see the thread upon the ledger lines patch that started
220  * on March 25, 2002 on the devel mailing list.  The below version of
221  * round_polygon () sticks to the moulding model, which the
222  * majority of the list participants finally voted for.  This,
223  * however, results in the above limitations and a much increased
224  * complexity of the algorithm, since it has to compute a shrinked
225  * polygon -- which is not trivial define precisely and unambigously.
226  * With the other approach, one simply could move a circle of size
227  * blotdiameter along all edges of the polygon (which is what the
228  * postscript routine in the backend effectively does, but on the
229  * shrinked polygon). --jr
230  *
231  * An extra parameter "extroversion" has been added since staying just
232  * inside of a polygon will reduce its visual size when tracing a
233  * rounded path.  If extroversion is zero, the polygon is just traced
234  * as-is.  If it is -1 (the default) the drawing will stay just within
235  * the given polygon.  If it is 1, the traced line will stay just
236  * outside of the given polygon.
237  */
238 Stencil
round_polygon(vector<Offset> const & points,Real blotdiameter,Real extroversion,bool filled)239 Lookup::round_polygon (vector<Offset> const &points,
240                        Real blotdiameter,
241                        Real extroversion,
242                        bool filled)
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       const auto 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                                 to_scm (filled));
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 (const auto a : {X_AXIS, Y_AXIS})
391     {
392       const auto o = other_axis (a);
393       for (const auto d : {LEFT, RIGHT})
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               const auto pattern_count
458                 = static_cast<int> (seg_length / dash_period);
459               Real pattern_length = 1.0 / (pattern_count + dash_fraction);
460               Real start_t, end_t;
461               for (int p = 0; p <= pattern_count; p++)
462                 {
463                   start_t = p * pattern_length;
464                   end_t = (p + dash_fraction) * pattern_length;
465                   back_dash
466                     = back_segment.extract (start_t, end_t);
467                   curve_dash
468                     = curve_segment.extract (start_t, end_t);
469                   return_value.add_stencil (bezier_sandwich (back_dash,
470                                                              curve_dash,
471                                                              linethick));
472                 }
473             }
474         }
475     }
476   return return_value;
477 }
478 
479 /*
480  * Bezier Sandwich:
481  *
482  *                               .|
483  *                        .       |
484  *              top .             |
485  *              . curve           |
486  *          .                     |
487  *       .                        |
488  *     .                          |
489  *    |                           |
490  *    |                          .|
491  *    |                     .
492  *    |         bottom .
493  *    |            . curve
494  *    |         .
495  *    |      .
496  *    |   .
497  *    | .
498  *    |.
499  *    |
500  *
501  */
502 Stencil
bezier_sandwich(Bezier top_curve,Bezier bottom_curve,Real thickness)503 Lookup::bezier_sandwich (Bezier top_curve, Bezier bottom_curve, Real thickness)
504 {
505   SCM commands = scm_list_n (ly_symbol2scm ("moveto"),
506                              to_scm (top_curve.control_[0][X_AXIS]),
507                              to_scm (top_curve.control_[0][Y_AXIS]),
508                              ly_symbol2scm ("curveto"),
509                              to_scm (top_curve.control_[1][X_AXIS]),
510                              to_scm (top_curve.control_[1][Y_AXIS]),
511                              to_scm (top_curve.control_[2][X_AXIS]),
512                              to_scm (top_curve.control_[2][Y_AXIS]),
513                              to_scm (top_curve.control_[3][X_AXIS]),
514                              to_scm (top_curve.control_[3][Y_AXIS]),
515                              ly_symbol2scm ("lineto"),
516                              to_scm (bottom_curve.control_[3][X_AXIS]),
517                              to_scm (bottom_curve.control_[3][Y_AXIS]),
518                              ly_symbol2scm ("curveto"),
519                              to_scm (bottom_curve.control_[2][X_AXIS]),
520                              to_scm (bottom_curve.control_[2][Y_AXIS]),
521                              to_scm (bottom_curve.control_[1][X_AXIS]),
522                              to_scm (bottom_curve.control_[1][Y_AXIS]),
523                              to_scm (bottom_curve.control_[0][X_AXIS]),
524                              to_scm (bottom_curve.control_[0][Y_AXIS]),
525                              ly_symbol2scm ("closepath"),
526                              SCM_UNDEFINED);
527 
528   SCM horizontal_bend = scm_list_n (ly_symbol2scm ("path"),
529                                     to_scm (thickness),
530                                     commands,
531                                     ly_symbol2scm ("round"),
532                                     ly_symbol2scm ("round"),
533                                     SCM_BOOL_T,
534                                     SCM_UNDEFINED);
535 
536   Interval x_extent = top_curve.extent (X_AXIS);
537   x_extent.unite (bottom_curve.extent (X_AXIS));
538   Interval y_extent = top_curve.extent (Y_AXIS);
539   y_extent.unite (bottom_curve.extent (Y_AXIS));
540   Box b (x_extent, y_extent);
541 
542   b.widen (0.5 * thickness, 0.5 * thickness);
543   return Stencil (b, horizontal_bend);
544 }
545 
546 Stencil
repeat_slash(Real w,Real s,Real t)547 Lookup::repeat_slash (Real w, Real s, Real t)
548 {
549 
550   Real x_width = hypot (t, t / s);
551   Real height = w * s;
552 
553   SCM controls = scm_list_n (ly_symbol2scm ("moveto"),
554                              to_scm (0),
555                              to_scm (0),
556                              ly_symbol2scm ("rlineto"),
557                              to_scm (x_width),
558                              to_scm (0),
559                              ly_symbol2scm ("rlineto"),
560                              to_scm (w),
561                              to_scm (height),
562                              ly_symbol2scm ("rlineto"),
563                              to_scm (-x_width),
564                              to_scm (0),
565                              ly_symbol2scm ("closepath"),
566                              SCM_UNDEFINED);
567 
568   SCM slashnodot = scm_list_n (ly_symbol2scm ("path"),
569                                to_scm (0),
570                                controls,
571                                ly_symbol2scm ("round"),
572                                ly_symbol2scm ("round"),
573                                SCM_BOOL_T,
574                                SCM_UNDEFINED);
575 
576   Box b (Interval (0, w + x_width),
577          Interval (0, height));
578 
579   return Stencil (b, slashnodot); //  http://slashnodot.org
580 }
581 
582 Stencil
bracket(Axis a,Interval iv,Real thick,Real protrude,Real blot)583 Lookup::bracket (Axis a, Interval iv, Real thick, Real protrude, Real blot)
584 {
585   Box b;
586   Axis other = other_axis (a);
587   b[a] = iv;
588   b[other] = Interval (-1, 1) * thick * 0.5;
589 
590   Stencil m = round_filled_box (b, blot);
591 
592   b[a] = Interval (iv[UP] - thick, iv[UP]);
593   Interval oi = Interval (-thick / 2, thick / 2 + fabs (protrude));
594   oi *= sign (protrude);
595   b[other] = oi;
596   m.add_stencil (round_filled_box (b, blot));
597   b[a] = Interval (iv[DOWN], iv[DOWN] + thick);
598   m.add_stencil (round_filled_box (b, blot));
599 
600   return m;
601 }
602 
603 Stencil
triangle(Interval iv,Real thick,Real protrude)604 Lookup::triangle (Interval iv, Real thick, Real protrude)
605 {
606   Box b;
607   b[X_AXIS] = Interval (0, iv.length ());
608   b[Y_AXIS] = Interval (std::min (0., protrude), std::max (0.0, protrude));
609 
610   vector<Offset> points;
611   points.push_back (Offset (iv[LEFT], 0));
612   points.push_back (Offset (iv[RIGHT], 0));
613   points.push_back (Offset (iv.center (), protrude));
614   points.push_back (Offset (iv[LEFT], 0));  // close triangle
615 
616   return points_to_line_stencil (thick, points);
617 
618 }
619 
620 Stencil
points_to_line_stencil(Real thick,vector<Offset> const & points)621 Lookup::points_to_line_stencil (Real thick, vector<Offset> const &points)
622 {
623   Stencil ret;
624   for (vsize i = 1; i < points.size (); i++)
625     {
626       if (points[i - 1].is_sane () && points[i].is_sane ())
627         {
628           Stencil line
629             = Line_interface::make_line (thick, points[i - 1], points[i]);
630           ret.add_stencil (line);
631         }
632     }
633   return ret;
634 }
635