]> git.donarmstrong.com Git - lilypond.git/blob - lily/constrained-breaking.cc
Merge branch 'lilypond/translation' of ssh://jomand@git.sv.gnu.org/srv/git/lilypond
[lilypond.git] / lily / constrained-breaking.cc
1 /*
2   constrained-breaking.cc -- implement a line breaker that
3   support limits on the number of systems
4
5   source file of the GNU LilyPond music typesetter
6
7   (c) 2006--2009 Joe Neeman <joeneeman@gmail.com>
8 */
9
10 #include "constrained-breaking.hh"
11
12 #include "international.hh"
13 #include "main.hh"
14 #include "output-def.hh"
15 #include "page-layout-problem.hh"
16 #include "paper-column.hh"
17 #include "paper-score.hh"
18 #include "simple-spacer.hh"
19 #include "system.hh"
20 #include "warn.hh"
21
22 /*
23   We use the following optimal substructure. Let W (A) be our weight function.
24
25   Let A_{k, n} = (a_{k, n, 1}, ... a_{k, n, k}) be the optimal set of line breaks
26   for k systems and n potential breakpoints. a_{k, n, k} = n (it is the end of
27   the piece)
28
29   Then A_{k+1, m} is contructed from
30   min_ {k < j < m} ( W (A_{k, j} :: m) )
31   where by A::m we denote appending m to the list A
32
33   Indices in the code:
34
35   The above algorithm makes it easy to end at a point before the end of the
36   score (just find A_{k, m} for some m < breaks_.size () - 1). However, we must
37   add information for starting at a point after the beginning. One constructor
38   allows the specification of a list of starting columns, start_. We then have
39   start_.size () different solution arrays. state_[i] is the array for the
40   solution starting at column number start_[i].
41
42   The indices "start" and "end" refer to the index in the start_ array of the
43   desired starting and ending columns.
44
45   each solution array looks like
46    a_{1,1,1} a_{2,1,2} a_{3,1,3} . . .
47        X     a_{2,2,2} a_{3,2,3} . . .
48        X         X     a_{3,3,3} . . .
49        .         .         .     .
50        .         .         .       .
51   where the X's mark invalid solutions (can't have more systems than
52   breakpoints). Note that each value is of the form a_{x, n, x}. This is because
53   a breakpoint of the form a_{x, n, x-1} will also be called a_{x-1, m, x-1} for
54   some m < n. Each cell in the array stores the value of its m (ie. the
55   ending breakpoint of the previous line) as "prev_".
56
57   For finding A_{sys, brk}, let "me" be the (sys_count, brk) cell in our
58   solution array (state_[start][sys * rank + brk]).
59
60   Then A_{sys, brk} = A_{sys - 1, me.prev_} :: me
61 */
62
63 /*
64   start and sys here are indexed from 0.
65   brk is indexed from starting_breakpoints_[start]
66   (for brk, starting_breakpoints_[start] is the beginning
67   of the piece; the smallest value we should ever see here is
68   starting_breakpoints_[start] + 1) */
69 bool
70 Constrained_breaking::calc_subproblem (vsize start, vsize sys, vsize brk)
71 {
72   assert (sys < systems_);
73   assert (start < start_.size ());
74   assert (brk < breaks_.size ());
75
76   bool found_something = false;
77   vsize start_col = starting_breakpoints_[start];
78   Matrix<Constrained_break_node> &st = state_[start];
79   vsize max_index = brk - start_col;
80   for (vsize j=max_index; j-- > sys;)
81     {
82       if (0 == sys && j > 0)
83         continue; /* the first line cannot have its first break after the beginning */
84
85       Line_details const &cur = lines_.at (brk, j + start_col);
86       if (isinf (cur.force_))
87         break;
88
89       Real prev_f = 0;
90       Real prev_dem = 0;
91
92       if (sys > 0)
93         {
94           prev_f = st.at (j, sys-1).details_.force_;
95           prev_dem = st.at (j, sys-1).demerits_;
96         }
97       if (isinf (prev_dem))
98         continue;
99
100       Real dem = combine_demerits (cur.force_, prev_f) + prev_dem + cur.break_penalty_;
101       Constrained_break_node &n = st.at (max_index, sys);
102       if (dem < n.demerits_)
103         {
104           found_something = true;
105           n.demerits_ = dem;
106           n.details_ = cur;
107           n.prev_ = j;
108         }
109     }
110   return found_something;
111 }
112
113
114 Column_x_positions
115 Constrained_breaking::space_line (vsize i, vsize j)
116 {
117   bool ragged_right = to_boolean (pscore_->layout ()->c_variable ("ragged-right"));
118   bool ragged_last = to_boolean (pscore_->layout ()->c_variable ("ragged-last"));
119   Column_x_positions col;
120
121   vector<Grob*> line (all_.begin () + breaks_[i],
122                       all_.begin () + breaks_[j] + 1);
123   Interval line_dims = line_dimensions_int (pscore_->layout (), i);
124   bool last = j == breaks_.size () - 1;
125   bool ragged = ragged_right || (last && ragged_last);
126
127   /* As a special case, if there is only one line in the score and ragged-right
128      hasn't been specifically forbidden and the line is stretched, use
129      ragged spacing. */
130   if (last && i == 0
131       && lines_.at (i, j).force_ >= 0
132       && !scm_is_bool (pscore_->layout ()->c_variable ("ragged-right"))
133       && !scm_is_bool (pscore_->layout ()->c_variable ("ragged-last")))
134     ragged = true;
135
136   return get_line_configuration (line, line_dims[RIGHT] - line_dims[LEFT], line_dims[LEFT], ragged);
137 }
138
139 void
140 Constrained_breaking::resize (vsize systems)
141 {
142   systems_ = systems;
143
144   if (pscore_ && systems_ > valid_systems_)
145     {
146       for (vsize i = 0; i < state_.size (); i++)
147         state_[i].resize (breaks_.size () - starting_breakpoints_[i], systems_, Constrained_break_node ());
148
149       /* fill out the matrices */
150       for (vsize i = 0; i < state_.size (); i++)
151         for (vsize j = valid_systems_; j < systems_; j++)
152           for (vsize k = starting_breakpoints_[i] + j + 1; k < breaks_.size (); k++)
153             if (!calc_subproblem (i, j, k))
154               break; /* if we couldn't break this, it is too cramped already */
155       valid_systems_ = systems_;
156     }
157 }
158
159 vector<Column_x_positions>
160 Constrained_breaking::solve (vsize start, vsize end, vsize sys_count)
161 {
162   vsize start_brk = starting_breakpoints_[start];
163   vsize end_brk = prepare_solution (start, end, sys_count);
164
165   Matrix<Constrained_break_node> const &st = state_[start];
166   vector<Column_x_positions> ret;
167
168   /* find the first solution that satisfies constraints */
169   for (vsize sys = sys_count-1; sys != VPOS; sys--)
170     {
171       for (vsize brk = end_brk; brk != VPOS; brk--)
172         {
173           if (!isinf (st.at (brk, sys).details_.force_))
174             {
175               if (brk != end_brk)
176                 {
177                   warning (_ ("cannot find line breaking that satisfies constraints" ));
178                   ret.push_back (space_line (brk, end_brk));
179                 }
180               /* build up the good solution */
181               for (vsize cur_sys = sys; cur_sys != VPOS; cur_sys--)
182                 {
183                   vsize prev_brk = st.at (brk, cur_sys).prev_;
184                   assert (brk != VPOS);
185                   ret.push_back (space_line (prev_brk + start_brk, brk + start_brk));
186                   brk = prev_brk;
187                 }
188               reverse (ret);
189               return ret;
190             }
191         }
192     }
193   /* if we get to here, just put everything on one line */
194   warning (_ ("cannot find line breaking that satisfies constraints"));
195   ret.push_back (space_line (0, end_brk));
196   return ret;
197 }
198
199 vector<Column_x_positions>
200 Constrained_breaking::best_solution (vsize start, vsize end)
201 {
202   vsize min_systems = min_system_count (start, end);
203   vsize max_systems = max_system_count (start, end);
204   Real best_demerits = infinity_f;
205   vector<Column_x_positions> best_so_far;
206
207   for (vsize i = min_systems; i <= max_systems; i++)
208     {
209       vsize brk = prepare_solution (start, end, i);
210       Real dem = state_[start].at (brk, i-1).demerits_;
211
212       if (dem < best_demerits)
213         {
214           best_demerits = dem;
215           best_so_far = solve (start, end, i);
216         }
217       else
218         {
219           vector<Column_x_positions> cur = solve (start, end, i);
220           bool too_many_lines = true;
221           
222           for (vsize j = 0; j < cur.size (); j++)
223             if (cur[j].force_ < 0)
224               {
225                 too_many_lines = false;
226                 break;
227               }
228           if (too_many_lines)
229             return best_so_far;
230         }
231     }
232   if (best_so_far.size ())
233     return best_so_far;
234   return solve (start, end, max_systems);
235 }
236
237 std::vector<Line_details>
238 Constrained_breaking::line_details (vsize start, vsize end, vsize sys_count)
239 {
240   vsize brk = prepare_solution (start, end, sys_count);
241   Matrix<Constrained_break_node> const &st = state_[start];
242   vector<Line_details> ret;
243
244   for (int sys = sys_count-1; sys >= 0 && brk != VPOS; sys--)
245     {
246       ret.push_back (st.at (brk, sys).details_);
247       brk = st.at (brk, sys).prev_;
248     }
249   reverse (ret);
250   return ret;
251 }
252
253 int
254 Constrained_breaking::min_system_count (vsize start, vsize end)
255 {
256   vsize sys_count;
257   vsize brk = prepare_solution (start, end, 1);
258   vsize rank = breaks_.size () - starting_breakpoints_[start];
259   Matrix<Constrained_break_node> const &st = state_[start];
260
261   /* sys_count < rank : rank is the # of breakpoints, we can't have more systems */
262   for (sys_count = 0; sys_count < rank; sys_count++)
263     {
264       if (sys_count >= valid_systems_)
265         {
266           resize (sys_count + 3);
267         }
268       if (!isinf (st.at (brk, sys_count).details_.force_))
269         return sys_count + 1;
270     }
271   /* no possible breaks satisfy constraints */
272   return 1;
273 }
274
275 int
276 Constrained_breaking::max_system_count (vsize start, vsize end)
277 {
278   vsize brk = (end >= start_.size ()) ? breaks_.size () - 1 : starting_breakpoints_[end];
279   return brk - starting_breakpoints_[start];
280 }
281
282 vsize
283 Constrained_breaking::prepare_solution (vsize start, vsize end, vsize sys_count)
284 {
285   assert (start < start_.size () && (end == VPOS || end <= start_.size ()));
286   assert (start < end);
287
288   resize (sys_count);
289   if (end == start_.size ())
290     end = VPOS;
291
292   vsize brk;
293   brk = end == VPOS ? breaks_.size () - 1 : starting_breakpoints_[end];
294   brk -= starting_breakpoints_[start];
295   return brk;
296 }
297
298 Constrained_breaking::Constrained_breaking (Paper_score *ps)
299 {
300   valid_systems_ = systems_ = 0;
301   start_.push_back (0);
302   pscore_ = ps;
303   initialize ();
304 }
305
306 Constrained_breaking::Constrained_breaking (Paper_score *ps, vector<vsize> const &start)
307   : start_ (start)
308 {
309   valid_systems_ = systems_ = 0;
310   pscore_ = ps;
311   initialize ();
312 }
313
314 static SCM
315 min_permission (SCM perm1, SCM perm2)
316 {
317   if (perm1 == ly_symbol2scm ("force"))
318     return perm2;
319   if (perm1 == ly_symbol2scm ("allow")
320      && perm2 != ly_symbol2scm ("force"))
321     return perm2;
322   return SCM_EOL;
323 }
324
325 /* find the forces for all possible lines and cache ragged_ and ragged_right_ */
326 void
327 Constrained_breaking::initialize ()
328 {
329   if (!pscore_)
330     return;
331
332   ragged_right_ = to_boolean (pscore_->layout ()->c_variable ("ragged-right"));
333   ragged_last_ = to_boolean (pscore_->layout ()->c_variable ("ragged-last"));
334       
335   Output_def *l = pscore_->layout ();
336   System *sys = pscore_->root_system ();
337
338   // TODO: add support for minimum-distance and stretchability here and
339   // to the page-breaker.
340   SCM spacing_spec = l->c_variable ("between-system-spacing");
341   SCM page_breaking_spacing_spec = l->c_variable ("page-breaking-between-system-spacing");
342   Real space = 0;
343   Real padding = 0;
344   Page_layout_problem::read_spacing_spec (spacing_spec, &padding, ly_symbol2scm ("padding"));
345   Page_layout_problem::read_spacing_spec (page_breaking_spacing_spec, &padding, ly_symbol2scm ("padding"));
346
347   Interval first_line = line_dimensions_int (pscore_->layout (), 0);
348   Interval other_lines = line_dimensions_int (pscore_->layout (), 1);
349   /* do all the rod/spring problems */
350   breaks_ = pscore_->find_break_indices ();
351   all_ = pscore_->root_system ()->used_columns ();
352   lines_.resize (breaks_.size (), breaks_.size (), Line_details ());
353   vector<Real> forces = get_line_forces (all_,
354                                          other_lines.length (),
355                                          other_lines.length () - first_line.length (),
356                                          ragged_right_);
357   for (vsize i = 0; i + 1 < breaks_.size (); i++)
358     {
359       for (vsize j = i + 1; j < breaks_.size (); j++)
360         {
361           int start = Paper_column::get_rank (all_[breaks_[i]]);
362           int end = Paper_column::get_rank (all_[breaks_[j]]);
363           Interval extent = sys->pure_height (sys, start, end);
364           bool last = j == breaks_.size () - 1;
365           bool ragged = ragged_right_ || (last && ragged_last_);
366           Line_details &line = lines_.at (j, i);
367
368           line.force_ = forces[i*breaks_.size () + j];
369           if (ragged && last && !isinf (line.force_))
370             line.force_ = (line.force_ < 0 && j > i + 1) ? infinity_f : 0;
371           if (isinf (line.force_))
372             break;
373
374           Grob *c = all_[breaks_[j]];
375           line.last_column_ = c;
376           line.break_penalty_ = robust_scm2double (c->get_property ("line-break-penalty"), 0);
377           line.page_penalty_ = robust_scm2double (c->get_property ("page-break-penalty"), 0);
378           line.turn_penalty_ = robust_scm2double (c->get_property ("page-turn-penalty"), 0);
379           line.break_permission_ = c->get_property ("line-break-permission");
380           line.page_permission_ = c->get_property ("page-break-permission");
381           line.turn_permission_ = c->get_property ("page-turn-permission");
382           
383           /* turn permission should always be stricter than page permission
384              and page permission should always be stricter than line permission */
385           line.page_permission_ = min_permission (line.break_permission_,
386                                                   line.page_permission_);
387           line.turn_permission_ = min_permission (line.page_permission_,
388                                                   line.turn_permission_);
389
390           // TODO: see the hack regarding begin_of_line and
391           // rest_of_line extents in align-interface.  Perhaps we
392           // should do the same thing here so that the effect extends
393           // between systems as well as within systems.  It isn't as
394           // crucial here, however, because the effect is largest when
395           // dealing with large systems.
396           line.extent_ = (extent.is_empty ()
397                           || isnan (extent[LEFT])
398                           || isnan (extent[RIGHT]))
399             ? Interval (0, 0) : extent;
400           line.padding_ = padding;
401           line.space_ = space;
402           line.inverse_hooke_ = extent.length () + space;
403         }
404     }
405
406   /* work out all the starting indices */
407   for (vsize i = 0; i < start_.size (); i++)
408     {
409       vsize j;
410       for (j = 0; j + 1 < breaks_.size () && breaks_[j] < start_[i]; j++)
411         ;
412       starting_breakpoints_.push_back (j);
413       start_[i] = breaks_[j];
414     }
415   state_.resize (start_.size ());
416 }
417
418 Real
419 Constrained_breaking::combine_demerits (Real force, Real prev_force)
420 {
421   if (ragged_right_)
422     return force * force;
423
424   return force * force + (prev_force - force) * (prev_force - force);
425 }
426