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