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