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