]> git.donarmstrong.com Git - lilypond.git/blob - lily/beam.cc
124dc7f9c06f70fa03f4f8d58492e2e480def09b
[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 ss = me->paper_l ()->get_var ("staffspace");
407   Real first_ideal = Stem::calc_stem_info (first_visible_stem (me)).idealy_f_;
408   Real last_ideal = Stem::calc_stem_info (last_visible_stem (me)).idealy_f_;
409   Real lengthened = gh_scm2double (me->get_elt_property ("outer-stem-length-limit")) * ss;
410   Real steep = gh_scm2double (me->get_elt_property ("slope-limit"));
411
412   // ugh -> use commonx
413   Real dx = last_visible_stem (me)->relative_coordinate (0, X_AXIS) - first_visible_stem (me)->relative_coordinate (0, X_AXIS);
414   Real dydx = dy && dx ? dy/dx : 0;
415
416   if (((y - first_ideal > lengthened) && (dydx > steep))
417       || ((y + dy - last_ideal > lengthened) && (dydx < -steep)))
418     {
419       return true;
420     }
421   return false;
422 }
423
424 /*
425   This neat trick is by Werner Lemberg,
426   damped = tanh (slope)
427   corresponds with some tables in [Wanske]
428 */
429 Real
430 Beam::calc_slope_damping_f (Score_element*me,Real dy) 
431 {
432   SCM damp = me->get_elt_property ("damping"); 
433   int damping = gh_scm2int (damp);
434
435   if (damping)
436     {
437   // ugh -> use commonx
438       Real dx = last_visible_stem (me)->relative_coordinate (0, X_AXIS)
439         - first_visible_stem (me)->relative_coordinate (0, X_AXIS);
440       Real dydx = dy && dx ? dy/dx : 0;
441       dydx = 0.6 * tanh (dydx) / damping;
442       return dydx * dx;
443     }
444   return dy;
445 }
446
447 Real
448 Beam::calc_stem_y_f (Score_element*me,Item* s, Real y, Real dy) 
449 {
450   int beam_multiplicity = get_multiplicity (me);
451   int stem_multiplicity = (Stem::flag_i (s) - 2) >? 0;
452
453   Real staffspace = me->paper_l ()->get_var ("staffspace");
454   
455   SCM space_proc = me->get_elt_property ("beam-space-function");
456   SCM space = gh_call1 (space_proc, gh_int2scm (beam_multiplicity));
457
458   Real thick = gh_scm2double (me->get_elt_property ("beam-thickness")) *staffspace;
459   Real interbeam_f = gh_scm2double (space) * staffspace;
460
461   // ugh -> use commonx
462   Real x0 = first_visible_stem (me)->relative_coordinate (0, X_AXIS);
463   Real dx = last_visible_stem (me)->relative_coordinate (0, X_AXIS) - x0;
464   Real stem_y = (dy && dx ? (s->relative_coordinate (0, X_AXIS) - x0) / dx * dy : 0) + y;
465
466   /* knee */
467    Direction dir  = Directional_element_interface::get (me);
468    Direction sdir = Directional_element_interface::get (s);
469    
470     /* knee */
471    if (dir!= sdir)
472       {
473        stem_y -= dir 
474         * (thick / 2 + (beam_multiplicity - 1) * interbeam_f);
475
476
477       
478       // huh, why not for first visible?
479        if (Staff_symbol_referencer::staff_symbol_l (s)
480            != Staff_symbol_referencer::staff_symbol_l (last_visible_stem (me)))
481          stem_y += Directional_element_interface::get (me)
482            * (beam_multiplicity - stem_multiplicity) * interbeam_f;
483       }
484
485   return stem_y;
486 }
487
488 Real
489 Beam::check_stem_length_f (Score_element*me,Real y, Real dy) 
490 {
491   Real shorten = 0;
492   Real lengthen = 0;
493   Direction dir = Directional_element_interface::get (me);
494
495   Link_array<Item> stems=
496     Pointer_group_interface__extract_elements (me, (Item*)0, "stems");
497
498   for (int i=0; i < stems.size(); i++)
499     {
500       Item* s = stems[i];
501       if (Stem::invisible_b (s))
502         continue;
503
504       Real stem_y = calc_stem_y_f (me, s, y, dy);
505         
506       stem_y *= dir;
507       Stem_info info = Stem::calc_stem_info (s);
508
509       // if (0 > info.maxy_f_ - stem_y)
510       shorten = shorten <? info.maxy_f_ - stem_y;
511       // if (0 < info.miny_f_ - stem_y)
512       lengthen = lengthen >? info.miny_f_ - stem_y; 
513     }
514
515   if (lengthen && shorten)
516     warning (_ ("weird beam vertical offset"));
517
518   /* when all stems are too short, normal stems win */
519   return dir * ((shorten) ?  shorten : lengthen);
520 }
521
522 /*
523   Hmm.  At this time, beam position and slope are determined.  Maybe,
524   stem directions and length should set to relative to the chord's
525   position of the beam.  */
526 void
527 Beam::set_stem_length (Score_element*me,Real y, Real dy)
528 {
529   Real half_space = Staff_symbol_referencer::staff_space (me)/2;
530   Link_array<Item> stems=
531     Pointer_group_interface__extract_elements (me, (Item*)0, "stems");
532
533
534   for (int i=0; i < stems.size (); i++)
535     {
536       Item* s = stems[i];
537       if (Stem::invisible_b (s))
538         continue;
539
540       Real stem_y = calc_stem_y_f (me, s, y, dy);
541
542       /* caution: stem measures in staff-positions */
543       Stem::set_stemend (s,(stem_y + calc_interstaff_dist (s, dynamic_cast<Spanner*> (me))) / half_space);
544     }
545 }
546
547 /*
548   [Ross] (simplification of)
549   Set dy complying with:
550     - zero
551     - thick / 2 + staffline_f / 2
552     - thick + staffline_f
553   + n * staff_space
554 */
555 Real
556 Beam::quantise_dy_f (Score_element*me,Real dy) 
557 {
558   Array<Real> a;
559   for (SCM s = scm_eval2 (ly_symbol2scm ("beam-height-quants"), SCM_EOL);
560        s !=SCM_EOL; s = gh_cdr (s))
561     a.push (gh_scm2double (gh_car (s)));
562   
563   if (a.size () <= 1)
564     return dy;
565
566   Real staff_space = Staff_symbol_referencer::staff_space (me);
567   
568   Interval iv = quantise_iv (a, abs (dy)/staff_space) * staff_space;
569   Real q = (abs (dy) - iv[SMALLER] <= iv[BIGGER] - abs (dy))
570     ? iv[SMALLER]
571     : iv[BIGGER];
572   
573   return q * sign (dy);
574 }
575
576 /*
577   Prevent interference from stafflines and beams.
578   See Documentation/tex/fonts.doc
579
580   We only need to quantise the (left) y-position of the beam,
581   since dy is quantised too.
582   if extend_b then stems must *not* get shorter
583  */
584 Real
585 Beam::quantise_y_f (Score_element*me,Real y, Real dy, int quant_dir)
586 {
587   int multiplicity = get_multiplicity (me);
588
589   Real staff_space = Staff_symbol_referencer::staff_space (me);
590   SCM quants = scm_eval2 (gh_list (ly_symbol2scm ("beam-vertical-position-quants"),
591                                   gh_int2scm (multiplicity),
592                                   gh_double2scm (dy/staff_space),
593                                   SCM_UNDEFINED),
594                           SCM_EOL);
595
596   Array<Real> a;
597
598   for (; quants != SCM_EOL; quants = gh_cdr (quants))
599     a.push (gh_scm2double (gh_car (quants)));
600
601   if (a.size () <= 1)
602     return y;
603
604   Real up_y = Directional_element_interface::get (me) * y;
605   Interval iv = quantise_iv (a, up_y/staff_space) * staff_space;
606
607   Real q = up_y - iv[SMALLER] <= iv[BIGGER] - up_y 
608     ? iv[SMALLER] : iv[BIGGER];
609   if (quant_dir)
610     q = iv[(Direction)quant_dir];
611
612   return q * Directional_element_interface::get (me);
613 }
614
615 void
616 Beam::set_beaming (Score_element*me,Beaming_info_list *beaming)
617 {
618   Link_array<Score_element> stems=
619     Pointer_group_interface__extract_elements (me, (Score_element*)0, "stems");
620   
621   Direction d = LEFT;
622   for (int i=0; i  < stems.size(); i++)
623     {
624       do
625         {
626           if (Stem::beam_count (stems[i], d) == 0)
627             Stem::set_beaming ( stems[i], beaming->infos_.elem (i).beams_i_drul_[d],d);
628         }
629       while (flip (&d) != LEFT);
630     }
631 }
632
633
634
635 /*
636   beams to go with one stem.
637
638   BURP
639   clean  me up.
640   */
641 Molecule
642 Beam::stem_beams (Score_element*me,Item *here, Item *next, Item *prev) 
643 {
644   // ugh -> use commonx
645   if ((next && !(next->relative_coordinate (0, X_AXIS) > here->relative_coordinate (0, X_AXIS))) ||
646       (prev && !(prev->relative_coordinate (0, X_AXIS) < here->relative_coordinate (0, X_AXIS))))
647       programming_error ("Beams are not left-to-right");
648
649   Real staffline_f = me->paper_l ()->get_var ("stafflinethickness");
650   int multiplicity = get_multiplicity (me);
651   Real staffspace =me->paper_l ()->get_var ("staffspace");
652
653   SCM space_proc = me->get_elt_property ("beam-space-function");
654   SCM space = gh_call1 (space_proc, gh_int2scm (multiplicity));
655
656   Real thick = gh_scm2double (me->get_elt_property ("beam-thickness")) *staffspace;
657   Real interbeam_f = gh_scm2double (space) * staffspace;
658     
659   Real bdy = interbeam_f;
660   Real stemdx = staffline_f;
661
662     // ugh -> use commonx
663   Real dx = visible_stem_count (me) ?
664     last_visible_stem (me)->relative_coordinate (0, X_AXIS) - first_visible_stem (me)->relative_coordinate (0, X_AXIS)
665     : 0.0;
666   Real dy = gh_scm2double (me->get_elt_property ("height"));
667   Real dydx = dy && dx ? dy/dx : 0;
668
669   Molecule leftbeams;
670   Molecule rightbeams;
671
672   /*
673     UGH: make a property of this.
674   */
675   Real nw_f;
676   if (!Stem::first_head (here))
677     nw_f = 0;
678   else {
679     int t = Stem::type_i (here); 
680
681     SCM proc = me->get_elt_property ("beam-flag-width-function");
682     SCM result = gh_call1 (proc, gh_int2scm (t));
683     nw_f = gh_scm2double (result) * staffspace;
684   }
685
686
687   Direction dir = Directional_element_interface::get (me);
688   
689   /* half beams extending to the left. */
690   if (prev)
691     {
692       int lhalfs= lhalfs = Stem::beam_count (here,LEFT) - Stem::beam_count (prev,RIGHT);
693       int lwholebeams= Stem::beam_count (here,LEFT) <? Stem::beam_count (prev,RIGHT) ;
694       /*
695        Half beam should be one note-width, 
696        but let's make sure two half-beams never touch
697        */
698       Real w = here->relative_coordinate (0, X_AXIS) - prev->relative_coordinate (0, X_AXIS);
699       w = w/2 <? nw_f;
700       Molecule a;
701       if (lhalfs)               // generates warnings if not
702         a =  me->lookup_l ()->beam (dydx, w, thick);
703       a.translate (Offset (-w, -w * dydx));
704       for (int j = 0; j  < lhalfs; j++)
705         {
706           Molecule b (a);
707           b.translate_axis (-dir * bdy * (lwholebeams+j), Y_AXIS);
708           leftbeams.add_molecule (b);
709         }
710     }
711
712   if (next)
713     {
714       int rhalfs  = Stem::beam_count (here,RIGHT) - Stem::beam_count (next,LEFT);
715       int rwholebeams= Stem::beam_count (here,RIGHT) <? Stem::beam_count (next,LEFT) ;
716
717       Real w = next->relative_coordinate (0, X_AXIS) - here->relative_coordinate (0, X_AXIS);
718       Molecule a = me->lookup_l ()->beam (dydx, w + stemdx, thick);
719       a.translate_axis( - stemdx/2, X_AXIS);
720       int j = 0;
721       Real gap_f = 0;
722
723       SCM gap = me->get_elt_property ("beam-gap");
724       if (gh_number_p (gap))
725         {
726           int gap_i = gh_scm2int ( (gap));
727           int nogap = rwholebeams - gap_i;
728           
729           for (; j  < nogap; j++)
730             {
731               Molecule b (a);
732               b.translate_axis (-dir  * bdy * j, Y_AXIS);
733               rightbeams.add_molecule (b);
734             }
735           // TODO: notehead widths differ for different types
736           gap_f = nw_f / 2;
737           w -= 2 * gap_f;
738           a = me->lookup_l ()->beam (dydx, w + stemdx, thick);
739         }
740
741       for (; j  < rwholebeams; j++)
742         {
743           Molecule b (a);
744           b.translate (Offset (Stem::invisible_b (here) ? 0 : gap_f, -dir * bdy * j));
745           rightbeams.add_molecule (b);
746         }
747
748       w = w/2 <? nw_f;
749       if (rhalfs)
750         a = me->lookup_l ()->beam (dydx, w, thick);
751
752       for (; j  < rwholebeams + rhalfs; j++)
753         {
754           Molecule b (a);
755           b.translate_axis (- dir * bdy * j, Y_AXIS);
756           rightbeams.add_molecule (b);
757         }
758
759     }
760   leftbeams.add_molecule (rightbeams);
761
762   /*
763     Does beam quanting think  of the asymetry of beams? 
764     Refpoint is on bottom of symbol. (FIXTHAT) --hwn.
765    */
766   return leftbeams;
767 }
768
769 MAKE_SCHEME_CALLBACK(Beam,brew_molecule);
770 SCM
771 Beam::brew_molecule (SCM smob)
772 {
773   Score_element * me =unsmob_element (smob);
774
775   Molecule mol;
776   if (!gh_pair_p (me->get_elt_property ("stems")))
777     return SCM_EOL;
778   Real x0,dx;
779   Link_array<Item>stems = 
780     Pointer_group_interface__extract_elements (me, (Item*) 0, "stems");  
781   if (visible_stem_count (me))
782     {
783   // ugh -> use commonx
784       x0 = first_visible_stem (me)->relative_coordinate (0, X_AXIS);
785       dx = last_visible_stem (me)->relative_coordinate (0, X_AXIS) - x0;
786     }
787   else
788     {
789       x0 = stems[0]->relative_coordinate (0, X_AXIS);
790       dx = stems.top()->relative_coordinate (0, X_AXIS) - x0;
791     }
792   
793   
794   Real dy = gh_scm2double (me->get_elt_property ("height"));
795   Real dydx = dy && dx ? dy/dx : 0;
796   Real y = gh_scm2double (me->get_elt_property ("y-position"));
797
798
799   for (int j=0; j <stems.size  (); j++)
800     {
801       Item *i = stems[j];
802       Item * prev = (j > 0)? stems[j-1] : 0;
803       Item * next = (j < stems.size()-1) ? stems[j+1] :0;
804
805       Molecule sb = stem_beams (me, i, next, prev);
806       Real x = i->relative_coordinate (0, X_AXIS)-x0;
807       sb.translate (Offset (x, x * dydx + y));
808       mol.add_molecule (sb);
809     }
810   mol.translate_axis (x0 
811     - dynamic_cast<Spanner*> (me)->get_bound (LEFT)->relative_coordinate (0, X_AXIS), X_AXIS);
812
813   return mol.create_scheme ();
814 }
815
816 int
817 Beam::forced_stem_count (Score_element*me) 
818 {
819   Link_array<Item>stems = 
820     Pointer_group_interface__extract_elements ( me, (Item*) 0, "stems");
821   int f = 0;
822   for (int i=0; i < stems.size (); i++)
823     {
824       Item *s = stems[i];
825
826       if (Stem::invisible_b (s))
827         continue;
828
829       if (((int)Stem::chord_start_f (s)) 
830         && (Stem::get_direction (s ) != Stem::get_default_dir (s )))
831         f++;
832     }
833   return f;
834 }
835
836
837
838
839 /* TODO:
840    use filter and standard list functions.
841  */
842 int
843 Beam::visible_stem_count (Score_element*me) 
844 {
845   Link_array<Item>stems = 
846     Pointer_group_interface__extract_elements (me, (Item*) 0, "stems");
847   int c = 0;
848   for (int i = stems.size (); i--;)
849     {
850       if (!Stem::invisible_b (stems[i]))
851         c++;
852     }
853   return c;
854 }
855
856 Item*
857 Beam::first_visible_stem(Score_element*me) 
858 {
859   Link_array<Item>stems = 
860     Pointer_group_interface__extract_elements ( me, (Item*) 0, "stems");
861   
862   for (int i = 0; i < stems.size (); i++)
863     {
864       if (!Stem::invisible_b (stems[i]))
865         return stems[i];
866     }
867   return 0;
868 }
869
870 Item*
871 Beam::last_visible_stem(Score_element*me) 
872 {
873   Link_array<Item>stems = 
874     Pointer_group_interface__extract_elements ( me, (Item*) 0, "stems");
875   for (int i = stems.size (); i--;)
876     {
877       if (!Stem::invisible_b (stems[i]))
878         return stems[i];
879     }
880   return 0;
881 }
882
883
884 /*
885   [TODO]
886   handle rest under beam (do_post: beams are calculated now)
887   what about combination of collisions and rest under beam.
888
889   Should lookup
890     
891     rest -> stem -> beam -> interpolate_y_position ()
892 */
893 Real
894 Beam::rest_collision_callback (Score_element *rest, Axis a )
895 {
896   assert (a == Y_AXIS);
897
898   Score_element * st = unsmob_element (rest->get_elt_property ("stem"));
899   Score_element * stem = st;
900   if (!stem)
901     return 0.0;
902   Score_element * beam = unsmob_element (stem->get_elt_property ("beam"));
903   if (!beam || !Beam::has_interface (beam) || !Beam::visible_stem_count (beam))
904     return 0.0;
905
906   // make callback for rest from this.
907   Real beam_dy = 0;
908   Real beam_y = 0;
909
910
911   // todo: make sure this calced already.
912   SCM s = beam->get_elt_property ("height");
913   if (gh_number_p (s))
914     beam_dy = gh_scm2double (s);
915   
916   s = beam->get_elt_property ("y-position");
917   if (gh_number_p (s))
918     beam_y = gh_scm2double (s);
919   
920   // ugh -> use commonx
921   Real x0 = first_visible_stem(beam)->relative_coordinate (0, X_AXIS);
922   Real dx = last_visible_stem(beam)->relative_coordinate (0, X_AXIS) - x0;
923   Real dydx = beam_dy && dx ? beam_dy/dx : 0;
924
925   Direction d = Stem::get_direction (stem);
926   Real beamy = (stem->relative_coordinate (0, X_AXIS) - x0) * dydx + beam_y;
927
928   Real staff_space =   Staff_symbol_referencer::staff_space (rest);
929   Real rest_dim = rest->extent (Y_AXIS)[d]*2.0 / staff_space ;
930
931   Real minimum_dist
932     = gh_scm2double (rest->get_elt_property ("minimum-beam-collision-distance"));
933   Real dist =
934     minimum_dist +  -d  * (beamy - rest_dim) >? 0;
935
936   int stafflines = Staff_symbol_referencer::line_count (rest);
937
938   // move discretely by half spaces.
939   int discrete_dist = int (ceil (dist));
940
941   // move by whole spaces inside the staff.
942   if (discrete_dist < stafflines+1)
943     discrete_dist = int (ceil (discrete_dist / 2.0)* 2.0);
944
945   return  (-d *  discrete_dist);
946 }
947
948
949 bool
950 Beam::has_interface (Score_element*me)
951 {
952   return me->has_interface (ly_symbol2scm ("beam-interface"));
953 }
954
955 void
956 Beam::set_interface (Score_element*me)
957 {
958   Pointer_group_interface g (me, "stems");
959   g.set_interface ();
960
961   /*
962     why the init? No way to tell difference between default and user
963     override.  */
964   me->set_elt_property ("height", gh_int2scm (0)); // ugh.
965   me->set_elt_property ("y-position" ,gh_int2scm (0));
966   me->set_interface (ly_symbol2scm("beam-interface"));
967 }