]> git.donarmstrong.com Git - lilypond.git/blob - lily/beam.cc
handle CID CFFs.
[lilypond.git] / lily / beam.cc
1 /*
2   beam.cc -- implement Beam
3
4   source file of the GNU LilyPond music typesetter
5
6   (c) 1997--2005 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7   Jan Nieuwenhuizen <janneke@gnu.org>
8 */
9
10 /*
11   TODO:
12
13   - Determine auto knees based on positions if it's set by the user.
14
15   - the code is littered with * and / staff_space calls for
16   #'positions. Consider moving to real-world coordinates?
17
18   Problematic issue is user tweaks (user tweaks are in staff-coordinates.)
19
20   Notes:
21
22   - Stems run to the Y-center of the beam.
23
24   - beam_translation is the offset between Y centers of the beam.
25 */
26
27 #include <math.h> // tanh.
28
29 #include "beam.hh"
30 #include "interval-set.hh"
31 #include "directional-element-interface.hh"
32 #include "beaming.hh"
33 #include "misc.hh"
34 #include "least-squares.hh"
35 #include "stem.hh"
36 #include "output-def.hh"
37 #include "lookup.hh"
38 #include "group-interface.hh"
39 #include "staff-symbol-referencer.hh"
40 #include "item.hh"
41 #include "spanner.hh"
42 #include "warn.hh"
43
44 #if DEBUG_QUANTING
45 #include "text-item.hh" // debug output.
46 #include "font-interface.hh" // debug output.
47 #endif
48
49 void
50 Beam::add_stem (Grob *me, Grob *s)
51 {
52   Pointer_group_interface::add_grob (me, ly_symbol2scm ("stems"), s);
53
54   s->add_dependency (me);
55
56   assert (!Stem::get_beam (s));
57   s->set_property ("beam", me->self_scm ());
58
59   add_bound_item (dynamic_cast<Spanner *> (me), dynamic_cast<Item *> (s));
60 }
61
62 Real
63 Beam::get_thickness (Grob *me)
64 {
65   return robust_scm2double (me->get_property ("thickness"), 0)
66     * Staff_symbol_referencer::staff_space (me);
67 }
68
69 /* Return the translation between 2 adjoining beams. */
70 Real
71 Beam::get_beam_translation (Grob *me)
72 {
73   SCM func = me->get_property ("space-function");
74
75   if (ly_c_procedure_p (func))
76     {
77       SCM s = scm_call_2 (func, me->self_scm (), scm_int2num (get_beam_count (me)));
78       return scm_to_double (s);
79     }
80   else
81     {
82       return 0.81;
83     }
84 }
85
86 /* Maximum beam_count. */
87 int
88 Beam::get_beam_count (Grob *me)
89 {
90   int m = 0;
91   for (SCM s = me->get_property ("stems"); scm_is_pair (s); s = scm_cdr (s))
92     {
93       Grob *stem = unsmob_grob (scm_car (s));
94       m = max (m, (Stem::beam_multiplicity (stem).length () + 1));
95     }
96   return m;
97 }
98
99 /*
100   Space return space between beams.
101 */
102 MAKE_SCHEME_CALLBACK (Beam, space_function, 2);
103 SCM
104 Beam::space_function (SCM smob, SCM beam_count)
105 {
106   Grob *me = unsmob_grob (smob);
107
108   Real staff_space = Staff_symbol_referencer::staff_space (me);
109   Real line = Staff_symbol_referencer::line_thickness (me);
110   Real thickness = get_thickness (me);
111
112   Real beam_translation = scm_to_int (beam_count) < 4
113     ? (2 * staff_space + line - thickness) / 2.0
114     : (3 * staff_space + line - thickness) / 3.0;
115
116   return scm_make_real (beam_translation);
117 }
118
119 /* After pre-processing all directions should be set.
120    Several post-processing routines (stem, slur, script) need stem/beam
121    direction.
122    Currenly, this means that beam has set all stem's directions.
123    [Alternatively, stems could set its own directions, according to
124    their beam, during 'final-pre-processing'.] */
125 MAKE_SCHEME_CALLBACK (Beam, before_line_breaking, 1);
126 SCM
127 Beam::before_line_breaking (SCM smob)
128 {
129   Grob *me = unsmob_grob (smob);
130
131   /* Beams with less than 2 two stems don't make much sense, but could happen
132      when you do
133
134      [r8 c8 r8].
135
136      For a beam that  only has one stem, we try to do some disappearance magic:
137      we revert the flag, and move on to The Eternal Engraving Fields. */
138
139   int count = visible_stem_count (me);
140   if (count < 2)
141     {
142       me->warning (_ ("beam has less than two visible stems"));
143
144       SCM stems = me->get_property ("stems");
145       if (scm_ilength (stems) == 1)
146         {
147           me->warning (_ ("removing beam with less than two stems"));
148
149           unsmob_grob (scm_car (stems))->set_property ("beam", SCM_EOL);
150           me->suicide ();
151
152           return SCM_UNSPECIFIED;
153         }
154       else if (scm_ilength (stems) == 0)
155         {
156           me->suicide ();
157           return SCM_UNSPECIFIED;
158         }
159     }
160   if (count >= 1)
161     {
162       Direction d = get_default_dir (me);
163
164       consider_auto_knees (me);
165       set_stem_directions (me, d);
166
167       connect_beams (me);
168
169       set_stem_shorten (me);
170     }
171
172   return SCM_EOL;
173 }
174
175 /* We want a maximal number of shared beams, but if there is choice, we
176  * take the one that is closest to the end of the stem. This is for
177  * situations like
178  *
179  *        x
180  *       |
181  *       |
182  *   |===|
183  *   |=
184  *   |
185  *  x
186  */
187 int
188 position_with_maximal_common_beams (SCM left_beaming, SCM right_beaming,
189                                     Direction left_dir,
190                                     Direction right_dir)
191 {
192   Slice lslice = int_list_to_slice (scm_cdr (left_beaming));
193
194   int best_count = 0;
195   int best_start = 0;
196   for (int i = lslice[-left_dir];
197        (i - lslice[left_dir]) * left_dir <= 0; i += left_dir)
198     {
199       int count = 0;
200       for (SCM s = scm_car (right_beaming); scm_is_pair (s); s = scm_cdr (s))
201         {
202           int k = -right_dir * scm_to_int (scm_car (s)) + i;
203           if (scm_c_memq (scm_int2num (k), left_beaming) != SCM_BOOL_F)
204             count++;
205         }
206
207       if (count >= best_count)
208         {
209           best_count = count;
210           best_start = i;
211         }
212     }
213
214   return best_start;
215 }
216
217 void
218 Beam::connect_beams (Grob *me)
219 {
220   Link_array<Grob> stems
221     = extract_grob_array (me, ly_symbol2scm ("stems"));
222
223   Slice last_int;
224   last_int.set_empty ();
225   SCM last_beaming = SCM_EOL;
226   Direction last_dir = CENTER;
227   for (int i = 0; i < stems.size (); i++)
228     {
229       Grob *this_stem = stems[i];
230       SCM this_beaming = this_stem->get_property ("beaming");
231
232       Direction this_dir = get_grob_direction (this_stem);
233       if (scm_is_pair (last_beaming) && scm_is_pair (this_beaming))
234         {
235           int start_point = position_with_maximal_common_beams
236             (last_beaming, this_beaming,
237              last_dir, this_dir);
238
239           Direction d = LEFT;
240           Slice new_slice;
241           do
242             {
243               if (d == RIGHT && i == stems.size () - 1)
244                 continue;
245
246               new_slice.set_empty ();
247               SCM s = index_get_cell (this_beaming, d);
248               for (; scm_is_pair (s); s = scm_cdr (s))
249                 {
250                   int new_beam_pos
251                     = start_point - this_dir * scm_to_int (scm_car (s));
252
253                   new_slice.add_point (new_beam_pos);
254                   scm_set_car_x (s, scm_int2num (new_beam_pos));
255                 }
256             }
257           while (flip (&d) != LEFT);
258
259           if (!new_slice.is_empty ())
260             last_int = new_slice;
261         }
262       else
263         {
264           scm_set_car_x (this_beaming, SCM_EOL);
265           SCM s = scm_cdr (this_beaming);
266           for (; scm_is_pair (s); s = scm_cdr (s))
267             {
268               int np = -this_dir * scm_to_int (scm_car (s));
269               scm_set_car_x (s, scm_int2num (np));
270               last_int.add_point (np);
271             }
272         }
273
274       if (i == stems.size () -1)
275         {
276           scm_set_cdr_x (this_beaming, SCM_EOL);
277         }
278
279       if (scm_ilength (scm_cdr (this_beaming)) > 0)
280         {
281           last_beaming = this_beaming;
282           last_dir = this_dir;
283         }
284     }
285 }
286
287 /*
288   TODO: should not make beams per stem, but per Y-level.
289 */
290 MAKE_SCHEME_CALLBACK (Beam, print, 1);
291 SCM
292 Beam::print (SCM grob)
293 {
294   Spanner *me = unsmob_spanner (grob);
295   position_beam (me);
296
297   Link_array<Grob> stems
298     = extract_grob_array (me, ly_symbol2scm ("stems"));
299   Grob *xcommon = common_refpoint_of_array (stems, me, X_AXIS);
300
301   xcommon = me->get_bound (LEFT)->common_refpoint (xcommon, X_AXIS);
302   xcommon = me->get_bound (RIGHT)->common_refpoint (xcommon, X_AXIS);
303
304   Real x0, dx;
305   if (visible_stem_count (me))
306     {
307       // ugh -> use commonx
308       x0 = first_visible_stem (me)->relative_coordinate (xcommon, X_AXIS);
309       dx = last_visible_stem (me)->relative_coordinate (xcommon, X_AXIS) - x0;
310     }
311   else
312     {
313       x0 = stems[0]->relative_coordinate (xcommon, X_AXIS);
314       dx = stems.top ()->relative_coordinate (xcommon, X_AXIS) - x0;
315     }
316
317   SCM posns = me->get_property ("positions");
318   Drul_array<Real> pos;
319   if (!is_number_pair (posns))
320     {
321       programming_error ("no beam positions?");
322       pos = Interval (0, 0);
323     }
324   else
325     pos = ly_scm2realdrul (posns);
326
327   scale_drul (&pos, Staff_symbol_referencer::staff_space (me));
328
329   Real dy = pos[RIGHT] - pos[LEFT];
330   Real slope = (dy && dx) ? dy / dx : 0;
331
332   Real thick = get_thickness (me);
333   Real bdy = get_beam_translation (me);
334
335   SCM last_beaming = SCM_EOL;
336   Real last_xposn = -1;
337   Real last_stem_width = -1;
338
339   Real gap_length = robust_scm2double (me->get_property ("gap"), 0.0);
340
341   Stencil the_beam;
342   Real lt = me->get_layout ()->get_dimension (ly_symbol2scm ("linethickness"));
343
344   for (int i = 0; i <= stems.size (); i++)
345     {
346       Grob *st = (i < stems.size ()) ? stems[i] : 0;
347
348       SCM this_beaming = st ? st->get_property ("beaming") : SCM_EOL;
349       Real xposn = st ? st->relative_coordinate (xcommon, X_AXIS) : 0.0;
350       Real stem_width = st ? robust_scm2double (st->get_property ("thickness"), 1.0) * lt : 0;
351       Direction stem_dir = st ? to_dir (st->get_property ("direction")) : CENTER;
352       /*
353         We do the space left of ST, with lfliebertjes pointing to the
354         right from the left stem, and rfliebertjes pointing left from
355         right stem.
356       */
357       SCM left = (i > 0) ? scm_cdr (last_beaming) : SCM_EOL;
358       SCM right = st ? scm_car (this_beaming) : SCM_EOL;
359
360       Array<int> full_beams;
361       Array<int> lfliebertjes;
362       Array<int> rfliebertjes;
363
364       for (SCM s = left;
365            scm_is_pair (s); s = scm_cdr (s))
366         {
367           int b = scm_to_int (scm_car (s));
368           if (scm_c_memq (scm_car (s), right) != SCM_BOOL_F)
369             {
370               full_beams.push (b);
371             }
372           else
373             {
374               lfliebertjes.push (b);
375             }
376         }
377       for (SCM s = right;
378            scm_is_pair (s); s = scm_cdr (s))
379         {
380           int b = scm_to_int (scm_car (s));
381           if (scm_c_memq (scm_car (s), left) == SCM_BOOL_F)
382             {
383               rfliebertjes.push (b);
384             }
385         }
386
387       /*
388         how much to stick out for beams across linebreaks
389       */
390       Real break_overshoot = 3.0;
391       Real w = (i > 0 && st) ? (xposn - last_xposn) : break_overshoot;
392
393       Real stem_offset = 0.0;
394       if (i > 0)
395         {
396           w += last_stem_width / 2;
397           stem_offset = -last_stem_width / 2;
398         }
399
400       if (st)
401         w += stem_width / 2;
402
403       Real blot = me->get_layout ()->get_dimension (ly_symbol2scm ("blotdiameter"));
404       Stencil whole = Lookup::beam (slope, w, thick, blot);
405       Stencil gapped;
406
407       int gap_count = 0;
408       if (scm_is_number (me->get_property ("gap-count")))
409         {
410           gap_count = scm_to_int (me->get_property ("gap-count"));
411           gapped = Lookup::beam (slope, w - 2 * gap_length, thick, blot);
412
413           full_beams.sort (default_compare);
414           if (stem_dir == UP)
415             full_beams.reverse ();
416         }
417
418       int k = 0;
419       for (int j = full_beams.size (); j--;)
420         {
421           Stencil b (whole);
422
423           if (k++ < gap_count)
424             {
425               b = gapped;
426               b.translate_axis (gap_length, X_AXIS);
427             }
428           b.translate_axis (last_xposn - x0 + stem_offset, X_AXIS);
429           b.translate_axis (slope * (last_xposn - x0) + bdy * full_beams[j], Y_AXIS);
430
431           the_beam.add_stencil (b);
432         }
433
434       if (lfliebertjes.size () || rfliebertjes.size ())
435         {
436           Real nw_f;
437
438           if (st)
439             {
440               int t = Stem::duration_log (st);
441
442               SCM proc = me->get_property ("flag-width-function");
443               SCM result = scm_call_1 (proc, scm_int2num (t));
444               nw_f = scm_to_double (result);
445             }
446           else
447             nw_f = break_overshoot / 2;
448
449           /* Half beam should be one note-width,
450              but let's make sure two half-beams never touch */
451           Real lw = nw_f;
452           Real rw = nw_f;
453           if (i > 0)
454             rw = min (nw_f, ((xposn - last_xposn) / 2));
455           else
456             /*
457               TODO: 0.5 is a guess.
458             */
459             rw = xposn - me->get_bound (LEFT)->extent (xcommon, X_AXIS)[RIGHT]
460               - 0.5;
461
462           if (st)
463             lw = min (nw_f, ((xposn - last_xposn) / 2));
464           else
465             lw = me->get_bound (RIGHT)->relative_coordinate (xcommon, X_AXIS)
466               - last_xposn;
467
468           Stencil rhalf = Lookup::beam (slope, rw, thick, blot);
469           Stencil lhalf = Lookup::beam (slope, lw, thick, blot);
470           for (int j = lfliebertjes.size (); j--;)
471             {
472               Stencil b (lhalf);
473               b.translate_axis (last_xposn - x0, X_AXIS);
474               b.translate_axis (slope * (last_xposn - x0) + bdy * lfliebertjes[j], Y_AXIS);
475               the_beam.add_stencil (b);
476             }
477           for (int j = rfliebertjes.size (); j--;)
478             {
479               Stencil b (rhalf);
480               b.translate_axis (xposn - x0 - rw, X_AXIS);
481               b.translate_axis (slope * (xposn - x0 -rw) + bdy * rfliebertjes[j], Y_AXIS);
482               the_beam.add_stencil (b);
483             }
484         }
485
486       last_xposn = xposn;
487       last_stem_width = stem_width;
488       last_beaming = this_beaming;
489     }
490
491   the_beam.translate_axis (x0 - me->relative_coordinate (xcommon, X_AXIS), X_AXIS);
492   the_beam.translate_axis (pos[LEFT], Y_AXIS);
493
494 #if (DEBUG_QUANTING)
495   SCM quant_score = me->get_property ("quant-score");
496   if (to_boolean (me->get_layout ()->lookup_variable (ly_symbol2scm ("debug-beam-quanting")))
497       && scm_is_string (quant_score))
498     {
499
500       /*
501         This code prints the demerits for each beam. Perhaps this
502         should be switchable for those who want to twiddle with the
503         parameters.
504       */
505       String str;
506       SCM properties = Font_interface::text_font_alist_chain (me);
507
508       Direction stem_dir = stems.size () ? to_dir (stems[0]->get_property ("direction")) : UP;
509
510       Stencil tm = *unsmob_stencil (Text_interface::interpret_markup
511                                     (me->get_layout ()->self_scm (), properties, quant_score));
512       the_beam.add_at_edge (Y_AXIS, stem_dir, tm, 1.0, 0);
513     }
514 #endif
515
516   return the_beam.smobbed_copy ();
517 }
518
519 Direction
520 Beam::get_default_dir (Grob *me)
521 {
522   Drul_array<int> total;
523   total[UP] = total[DOWN] = 0;
524   Drul_array<int> count;
525   count[UP] = count[DOWN] = 0;
526   Direction d = DOWN;
527
528   Link_array<Grob> stems
529     = extract_grob_array (me, ly_symbol2scm ("stems"));
530
531   for (int i = 0; i < stems.size (); i++)
532     do
533       {
534         Grob *s = stems[i];
535         Direction sd = get_grob_direction (s);
536
537         int center_distance = max (int (- d * Stem::head_positions (s) [-d]), 0);
538         int current = sd ? (1 + d * sd) / 2 : center_distance;
539
540         if (current)
541           {
542             total[d] += current;
543             count[d]++;
544           }
545       }
546     while (flip (&d) != DOWN);
547
548   SCM func = me->get_property ("dir-function");
549   SCM s = scm_call_2 (func,
550                       scm_cons (scm_int2num (count[UP]),
551                                 scm_int2num (count[DOWN])),
552                       scm_cons (scm_int2num (total[UP]),
553                                 scm_int2num (total[DOWN])));
554
555   if (scm_is_number (s) && scm_to_int (s))
556     return to_dir (s);
557
558   /* If dir is not determined: get default */
559   return to_dir (me->get_property ("neutral-direction"));
560 }
561
562 /* Set all stems with non-forced direction to beam direction.
563    Urg: non-forced should become `without/with unforced' direction,
564    once stem gets cleaned-up. */
565 void
566 Beam::set_stem_directions (Grob *me, Direction d)
567 {
568   Link_array<Grob> stems
569     = extract_grob_array (me, ly_symbol2scm ("stems"));
570
571   for (int i = 0; i < stems.size (); i++)
572     {
573       Grob *s = stems[i];
574
575       SCM forcedir = s->get_property ("direction");
576       if (!to_dir (forcedir))
577         set_grob_direction (s, d);
578     }
579 }
580
581 /*
582   Only try horizontal beams for knees.  No reliable detection of
583   anything else is possible here, since we don't know funky-beaming
584   settings, or X-distances (slopes!)  People that want sloped
585   knee-beams, should set the directions manually.
586
587
588   TODO:
589
590   this routine should take into account the stemlength scoring
591   of a possible knee/nonknee beam.
592 */
593 void
594 Beam::consider_auto_knees (Grob *me)
595 {
596   SCM scm = me->get_property ("auto-knee-gap");
597   if (!scm_is_number (scm))
598     return;
599
600   Interval_set gaps;
601
602   gaps.set_full ();
603
604   Link_array<Grob> stems
605     = extract_grob_array (me, ly_symbol2scm ("stems"));
606
607   Grob *common = common_refpoint_of_array (stems, me, Y_AXIS);
608   Real staff_space = Staff_symbol_referencer::staff_space (me);
609
610   Array<Interval> head_extents_array;
611   for (int i = 0; i < stems.size (); i++)
612     {
613       Grob *stem = stems[i];
614       if (Stem::is_invisible (stem))
615         continue;
616
617       Interval head_extents = Stem::head_positions (stem);
618       if (!head_extents.is_empty ())
619         {
620           head_extents[LEFT] += -1;
621           head_extents[RIGHT] += 1;
622           head_extents *= staff_space * 0.5;
623
624           /*
625             We could subtract beam Y position, but this routine only
626             sets stem directions, a constant shift does not have an
627             influence.
628           */
629           head_extents += stem->relative_coordinate (common, Y_AXIS);
630
631           if (to_dir (stem->get_property ("direction")))
632             {
633               Direction stemdir = to_dir (stem->get_property ("direction"));
634               head_extents[-stemdir] = -stemdir * infinity_f;
635             }
636         }
637       head_extents_array.push (head_extents);
638
639       gaps.remove_interval (head_extents);
640     }
641
642   Interval max_gap;
643   Real max_gap_len = 0.0;
644
645   for (int i = gaps.allowed_regions_.size () -1; i >= 0; i--)
646     {
647       Interval gap = gaps.allowed_regions_[i];
648
649       /*
650         the outer gaps are not knees.
651       */
652       if (isinf (gap[LEFT]) || isinf (gap[RIGHT]))
653         continue;
654
655       if (gap.length () >= max_gap_len)
656         {
657           max_gap_len = gap.length ();
658           max_gap = gap;
659         }
660     }
661
662   Real beam_translation = get_beam_translation (me);
663   Real beam_thickness = Beam::get_thickness (me);
664   int beam_count = Beam::get_beam_count (me);
665   Real height_of_beams = beam_thickness / 2
666     + (beam_count - 1) * beam_translation;
667   Real threshold = scm_to_double (scm) + height_of_beams;
668
669   if (max_gap_len > threshold)
670     {
671       int j = 0;
672       for (int i = 0; i < stems.size (); i++)
673         {
674           Grob *stem = stems[i];
675           if (Stem::is_invisible (stem))
676             continue;
677
678           Interval head_extents = head_extents_array[j++];
679
680           Direction d = (head_extents.center () < max_gap.center ())
681             ? UP : DOWN;
682
683           stem->set_property ("direction", scm_int2num (d));
684
685           head_extents.intersect (max_gap);
686           assert (head_extents.is_empty () || head_extents.length () < 1e-6);
687         }
688     }
689 }
690
691 /* Set stem's shorten property if unset.
692
693 TODO:
694 take some y-position (chord/beam/nearest?) into account
695 scmify forced-fraction
696
697 This is done in beam because the shorten has to be uniform over the
698 entire beam.
699 */
700 void
701 Beam::set_stem_shorten (Grob *me)
702 {
703   /*
704     shortening looks silly for x staff beams
705   */
706   if (is_knee (me))
707     return;
708
709   Real forced_fraction = 1.0 * forced_stem_count (me)
710     / visible_stem_count (me);
711
712   int beam_count = get_beam_count (me);
713
714   SCM shorten_list = me->get_property ("beamed-stem-shorten");
715   if (shorten_list == SCM_EOL)
716     return;
717
718   Real staff_space = Staff_symbol_referencer::staff_space (me);
719
720   SCM shorten_elt
721     = robust_list_ref (beam_count -1, shorten_list);
722   Real shorten_f = scm_to_double (shorten_elt) * staff_space;
723
724   /* your similar cute comment here */
725   shorten_f *= forced_fraction;
726
727   if (shorten_f)
728     me->set_property ("shorten", scm_make_real (shorten_f));
729 }
730
731 /*  Call list of y-dy-callbacks, that handle setting of
732     grob-properties
733 */
734 MAKE_SCHEME_CALLBACK (Beam, after_line_breaking, 1);
735 SCM
736 Beam::after_line_breaking (SCM smob)
737 {
738   Grob *me = unsmob_grob (smob);
739
740   position_beam (me);
741   return SCM_UNSPECIFIED;
742 }
743
744 void
745 Beam::position_beam (Grob *me)
746 {
747   if (!me->is_live ())
748     return;
749   if (to_boolean (me->get_property ("positioning-done")))
750     return;
751
752   me->set_property ("positioning-done", SCM_BOOL_T);
753
754   /* Copy to mutable list. */
755   SCM s = ly_deep_copy (me->get_property ("positions"));
756   me->set_property ("positions", s);
757
758   if (scm_car (s) == SCM_BOOL_F)
759     {
760       // one wonders if such genericity is necessary  --hwn.
761       SCM callbacks = me->get_property ("position-callbacks");
762       for (SCM i = callbacks; scm_is_pair (i); i = scm_cdr (i))
763         scm_call_1 (scm_car (i), me->self_scm ());
764     }
765
766   set_stem_lengths (me);
767 }
768
769 void
770 set_minimum_dy (Grob *me, Real *dy)
771 {
772   if (*dy)
773     {
774       /*
775         If dy is smaller than the smallest quant, we
776         get absurd direction-sign penalties.
777       */
778
779       Real ss = Staff_symbol_referencer::staff_space (me);
780       Real thickness = Beam::get_thickness (me) / ss;
781       Real slt = Staff_symbol_referencer::line_thickness (me) / ss;
782       Real sit = (thickness - slt) / 2;
783       Real inter = 0.5;
784       Real hang = 1.0 - (thickness - slt) / 2;
785
786       *dy = sign (*dy) * max (fabs (*dy),
787                               min (min (sit, inter), hang));
788     }
789 }
790
791 /*
792   Compute  a first approximation to the beam slope.
793 */
794 MAKE_SCHEME_CALLBACK (Beam, least_squares, 1);
795 SCM
796 Beam::least_squares (SCM smob)
797 {
798   Grob *me = unsmob_grob (smob);
799
800   int count = visible_stem_count (me);
801   Interval pos (0, 0);
802
803   if (count < 1)
804     {
805       me->set_property ("positions", ly_interval2scm (pos));
806       return SCM_UNSPECIFIED;
807     }
808
809   Array<Real> x_posns;
810   Link_array<Grob> stems
811     = extract_grob_array (me, ly_symbol2scm ("stems"));
812   Grob *commonx = common_refpoint_of_array (stems, me, X_AXIS);
813   Grob *commony = common_refpoint_of_array (stems, me, Y_AXIS);
814
815   Real my_y = me->relative_coordinate (commony, Y_AXIS);
816
817   Grob *fvs = first_visible_stem (me);
818   Grob *lvs = last_visible_stem (me);
819
820   Interval ideal (Stem::get_stem_info (fvs).ideal_y_
821                   + fvs->relative_coordinate (commony, Y_AXIS) -my_y,
822                   Stem::get_stem_info (lvs).ideal_y_
823                   + lvs->relative_coordinate (commony, Y_AXIS) - my_y);
824
825   Real x0 = first_visible_stem (me)->relative_coordinate (commonx, X_AXIS);
826   for (int i = 0; i < stems.size (); i++)
827     {
828       Grob *s = stems[i];
829
830       Real x = s->relative_coordinate (commonx, X_AXIS) - x0;
831       x_posns.push (x);
832     }
833   Real dx = last_visible_stem (me)->relative_coordinate (commonx, X_AXIS) - x0;
834
835   Real y = 0;
836   Real slope = 0;
837   Real dy = 0;
838
839   if (!ideal.delta ())
840     {
841       Interval chord (Stem::chord_start_y (first_visible_stem (me)),
842                       Stem::chord_start_y (last_visible_stem (me)));
843
844       /* Simple beams (2 stems) on middle line should be allowed to be
845          slightly sloped.
846
847          However, if both stems reach middle line,
848          ideal[LEFT] == ideal[RIGHT] and ideal.delta () == 0.
849
850          For that case, we apply artificial slope */
851       if (!ideal[LEFT] && chord.delta () && count == 2)
852         {
853           /* FIXME. -> UP */
854           Direction d = (Direction) (sign (chord.delta ()) * UP);
855           pos[d] = get_thickness (me) / 2;
856           pos[-d] = -pos[d];
857         }
858       else
859         {
860           pos = ideal;
861         }
862
863       /*
864         For broken beams this doesn't work well. In this case, the
865         slope esp. of the first part of a broken beam should predict
866         where the second part goes.
867       */
868       me->set_property ("least-squares-dy",
869                         scm_make_real (pos[RIGHT] - pos[LEFT]));
870     }
871   else
872     {
873       Array<Offset> ideals;
874       for (int i = 0; i < stems.size (); i++)
875         {
876           Grob *s = stems[i];
877           if (Stem::is_invisible (s))
878             continue;
879           ideals.push (Offset (x_posns[i],
880                                Stem::get_stem_info (s).ideal_y_
881                                + s->relative_coordinate (commony, Y_AXIS)
882                                - my_y));
883         }
884
885       minimise_least_squares (&slope, &y, ideals);
886
887       dy = slope * dx;
888
889       set_minimum_dy (me, &dy);
890       me->set_property ("least-squares-dy", scm_make_real (dy));
891       pos = Interval (y, (y + dy));
892     }
893
894   /*
895     "position" is relative to the staff.
896   */
897   scale_drul (&pos, 1 / Staff_symbol_referencer::staff_space (me));
898
899   me->set_property ("positions", ly_interval2scm (pos));
900
901   return SCM_UNSPECIFIED;
902 }
903
904 /*
905   We can't combine with previous function, since check concave and
906   slope damping comes first.
907
908   TODO: we should use the concaveness to control the amount of damping
909   applied.
910 */
911 MAKE_SCHEME_CALLBACK (Beam, shift_region_to_valid, 1);
912 SCM
913 Beam::shift_region_to_valid (SCM grob)
914 {
915   Grob *me = unsmob_grob (grob);
916   /*
917     Code dup.
918   */
919   Array<Real> x_posns;
920   Link_array<Grob> stems
921     = extract_grob_array (me, ly_symbol2scm ("stems"));
922   Grob *commonx = common_refpoint_of_array (stems, me, X_AXIS);
923   Grob *commony = common_refpoint_of_array (stems, me, Y_AXIS);
924
925   Grob *fvs = first_visible_stem (me);
926
927   if (!fvs)
928     return SCM_UNSPECIFIED;
929
930   Real x0 = fvs->relative_coordinate (commonx, X_AXIS);
931   for (int i = 0; i < stems.size (); i++)
932     {
933       Grob *s = stems[i];
934
935       Real x = s->relative_coordinate (commonx, X_AXIS) - x0;
936       x_posns.push (x);
937     }
938
939   Grob *lvs = last_visible_stem (me);
940   if (!lvs)
941     return SCM_UNSPECIFIED;
942
943   Real dx = lvs->relative_coordinate (commonx, X_AXIS) - x0;
944
945   Drul_array<Real> pos = ly_scm2interval (me->get_property ("positions"));
946
947   scale_drul (&pos, Staff_symbol_referencer::staff_space (me));
948
949   Real dy = pos[RIGHT] - pos[LEFT];
950   Real y = pos[LEFT];
951   Real slope = dy / dx;
952
953   /*
954     Shift the positions so that we have a chance of finding good
955     quants (i.e. no short stem failures.)
956   */
957   Interval feasible_left_point;
958   feasible_left_point.set_full ();
959   for (int i = 0; i < stems.size (); i++)
960     {
961       Grob *s = stems[i];
962       if (Stem::is_invisible (s))
963         continue;
964
965       Direction d = Stem::get_direction (s);
966
967       Real left_y
968         = Stem::get_stem_info (s).shortest_y_
969         - slope * x_posns [i];
970
971       /*
972         left_y is now relative to the stem S. We want relative to
973         ourselves, so translate:
974       */
975       left_y
976         += + s->relative_coordinate (commony, Y_AXIS)
977         - me->relative_coordinate (commony, Y_AXIS);
978
979       Interval flp;
980       flp.set_full ();
981       flp[-d] = left_y;
982
983       feasible_left_point.intersect (flp);
984     }
985
986   if (feasible_left_point.is_empty ())
987     warning (_ ("no viable initial configuration found: may not find good beam slope"));
988   else if (!feasible_left_point.contains (y))
989     {
990       if (isinf (feasible_left_point[DOWN]))
991         y = feasible_left_point[UP] - REGION_SIZE;
992       else if (isinf (feasible_left_point[UP]))
993         y = feasible_left_point[DOWN]+ REGION_SIZE;
994       else
995         y = feasible_left_point.center ();
996     }
997
998   pos = Drul_array<Real> (y, (y + dy));
999   scale_drul (&pos, 1 / Staff_symbol_referencer::staff_space (me));
1000
1001   me->set_property ("positions", ly_interval2scm (pos));
1002   return SCM_UNSPECIFIED;
1003 }
1004
1005 /* This neat trick is by Werner Lemberg,
1006    damped = tanh (slope)
1007    corresponds with some tables in [Wanske] CHECKME */
1008 MAKE_SCHEME_CALLBACK (Beam, slope_damping, 1);
1009 SCM
1010 Beam::slope_damping (SCM smob)
1011 {
1012   Grob *me = unsmob_grob (smob);
1013
1014   if (visible_stem_count (me) <= 1)
1015     return SCM_UNSPECIFIED;
1016
1017   SCM s = me->get_property ("damping");
1018   Real damping = scm_to_double (s);
1019
1020   if (damping)
1021     {
1022       Drul_array<Real> pos = ly_scm2interval (me->get_property ("positions"));
1023       scale_drul (&pos, Staff_symbol_referencer::staff_space (me));
1024
1025       Real dy = pos[RIGHT] - pos[LEFT];
1026
1027       Grob *fvs = first_visible_stem (me);
1028       Grob *lvs = last_visible_stem (me);
1029
1030       Grob *commonx = fvs->common_refpoint (lvs, X_AXIS);
1031
1032       Real dx = last_visible_stem (me)->relative_coordinate (commonx, X_AXIS)
1033         - first_visible_stem (me)->relative_coordinate (commonx, X_AXIS);
1034
1035       Real slope = dy && dx ? dy / dx : 0;
1036
1037       Real concaveness = robust_scm2double (me->get_property ("concaveness"), 0.0);
1038
1039       slope = 0.6 * tanh (slope) / (damping + concaveness);
1040
1041       Real damped_dy = slope * dx;
1042
1043       set_minimum_dy (me, &damped_dy);
1044
1045       pos[LEFT] += (dy - damped_dy) / 2;
1046       pos[RIGHT] -= (dy - damped_dy) / 2;
1047
1048       scale_drul (&pos, 1 / Staff_symbol_referencer::staff_space (me));
1049
1050       me->set_property ("positions", ly_interval2scm (pos));
1051     }
1052   return SCM_UNSPECIFIED;
1053 }
1054
1055 /*
1056   Report slice containing the numbers that are both in (car BEAMING)
1057   and (cdr BEAMING)
1058 */
1059 Slice
1060 where_are_the_whole_beams (SCM beaming)
1061 {
1062   Slice l;
1063
1064   for (SCM s = scm_car (beaming); scm_is_pair (s); s = scm_cdr (s))
1065     {
1066       if (scm_c_memq (scm_car (s), scm_cdr (beaming)) != SCM_BOOL_F)
1067
1068         l.add_point (scm_to_int (scm_car (s)));
1069     }
1070
1071   return l;
1072 }
1073
1074 /* Return the Y position of the stem-end, given the Y-left, Y-right
1075    in POS for stem S.  This Y position is relative to S. */
1076 Real
1077 Beam::calc_stem_y (Grob *me, Grob *s, Grob ** common,
1078                    Real xl, Real xr,
1079                    Drul_array<Real> pos, bool french)
1080 {
1081   Real beam_translation = get_beam_translation (me);
1082
1083   Real r = s->relative_coordinate (common[X_AXIS], X_AXIS) - xl;
1084   Real dy = pos[RIGHT] - pos[LEFT];
1085   Real dx = xr - xl;
1086   Real stem_y_beam0 = (dy && dx
1087                        ? r / dx
1088                        * dy
1089                        : 0) + pos[LEFT];
1090
1091   Direction my_dir = get_grob_direction (s);
1092   SCM beaming = s->get_property ("beaming");
1093
1094   Real stem_y = stem_y_beam0;
1095   if (french)
1096     {
1097       Slice bm = where_are_the_whole_beams (beaming);
1098       if (!bm.is_empty ())
1099         stem_y += beam_translation * bm[-my_dir];
1100     }
1101   else
1102     {
1103       Slice bm = Stem::beam_multiplicity (s);
1104       if (!bm.is_empty ())
1105         stem_y += bm[my_dir] * beam_translation;
1106     }
1107
1108   Real id = me->relative_coordinate (common[Y_AXIS], Y_AXIS)
1109     - s->relative_coordinate (common[Y_AXIS], Y_AXIS);
1110
1111   return stem_y + id;
1112 }
1113
1114 /*
1115   Hmm.  At this time, beam position and slope are determined.  Maybe,
1116   stem directions and length should set to relative to the chord's
1117   position of the beam.  */
1118 void
1119 Beam::set_stem_lengths (Grob *me)
1120 {
1121   Link_array<Grob> stems
1122     = extract_grob_array (me, ly_symbol2scm ("stems"));
1123
1124   if (!stems.size ())
1125     return;
1126
1127   Grob *common[2];
1128   for (int a = 2; a--;)
1129     common[a] = common_refpoint_of_array (stems, me, Axis (a));
1130
1131   Drul_array<Real> pos = ly_scm2realdrul (me->get_property ("positions"));
1132   Real staff_space = Staff_symbol_referencer::staff_space (me);
1133   scale_drul (&pos, staff_space);
1134
1135   bool gap = false;
1136   Real thick = 0.0;
1137   if (scm_is_number (me->get_property ("gap-count"))
1138       &&scm_to_int (me->get_property ("gap-count")))
1139     {
1140       gap = true;
1141       thick = get_thickness (me);
1142     }
1143
1144   // ugh -> use commonx
1145   Grob *fvs = first_visible_stem (me);
1146   Grob *lvs = last_visible_stem (me);
1147
1148   Real xl = fvs ? fvs->relative_coordinate (common[X_AXIS], X_AXIS) : 0.0;
1149   Real xr = lvs ? lvs->relative_coordinate (common[X_AXIS], X_AXIS) : 0.0;
1150
1151   for (int i = 0; i < stems.size (); i++)
1152     {
1153       Grob *s = stems[i];
1154       if (Stem::is_invisible (s))
1155         continue;
1156
1157       bool french = to_boolean (s->get_property ("french-beaming"));
1158       Real stem_y = calc_stem_y (me, s, common,
1159                                  xl, xr,
1160                                  pos, french && s != lvs && s!= fvs);
1161
1162       /*
1163         Make the stems go up to the end of the beam. This doesn't matter
1164         for normal beams, but for tremolo beams it looks silly otherwise.
1165       */
1166       if (gap)
1167         stem_y += thick * 0.5 * get_grob_direction (s);
1168
1169       Stem::set_stemend (s, 2 * stem_y / staff_space);
1170     }
1171 }
1172
1173 void
1174 Beam::set_beaming (Grob *me, Beaming_info_list *beaming)
1175 {
1176   Link_array<Grob> stems
1177     = extract_grob_array (me, ly_symbol2scm ("stems"));
1178
1179   Direction d = LEFT;
1180   for (int i = 0; i < stems.size (); i++)
1181     {
1182       /*
1183         Don't overwrite user settings.
1184       */
1185
1186       do
1187         {
1188           /* Don't set beaming for outside of outer stems */
1189           if ((d == LEFT && i == 0)
1190               || (d == RIGHT && i == stems.size () -1))
1191             continue;
1192
1193           Grob *st = stems[i];
1194           SCM beaming_prop = st->get_property ("beaming");
1195           if (beaming_prop == SCM_EOL
1196               || index_get_cell (beaming_prop, d) == SCM_EOL)
1197             {
1198               int b = beaming->infos_.elem (i).beams_i_drul_[d];
1199               if (i > 0
1200                   && i < stems.size () -1
1201                   && Stem::is_invisible (st))
1202                 b = min (b, beaming->infos_.elem (i).beams_i_drul_[-d]);
1203
1204               Stem::set_beaming (st, b, d);
1205             }
1206         }
1207       while (flip (&d) != LEFT);
1208     }
1209 }
1210
1211 int
1212 Beam::forced_stem_count (Grob *me)
1213 {
1214   Link_array<Grob> stems
1215     = extract_grob_array (me, ly_symbol2scm ("stems"));
1216   int f = 0;
1217   for (int i = 0; i < stems.size (); i++)
1218     {
1219       Grob *s = stems[i];
1220
1221       if (Stem::is_invisible (s))
1222         continue;
1223
1224       /* I can imagine counting those boundaries as a half forced stem,
1225          but let's count them full for now. */
1226       if (abs (Stem::chord_start_y (s)) > 0.1
1227           && (Stem::get_direction (s) != Stem::get_default_dir (s)))
1228         f++;
1229     }
1230   return f;
1231 }
1232
1233 int
1234 Beam::visible_stem_count (Grob *me)
1235 {
1236   Link_array<Grob> stems
1237     = extract_grob_array (me, ly_symbol2scm ("stems"));
1238   int c = 0;
1239   for (int i = stems.size (); i--;)
1240     {
1241       if (!Stem::is_invisible (stems[i]))
1242         c++;
1243     }
1244   return c;
1245 }
1246
1247 Grob *
1248 Beam::first_visible_stem (Grob *me)
1249 {
1250   Link_array<Grob> stems
1251     = extract_grob_array (me, ly_symbol2scm ("stems"));
1252
1253   for (int i = 0; i < stems.size (); i++)
1254     {
1255       if (!Stem::is_invisible (stems[i]))
1256         return stems[i];
1257     }
1258   return 0;
1259 }
1260
1261 Grob *
1262 Beam::last_visible_stem (Grob *me)
1263 {
1264   Link_array<Grob> stems
1265     = extract_grob_array (me, ly_symbol2scm ("stems"));
1266   for (int i = stems.size (); i--;)
1267     {
1268       if (!Stem::is_invisible (stems[i]))
1269         return stems[i];
1270     }
1271   return 0;
1272 }
1273
1274 /*
1275   [TODO]
1276
1277   handle rest under beam (do_post: beams are calculated now)
1278   what about combination of collisions and rest under beam.
1279
1280   Should lookup
1281
1282   rest -> stem -> beam -> interpolate_y_position ()
1283 */
1284 MAKE_SCHEME_CALLBACK (Beam, rest_collision_callback, 2);
1285 SCM
1286 Beam::rest_collision_callback (SCM element_smob, SCM axis)
1287 {
1288   Grob *rest = unsmob_grob (element_smob);
1289   (void) axis;
1290
1291   if (scm_is_number (rest->get_property ("staff-position")))
1292     return scm_int2num (0);
1293
1294   assert (scm_to_int (axis) == Y_AXIS);
1295
1296   Grob *st = unsmob_grob (rest->get_property ("stem"));
1297   Grob *stem = st;
1298   if (!stem)
1299     return scm_make_real (0.0);
1300   Grob *beam = unsmob_grob (stem->get_property ("beam"));
1301   if (!beam
1302       || !Beam::has_interface (beam)
1303       || !Beam::visible_stem_count (beam))
1304     return scm_make_real (0.0);
1305
1306   Drul_array<Real> pos (0, 0);
1307   SCM s = beam->get_property ("positions");
1308   if (scm_is_pair (s) && scm_is_number (scm_car (s)))
1309     pos = ly_scm2interval (s);
1310   Real staff_space = Staff_symbol_referencer::staff_space (rest);
1311
1312   scale_drul (&pos, staff_space);
1313
1314   Real dy = pos[RIGHT] - pos[LEFT];
1315
1316   // ugh -> use commonx
1317   Real x0 = first_visible_stem (beam)->relative_coordinate (0, X_AXIS);
1318   Real dx = last_visible_stem (beam)->relative_coordinate (0, X_AXIS) - x0;
1319   Real slope = dy && dx ? dy / dx : 0;
1320
1321   Direction d = Stem::get_direction (stem);
1322   Real stem_y = pos[LEFT] + (stem->relative_coordinate (0, X_AXIS) - x0) * slope;
1323
1324   Real beam_translation = get_beam_translation (beam);
1325   Real beam_thickness = Beam::get_thickness (beam);
1326
1327   /*
1328     TODO: this is not strictly correct for 16th knee beams.
1329   */
1330   int beam_count
1331     = Stem::beam_multiplicity (stem).length () + 1;
1332
1333   Real height_of_my_beams = beam_thickness / 2
1334     + (beam_count - 1) * beam_translation;
1335   Real beam_y = stem_y - d * height_of_my_beams;
1336
1337   Grob *common_y = rest->common_refpoint (beam, Y_AXIS);
1338
1339   Real rest_dim = rest->extent (common_y, Y_AXIS)[d];
1340   Real minimum_distance
1341     = + staff_space * (robust_scm2double (stem->get_property ("stemlet-length"), 0.0)
1342                        + robust_scm2double (rest->get_property ("minimum-distance"), 0.0));
1343
1344   Real shift = d * min (((beam_y - d * minimum_distance) - rest_dim) * d, 0.0);
1345
1346   shift /= staff_space;
1347   Real rad = Staff_symbol_referencer::line_count (rest) * staff_space / 2;
1348
1349   /* Always move discretely by half spaces */
1350   shift = ceil (fabs (shift * 2.0)) / 2.0 * sign (shift);
1351
1352   /* Inside staff, move by whole spaces*/
1353   if ((rest->extent (common_y, Y_AXIS)[d] + staff_space * shift) * d
1354       < rad
1355       || (rest->extent (common_y, Y_AXIS)[-d] + staff_space * shift) * -d
1356       < rad)
1357     shift = ceil (fabs (shift)) * sign (shift);
1358
1359   return scm_make_real (staff_space * shift);
1360 }
1361
1362 bool
1363 Beam::is_knee (Grob *me)
1364 {
1365   SCM k = me->get_property ("knee");
1366   if (scm_is_bool (k))
1367     return ly_scm2bool (k);
1368
1369   bool knee = false;
1370   int d = 0;
1371   for (SCM s = me->get_property ("stems"); scm_is_pair (s); s = scm_cdr (s))
1372     {
1373       Direction dir = get_grob_direction (unsmob_grob (scm_car (s)));
1374       if (d && d != dir)
1375         {
1376           knee = true;
1377           break;
1378         }
1379       d = dir;
1380     }
1381
1382   me->set_property ("knee", ly_bool2scm (knee));
1383
1384   return knee;
1385 }
1386
1387 int
1388 Beam::get_direction_beam_count (Grob *me, Direction d)
1389 {
1390   Link_array<Grob> stems
1391     = extract_grob_array (me, ly_symbol2scm ("stems"));
1392   int bc = 0;
1393
1394   for (int i = stems.size (); i--;)
1395     {
1396       /*
1397         Should we take invisible stems into account?
1398       */
1399       if (Stem::get_direction (stems[i]) == d)
1400         bc = max (bc, (Stem::beam_multiplicity (stems[i]).length () + 1));
1401     }
1402
1403   return bc;
1404 }
1405
1406 ADD_INTERFACE (Beam, "beam-interface",
1407                "A beam. \n\n"
1408                "The @code{thickness} property is the weight of beams, and is measured "
1409                "in  staffspace",
1410                "knee positioning-done position-callbacks "
1411                "concaveness dir-function quant-score auto-knee-gap gap "
1412                "gap-count chord-tremolo beamed-stem-shorten shorten least-squares-dy "
1413                "damping inspect-quants flag-width-function neutral-direction positions space-function "
1414                "thickness");
1415