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