Debian Codegraph @

converter/other/pamtosvg/fit.c

raw symbols SCIP
1 /* fit.c: turn a bitmap representation of a curve into a list of splines.
2 Some of the ideas, but not the code, comes from the Phoenix thesis.
3 See README for the reference.
4
5 The code was partially derived from limn.
6
7 Copyright (C) 1992 Free Software Foundation, Inc.
8
9 This program is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2, or (at your option)
12 any later version.
13
14 This program is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with this program; if not, write to the Free Software
21 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */
22
23 #include <math.h>
24 #include <limits.h>
25 #include <float.h>
26 #include <string.h>
27 #include <assert.h>
28
29 #include "pm_c_util.h"
30 #include "mallocvar.h"
31
32 #include "autotrace.h"
33 #include "fit.h"
34 #include "message.h"
35 #include "logreport.h"
36 #include "spline.h"
37 #include "point.h"
38 #include "vector.h"
39 #include "curve.h"
40 #include "pxl-outline.h"
41 #include "epsilon.h"
42
43 #define CUBE(x) ((x) * (x) * (x))
44
45 typedef enum {LINEEND_INIT, LINEEND_TERM} LineEnd;
46
47 static LineEnd
48 otherEnd(LineEnd const thisEnd) {
49
50 switch (thisEnd) {
51 case LINEEND_INIT: return LINEEND_TERM;
52 case LINEEND_TERM: return LINEEND_INIT;
53 }
54 assert(false); /* All cases handled above */
55 return LINEEND_INIT; /* silence bogus compiler warning */
56 }
57
58
59
60 /* We need to manipulate lists of array indices. */
61
62 typedef struct IndexList {
63 unsigned int * data;
64 unsigned int length;
65 } IndexList;
66
67 /* The usual accessor macros. */
68 #define GET_INDEX(i_l, n) ((i_l).data[n])
69 #define INDEX_LIST_LENGTH(iL) ((iL).length)
70 #define GET_LAST_INDEX(iL) ((iL).data[INDEX_LIST_LENGTH(iL) - 1])
71
72
73
74
75 static pm_pixelcoord
76 intCoordFmReal(Point const realCoord) {
77 /*----------------------------------------------------------------------------
78 Turn an real point into a integer one.
79 -----------------------------------------------------------------------------*/
80
81 pm_pixelcoord intCoord;
82
83 intCoord.col = ROUND(realCoord.x);
84 intCoord.row = ROUND(realCoord.y);
85
86 return intCoord;
87 }
88
89
90
91 /* Lists of array indices (well, that is what we use it for). */
92
93 static IndexList
94 indexList_new(void) {
95
96 IndexList indexList;
97
98 indexList.data = NULL;
99 INDEX_LIST_LENGTH(indexList) = 0;
100
101 return indexList;
102 }
103
104
105
106 static void
107 indexList_free(IndexList * const indexListP) {
108
109 if (INDEX_LIST_LENGTH(*indexListP) > 0) {
110 free(indexListP->data);
111 indexListP->data = NULL;
112 INDEX_LIST_LENGTH(*indexListP) = 0;
113 }
114 }
115
116
117
118 static void
119 indexList_append(IndexList * const listP,
120 unsigned int const newIndex) {
121
122 INDEX_LIST_LENGTH(*listP)++;
123 REALLOCARRAY_NOFAIL(listP->data, INDEX_LIST_LENGTH(*listP));
124 listP->data[INDEX_LIST_LENGTH(*listP) - 1] = newIndex;
125 }
126
127
128
129 static void
130 appendCorner(IndexList * const cornerListP,
131 unsigned int const pixelSeq,
132 pixel_outline_type const outline,
133 float const angle,
134 char const logType) {
135
136 pm_pixelcoord const coord = O_COORDINATE(outline, pixelSeq);
137
138 indexList_append(cornerListP, pixelSeq);
139 LOG4(" (%d,%d)%c%.3f", coord.col, coord.row, logType, angle);
140 }
141
142
143
144 static void
145 findVectors(unsigned int const testIndex,
146 pixel_outline_type const outline,
147 Vector * const inP,
148 Vector * const outP,
149 unsigned int const cornerSurround) {
150 /*----------------------------------------------------------------------------
151 Return the difference vectors coming in and going out of the outline
152 OUTLINE at the point whose index is TEST_INDEX. In Phoenix,
153 Schneider looks at a single point on either side of the point we're
154 considering. That works for him because his points are not touching.
155 But our points *are* touching, and so we have to look at
156 'cornerSurround' points on either side, to get a better picture of
157 the outline's shape.
158 -----------------------------------------------------------------------------*/
159 pm_pixelcoord const candidate = O_COORDINATE(outline, testIndex);
160
161 unsigned int i;
162 unsigned int doneCt;
163
164 inP->dx = inP->dy = inP->dz = 0.0;
165 outP->dx = outP->dy = outP->dz = 0.0;
166
167 /* Add up the differences from p of the `corner_surround' points before p.
168 */
169 for (i = O_PREV(outline, testIndex), doneCt = 0;
170 doneCt < cornerSurround;
171 i = O_PREV(outline, i), ++doneCt)
172 *inP = vector_sum(*inP, vector_IPointDiff(O_COORDINATE(outline, i),
173 candidate));
174
175 /* And the points after p. */
176 for (i = O_NEXT(outline, testIndex), doneCt = 0;
177 doneCt < cornerSurround;
178 i = O_NEXT(outline, i), ++doneCt)
179 *outP = vector_sum(*outP, vector_IPointDiff(O_COORDINATE(outline, i),
180 candidate));
181 }
182
183
184
185 static void
186 lookAheadForBetterCorner(pixel_outline_type const outline,
187 unsigned int const basePixelSeq,
188 float const baseCornerAngle,
189 unsigned int const cornerSurround,
190 unsigned int const cornerAlwaysThreshold,
191 unsigned int * const highestExaminedP,
192 float * const bestCornerAngleP,
193 unsigned int * const bestCornerIndexP,
194 IndexList * const equallyGoodListP,
195 IndexList * const cornerListP,
196 at_exception_type * const exceptionP) {
197 /*----------------------------------------------------------------------------
198 'basePixelSeq' is the sequence position within 'outline' of a pixel
199 that has a sufficiently small angle (to wit 'baseCornerAngle') to
200 be a corner. We look ahead in 'outline' for an even better one.
201 We'll look up to 'cornerSurround' pixels ahead.
202
203 We return the pixel sequence of the best corner we find (which could
204 be the base) as *bestCornerIndexP. Its angle is *bestCornerAngleP.
205
206 We return as *highestExaminedP the pixel sequence of the last pixel
207 we examined in our search (Caller can use this information to avoid
208 examining them again).
209
210 And we have this really dirty side effect: If we encounter any
211 corner whose angle is less than 'cornerAlwaysThreshold', we add
212 that to the list *cornerListP along the way.
213 -----------------------------------------------------------------------------*/
214 float bestCornerAngle;
215 unsigned bestCornerIndex;
216 IndexList equallyGoodList;
217 unsigned int q;
218 unsigned int i;
219
220 bestCornerIndex = basePixelSeq; /* initial assumption */
221 bestCornerAngle = baseCornerAngle; /* initial assumption */
222
223 equallyGoodList = indexList_new();
224
225 q = basePixelSeq;
226 i = basePixelSeq + 1; /* Start with the next pixel */
227
228 while (i < bestCornerIndex + cornerSurround &&
229 i < O_LENGTH(outline) &&
230 !at_exception_got_fatal(exceptionP)) {
231
232 Vector inVector, outVector;
233 float cornerAngle;
234
235 /* Check the angle. */
236
237 q = i % O_LENGTH(outline);
238 findVectors(q, outline, &inVector, &outVector, cornerSurround);
239 cornerAngle = vector_angle(inVector, outVector, exceptionP);
240 if (!at_exception_got_fatal(exceptionP)) {
241 /* Perhaps the angle is sufficiently small that we want to
242 consider this a corner, even if it's not the best
243 (unless we've already wrapped around in the search, in
244 which case we have already added the corner, and we
245 don't want to add it again).
246 */
247 if (cornerAngle <= cornerAlwaysThreshold && q >= basePixelSeq)
248 appendCorner(cornerListP, q, outline, cornerAngle, '\\');
249
250 if (epsilon_equal(cornerAngle, bestCornerAngle))
251 indexList_append(&equallyGoodList, q);
252 else if (cornerAngle < bestCornerAngle) {
253 bestCornerAngle = cornerAngle;
254 /* We want to check `cornerSurround' pixels beyond the
255 new best corner.
256 */
257 i = bestCornerIndex = q;
258 indexList_free(&equallyGoodList);
259 equallyGoodList = indexList_new();
260 }
261 ++i;
262 }
263 }
264 *bestCornerAngleP = bestCornerAngle;
265 *bestCornerIndexP = bestCornerIndex;
266 *equallyGoodListP = equallyGoodList;
267 *highestExaminedP = q;
268 }
269
270
271
272 static void
273 establishCornerSearchLimits(pixel_outline_type const outline,
274 fitting_opts_type * const fittingOptsP,
275 unsigned int * const firstP,
276 unsigned int * const lastP) {
277 /*----------------------------------------------------------------------------
278 Determine where in the outline 'outline' we should look for corners.
279 -----------------------------------------------------------------------------*/
280 assert(O_LENGTH(outline) >= 1);
281 assert(O_LENGTH(outline) - 1 >= fittingOptsP->corner_surround);
282
283 *firstP = 0;
284 *lastP = O_LENGTH(outline) - 1;
285 if (outline.open) {
286 *firstP += fittingOptsP->corner_surround;
287 *lastP -= fittingOptsP->corner_surround;
288 }
289 }
290
291
292
293 static void
294 removeAdjacentCorners(IndexList * const listP,
295 unsigned int const lastIndex,
296 bool const mustRemoveAdjCorners,
297 at_exception_type * const exception) {
298 /*----------------------------------------------------------------------------
299 Remove adjacent points from the index list LIST. We do this by first
300 sorting the list and then running through it. Since these lists are
301 quite short, a straight selection sort (e.g., p.139 of the Art of
302 Computer Programming, vol.3) is good enough. LAST_INDEX is the index
303 of the last pixel on the outline, i.e., the next one is the first
304 pixel. We need this for checking the adjacency of the last corner.
305
306 We need to do this because the adjacent corners turn into
307 two-pixel-long curves, which can be fit only by straight lines.
308 -----------------------------------------------------------------------------*/
309 unsigned int j;
310 unsigned int last;
311 IndexList newList;
312
313 newList = indexList_new(); /* initial value */
314
315 for (j = INDEX_LIST_LENGTH (*listP) - 1; j > 0; --j) {
316 unsigned int search;
317 unsigned int maxIndex;
318 /* We find maximal element below `j' */
319
320 for (search = 0, maxIndex = j; search < j; ++search)
321 if (GET_INDEX (*listP, search) > GET_INDEX (*listP, maxIndex))
322 maxIndex = search;
323
324 if (maxIndex != j) {
325 unsigned int const temp = GET_INDEX (*listP, j);
326 GET_INDEX (*listP, j) = GET_INDEX (*listP, maxIndex);
327 GET_INDEX (*listP, maxIndex) = temp;
328 }
329 }
330
331 /* The list is sorted. Now look for adjacent entries. Each time through
332 the loop we insert the current entry and, if appropriate, the next
333 entry.
334 */
335 for (j = 0; j < INDEX_LIST_LENGTH(*listP) - 1; ++j) {
336 unsigned int const current = GET_INDEX(*listP, j);
337 unsigned int const next = GET_INDEX(*listP, j + 1);
338
339 /* We should never have inserted the same element twice. */
340 /* assert (current != next); */
341
342 if ((mustRemoveAdjCorners) && ((next == current + 1) ||
343 (next == current)))
344 ++j;
345
346 indexList_append(&newList, current);
347 }
348
349 /* Don't append the last element if it is 1) adjacent to the previous one;
350 or 2) adjacent to the very first one.
351 */
352 last = GET_LAST_INDEX(*listP);
353 if (INDEX_LIST_LENGTH(newList) == 0
354 || !(last == GET_LAST_INDEX(newList) + 1
355 || (last == lastIndex && GET_INDEX(*listP, 0) == 0)))
356 indexList_append(&newList, last);
357
358 indexList_free(listP);
359 *listP = newList;
360 }
361
362
363
364 /* A ``knee'' is a point which forms a ``right angle'' with its
365 predecessor and successor. See the documentation (the `Removing
366 knees' section) for an example and more details.
367
368 The argument CLOCKWISE tells us which direction we're moving. (We
369 can't figure that information out from just the single segment with
370 which we are given to work.)
371
372 We should never find two consecutive knees.
373
374 Since the first and last points are corners (unless the curve is
375 cyclic), it doesn't make sense to remove those.
376 */
377
378 /* This evaluates to true if the vector V is zero in one direction and
379 nonzero in the other. */
380 #define ONLY_ONE_ZERO(v) \
381 (((v).dx == 0.0 && (v).dy != 0.0) || ((v).dy == 0.0 && (v).dx != 0.0))
382
383 /* There are four possible cases for knees, one for each of the four
384 corners of a rectangle; and then the cases differ depending on which
385 direction we are going around the curve. The tests are listed here
386 in the order of upper left, upper right, lower right, lower left.
387 Perhaps there is some simple pattern to the
388 clockwise/counterclockwise differences, but I don't see one. */
389 #define CLOCKWISE_KNEE(prev_delta, next_delta) \
390 ((prev_delta.dx == -1.0 && next_delta.dy == 1.0) \
391 || (prev_delta.dy == 1.0 && next_delta.dx == 1.0) \
392 || (prev_delta.dx == 1.0 && next_delta.dy == -1.0) \
393 || (prev_delta.dy == -1.0 && next_delta.dx == -1.0))
394
395 #define COUNTERCLOCKWISE_KNEE(prev_delta, next_delta) \
396 ((prev_delta.dy == 1.0 && next_delta.dx == -1.0) \
397 || (prev_delta.dx == 1.0 && next_delta.dy == 1.0) \
398 || (prev_delta.dy == -1.0 && next_delta.dx == 1.0) \
399 || (prev_delta.dx == -1.0 && next_delta.dy == -1.0))
400
401
402
403 static void
404 remove_knee_points(Curve * const curveP,
405 bool const clockwise) {
406
407 unsigned int const offset = CURVE_CYCLIC(curveP) ? 0 : 1;
408 Curve * const trimmedCurveP = curve_copyMost(curveP);
409
410 pm_pixelcoord previous;
411 unsigned int i;
412
413 if (!CURVE_CYCLIC(curveP))
414 curve_appendPixel(trimmedCurveP,
415 intCoordFmReal(CURVE_POINT(curveP, 0)));
416
417 previous = intCoordFmReal(CURVE_POINT(curveP,
418 CURVE_PREV(curveP, offset)));
419
420 for (i = offset; i < CURVE_LENGTH(curveP) - offset; ++i) {
421 pm_pixelcoord const current =
422 intCoordFmReal(CURVE_POINT(curveP, i));
423 pm_pixelcoord const next =
424 intCoordFmReal(CURVE_POINT(curveP, CURVE_NEXT(curveP, i)));
425 Vector const prev_delta = vector_IPointDiff(previous, current);
426 Vector const next_delta = vector_IPointDiff(next, current);
427
428 if (ONLY_ONE_ZERO(prev_delta) && ONLY_ONE_ZERO(next_delta)
429 && ((clockwise && CLOCKWISE_KNEE(prev_delta, next_delta))
430 || (!clockwise
431 && COUNTERCLOCKWISE_KNEE(prev_delta, next_delta))))
432 LOG2(" (%d,%d)", current.col, current.row);
433 else {
434 previous = current;
435 curve_appendPixel(trimmedCurveP, current);
436 }
437 }
438
439 if (!CURVE_CYCLIC(curveP))
440 curve_appendPixel(trimmedCurveP,
441 intCoordFmReal(LAST_CURVE_POINT(curveP)));
442
443 if (CURVE_LENGTH(trimmedCurveP) == CURVE_LENGTH(curveP))
444 LOG(" (none)");
445
446 LOG(".\n");
447
448 curve_move(curveP, trimmedCurveP);
449 }
450
451
452
453 static void
454 filter(Curve * const curveP,
455 fitting_opts_type * const fittingOptsP) {
456 /*----------------------------------------------------------------------------
457 Smooth the curve by adding in neighboring points. Do this
458 fittingOptsP->filter_iterations times. But don't change the corners.
459 -----------------------------------------------------------------------------*/
460 unsigned int const offset = CURVE_CYCLIC(curveP) ? 0 : 1;
461
462 unsigned int iteration, thisPoint;
463 Point prevNewPoint;
464
465 /* We must have at least three points -- the previous one, the current
466 one, and the next one. But if we don't have at least five, we will
467 probably collapse the curve down onto a single point, which means
468 we won't be able to fit it with a spline.
469 */
470 if (CURVE_LENGTH(curveP) < 5) {
471 LOG1("Length is %u, not enough to filter.\n", CURVE_LENGTH(curveP));
472 return;
473 }
474
475 prevNewPoint.x = FLT_MAX;
476 prevNewPoint.y = FLT_MAX;
477 prevNewPoint.z = FLT_MAX;
478
479 for (iteration = 0;
480 iteration < fittingOptsP->filter_iterations;
481 ++iteration) {
482 Curve * const newcurveP = curve_copyMost(curveP);
483
484 bool collapsed;
485
486 collapsed = false; /* initial value */
487
488 /* Keep the first point on the curve. */
489 if (offset)
490 curve_appendPoint(newcurveP, CURVE_POINT(curveP, 0));
491
492 for (thisPoint = offset;
493 thisPoint < CURVE_LENGTH(curveP) - offset;
494 ++thisPoint) {
495 Vector in, out, sum;
496 Point newPoint;
497
498 /* Calculate the vectors in and out, computed by looking
499 at n points on either side of this_point. Experimental
500 it was found that 2 is optimal.
501 */
502
503 signed int prev, prevprev; /* have to be signed */
504 unsigned int next, nextnext;
505 Point candidate = CURVE_POINT(curveP, thisPoint);
506
507 prev = CURVE_PREV(curveP, thisPoint);
508 prevprev = CURVE_PREV(curveP, prev);
509 next = CURVE_NEXT(curveP, thisPoint);
510 nextnext = CURVE_NEXT(curveP, next);
511
512 /* Add up the differences from p of the `surround' points
513 before p.
514 */
515 in.dx = in.dy = in.dz = 0.0;
516
517 in = vector_sum(in,
518 vector_fromTwoPoints(CURVE_POINT(curveP, prev),
519 candidate));
520 if (prevprev >= 0)
521 in = vector_sum(
522 in,
523 vector_fromTwoPoints(CURVE_POINT(curveP, prevprev),
524 candidate));
525
526 /* And the points after p. Don't use more points after p than we
527 ended up with before it.
528 */
529 out.dx = out.dy = out.dz = 0.0;
530
531 out = vector_sum(
532 out,
533 vector_fromTwoPoints(CURVE_POINT(curveP, next), candidate));
534 if (nextnext < CURVE_LENGTH(curveP))
535 out = vector_sum(
536 out,
537 vector_fromTwoPoints(CURVE_POINT(curveP, nextnext),
538 candidate));
539
540 /* Start with the old point. */
541 newPoint = candidate;
542 sum = vector_sum(in, out);
543 /* We added 2*n+2 points, so we have to divide the sum by 2*n+2 */
544 newPoint.x += sum.dx / 6;
545 newPoint.y += sum.dy / 6;
546 newPoint.z += sum.dz / 6;
547 if (fabs(prevNewPoint.x - newPoint.x) < 0.3
548 && fabs (prevNewPoint.y - newPoint.y) < 0.3
549 && fabs (prevNewPoint.z - newPoint.z) < 0.3) {
550 collapsed = true;
551 break;
552 }
553
554 /* Put the newly computed point into a separate curve, so it
555 doesn't affect future computation (on this iteration).
556 */
557 curve_appendPoint(newcurveP, prevNewPoint = newPoint);
558 }
559
560 if (collapsed)
561 curve_free(newcurveP);
562 else {
563 /* Just as with the first point, we have to keep the last
564 point.
565 */
566 if (offset)
567 curve_appendPoint(newcurveP, LAST_CURVE_POINT(curveP));
568
569 /* Set the original curve to the newly filtered one, and go
570 again.
571 */
572 curve_move(curveP, newcurveP);
573 }
574 }
575 curve_log(curveP, false);
576 }
577
578
579
580 static void
581 removeAdjacent(IndexList * const cornerListP,
582 pixel_outline_type const outline,
583 fitting_opts_type * const fittingOptsP,
584 at_exception_type * const exception) {
585
586 /* We never want two corners next to each other, since the
587 only way to fit such a ``curve'' would be with a straight
588 line, which usually interrupts the continuity dreadfully.
589 */
590
591 if (INDEX_LIST_LENGTH(*cornerListP) > 0)
592 removeAdjacentCorners(
593 cornerListP,
594 O_LENGTH(outline) - (outline.open ? 2 : 1),
595 fittingOptsP->remove_adjacent_corners,
596 exception);
597 }
598
599
600
601 static IndexList
602 findCorners(pixel_outline_type const outline,
603 fitting_opts_type * const fittingOptsP,
604 at_exception_type * const exceptionP) {
605
606 /* We consider a point to be a corner if (1) the angle defined by
607 the `corner_surround' points coming into it and going out from
608 it is less than `corner_threshold' degrees, and no point within
609 `corner_surround' points has a smaller angle; or (2) the angle
610 is less than `corner_always_threshold' degrees.
611 */
612 unsigned int p;
613 unsigned int firstPixelSeq, lastPixelSeq;
614 IndexList cornerList;
615
616 cornerList = indexList_new();
617
618 if (O_LENGTH(outline) <= fittingOptsP->corner_surround * 2 + 1)
619 return cornerList;
620
621 establishCornerSearchLimits(outline, fittingOptsP,
622 &firstPixelSeq, &lastPixelSeq);
623
624 /* Consider each pixel on the outline in turn. */
625 for (p = firstPixelSeq; p <= lastPixelSeq;) {
626 Vector inVector, outVector;
627 float cornerAngle;
628
629 /* Check if the angle is small enough. */
630 findVectors(p, outline, &inVector, &outVector,
631 fittingOptsP->corner_surround);
632 cornerAngle = vector_angle(inVector, outVector, exceptionP);
633 if (at_exception_got_fatal(exceptionP))
634 goto cleanup;
635
636 if (fabs(cornerAngle) <= fittingOptsP->corner_threshold) {
637 /* We want to keep looking, instead of just appending the
638 first pixel we find with a small enough angle, since there
639 might be another corner within `corner_surround' pixels, with
640 a smaller angle. If that is the case, we want that one.
641
642 If we come across a corner that is just as good as the
643 best one, we should make it a corner, too. This
644 happens, for example, at the points on the `W' in some
645 typefaces, where the "points" are flat.
646 */
647 float bestCornerAngle;
648 unsigned bestCornerIndex;
649 IndexList equallyGoodList;
650 unsigned int q;
651
652 if (cornerAngle <= fittingOptsP->corner_always_threshold)
653 /* The angle is sufficiently small that we want to
654 consider this a corner, even if it's not the best.
655 */
656 appendCorner(&cornerList, p, outline, cornerAngle, '\\');
657
658 lookAheadForBetterCorner(outline, p, cornerAngle,
659 fittingOptsP->corner_surround,
660 fittingOptsP->corner_always_threshold,
661 &q,
662 &bestCornerAngle, &bestCornerIndex,
663 &equallyGoodList,
664 &cornerList,
665 exceptionP);
666
667 if (at_exception_got_fatal(exceptionP))
668 goto cleanup;
669
670 /* `q' is the index of the last point lookAhead checked.
671 He added the corner if `bestCornerAngle' is less than
672 `corner_always_threshold'. If we've wrapped around, we
673 added the corner on the first pass. Otherwise, we add
674 the corner now.
675 */
676 if (bestCornerAngle > fittingOptsP->corner_always_threshold
677 && bestCornerIndex >= p) {
678
679 unsigned int j;
680
681 appendCorner(&cornerList, bestCornerIndex,
682 outline, bestCornerAngle, '/');
683
684 for (j = 0; j < INDEX_LIST_LENGTH (equallyGoodList); ++j)
685 appendCorner(&cornerList, GET_INDEX(equallyGoodList, j),
686 outline, bestCornerAngle, '@');
687 }
688 indexList_free(&equallyGoodList);
689
690 /* If we wrapped around in our search, we're done;
691 otherwise, we move on to the pixel after the highest
692 one we just checked.
693 */
694 p = (q < p) ? O_LENGTH(outline) : q + 1;
695 } else
696 ++p;
697 }
698 removeAdjacent(&cornerList, outline, fittingOptsP, exceptionP);
699
700 cleanup:
701 return cornerList;
702 }
703
704
705
706 static void
707 makeOutlineOneCurve(pixel_outline_type const outline,
708 CurveList * const curveListP) {
709 /*----------------------------------------------------------------------------
710 Add to *curveListP a single curve that represents the outline 'outline'.
711
712 That curve does not have beginning and ending slope information.
713 -----------------------------------------------------------------------------*/
714 Curve * curveP;
715 unsigned int pixelSeq;
716
717 curveP = curve_new();
718
719 for (pixelSeq = 0; pixelSeq < O_LENGTH(outline); ++pixelSeq)
720 curve_appendPixel(curveP, O_COORDINATE(outline, pixelSeq));
721
722 if (outline.open)
723 CURVE_CYCLIC(curveP) = false;
724 else
725 CURVE_CYCLIC(curveP) = true;
726
727 /* Make it a one-curve cycle */
728 NEXT_CURVE(curveP) = curveP;
729 PREVIOUS_CURVE(curveP) = curveP;
730
731 curve_appendList(curveListP, curveP);
732 }
733
734
735
736 static void
737 addCurveStartingAtCorner(pixel_outline_type const outline,
738 IndexList const cornerList,
739 unsigned int const cornerSeq,
740 CurveList * const curveListP,
741 Curve ** const curCurvePP) {
742 /*----------------------------------------------------------------------------
743 Add to the list *curveListP a new curve that starts at the cornerSeq'th
744 corner in outline 'outline' (whose corners are 'cornerList') and
745 goes to the next corner (or the end of the outline if no next corner).
746
747 Furthermore, add that curve to the curve chain whose end is pointed
748 to by *curCurvePP (NULL means chain is empty).
749
750 Don't include beginning and ending slope information for that curve.
751 -----------------------------------------------------------------------------*/
752 unsigned int const cornerPixelSeq = GET_INDEX(cornerList, cornerSeq);
753
754 unsigned int lastPixelSeq;
755 Curve * curveP;
756 unsigned int pixelSeq;
757
758 if (cornerSeq + 1 >= cornerList.length)
759 /* No more corners, so we go through the end of the outline. */
760 lastPixelSeq = O_LENGTH(outline) - 1;
761 else
762 /* Go through the next corner */
763 lastPixelSeq = GET_INDEX(cornerList, cornerSeq + 1);
764
765 curveP = curve_new();
766
767 for (pixelSeq = cornerPixelSeq; pixelSeq <= lastPixelSeq; ++pixelSeq)
768 curve_appendPixel(curveP, O_COORDINATE(outline, pixelSeq));
769
770 curve_appendList(curveListP, curveP);
771 {
772 /* Add the new curve to the outline chain */
773
774 Curve * const oldCurCurveP = *curCurvePP;
775
776 if (oldCurCurveP) {
777 NEXT_CURVE(oldCurCurveP) = curveP;
778 PREVIOUS_CURVE(curveP) = oldCurCurveP;
779 }
780 *curCurvePP = curveP;
781 }
782 }
783
784
785
786 static void
787 divideOutlineWithCorners(pixel_outline_type const outline,
788 IndexList const cornerList,
789 CurveList * const curveListP) {
790 /*----------------------------------------------------------------------------
791 Divide the outline 'outline' into curves at the corner points
792 'cornerList' and add each curve to *curveListP.
793
794 Each curve contains the corners at each end.
795
796 The last curve is special. It consists of the pixels (inclusive)
797 between the last corner and the end of the outline, and the
798 beginning of the outline and the first corner.
799
800 We link the curves in a chain. If the outline (and therefore the
801 curve list) is closed, the chain is a cycle of all the curves. If
802 it is open, the chain is a linear chain of all the curves except
803 the last one (the one that goes from the last corner to the first
804 corner).
805
806 Assume there is at least one corner.
807
808 The curves do not have beginning and ending slope information.
809 -----------------------------------------------------------------------------*/
810 unsigned int const firstCurveSeq = CURVE_LIST_LENGTH(*curveListP);
811 /* Index in curve list of the first curve we add */
812 unsigned int cornerSeq;
813 Curve * curCurveP;
814 /* Pointer to the curve we most recently added for this outline.
815 Null if none
816 */
817
818 assert(cornerList.length > 0);
819
820 curCurveP = NULL; /* No curves in outline chain yet */
821
822 if (outline.open) {
823 /* Start with a curve that contains the points up to the first
824 corner
825 */
826 Curve * curveP;
827 unsigned int pixelSeq;
828
829 curveP = curve_new();
830
831 for (pixelSeq = 0; pixelSeq <= GET_INDEX(cornerList, 0); ++pixelSeq)
832 curve_appendPixel(curveP, O_COORDINATE(outline, pixelSeq));
833
834 curve_appendList(curveListP, curveP);
835 curCurveP = curveP; /* Only curve in outline chain now */
836 } else {
837 /* We'll pick up the pixels before the first corner at the end */
838 }
839 /* Add to the list a curve that starts at each corner and goes
840 through the following corner, or the end of the outline if
841 there is no following corner. Do it in order of the corners.
842 */
843 for (cornerSeq = 0; cornerSeq < cornerList.length; ++cornerSeq)
844 addCurveStartingAtCorner(outline, cornerList, cornerSeq, curveListP,
845 &curCurveP);
846
847 if (!outline.open) {
848 /* Come around to the start of the curve list -- add the pixels
849 before the first corner to the last curve, and chain the last
850 curve to the first one.
851 */
852 Curve * const firstCurveP = CURVE_LIST_ELT(*curveListP, firstCurveSeq);
853
854 unsigned int pixelSeq;
855
856 for (pixelSeq = 0; pixelSeq <= GET_INDEX(cornerList, 0); ++pixelSeq)
857 curve_appendPixel(curCurveP, O_COORDINATE(outline, pixelSeq));
858
859 NEXT_CURVE(curCurveP) = firstCurveP;
860 PREVIOUS_CURVE(firstCurveP) = curCurveP;
861 }
862 }
863
864
865
866 static CurveListArray
867 split_at_corners(pixel_outline_list_type const pixelList,
868 fitting_opts_type * const fittingOptsP,
869 at_exception_type * const exception) {
870 /*----------------------------------------------------------------------------
871 Find the corners in 'pixelList', the list of points. (Presumably we
872 can't fit a single spline around a corner.) The general strategy
873 is to look through all the points, remembering which we want to
874 consider corners. Then go through that list, producing the
875 curve_list. This is dictated by the fact that 'pixelList' does not
876 necessarily start on a corner---it just starts at the character's
877 first outline pixel, going left-to-right, top-to-bottom. But we
878 want all our splines to start and end on real corners.
879
880 For example, consider the top of a capital `C' (this is in cmss20):
881 x
882 ***********
883 ******************
884
885 'pixelList' will start at the pixel below the `x'. If we considered
886 this pixel a corner, we would wind up matching a very small segment
887 from there to the end of the line, probably as a straight line, which
888 is certainly not what we want.
889
890 'pixelList' has one element for each closed outline on the character.
891 To preserve this information, we return an array of curve_lists, one
892 element (which in turn consists of several curves, one between each
893 pair of corners) for each element in 'pixelList'.
894
895 The curves we return do not have beginning and ending slope
896 information.
897 -----------------------------------------------------------------------------*/
898 unsigned outlineSeq;
899 CurveListArray curveArray;
900
901 curveArray = curve_newListArray();
902
903 LOG("\nFinding corners:\n");
904
905 for (outlineSeq = 0;
906 outlineSeq < O_LIST_LENGTH(pixelList);
907 ++outlineSeq) {
908
909 pixel_outline_type const outline =
910 O_LIST_OUTLINE(pixelList, outlineSeq);
911
912 IndexList cornerList;
913 CurveList curveList;
914
915 curveList = curve_newList();
916
917 CURVE_LIST_CLOCKWISE(curveList) = O_CLOCKWISE(outline);
918 curveList.color = outline.color;
919 curveList.open = outline.open;
920
921 LOG1("#%u:", outlineSeq);
922
923 /* If the outline does not have enough points, we can't do
924 anything. The endpoints of the outlines are automatically
925 corners. We need at least `corner_surround' more pixels on
926 either side of a point before it is conceivable that we might
927 want another corner.
928 */
929 if (O_LENGTH(outline) > fittingOptsP->corner_surround * 2 + 2)
930 cornerList = findCorners(outline, fittingOptsP, exception);
931
932 else {
933 int const surround = (O_LENGTH(outline) - 3) / 2;
934 if (surround >= 2) {
935 unsigned int const oldCornerSurround =
936 fittingOptsP->corner_surround;
937 fittingOptsP->corner_surround = surround;
938 cornerList = findCorners(outline, fittingOptsP, exception);
939 fittingOptsP->corner_surround = oldCornerSurround;
940 } else {
941 cornerList.length = 0;
942 cornerList.data = NULL;
943 }
944 }
945
946 if (cornerList.length == 0)
947 /* No corners. Use all of the pixel outline as the one curve. */
948 makeOutlineOneCurve(outline, &curveList);
949 else
950 divideOutlineWithCorners(outline, cornerList, &curveList);
951
952 LOG1(" [%u].\n", cornerList.length);
953 indexList_free(&cornerList);
954
955 /* And now add the just-completed curve list to the array. */
956 curve_appendArray(&curveArray, curveList);
957 }
958
959 return curveArray;
960 }
961
962
963
964 static void
965 removeKnees(CurveList const curveList) {
966 /*----------------------------------------------------------------------------
967 Remove the extraneous ``knee'' points before filtering. Since the
968 corners have already been found, we don't need to worry about
969 removing a point that should be a corner.
970 -----------------------------------------------------------------------------*/
971 unsigned int curveSeq;
972
973 LOG("\nRemoving knees:\n");
974
975 for (curveSeq = 0; curveSeq < curveList.length; ++curveSeq) {
976 LOG1("#%u:", curveSeq);
977 remove_knee_points(CURVE_LIST_ELT(curveList, curveSeq),
978 CURVE_LIST_CLOCKWISE(curveList));
979 }
980 }
981
982
983
984 static void
985 computePointWeights(CurveList const curveList,
986 fitting_opts_type * const fittingOptsP,
987 distance_map_type * const distP) {
988
989 unsigned int const height = distP->height;
990
991 unsigned int curveSeq;
992
993 for (curveSeq = 0; curveSeq < curveList.length; ++curveSeq) {
994 Curve * const curveP = CURVE_LIST_ELT(curveList, curveSeq);
995
996 unsigned pointSeq;
997
998 for (pointSeq = 0; pointSeq < CURVE_LENGTH(curveP); ++pointSeq) {
999 Point * const coordP = &CURVE_POINT(curveP, pointSeq);
1000 unsigned int const x = coordP->x;
1001 unsigned int const y = height - (unsigned int)coordP->y - 1;
1002
1003 float width, w;
1004
1005 /* Each (x, y) is a point on the skeleton of the curve, which
1006 might be offset from the true centerline, where the width
1007 is maximal. Therefore, use as the local line width the
1008 maximum distance over the neighborhood of (x, y).
1009 */
1010 width = distP->d[y][x]; /* initial value */
1011 if (y - 1 >= 0) {
1012 if ((w = distP->d[y-1][x]) > width)
1013 width = w;
1014 if (x - 1 >= 0) {
1015 if ((w = distP->d[y][x-1]) > width)
1016 width = w;
1017 if ((w = distP->d[y-1][x-1]) > width)
1018 width = w;
1019 }
1020 if (x + 1 < distP->width) {
1021 if ((w = distP->d[y][x+1]) > width)
1022 width = w;
1023 if ((w = distP->d[y-1][x+1]) > width)
1024 width = w;
1025 }
1026 }
1027 if (y + 1 < height) {
1028 if ((w = distP->d[y+1][x]) > width)
1029 width = w;
1030 if (x - 1 >= 0 && (w = distP->d[y+1][x-1]) > width)
1031 width = w;
1032 if (x + 1 < distP->width && (w = distP->d[y+1][x+1]) > width)
1033 width = w;
1034 }
1035 coordP->z = width * (fittingOptsP->width_weight_factor);
1036 }
1037 }
1038 }
1039
1040
1041
1042 static void
1043 filterCurves(CurveList const curveList,
1044 fitting_opts_type * const fittingOptsP) {
1045
1046 unsigned int curveSeq;
1047
1048 LOG("\nFiltering curves:\n");
1049
1050 for (curveSeq = 0; curveSeq < curveList.length; ++curveSeq) {
1051 LOG1("#%u: ", curveSeq);
1052 filter(CURVE_LIST_ELT(curveList, curveSeq), fittingOptsP);
1053 }
1054 }
1055
1056
1057
1058 static void
1059 logSplinesForCurve(unsigned int const curveSeq,
1060 spline_list_type const curveSplines) {
1061
1062 unsigned int splineSeq;
1063
1064 LOG1("Fitted splines for curve #%u:\n", curveSeq);
1065 for (splineSeq = 0;
1066 splineSeq < SPLINE_LIST_LENGTH(curveSplines);
1067 ++splineSeq) {
1068 LOG1(" %u: ", splineSeq);
1069 if (log_file)
1070 print_spline(log_file, SPLINE_LIST_ELT(curveSplines, splineSeq));
1071 }
1072 }
1073
1074
1075
1076 static void
1077 changeBadLines(spline_list_type * const splineListP,
1078 const fitting_opts_type * const fittingOptsP) {
1079
1080 /* Unfortunately, we cannot tell in isolation whether a given spline
1081 should be changed to a line or not. That be known only after the
1082 entire curve has been fit to a list of splines. (The curve is the
1083 pixel outline between two corners.) After subdividing the curve, a
1084 line may very well fit a portion of the curve just as well as the
1085 spline---but unless a spline is truly close to being a line, it should
1086 not be combined with other lines.
1087 */
1088
1089 unsigned int const length = SPLINE_LIST_LENGTH(*splineListP);
1090
1091 unsigned int thisSpline;
1092 bool foundCubic;
1093
1094 LOG1("\nChecking for bad lines (length %u):\n", length);
1095
1096 /* First see if there are any splines in the fitted shape. */
1097 for (thisSpline = 0, foundCubic = false;
1098 thisSpline < length;
1099 ++thisSpline) {
1100 if (SPLINE_DEGREE(SPLINE_LIST_ELT(*splineListP, thisSpline)) ==
1101 CUBICTYPE) {
1102 foundCubic = true;
1103 break;
1104 }
1105 }
1106
1107 /* If so, change lines back to splines (we haven't done anything to
1108 their control points, so we only have to change the degree) unless
1109 the spline is close enough to being a line.
1110 */
1111 if (foundCubic) {
1112 unsigned int thisSpline;
1113
1114 for (thisSpline = 0; thisSpline < length; ++thisSpline) {
1115 spline_type const s = SPLINE_LIST_ELT(*splineListP, thisSpline);
1116
1117 if (SPLINE_DEGREE(s) == LINEARTYPE) {
1118 LOG1(" #%u: ", thisSpline);
1119 if (SPLINE_LINEARITY(s) >
1120 fittingOptsP->line_reversion_threshold) {
1121 LOG("reverted, ");
1122 SPLINE_DEGREE(SPLINE_LIST_ELT(*splineListP, thisSpline))
1123 = CUBICTYPE;
1124 }
1125 LOG1("linearity %.3f.\n", SPLINE_LINEARITY(s));
1126 }
1127 }
1128 } else
1129 LOG(" No lines.\n");
1130 }
1131
1132
1133
1134 static bool
1135 splineLinearEnough(spline_type * const splineP,
1136 Curve * const curve,
1137 const fitting_opts_type * const fittingOptsP) {
1138
1139 /* Supposing that we have accepted the error, another question arises:
1140 would we be better off just using a straight line?
1141 */
1142
1143 float A, B, C;
1144 unsigned int thisPoint;
1145 float dist;
1146 float startEndDist;
1147 float threshold;
1148
1149 LOG ("Checking linearity:\n");
1150
1151 A = END_POINT(*splineP).x - BEG_POINT(*splineP).x;
1152 B = END_POINT(*splineP).y - BEG_POINT(*splineP).y;
1153 C = END_POINT(*splineP).z - BEG_POINT(*splineP).z;
1154
1155 startEndDist = (float) (SQR(A) + SQR(B) + SQR(C));
1156 LOG1("start_end_distance is %.3f.\n", sqrt(startEndDist));
1157
1158 LOG3(" Line endpoints are (%.3f, %.3f, %.3f) and ",
1159 BEG_POINT(*splineP).x,
1160 BEG_POINT(*splineP).y,
1161 BEG_POINT(*splineP).z);
1162 LOG3("(%.3f, %.3f, %.3f)\n",
1163 END_POINT(*splineP).x, END_POINT(*splineP).y, END_POINT(*splineP).z);
1164
1165 /* LOG3(" Line is %.3fx + %.3fy + %.3f = 0.\n", A, B, C); */
1166
1167 for (thisPoint = 0, dist = 0.0;
1168 thisPoint < CURVE_LENGTH(curve);
1169 ++thisPoint) {
1170
1171 float const t = CURVE_DIST(curve, thisPoint);
1172 Point const splinePoint = evaluate_spline(*splineP, t);
1173
1174 float const a = splinePoint.x - BEG_POINT(*splineP).x;
1175 float const b = splinePoint.y - BEG_POINT(*splineP).y;
1176 float const c = splinePoint.z - BEG_POINT(*splineP).z;
1177
1178 float const w = (A*a + B*b + C*c) / startEndDist;
1179
1180 dist += (float)sqrt(SQR(a-A*w) + SQR(b-B*w) + SQR(c-C*w));
1181 }
1182 LOG1(" Total distance is %.3f, ", dist);
1183
1184 dist /= (CURVE_LENGTH (curve) - 1);
1185
1186 LOG1 ("which is %.3f normalized.\n", dist);
1187
1188 /* We want reversion of short curves to splines to be more likely than
1189 reversion of long curves, hence the second division by the curve
1190 length, for use in `change_bad_lines'.
1191 */
1192 SPLINE_LINEARITY(*splineP) = dist;
1193 LOG1(" Final linearity: %.3f.\n", SPLINE_LINEARITY (*splineP));
1194
1195 if (startEndDist * (float) 0.5 > fittingOptsP->line_threshold)
1196 threshold = fittingOptsP->line_threshold;
1197 else
1198 threshold = startEndDist * (float) 0.5;
1199 LOG1("threshold is %.3f .\n", threshold);
1200
1201 if (dist < threshold)
1202 return true;
1203 else
1204 return false;
1205 }
1206
1207
1208
1209 /* Forward declaration for recursion */
1210
1211 static spline_list_type *
1212 fitCurve(Curve * const curveP,
1213 Vector const begSlope,
1214 Vector const endSlope,
1215 const fitting_opts_type * const fittingOptsP,
1216 at_exception_type * const exceptionP);
1217
1218
1219
1220 static spline_list_type *
1221 fitWithLine(Curve * const curveP) {
1222 /*----------------------------------------------------------------------------
1223 Return a list of splines that fit curve *curveP in a very simple way:
1224 a single spline which is a straight line through the first and last
1225 points on the curve.
1226
1227 This simplicity is useful only on a very short curve.
1228 -----------------------------------------------------------------------------*/
1229 spline_type line;
1230
1231 LOG("Fitting with straight line:\n");
1232
1233 SPLINE_DEGREE(line) = LINEARTYPE;
1234 BEG_POINT(line) = CONTROL1(line) = CURVE_POINT(curveP, 0);
1235 END_POINT(line) = CONTROL2(line) = LAST_CURVE_POINT(curveP);
1236
1237 /* Make sure that this line is never changed to a cubic. */
1238 SPLINE_LINEARITY(line) = 0;
1239
1240 if (log_file) {
1241 LOG(" ");
1242 print_spline(log_file, line);
1243 }
1244
1245 return new_spline_list_with_spline(line);
1246 }
1247
1248
1249
1250 static float
1251 b2(float const fracCurveDist) {
1252 /*----------------------------------------------------------------------------
1253 Some mysterious weighting function
1254
1255 'fracCurveDist' is a fraction (range [0.0-1.0]) of the distance along
1256 a curve that a point on the curve is.
1257 -----------------------------------------------------------------------------*/
1258 return 3.0 * SQR(fracCurveDist) * (1.0 - fracCurveDist);
1259 }
1260
1261
1262
1263 struct Mat22 {
1264 struct { float beg; float end; } beg;
1265 struct { float beg; float end; } end;
1266 };
1267
1268 struct Mat2 { float beg; float end; };
1269
1270 struct VectorBegEndPair {
1271 Vector beg;
1272 Vector end;
1273 };
1274
1275
1276 static void
1277 computeCX(Curve * const curveP,
1278 struct VectorBegEndPair const tang,
1279 struct Mat22 * const cP,
1280 struct Mat2 * const xP) {
1281
1282 Vector const begVector = vector_fromPoint(CURVE_POINT(curveP, 0));
1283 Vector const endVector = vector_fromPoint(LAST_CURVE_POINT(curveP));
1284
1285 unsigned int pointSeq;
1286
1287 cP->beg.beg = 0.0; cP->beg.end = 0.0; cP->end.beg = 0.0; cP->end.end = 0.0;
1288 /* initial value */
1289
1290 xP->beg = 0.0; xP->end = 0.0; /* initial value */
1291
1292 for (pointSeq = 0; pointSeq < CURVE_LENGTH(curveP); ++pointSeq) {
1293 float const curveDistFmBeg = CURVE_DIST(curveP, pointSeq);
1294 float const curveDistToEnd = 1.0 - curveDistFmBeg;
1295 struct VectorBegEndPair a; /* constant */
1296 /* I don't know the meaning of this, but the vectors of the pair
1297 are in the direction of the beginning and points of the curve,
1298 respectively, with magnitude a function of the fractional
1299 distance from their respective endpoints of the current point.
1300 "Fractional distance" means e.g. "this point is 20% of the way
1301 to the end of the curve from its beginning". The function is
1302
1303 3 * <fracdistance> * SQR(1-<fracdistance>) .
1304 */
1305 Vector temp, temp0, temp1;
1306
1307 a.beg = vector_scaled(tang.beg, b2(curveDistToEnd));
1308 a.end = vector_scaled(tang.end, b2(curveDistFmBeg));
1309
1310 cP->beg.beg += vector_dotProduct(a.beg, a.beg);
1311 cP->beg.end += vector_dotProduct(a.beg, a.end);
1312 cP->end.beg += vector_dotProduct(a.end, a.beg);
1313 cP->end.end += vector_dotProduct(a.end, a.end);
1314
1315 /* Now the right-hand side of the equation in the paper. */
1316 temp0 = vector_scaled(begVector,
1317 CUBE(curveDistToEnd) + b2(curveDistToEnd));
1318 temp1 = vector_scaled(endVector,
1319 CUBE(curveDistFmBeg) + b2(curveDistFmBeg));
1320
1321 temp = vector_fromPoint(
1322 vector_diffPoint(
1323 CURVE_POINT(curveP, pointSeq), vector_sum(temp0, temp1)));
1324
1325 xP->beg += vector_dotProduct(temp, a.beg);
1326 xP->end += vector_dotProduct(temp, a.end);
1327 }
1328 }
1329
1330
1331
1332 static spline_type
1333 fitOneSpline(Curve * const curveP,
1334 Vector const begSlope,
1335 Vector const endSlope,
1336 at_exception_type * const exceptionP) {
1337 /*----------------------------------------------------------------------------
1338 Return a spline that best fits the points of curve *curveP, passing through
1339 the endpoints of *curveP and having slope 'begSlope' at its beginning and
1340 'endSlope' at its end (both are unit vectors).
1341
1342 Make it a cubic spline.
1343 -----------------------------------------------------------------------------*/
1344 /* We already have the start and end points of the spline, so all we need
1345 are the control points. And we know in what direction each control
1346 point is from its respective end point, so all we need to figure out is
1347 its distance. (The control point's distance from the end point is an
1348 indication of how long the curve goes in its direction).
1349
1350 We call the distance from an end point to the associated control point
1351 "alpha".
1352
1353 We want to find starting and ending alpha that minimize the
1354 least-square error in approximating *curveP with the spline.
1355
1356 How we do that is a complete mystery to me, but the original author
1357 said to see pp. 57-59 of the Phoenix thesis. Whatever that is, I
1358 haven't seen it.
1359
1360 In our expression of the math here, we use a struct with "beg" and
1361 "end" members where the paper uses a matrix with "1" and "2"
1362 subscripts, respectively. A C array is a closer match to a math
1363 matrix, but we think the struct is easier to read.
1364
1365 The B?(t) here corresponds to B_i^3(U_i) there.
1366 The Bernstein polynomials of degree n are defined by
1367 B_i^n(t) = { n \choose i } t^i (1-t)^{n-i}, i = 0..n
1368 */
1369 struct VectorBegEndPair tang;
1370 spline_type spline;
1371 struct Mat22 C;
1372 struct Mat2 X;
1373
1374 tang.beg = begSlope; tang.end = endSlope;
1375
1376 computeCX(curveP, tang, &C, &X);
1377
1378 {
1379 float const XCendDet = X.beg * C.end.end - X.end * C.beg.end;
1380 float const CbegXDet = C.beg.beg * X.end - C.beg.end * X.beg;
1381 float const CDet = C.beg.beg * C.end.end - C.end.beg * C.beg.end;
1382
1383 if (CDet == 0.0) {
1384 LOG("zero determinant of C matrix");
1385 at_exception_fatal(exceptionP, "zero determinant of C matrix");
1386 } else {
1387 /* See above for meaning of "alpha */
1388 float const alphaBeg = XCendDet / CDet;
1389 float const alphaEnd = CbegXDet / CDet;
1390
1391 BEG_POINT(spline) = CURVE_POINT(curveP, 0);
1392 END_POINT(spline) = LAST_CURVE_POINT(curveP);
1393 CONTROL1(spline) = vector_sumPoint(
1394 BEG_POINT(spline), vector_scaled(tang.beg, alphaBeg));
1395 CONTROL2(spline) = vector_sumPoint(
1396 END_POINT(spline), vector_scaled(tang.end, alphaEnd));
1397 SPLINE_DEGREE(spline) = CUBICTYPE;
1398 }
1399 }
1400 return spline;
1401 }
1402
1403
1404
1405 static void
1406 logSplineFit(spline_type const spline) {
1407
1408 if (SPLINE_DEGREE(spline) == LINEARTYPE)
1409 LOG(" fitted to line:\n");
1410 else
1411 LOG(" fitted to spline:\n");
1412
1413 if (log_file) {
1414 LOG (" ");
1415 print_spline(log_file, spline);
1416 }
1417 }
1418
1419
1420
1421 static Vector
1422 findHalfTangent(LineEnd const toWhichEnd,
1423 Curve * const curveP,
1424 unsigned int const tangentSurround) {
1425 /*----------------------------------------------------------------------------
1426 Find the slope in the vicinity of one of the ends of the curve *curveP,
1427 as specified by 'toWhichEnd'.
1428
1429 To wit, this is the mean slope between the end point and each of the
1430 'tangentSurround' adjacent points, up to half the curve.
1431
1432 For example, if 'toWhichEnd' is LINEEND_INIT and 'tangentSurround' is 3 and
1433 the curve is 10 points long, we imagine a line through Point 0 and Point 1,
1434 another through Point 0 and Point 2, and a third through Point 0 and Point
1435 3. We return the mean of the slopes of those 3 lines.
1436
1437 Don't consider points that are identical to the end point (as there could
1438 be no slope between those points) -- they're part of the count, but don't
1439 contribute to the slope. If _all_ of the points to be considered are
1440 identical to the end point, arbitrarily return a horizontal slope.
1441
1442 Return the slope as an unnormalized vector. (I don't know if that was
1443 intended by the designer, since it isn't sensible unless it's a
1444 computational efficiency thing; it's just how I found the code).
1445
1446 It is possible for the mean described above to be the zero vector, because
1447 the mean of a vector pointing left and one pointing right is the zero
1448 vector. In that case, we use fewer "tangentSurround" points.
1449 -----------------------------------------------------------------------------*/
1450 Point const tangentPoint =
1451 CURVE_POINT(curveP,
1452 toWhichEnd == LINEEND_INIT ? 0 : CURVE_LENGTH(curveP) - 1);
1453 Vector const zeroZero = { 0.0, 0.0 };
1454
1455 unsigned int surroundCt;
1456 bool gotNonzero;
1457 Vector mean;
1458
1459 for (surroundCt = MIN(CURVE_LENGTH(curveP) / 2, tangentSurround),
1460 gotNonzero = false;
1461 !gotNonzero;
1462 --surroundCt) {
1463
1464 unsigned int i;
1465 Vector sum;
1466 unsigned int n;
1467
1468 for (i = 0, n = 0, sum = zeroZero; i < surroundCt; ++i) {
1469 unsigned int const thisIndex =
1470 toWhichEnd == LINEEND_INIT ?
1471 i + 1 : CURVE_LENGTH(curveP) - 1 - i;
1472 Point const thisPoint = CURVE_POINT(curveP, thisIndex);
1473
1474 if (!point_equal(thisPoint, tangentPoint)) {
1475 /* Perhaps we should weight the tangent from `thisPoint' by
1476 some factor dependent on the distance from the tangent
1477 point.
1478 */
1479 sum = vector_sum(sum, vector_pointDirection(thisPoint,
1480 tangentPoint));
1481 ++n;
1482 }
1483 }
1484 mean = n > 0 ? vector_scaled(sum, 1.0 / n) : vector_horizontal();
1485
1486 if (vector_equal(mean, vector_zero())) {
1487 /* We have points on multiple sides of the endpoint whose vectors
1488 happen to add up to zero, which is not usable.
1489 */
1490 assert(surroundCt > 0);
1491 } else
1492 gotNonzero = true;
1493 }
1494
1495 return mean;
1496 }
1497
1498
1499
1500 static void
1501 findTangent(Curve * const curveP,
1502 LineEnd const toWhichEnd,
1503 Curve * const adjacentCurveP,
1504 unsigned int const tangentSurround,
1505 Vector * const tangentP) {
1506 /*----------------------------------------------------------------------------
1507 Find an approximation to the slope of *curveP (i.e. slope of tangent
1508 line) at an endpoint (per 'toWhichEnd').
1509
1510 This approximation is the mean of the slopes between the end of the curve
1511 and the 'tangentSurround' points leading up to it (but not more than one
1512 point beyond the midpoint of the curve). Note that the curve may loop.
1513 Since there is no slope between two identical points, we ignore points that
1514 are identical to the endpoint. They count toward the limit; they just
1515 aren't included in the result. If none of the points to be considered are
1516 distinct from the endpoint, we arbitrarily consider the curve to be
1517 horizontal there.
1518
1519 If 'adjacentCurveP' is non-null, average this slope with the slope of the
1520 other end of curve *adjacentCurveP, which we assume is adjacent. Adjacent
1521 means the previous curve in the outline chain for the slope at the start
1522 point ('toWhichEnd' == LINEEND_BEG), the next curve otherwise. If *curveP
1523 is cyclic, then it is its own adjacent curve.
1524
1525 It is important to compute an accurate approximation, because the
1526 control points that we eventually decide upon to fit the curve will
1527 be placed on the half-lines defined by the slopes and endpoints, and
1528 we never recompute the tangent after this.
1529 -----------------------------------------------------------------------------*/
1530 Vector const slopeThisCurve =
1531 findHalfTangent(toWhichEnd, curveP, tangentSurround);
1532
1533 LOG2(" tangent to %s of curve %lx: ",
1534 toWhichEnd == LINEEND_INIT ? "start" : "end", (unsigned long)curveP);
1535
1536 LOG3("(this curve half tangent (%.3f,%.3f,%.3f)) ",
1537 slopeThisCurve.dx, slopeThisCurve.dy, slopeThisCurve.dz);
1538
1539 if (adjacentCurveP) {
1540 Vector const slopeAdjCurve =
1541 findHalfTangent(otherEnd(toWhichEnd),
1542 adjacentCurveP,
1543 tangentSurround);
1544
1545 LOG3("(adjacent curve half tangent (%.3f,%.3f,%.3f)) ",
1546 slopeAdjCurve.dx, slopeAdjCurve.dy, slopeAdjCurve.dz);
1547 *tangentP = vector_scaled(vector_sum(slopeThisCurve, slopeAdjCurve),
1548 0.5);
1549 } else
1550 *tangentP = slopeThisCurve;
1551
1552 LOG3("(%.3f,%.3f,%.3f).\n", tangentP->dx, tangentP->dy, tangentP->dz);
1553 }
1554
1555
1556
1557 static void
1558 findError(Curve * const curveP,
1559 spline_type const spline,
1560 float * const errorP,
1561 unsigned int * const worstPointP,
1562 at_exception_type * const exceptionP) {
1563 /*----------------------------------------------------------------------------
1564 Tell how good a fit 'spline' is for *curveP.
1565
1566 Return the error (maximum Euclidean distance between a point on
1567 *curveP and the corresponding point on 'spline') as *errorP and the
1568 sequence number of the point on the curve where the error is
1569 greatest as *worstPointP.
1570
1571 If there are multiple equally bad points, return an arbitrary one of
1572 them as *worstPointP.
1573 -----------------------------------------------------------------------------*/
1574 unsigned int thisPoint;
1575 float totalError;
1576 float worstError;
1577 unsigned int worstPoint;
1578
1579 assert(CURVE_LENGTH(curveP) > 0);
1580
1581 totalError = 0.0; /* initial value */
1582 worstError = FLT_MIN; /* initial value */
1583 worstPoint = 0;
1584
1585 for (thisPoint = 0; thisPoint < CURVE_LENGTH(curveP); ++thisPoint) {
1586 Point const curvePoint = CURVE_POINT(curveP, thisPoint);
1587 float const t = CURVE_DIST(curveP, thisPoint);
1588 Point const splinePoint = evaluate_spline(spline, t);
1589 float const thisError = point_distance(curvePoint, splinePoint);
1590 if (thisError >= worstError) {
1591 worstPoint = thisPoint;
1592 worstError = thisError;
1593 }
1594 totalError += thisError;
1595 }
1596
1597 if (epsilon_equal(totalError, 0.0))
1598 LOG(" Every point fits perfectly.\n");
1599 else {
1600 LOG5(" Worst error (at (%.3f,%.3f,%.3f), point #%u) was %.3f.\n",
1601 CURVE_POINT(curveP, worstPoint).x,
1602 CURVE_POINT(curveP, worstPoint).y,
1603 CURVE_POINT(curveP, worstPoint).z,
1604 worstPoint, worstError);
1605 LOG1(" Total error was %.3f.\n", totalError);
1606 LOG2(" Average error (over %u points) was %.3f.\n",
1607 CURVE_LENGTH(curveP), totalError / CURVE_LENGTH(curveP));
1608 }
1609 assert(worstPoint < CURVE_LENGTH(curveP));
1610 *errorP = worstError;
1611 *worstPointP = worstPoint;
1612 }
1613
1614
1615
1616 static void
1617 subdivideCurve(Curve * const curveP,
1618 unsigned int const subdivisionIndex,
1619 const fitting_opts_type * const fittingOptsP,
1620 Curve ** const leftCurvePP,
1621 Curve ** const rghtCurvePP,
1622 Vector * const joinSlopeP) {
1623 /*----------------------------------------------------------------------------
1624 Split curve *curveP into two, at 'subdivisionIndex'. (Actually,
1625 leave *curveP alone, but return as *leftCurvePP and *rghtCurvePP
1626 two new curves that are the pieces).
1627
1628 Return as *joinSlopeP what should be the slope where the subcurves
1629 join, i.e. the slope of the end of the left subcurve and of the start
1630 of the right subcurve.
1631
1632 To be precise, the point with sequence number 'subdivisionIndex'
1633 becomes the first pixel of the right-hand curve.
1634 -----------------------------------------------------------------------------*/
1635 Curve * leftCurveP;
1636 Curve * rghtCurveP;
1637
1638 leftCurveP = curve_new();
1639 rghtCurveP = curve_new();
1640
1641 LOG4(" Subdividing curve %lx into %lx and %lx at point #%u\n",
1642 (unsigned long)curveP,
1643 (unsigned long)leftCurveP, (unsigned long)rghtCurveP,
1644 subdivisionIndex);
1645
1646 /* The last point of the left-hand curve will also be the first
1647 point of the right-hand curve.
1648 */
1649 assert(subdivisionIndex < CURVE_LENGTH(curveP));
1650 CURVE_LENGTH(leftCurveP) = subdivisionIndex + 1;
1651 CURVE_LENGTH(rghtCurveP) = CURVE_LENGTH(curveP) - subdivisionIndex;
1652
1653 MALLOCARRAY_NOFAIL(leftCurveP->pointList, CURVE_LENGTH(leftCurveP));
1654 memcpy(leftCurveP->pointList, &curveP->pointList[0],
1655 CURVE_LENGTH(leftCurveP) * sizeof(curveP->pointList[0]));
1656
1657 MALLOCARRAY_NOFAIL(rghtCurveP->pointList, CURVE_LENGTH(rghtCurveP));
1658 memcpy(rghtCurveP->pointList, &curveP->pointList[subdivisionIndex],
1659 CURVE_LENGTH(rghtCurveP) * sizeof(curveP->pointList[0]));
1660
1661 /* We have to set up the two curves before finding the slope at
1662 the subdivision point. The slope at that point must be the
1663 same for both curves, or noticeable bumps will occur in the
1664 character. But we want to use information on both sides of the
1665 point to compute the slope, hence we use adjacentCurveP.
1666 */
1667 findTangent(leftCurveP,
1668 LINEEND_TERM,
1669 /* adjacentCurveP: */ rghtCurveP,
1670 fittingOptsP->tangent_surround, joinSlopeP);
1671
1672 *leftCurvePP = leftCurveP;
1673 *rghtCurvePP = rghtCurveP;
1674 }
1675
1676
1677
1678 static spline_list_type *
1679 leftRightConcat(const spline_list_type * const leftSplineListP,
1680 const spline_list_type * const rghtSplineListP,
1681 at_exception_type * const exceptionP) {
1682 /*----------------------------------------------------------------------------
1683 Return a spline list which is the concatenation of the spline lists
1684 obtained by splitting a curve in two and fitting each independently.
1685 NULL for a spline list pointer means Caller was unable to fit a list
1686 of splines to that side of the curve.
1687 -----------------------------------------------------------------------------*/
1688 spline_list_type * retval;
1689
1690 retval = new_spline_list();
1691
1692 if (leftSplineListP == NULL) {
1693 LOG("Could not fit spline to left curve.\n");
1694 at_exception_warning(exceptionP, "Could not fit left spline list");
1695 } else
1696 concat_spline_lists(retval, *leftSplineListP);
1697
1698 if (rghtSplineListP == NULL) {
1699 LOG("Could not fit spline to right curve.\n");
1700 at_exception_warning(exceptionP, "Could not fit right spline list");
1701 } else
1702 concat_spline_lists(retval, *rghtSplineListP);
1703
1704 return retval;
1705 }
1706
1707
1708
1709 static unsigned int
1710 divisionPoint(Curve * const curveP,
1711 unsigned int const worstFitPoint) {
1712 /*----------------------------------------------------------------------------
1713 Return the sequence number of the point at which we should divide
1714 curve *curveP for the purpose of doing a separate fit of each side,
1715 assuming the point which least matches a single spline is sequence
1716 number 'worstFitPoint'.
1717
1718 We get as close as we can to that while still having at least two
1719 points on each side.
1720
1721 Assume the curve is at least 4 points long.
1722
1723 The return value is the sequence number of the first point of the
1724 second (right-hand) subcurve.
1725 -----------------------------------------------------------------------------*/
1726 assert(CURVE_LENGTH(curveP) >= 4);
1727
1728 return MAX(2, MIN(worstFitPoint, CURVE_LENGTH(curveP) - 2));
1729 }
1730
1731
1732
1733 static spline_list_type *
1734 divideAndFit(Curve * const curveP,
1735 Vector const begSlope,
1736 Vector const endSlope,
1737 unsigned int const subdivisionIndex,
1738 const fitting_opts_type * const fittingOptsP,
1739 at_exception_type * const exceptionP) {
1740 /*----------------------------------------------------------------------------
1741 Same as fitWithLeastSquares() (i.e. return a list of splines that fit
1742 the curve *curveP), except assuming no single spline will fit the
1743 entire curve.
1744
1745 Divide it into two curves at 'subdivisionIndex' and fit each
1746 separately to a list of splines. Return the concatenation of those
1747 spline lists.
1748
1749 Assume 'subdivisionIndex' leaves at least two pixels on each side.
1750 -----------------------------------------------------------------------------*/
1751 spline_list_type * retval;
1752 Curve * leftCurveP;
1753 /* The beginning (lower indexes) subcurve */
1754 Curve * rghtCurveP;
1755 /* The other subcurve */
1756 Vector joinSlope;
1757 /* The slope of the end of the left subcurve and start of the right
1758 subcurve.
1759 */
1760 spline_list_type * leftSplineListP;
1761
1762 assert(subdivisionIndex > 1);
1763 assert(subdivisionIndex < CURVE_LENGTH(curveP)-1);
1764 subdivideCurve(curveP, subdivisionIndex, fittingOptsP,
1765 &leftCurveP, &rghtCurveP, &joinSlope);
1766
1767 leftSplineListP = fitCurve(leftCurveP, begSlope, joinSlope,
1768 fittingOptsP, exceptionP);
1769
1770 if (!at_exception_got_fatal(exceptionP)) {
1771 spline_list_type * rghtSplineListP;
1772
1773 rghtSplineListP = fitCurve(rghtCurveP, joinSlope, endSlope,
1774 fittingOptsP, exceptionP);
1775
1776 if (!at_exception_got_fatal(exceptionP)) {
1777 if (leftSplineListP == NULL && rghtSplineListP == NULL)
1778 retval = NULL;
1779 else
1780 retval = leftRightConcat(leftSplineListP, rghtSplineListP,
1781 exceptionP);
1782
1783 if (rghtSplineListP) {
1784 free_spline_list(*rghtSplineListP);
1785 free(rghtSplineListP);
1786 }
1787 }
1788 if (leftSplineListP) {
1789 free_spline_list(*leftSplineListP);
1790 free(leftSplineListP);
1791 }
1792 }
1793
1794 curve_free(leftCurveP);
1795 curve_free(rghtCurveP);
1796
1797 return retval;
1798 }
1799
1800
1801
1802 static spline_list_type *
1803 fitWithLeastSquares(Curve * const curveP,
1804 Vector const begSlope,
1805 Vector const endSlope,
1806 const fitting_opts_type * const fittingOptsP,
1807 at_exception_type * const exceptionP) {
1808 /*----------------------------------------------------------------------------
1809 The least squares method is well described in Schneider's thesis.
1810 Briefly, we try to fit the entire curve with one spline. If that
1811 fails, we subdivide the curve.
1812 -----------------------------------------------------------------------------*/
1813 spline_list_type * retval;
1814 spline_type spline;
1815
1816 LOG("\nFitting with least squares:\n");
1817
1818 /* Phoenix reduces the number of points with a "linear spline technique."
1819 But for fitting letterforms, that is inappropriate. We want all the
1820 points we can get.
1821 */
1822
1823 curve_setDistance(curveP);
1824
1825 if (CURVE_CYCLIC(curveP) && CURVE_LENGTH(curveP) < 4) {
1826 unsigned i;
1827 for (i = 0; i < CURVE_LENGTH(curveP); ++i) {
1828 Point const point = CURVE_POINT(curveP, i);
1829 fprintf(stderr, "point %u = (%f, %f)\n", i, point.x, point.y);
1830 }
1831 }
1832
1833 /* Try a single spline over whole curve */
1834
1835 spline = fitOneSpline(curveP, begSlope, endSlope, exceptionP);
1836 if (!at_exception_got_fatal(exceptionP)) {
1837 float error;
1838 unsigned int worstPoint;
1839
1840 logSplineFit(spline);
1841
1842 findError(curveP, spline, &error, &worstPoint, exceptionP);
1843 assert(worstPoint < CURVE_LENGTH(curveP));
1844
1845 if (error < fittingOptsP->error_threshold && !CURVE_CYCLIC(curveP)) {
1846 /* The points were fitted adequately with a spline. But
1847 see if the "curve" that was fit should really just be a
1848 straight line.
1849 */
1850 if (splineLinearEnough(&spline, curveP, fittingOptsP)) {
1851 SPLINE_DEGREE(spline) = LINEARTYPE;
1852 LOG("Changed to line.\n");
1853 }
1854 retval = new_spline_list_with_spline(spline);
1855 LOG1("Accepted error of %.3f.\n", error);
1856 } else {
1857 /* We couldn't fit the curve acceptably with a single spline,
1858 so divide into two curves and try to fit each separately.
1859 */
1860 unsigned int const divIndex = divisionPoint(curveP, worstPoint);
1861 LOG1("\nSubdividing at point #%u\n", divIndex);
1862 LOG4(" Worst match point: (%.3f,%.3f), #%u. Error %.3f\n",
1863 CURVE_POINT(curveP, worstPoint).x,
1864 CURVE_POINT(curveP, worstPoint).y, worstPoint, error);
1865
1866 retval = divideAndFit(curveP, begSlope, endSlope, divIndex,
1867 fittingOptsP, exceptionP);
1868 }
1869 } else
1870 retval = NULL; /* quiet compiler warning */
1871
1872 return retval;
1873 }
1874
1875
1876
1877 static spline_list_type *
1878 fitCurve(Curve * const curveP,
1879 Vector const begSlope,
1880 Vector const endSlope,
1881 const fitting_opts_type * const fittingOptsP,
1882 at_exception_type * const exceptionP) {
1883 /*----------------------------------------------------------------------------
1884 Transform a set of locations to a list of splines (the fewer the
1885 better). We are guaranteed that *curveP does not contain any corners.
1886 We return NULL if we cannot fit the points at all.
1887 -----------------------------------------------------------------------------*/
1888 spline_list_type * fittedSplinesP;
1889
1890 if (CURVE_LENGTH(curveP) < 2) {
1891 LOG("Tried to fit curve with fewer than two points");
1892 at_exception_warning(exceptionP,
1893 "Tried to fit curve with less than two points");
1894 fittedSplinesP = NULL;
1895 } else if (CURVE_LENGTH(curveP) < 4)
1896 fittedSplinesP = fitWithLine(curveP);
1897 else
1898 fittedSplinesP =
1899 fitWithLeastSquares(curveP, begSlope, endSlope, fittingOptsP,
1900 exceptionP);
1901
1902 return fittedSplinesP;
1903 }
1904
1905
1906
1907 static void
1908 fitCurves(CurveList const curveList,
1909 pixel const color,
1910 const fitting_opts_type * const fittingOptsP,
1911 spline_list_type * const splinesP,
1912 at_exception_type * const exceptionP) {
1913
1914 spline_list_type curveListSplines;
1915 unsigned int curveSeq;
1916
1917 curveListSplines = empty_spline_list();
1918
1919 curveListSplines.open = curveList.open;
1920 curveListSplines.clockwise = curveList.clockwise;
1921 curveListSplines.color = color;
1922
1923 for (curveSeq = 0;
1924 curveSeq < curveList.length && !at_exception_got_fatal(exceptionP);
1925 ++curveSeq) {
1926
1927 Curve * const curveP = CURVE_LIST_ELT(curveList, curveSeq);
1928
1929 Vector begSlope, endSlope;
1930 spline_list_type * curveSplinesP;
1931
1932 LOG2("\nFitting curve #%u (%lx):\n", curveSeq, (unsigned long)curveP);
1933
1934 LOG("Finding tangents:\n");
1935 findTangent(curveP, LINEEND_INIT,
1936 CURVE_CYCLIC(curveP) ? curveP : NULL,
1937 fittingOptsP->tangent_surround,
1938 &begSlope);
1939 findTangent(curveP, LINEEND_TERM,
1940 CURVE_CYCLIC(curveP) ? curveP : NULL,
1941 fittingOptsP->tangent_surround, &endSlope);
1942
1943 curveSplinesP = fitCurve(curveP, begSlope, endSlope, fittingOptsP,
1944 exceptionP);
1945 if (!at_exception_got_fatal(exceptionP)) {
1946 if (curveSplinesP == NULL) {
1947 LOG1("Could not fit curve #%u", curveSeq);
1948 at_exception_warning(exceptionP, "Could not fit curve");
1949 } else {
1950 logSplinesForCurve(curveSeq, *curveSplinesP);
1951
1952 /* After fitting, we may need to change some would-be lines
1953 back to curves, because they are in a list with other
1954 curves.
1955 */
1956 changeBadLines(curveSplinesP, fittingOptsP);
1957
1958 concat_spline_lists(&curveListSplines, *curveSplinesP);
1959 free_spline_list(*curveSplinesP);
1960 free(curveSplinesP);
1961 }
1962 }
1963 }
1964 if (at_exception_got_fatal(exceptionP))
1965 free_spline_list(curveListSplines);
1966 else
1967 *splinesP = curveListSplines;
1968 }
1969
1970
1971
1972 static void
1973 logFittedSplines(spline_list_type const curve_list_splines) {
1974
1975 unsigned int splineSeq;
1976
1977 LOG("\nFitted splines are:\n");
1978 for (splineSeq = 0;
1979 splineSeq < SPLINE_LIST_LENGTH(curve_list_splines);
1980 ++splineSeq) {
1981 LOG1(" %u: ", splineSeq);
1982 print_spline(log_file,
1983 SPLINE_LIST_ELT(curve_list_splines, splineSeq));
1984 }
1985 }
1986
1987
1988
1989 static void
1990 fitCurveList(CurveList const curveList,
1991 fitting_opts_type * const fittingOptsP,
1992 distance_map_type * const dist,
1993 pixel const color,
1994 spline_list_type * const splineListP,
1995 at_exception_type * const exception) {
1996 /*----------------------------------------------------------------------------
1997 Fit the list of curves CURVE_LIST to a list of splines, and return
1998 it. CURVE_LIST represents a single closed paths, e.g., either the
1999 inside or outside outline of an `o'.
2000 -----------------------------------------------------------------------------*/
2001 Curve * curveP;
2002 spline_list_type curveListSplines;
2003
2004 removeKnees(curveList);
2005
2006 if (dist != NULL)
2007 computePointWeights(curveList, fittingOptsP, dist);
2008
2009 /* We filter all the curves in 'curveList' at once; otherwise, we
2010 would look at an unfiltered curve when computing tangents.
2011 */
2012 filterCurves(curveList, fittingOptsP);
2013
2014 /* Make the first point in the first curve also be the last point in
2015 the last curve, so the fit to the whole curve list will begin and
2016 end at the same point. This may cause slight errors in computing
2017 the tangents and t values, but it's worth it for the continuity.
2018 Of course we don't want to do this if the two points are already
2019 the same, as they are if the curve is cyclic. (We don't append it
2020 earlier, in `split_at_corners', because that confuses the
2021 filtering.) Finally, we can't append the point if the curve is
2022 exactly three points long, because we aren't adding any more data,
2023 and three points isn't enough to determine a spline. Therefore,
2024 the fitting will fail.
2025 */
2026 curveP = CURVE_LIST_ELT(curveList, 0);
2027 if (CURVE_CYCLIC(curveP))
2028 curve_appendPoint(curveP, CURVE_POINT(curveP, 0));
2029
2030 /* Finally, fit each curve in the list to a list of splines. */
2031
2032 fitCurves(curveList, color, fittingOptsP, &curveListSplines, exception);
2033 if (!at_exception_got_fatal(exception)) {
2034 if (log_file)
2035 logFittedSplines(curveListSplines);
2036 *splineListP = curveListSplines;
2037 }
2038 }
2039
2040
2041
2042 static void
2043 fitCurvesToSplines(CurveListArray const curveArray,
2044 fitting_opts_type * const fittingOptsP,
2045 distance_map_type * const dist,
2046 unsigned short const width,
2047 unsigned short const height,
2048 at_exception_type * const exception,
2049 at_progress_func notifyProgress,
2050 void * const progressData,
2051 at_testcancel_func testCancel,
2052 void * const testcancelData,
2053 spline_list_array_type * const splineListArrayP) {
2054
2055 unsigned splineListSeq;
2056 bool cancelled;
2057 spline_list_array_type splineListArray;
2058
2059 splineListArray = new_spline_list_array();
2060 splineListArray.centerline = fittingOptsP->centerline;
2061 splineListArray.preserve_width = fittingOptsP->preserve_width;
2062 splineListArray.width_weight_factor = fittingOptsP->width_weight_factor;
2063 splineListArray.backgroundSpec = fittingOptsP->backgroundSpec;
2064 splineListArray.background_color = fittingOptsP->background_color;
2065 /* Set dummy values. Real value is set in upper context. */
2066 splineListArray.width = width;
2067 splineListArray.height = height;
2068
2069 for (splineListSeq = 0, cancelled = false;
2070 splineListSeq < CURVE_LIST_ARRAY_LENGTH(curveArray) &&
2071 !at_exception_got_fatal(exception) && !cancelled;
2072 ++splineListSeq) {
2073
2074 CurveList const curveList =
2075 CURVE_LIST_ARRAY_ELT(curveArray, splineListSeq);
2076
2077 spline_list_type curveSplineList;
2078
2079 if (notifyProgress)
2080 notifyProgress((((float)splineListSeq)/
2081 ((float)CURVE_LIST_ARRAY_LENGTH(curveArray) *
2082 (float)3.0) + (float)0.333),
2083 progressData);
2084 if (testCancel && testCancel(testcancelData))
2085 cancelled = true;
2086
2087 LOG1("\nFitting curve list #%u:\n", splineListSeq);
2088
2089 fitCurveList(curveList, fittingOptsP, dist, curveList.color,
2090 &curveSplineList, exception);
2091 if (!at_exception_got_fatal(exception))
2092 append_spline_list(&splineListArray, curveSplineList);
2093 }
2094 *splineListArrayP = splineListArray;
2095 }
2096
2097
2098
2099 void
2100 fit_outlines_to_splines(pixel_outline_list_type const pixelOutlineList,
2101 fitting_opts_type * const fittingOptsP,
2102 distance_map_type * const dist,
2103 unsigned short const width,
2104 unsigned short const height,
2105 at_exception_type * const exception,
2106 at_progress_func notifyProgress,
2107 void * const progressData,
2108 at_testcancel_func testCancel,
2109 void * const testcancelData,
2110 spline_list_array_type * const splineListArrayP) {
2111 /*----------------------------------------------------------------------------
2112 Transform a list of pixels in the outlines of the original character to
2113 a list of spline lists fitted to those pixels.
2114 -----------------------------------------------------------------------------*/
2115 CurveListArray const curveListArray =
2116 split_at_corners(pixelOutlineList, fittingOptsP, exception);
2117
2118 fitCurvesToSplines(curveListArray, fittingOptsP, dist, width, height,
2119 exception, notifyProgress, progressData,
2120 testCancel, testcancelData, splineListArrayP);
2121
2122 curve_freeListArray(&curveListArray, notifyProgress, progressData);
2123
2124 flush_log_output();
2125 }
2126
2127
2128