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