]> git.donarmstrong.com Git - lilypond.git/blob - lily/beam.cc
release: 1.3.88
[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--2000 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7     Jan Nieuwenhuizen <janneke@gnu.org>
8
9 */
10
11 /*
12   [TODO]
13   * shorter! (now +- 1000 lines)
14     * less hairy code
15     * move paper vars to scm
16
17   remove *-hs variables, and do all y-position stuff in staff-space.
18 */
19
20
21 #include <math.h> // tanh.
22
23
24 #include "directional-element-interface.hh"
25 #include "beaming.hh"
26 #include "beam.hh"
27 #include "misc.hh"
28 #include "least-squares.hh"
29 #include "stem.hh"
30 #include "paper-def.hh"
31 #include "lookup.hh"
32 #include "group-interface.hh"
33 #include "staff-symbol-referencer.hh"
34 #include "cross-staff.hh"
35 #include "item.hh"
36 #include "spanner.hh"
37 #include "warn.hh"
38
39 void
40 Beam::add_stem (Score_element*me, Score_element*s)
41 {
42   Pointer_group_interface gi (me, "stems");
43   gi.add_element (s);
44   
45   s->add_dependency (me);
46
47   assert (!Stem::beam_l (s));
48   s->set_elt_property ("beam", me->self_scm ());
49
50   add_bound_item (dynamic_cast<Spanner*> (me), dynamic_cast<Item*> (s));
51 }
52
53 int
54 Beam::get_multiplicity (Score_element*me) 
55 {
56   int m = 0;
57   for (SCM s = me->get_elt_property ("stems"); gh_pair_p (s); s = gh_cdr (s))
58     {
59       Score_element * sc = unsmob_element (gh_car (s));
60
61       if (Stem::has_interface (sc))
62         m = m >? Stem::beam_count (sc,LEFT) >? Stem::beam_count (sc,RIGHT);
63     }
64   return m;
65 }
66
67 /*
68   After pre-processing all directions should be set.
69   Several post-processing routines (stem, slur, script) need stem/beam
70   direction.
71   Currenly, this means that beam has set all stem's directions.
72   [Alternatively, stems could set its own directions, according to
73    their beam, during 'final-pre-processing'.]
74  */
75 MAKE_SCHEME_CALLBACK(Beam,before_line_breaking);
76 SCM
77 Beam::before_line_breaking (SCM smob)
78 {
79   Score_element * me =  unsmob_element (smob);
80
81   // Why?
82   if (visible_stem_count (me) < 2)
83     {
84       warning (_ ("beam has less than two stems"));
85     }
86
87   if (!Directional_element_interface::get (me))
88     Directional_element_interface::set (me, get_default_dir (me));
89
90   auto_knees (me);
91   set_stem_directions (me);
92   set_stem_shorten (me);
93
94   return SCM_EOL;
95 }
96
97 /*
98  FIXME
99  */
100 Direction
101 Beam::get_default_dir (Score_element*me) 
102 {
103   Drul_array<int> total;
104   total[UP]  = total[DOWN] = 0;
105   Drul_array<int> count; 
106   count[UP]  = count[DOWN] = 0;
107   Direction d = DOWN;
108
109   Link_array<Item> stems=
110         Pointer_group_interface__extract_elements (me, (Item*)0, "stems");
111
112   for (int i=0; i <stems.size (); i++)
113     do { // HUH -- waar slaat dit op?
114       Score_element *s = stems[i];
115       Direction sd = Directional_element_interface::get (s);
116       int current = sd  ? (1 + d * sd)/2
117         : Stem::get_center_distance (s, (Direction)-d);
118
119       if (current)
120         {
121           total[d] += current;
122           count[d] ++;
123         }
124
125     } while (flip(&d) != DOWN);
126   
127
128   SCM s = scm_eval2 (gh_list (ly_symbol2scm ("beam-dir-algorithm"),
129                              ly_quote_scm (gh_cons (gh_int2scm (count[UP]),
130                                                     gh_int2scm (count[DOWN]))),
131                              ly_quote_scm (gh_cons (gh_int2scm (total[UP]),
132                                                     gh_int2scm (total[DOWN]))),
133                              SCM_UNDEFINED),
134                      SCM_EOL);
135   if (gh_number_p (s) && gh_scm2int (s))
136     return to_dir (s);
137   
138   /*
139     If dir is not determined: get default
140   */
141   return to_dir (me->get_elt_property ("default-neutral-direction"));
142 }
143
144
145 /*
146   Set all stems with non-forced direction to beam direction.
147   Urg: non-forced should become `without/with unforced' direction,
148        once stem gets cleaned-up.
149  */
150 void
151 Beam::set_stem_directions (Score_element*me)
152 {
153   Link_array<Item> stems
154     =Pointer_group_interface__extract_elements (me,  (Item*) 0, "stems");
155   Direction d = Directional_element_interface::get (me);
156   
157   for (int i=0; i <stems.size (); i++)
158     {
159       Score_element *s = stems[i];
160       SCM force = s->remove_elt_property ("dir-forced");
161       if (!gh_boolean_p (force) || !gh_scm2bool (force))
162         Directional_element_interface ::set (s,d);
163     }
164
165
166 void
167 Beam::auto_knees (Score_element*me)
168 {
169   if (!auto_knee (me,"auto-interstaff-knee-gap", true))
170     auto_knee (me, "auto-knee-gap", false);
171 }
172
173 /*
174   Simplistic auto-knees; only consider vertical gap between two
175   adjacent chords.
176
177   `Forced' stem directions are ignored.  If you don't want auto-knees,
178   don't set, or unset autoKneeGap/autoInterstaffKneeGap.
179  */
180 bool
181 Beam::auto_knee (Score_element*me, String gap_str, bool interstaff_b)
182 {
183   bool knee_b = false;
184   int knee_y = 0;
185   SCM gap = me->get_elt_property (gap_str.ch_C());
186
187   Direction d = Directional_element_interface::get (me);
188       Link_array<Item> stems=
189         Pointer_group_interface__extract_elements (me, (Item*)0, "stems");
190   
191   if (gh_number_p (gap))
192     {
193       Spanner*sp = dynamic_cast<Spanner*> (me);
194       int auto_gap_i = gh_scm2int (gap);
195       for (int i=1; i < stems.size (); i++)
196         {
197           bool is_b = (bool)(calc_interstaff_dist (stems[i], sp) 
198             - calc_interstaff_dist (stems[i-1], sp));
199           int l_y = (int)(Stem::head_positions(stems[i-1])[d])
200             + (int)calc_interstaff_dist (stems[i-1], sp);
201           int r_y = (int)(Stem::head_positions(stems[i])[d])
202             + (int)calc_interstaff_dist (stems[i], sp);
203           int gap_i = r_y - l_y;
204
205           if ((abs (gap_i) >= auto_gap_i) && (!interstaff_b || is_b))
206             {
207               knee_y = (r_y + l_y) / 2;
208               knee_b = true;
209               break;
210             }
211         }
212     }
213   if (knee_b)
214     {
215       for (int i=0; i < stems.size (); i++)
216         {
217           Item *s = stems[i];     
218           int y = (int)(Stem::head_positions(s)[d])
219             + (int)calc_interstaff_dist (s, dynamic_cast<Spanner*> (me));
220
221           Directional_element_interface::set (s,y < knee_y ? UP : DOWN);
222           s->set_elt_property ("dir-forced", SCM_BOOL_T);
223         }
224     }
225   return knee_b;
226 }
227
228 /*
229  Set stem's shorten property if unset.
230  TODO:
231     take some y-position (chord/beam/nearest?) into account
232     scmify forced-fraction
233  */
234 void
235 Beam::set_stem_shorten (Score_element*m)
236 {
237   Spanner*me = dynamic_cast<Spanner*> (m);
238   if (!visible_stem_count (me))
239     return;
240
241   Real forced_fraction = forced_stem_count (me) / visible_stem_count (me);
242   if (forced_fraction < 0.5)
243     return;
244
245   int multiplicity = get_multiplicity (me);
246
247   // grace stems?
248   SCM shorten = scm_eval2 (ly_symbol2scm ("beamed-stem-shorten"), SCM_EOL);
249
250   if (shorten == SCM_EOL)
251     return;
252
253   int sz = scm_ilength (shorten);
254   
255   Real staff_space = Staff_symbol_referencer::staff_space (me);
256   SCM shorten_elt = scm_list_ref (shorten, gh_int2scm (multiplicity <? (sz - 1)));
257   Real shorten_f = gh_scm2double (shorten_elt) * staff_space;
258
259   /* cute, but who invented me -- how to customise ? */
260   if (forced_fraction < 1)
261     shorten_f /= 2;
262
263   Link_array<Item> stems=
264     Pointer_group_interface__extract_elements (me, (Item*)0, "stems");
265
266   for (int i=0; i < stems.size (); i++)
267     {
268       Item* s = stems[i];
269       if (Stem::invisible_b (s))
270         continue;
271       if (gh_number_p (s->get_elt_property ("shorten")))
272         s->set_elt_property ("shorten", gh_double2scm (shorten_f));
273     }
274 }
275
276 /*
277   Set elt properties height and y-position if not set.
278   Adjust stem lengths to reach beam.
279  */
280 MAKE_SCHEME_CALLBACK(Beam,after_line_breaking);
281 SCM
282 Beam::after_line_breaking (SCM smob)
283 {
284   Score_element * me =  unsmob_element (smob);
285
286   /* first, calculate y, dy */
287   Real y, dy;
288   calc_default_position_and_height (me, &y, &dy);
289   if (visible_stem_count (me))
290     {
291       if (suspect_slope_b (me, y, dy))
292         dy = 0;
293
294       Real damped_dy = calc_slope_damping_f (me, dy);
295       Real quantised_dy = quantise_dy_f (me, damped_dy);
296
297       y += (dy - quantised_dy) / 2;
298       dy = quantised_dy;
299     }
300   /*
301     until here, we used only stem_info, which acts as if dir=up
302    */
303   y *= Directional_element_interface::get (me);
304   dy *= Directional_element_interface::get (me);
305
306
307   Real half_space = Staff_symbol_referencer::staff_space (me) / 2;
308
309   /* weird: why do we do calc_position_and_height () ? regardless of
310      this setting?
311
312   */
313   /* check for user-override of dy */
314   SCM s = me->remove_elt_property ("height-hs");
315   if (gh_number_p (s))
316     {
317       dy = gh_scm2double (s) * half_space;
318     }
319   me->set_elt_property ("height", gh_double2scm (dy));
320
321   /* check for user-override of y */
322   s = me->remove_elt_property ("y-position-hs");
323   if (gh_number_p (s))
324     {
325       y = gh_scm2double (s) * half_space;
326     }
327   else
328     { 
329       /* we can modify y, so we should quantise y */
330       Real y_shift = check_stem_length_f (me, y, dy);
331       y += y_shift;
332       y = quantise_y_f (me,y, dy, 0);
333       set_stem_length (me, y, dy);
334       y_shift = check_stem_length_f (me, y, dy);
335
336       if (y_shift > half_space / 4)
337         {
338           y += y_shift;
339
340           /*
341             for significantly lengthened or shortened stems,
342             request quanting the other way.
343           */
344           int quant_dir = 0;
345           if (abs (y_shift) > half_space / 2)
346             quant_dir = sign (y_shift) * Directional_element_interface::get (me);
347           y = quantise_y_f (me, y, dy, quant_dir);
348         }
349     }
350   // UGH. Y is not in staff position unit?
351   // Ik dacht datwe daar juist van weg wilden?
352   set_stem_length (me, y, dy);
353   me->set_elt_property ("y-position", gh_double2scm (y));
354
355   return SCM_UNSPECIFIED;
356 }
357
358 /*
359   See Documentation/tex/fonts.doc
360  */
361 void
362 Beam::calc_default_position_and_height (Score_element*me,Real* y, Real* dy) 
363 {
364   *y = 0;
365   *dy = 0;  
366   if (visible_stem_count (me) <= 1)
367     return;
368
369   Real first_ideal = Stem::calc_stem_info (first_visible_stem (me)).idealy_f_;
370   if (first_ideal == Stem::calc_stem_info (last_visible_stem (me)).idealy_f_)
371     {
372       *dy = 0;
373       *y = first_ideal;
374       return;
375     }
376
377   Array<Offset> ideals;
378
379   // ugh -> use commonx
380   Real x0 = first_visible_stem (me)->relative_coordinate (0, X_AXIS);
381   Link_array<Item> stems=
382     Pointer_group_interface__extract_elements (me, (Item*)0, "stems");
383
384   for (int i=0; i < stems.size (); i++)
385     {
386       Item* s = stems[i];
387       if (Stem::invisible_b (s))
388         continue;
389       ideals.push (Offset (s->relative_coordinate (0, X_AXIS) - x0, 
390                            Stem::calc_stem_info (s).idealy_f_));
391     }
392   Real dydx;
393   minimise_least_squares (&dydx, y, ideals); // duh, takes references
394
395   Real dx = last_visible_stem (me)->relative_coordinate (0, X_AXIS) - x0;
396   *dy = dydx * dx;
397 }
398
399 bool
400 Beam::suspect_slope_b (Score_element*me, Real y, Real dy) 
401 {
402   /* first, calculate y, dy */
403   /*
404     steep slope running against lengthened stem is suspect
405   */
406   Real first_ideal = Stem::calc_stem_info (first_visible_stem (me)).idealy_f_;
407   Real last_ideal = Stem::calc_stem_info (last_visible_stem (me)).idealy_f_;
408   Real lengthened = me->paper_l ()->get_var ("beam_lengthened");
409   Real steep = me->paper_l ()->get_var ("beam_steep_slope");
410
411   // ugh -> use commonx
412   Real dx = last_visible_stem (me)->relative_coordinate (0, X_AXIS) - first_visible_stem (me)->relative_coordinate (0, X_AXIS);
413   Real dydx = dy && dx ? dy/dx : 0;
414
415   if (((y - first_ideal > lengthened) && (dydx > steep))
416       || ((y + dy - last_ideal > lengthened) && (dydx < -steep)))
417     {
418       return true;
419     }
420   return false;
421 }
422
423 /*
424   This neat trick is by Werner Lemberg,
425   damped = tanh (slope)
426   corresponds with some tables in [Wanske]
427 */
428 Real
429 Beam::calc_slope_damping_f (Score_element*me,Real dy) 
430 {
431   SCM damp = me->get_elt_property ("damping"); 
432   int damping = gh_scm2int (damp);
433
434   if (damping)
435     {
436   // ugh -> use commonx
437       Real dx = last_visible_stem (me)->relative_coordinate (0, X_AXIS)
438         - first_visible_stem (me)->relative_coordinate (0, X_AXIS);
439       Real dydx = dy && dx ? dy/dx : 0;
440       dydx = 0.6 * tanh (dydx) / damping;
441       return dydx * dx;
442     }
443   return dy;
444 }
445
446 Real
447 Beam::calc_stem_y_f (Score_element*me,Item* s, Real y, Real dy) 
448 {
449   int beam_multiplicity = get_multiplicity (me);
450   int stem_multiplicity = (Stem::flag_i (s) - 2) >? 0;
451
452   Real staffspace = me->paper_l ()->get_var ("staffspace");
453   
454   SCM space_proc = me->get_elt_property ("beam-space-function");
455   SCM space = gh_call1 (space_proc, gh_int2scm (beam_multiplicity));
456
457   Real thick = gh_scm2double (me->get_elt_property ("beam-thickness")) *staffspace;
458   Real interbeam_f = gh_scm2double (space) * staffspace;
459
460   // ugh -> use commonx
461   Real x0 = first_visible_stem (me)->relative_coordinate (0, X_AXIS);
462   Real dx = last_visible_stem (me)->relative_coordinate (0, X_AXIS) - x0;
463   Real stem_y = (dy && dx ? (s->relative_coordinate (0, X_AXIS) - x0) / dx * dy : 0) + y;
464
465   /* knee */
466    Direction dir  = Directional_element_interface::get (me);
467    Direction sdir = Directional_element_interface::get (s);
468    
469     /* knee */
470    if (dir!= sdir)
471       {
472        stem_y -= dir 
473         * (thick / 2 + (beam_multiplicity - 1) * interbeam_f);
474
475
476       
477       // huh, why not for first visible?
478        if (Staff_symbol_referencer::staff_symbol_l (s)
479            != Staff_symbol_referencer::staff_symbol_l (last_visible_stem (me)))
480          stem_y += Directional_element_interface::get (me)
481            * (beam_multiplicity - stem_multiplicity) * interbeam_f;
482       }
483
484   return stem_y;
485 }
486
487 Real
488 Beam::check_stem_length_f (Score_element*me,Real y, Real dy) 
489 {
490   Real shorten = 0;
491   Real lengthen = 0;
492   Direction dir = Directional_element_interface::get (me);
493
494   Link_array<Item> stems=
495     Pointer_group_interface__extract_elements (me, (Item*)0, "stems");
496
497   for (int i=0; i < stems.size(); i++)
498     {
499       Item* s = stems[i];
500       if (Stem::invisible_b (s))
501         continue;
502
503       Real stem_y = calc_stem_y_f (me, s, y, dy);
504         
505       stem_y *= dir;
506       Stem_info info = Stem::calc_stem_info (s);
507
508       // if (0 > info.maxy_f_ - stem_y)
509       shorten = shorten <? info.maxy_f_ - stem_y;
510       // if (0 < info.miny_f_ - stem_y)
511       lengthen = lengthen >? info.miny_f_ - stem_y; 
512     }
513
514   if (lengthen && shorten)
515     warning (_ ("weird beam vertical offset"));
516
517   /* when all stems are too short, normal stems win */
518   return dir * ((shorten) ?  shorten : lengthen);
519 }
520
521 /*
522   Hmm.  At this time, beam position and slope are determined.  Maybe,
523   stem directions and length should set to relative to the chord's
524   position of the beam.  */
525 void
526 Beam::set_stem_length (Score_element*me,Real y, Real dy)
527 {
528   Real half_space = Staff_symbol_referencer::staff_space (me)/2;
529   Link_array<Item> stems=
530     Pointer_group_interface__extract_elements (me, (Item*)0, "stems");
531
532
533   for (int i=0; i < stems.size (); i++)
534     {
535       Item* s = stems[i];
536       if (Stem::invisible_b (s))
537         continue;
538
539       Real stem_y = calc_stem_y_f (me, s, y, dy);
540
541       /* caution: stem measures in staff-positions */
542       Stem::set_stemend (s,(stem_y + calc_interstaff_dist (s, dynamic_cast<Spanner*> (me))) / half_space);
543     }
544 }
545
546 /*
547   [Ross] (simplification of)
548   Set dy complying with:
549     - zero
550     - thick / 2 + staffline_f / 2
551     - thick + staffline_f
552   + n * staff_space
553 */
554 Real
555 Beam::quantise_dy_f (Score_element*me,Real dy) 
556 {
557   Array<Real> a;
558   for (SCM s = scm_eval2 (ly_symbol2scm ("beam-height-quants"), SCM_EOL);
559        s !=SCM_EOL; s = gh_cdr (s))
560     a.push (gh_scm2double (gh_car (s)));
561   
562   if (a.size () <= 1)
563     return dy;
564
565   Real staff_space = Staff_symbol_referencer::staff_space (me);
566   
567   Interval iv = quantise_iv (a, abs (dy)/staff_space) * staff_space;
568   Real q = (abs (dy) - iv[SMALLER] <= iv[BIGGER] - abs (dy))
569     ? iv[SMALLER]
570     : iv[BIGGER];
571   
572   return q * sign (dy);
573 }
574
575 /*
576   Prevent interference from stafflines and beams.
577   See Documentation/tex/fonts.doc
578
579   We only need to quantise the (left) y-position of the beam,
580   since dy is quantised too.
581   if extend_b then stems must *not* get shorter
582  */
583 Real
584 Beam::quantise_y_f (Score_element*me,Real y, Real dy, int quant_dir)
585 {
586   int multiplicity = get_multiplicity (me);
587
588   Real staff_space = Staff_symbol_referencer::staff_space (me);
589   SCM quants = scm_eval2 (gh_list (ly_symbol2scm ("beam-vertical-position-quants"),
590                                   gh_int2scm (multiplicity),
591                                   gh_double2scm (dy/staff_space),
592                                   SCM_UNDEFINED),
593                           SCM_EOL);
594
595   Array<Real> a;
596
597   for (; quants != SCM_EOL; quants = gh_cdr (quants))
598     a.push (gh_scm2double (gh_car (quants)));
599
600   if (a.size () <= 1)
601     return y;
602
603   Real up_y = Directional_element_interface::get (me) * y;
604   Interval iv = quantise_iv (a, up_y/staff_space) * staff_space;
605
606   Real q = up_y - iv[SMALLER] <= iv[BIGGER] - up_y 
607     ? iv[SMALLER] : iv[BIGGER];
608   if (quant_dir)
609     q = iv[(Direction)quant_dir];
610
611   return q * Directional_element_interface::get (me);
612 }
613
614 void
615 Beam::set_beaming (Score_element*me,Beaming_info_list *beaming)
616 {
617   Link_array<Score_element> stems=
618     Pointer_group_interface__extract_elements (me, (Score_element*)0, "stems");
619   
620   Direction d = LEFT;
621   for (int i=0; i  < stems.size(); i++)
622     {
623       do
624         {
625           if (Stem::beam_count (stems[i], d) == 0)
626             Stem::set_beaming ( stems[i], beaming->infos_.elem (i).beams_i_drul_[d],d);
627         }
628       while (flip (&d) != LEFT);
629     }
630 }
631
632
633
634 /*
635   beams to go with one stem.
636
637   BURP
638   clean  me up.
639   */
640 Molecule
641 Beam::stem_beams (Score_element*me,Item *here, Item *next, Item *prev) 
642 {
643   // ugh -> use commonx
644   if ((next && !(next->relative_coordinate (0, X_AXIS) > here->relative_coordinate (0, X_AXIS))) ||
645       (prev && !(prev->relative_coordinate (0, X_AXIS) < here->relative_coordinate (0, X_AXIS))))
646       programming_error ("Beams are not left-to-right");
647
648   Real staffline_f = me->paper_l ()->get_var ("stafflinethickness");
649   int multiplicity = get_multiplicity (me);
650   Real staffspace =me->paper_l ()->get_var ("staffspace");
651
652   SCM space_proc = me->get_elt_property ("beam-space-function");
653   SCM space = gh_call1 (space_proc, gh_int2scm (multiplicity));
654
655   Real thick = gh_scm2double (me->get_elt_property ("beam-thickness")) *staffspace;
656   Real interbeam_f = gh_scm2double (space) * staffspace;
657     
658   Real bdy = interbeam_f;
659   Real stemdx = staffline_f;
660
661     // ugh -> use commonx
662   Real dx = visible_stem_count (me) ?
663     last_visible_stem (me)->relative_coordinate (0, X_AXIS) - first_visible_stem (me)->relative_coordinate (0, X_AXIS)
664     : 0.0;
665   Real dy = gh_scm2double (me->get_elt_property ("height"));
666   Real dydx = dy && dx ? dy/dx : 0;
667
668   Molecule leftbeams;
669   Molecule rightbeams;
670
671   /*
672     UGH: make a property of this.
673   */
674   Real nw_f;
675   if (!Stem::first_head (here))
676     nw_f = 0;
677   else {
678     int t = Stem::type_i (here); 
679
680     SCM proc = me->get_elt_property ("beam-flag-width-function");
681     SCM result = gh_call1 (proc, gh_int2scm (t));
682     nw_f = gh_scm2double (result) * staffspace;
683   }
684
685
686   Direction dir = Directional_element_interface::get (me);
687   
688   /* half beams extending to the left. */
689   if (prev)
690     {
691       int lhalfs= lhalfs = Stem::beam_count (here,LEFT) - Stem::beam_count (prev,RIGHT);
692       int lwholebeams= Stem::beam_count (here,LEFT) <? Stem::beam_count (prev,RIGHT) ;
693       /*
694        Half beam should be one note-width, 
695        but let's make sure two half-beams never touch
696        */
697       Real w = here->relative_coordinate (0, X_AXIS) - prev->relative_coordinate (0, X_AXIS);
698       w = w/2 <? nw_f;
699       Molecule a;
700       if (lhalfs)               // generates warnings if not
701         a =  me->lookup_l ()->beam (dydx, w, thick);
702       a.translate (Offset (-w, -w * dydx));
703       for (int j = 0; j  < lhalfs; j++)
704         {
705           Molecule b (a);
706           b.translate_axis (-dir * bdy * (lwholebeams+j), Y_AXIS);
707           leftbeams.add_molecule (b);
708         }
709     }
710
711   if (next)
712     {
713       int rhalfs  = Stem::beam_count (here,RIGHT) - Stem::beam_count (next,LEFT);
714       int rwholebeams= Stem::beam_count (here,RIGHT) <? Stem::beam_count (next,LEFT) ;
715
716       Real w = next->relative_coordinate (0, X_AXIS) - here->relative_coordinate (0, X_AXIS);
717       Molecule a = me->lookup_l ()->beam (dydx, w + stemdx, thick);
718       a.translate_axis( - stemdx/2, X_AXIS);
719       int j = 0;
720       Real gap_f = 0;
721
722       SCM gap = me->get_elt_property ("beam-gap");
723       if (gh_number_p (gap))
724         {
725           int gap_i = gh_scm2int ( (gap));
726           int nogap = rwholebeams - gap_i;
727           
728           for (; j  < nogap; j++)
729             {
730               Molecule b (a);
731               b.translate_axis (-dir  * bdy * j, Y_AXIS);
732               rightbeams.add_molecule (b);
733             }
734           // TODO: notehead widths differ for different types
735           gap_f = nw_f / 2;
736           w -= 2 * gap_f;
737           a = me->lookup_l ()->beam (dydx, w + stemdx, thick);
738         }
739
740       for (; j  < rwholebeams; j++)
741         {
742           Molecule b (a);
743           b.translate (Offset (Stem::invisible_b (here) ? 0 : gap_f, -dir * bdy * j));
744           rightbeams.add_molecule (b);
745         }
746
747       w = w/2 <? nw_f;
748       if (rhalfs)
749         a = me->lookup_l ()->beam (dydx, w, thick);
750
751       for (; j  < rwholebeams + rhalfs; j++)
752         {
753           Molecule b (a);
754           b.translate_axis (- dir * bdy * j, Y_AXIS);
755           rightbeams.add_molecule (b);
756         }
757
758     }
759   leftbeams.add_molecule (rightbeams);
760
761   /*
762     Does beam quanting think  of the asymetry of beams? 
763     Refpoint is on bottom of symbol. (FIXTHAT) --hwn.
764    */
765   return leftbeams;
766 }
767
768 MAKE_SCHEME_CALLBACK(Beam,brew_molecule);
769 SCM
770 Beam::brew_molecule (SCM smob)
771 {
772   Score_element * me =unsmob_element (smob);
773
774   Molecule mol;
775   if (!gh_pair_p (me->get_elt_property ("stems")))
776     return SCM_EOL;
777   Real x0,dx;
778   Link_array<Item>stems = 
779     Pointer_group_interface__extract_elements (me, (Item*) 0, "stems");  
780   if (visible_stem_count (me))
781     {
782   // ugh -> use commonx
783       x0 = first_visible_stem (me)->relative_coordinate (0, X_AXIS);
784       dx = last_visible_stem (me)->relative_coordinate (0, X_AXIS) - x0;
785     }
786   else
787     {
788       x0 = stems[0]->relative_coordinate (0, X_AXIS);
789       dx = stems.top()->relative_coordinate (0, X_AXIS) - x0;
790     }
791   
792   
793   Real dy = gh_scm2double (me->get_elt_property ("height"));
794   Real dydx = dy && dx ? dy/dx : 0;
795   Real y = gh_scm2double (me->get_elt_property ("y-position"));
796
797
798   for (int j=0; j <stems.size  (); j++)
799     {
800       Item *i = stems[j];
801       Item * prev = (j > 0)? stems[j-1] : 0;
802       Item * next = (j < stems.size()-1) ? stems[j+1] :0;
803
804       Molecule sb = stem_beams (me, i, next, prev);
805       Real x = i->relative_coordinate (0, X_AXIS)-x0;
806       sb.translate (Offset (x, x * dydx + y));
807       mol.add_molecule (sb);
808     }
809   mol.translate_axis (x0 
810     - dynamic_cast<Spanner*> (me)->get_bound (LEFT)->relative_coordinate (0, X_AXIS), X_AXIS);
811
812   return mol.create_scheme ();
813 }
814
815 int
816 Beam::forced_stem_count (Score_element*me) 
817 {
818   Link_array<Item>stems = 
819     Pointer_group_interface__extract_elements ( me, (Item*) 0, "stems");
820   int f = 0;
821   for (int i=0; i < stems.size (); i++)
822     {
823       Item *s = stems[i];
824
825       if (Stem::invisible_b (s))
826         continue;
827
828       if (((int)Stem::chord_start_f (s)) 
829         && (Stem::get_direction (s ) != Stem::get_default_dir (s )))
830         f++;
831     }
832   return f;
833 }
834
835
836
837
838 /* TODO:
839    use filter and standard list functions.
840  */
841 int
842 Beam::visible_stem_count (Score_element*me) 
843 {
844   Link_array<Item>stems = 
845     Pointer_group_interface__extract_elements (me, (Item*) 0, "stems");
846   int c = 0;
847   for (int i = stems.size (); i--;)
848     {
849       if (!Stem::invisible_b (stems[i]))
850         c++;
851     }
852   return c;
853 }
854
855 Item*
856 Beam::first_visible_stem(Score_element*me) 
857 {
858   Link_array<Item>stems = 
859     Pointer_group_interface__extract_elements ( me, (Item*) 0, "stems");
860   
861   for (int i = 0; i < stems.size (); i++)
862     {
863       if (!Stem::invisible_b (stems[i]))
864         return stems[i];
865     }
866   return 0;
867 }
868
869 Item*
870 Beam::last_visible_stem(Score_element*me) 
871 {
872   Link_array<Item>stems = 
873     Pointer_group_interface__extract_elements ( me, (Item*) 0, "stems");
874   for (int i = stems.size (); i--;)
875     {
876       if (!Stem::invisible_b (stems[i]))
877         return stems[i];
878     }
879   return 0;
880 }
881
882
883 /*
884   [TODO]
885   handle rest under beam (do_post: beams are calculated now)
886   what about combination of collisions and rest under beam.
887
888   Should lookup
889     
890     rest -> stem -> beam -> interpolate_y_position ()
891 */
892 Real
893 Beam::rest_collision_callback (Score_element *rest, Axis a )
894 {
895   assert (a == Y_AXIS);
896
897   Score_element * st = unsmob_element (rest->get_elt_property ("stem"));
898   Score_element * stem = st;
899   if (!stem)
900     return 0.0;
901   Score_element * beam = unsmob_element (stem->get_elt_property ("beam"));
902   if (!beam || !Beam::has_interface (beam) || !Beam::visible_stem_count (beam))
903     return 0.0;
904
905   // make callback for rest from this.
906   Real beam_dy = 0;
907   Real beam_y = 0;
908
909
910   // todo: make sure this calced already.
911   SCM s = beam->get_elt_property ("height");
912   if (gh_number_p (s))
913     beam_dy = gh_scm2double (s);
914   
915   s = beam->get_elt_property ("y-position");
916   if (gh_number_p (s))
917     beam_y = gh_scm2double (s);
918   
919   // ugh -> use commonx
920   Real x0 = first_visible_stem(beam)->relative_coordinate (0, X_AXIS);
921   Real dx = last_visible_stem(beam)->relative_coordinate (0, X_AXIS) - x0;
922   Real dydx = beam_dy && dx ? beam_dy/dx : 0;
923
924   Direction d = Stem::get_direction (stem);
925   Real beamy = (stem->relative_coordinate (0, X_AXIS) - x0) * dydx + beam_y;
926
927   Real staff_space =   Staff_symbol_referencer::staff_space (rest);
928   Real rest_dim = rest->extent (Y_AXIS)[d]*2.0 / staff_space ;
929
930   Real minimum_dist
931     = gh_scm2double (rest->get_elt_property ("minimum-beam-collision-distance"));
932   Real dist =
933     minimum_dist +  -d  * (beamy - rest_dim) >? 0;
934
935   int stafflines = Staff_symbol_referencer::line_count (rest);
936
937   // move discretely by half spaces.
938   int discrete_dist = int (ceil (dist));
939
940   // move by whole spaces inside the staff.
941   if (discrete_dist < stafflines+1)
942     discrete_dist = int (ceil (discrete_dist / 2.0)* 2.0);
943
944   return  (-d *  discrete_dist);
945 }
946
947
948 bool
949 Beam::has_interface (Score_element*me)
950 {
951   return me->has_interface (ly_symbol2scm ("beam-interface"));
952 }
953
954 void
955 Beam::set_interface (Score_element*me)
956 {
957   Pointer_group_interface g (me, "stems");
958   g.set_interface ();
959
960   /*
961     why the init? No way to tell difference between default and user
962     override.  */
963   me->set_elt_property ("height", gh_int2scm (0)); // ugh.
964   me->set_elt_property ("y-position" ,gh_int2scm (0));
965   me->set_interface (ly_symbol2scm("beam-interface"));
966 }