1/***************************************************************************/
2/*                                                                         */
3/*  cf2hints.c                                                             */
4/*                                                                         */
5/*    Adobe's code for handling CFF hints (body).                          */
6/*                                                                         */
7/*  Copyright 2007-2014 Adobe Systems Incorporated.                        */
8/*                                                                         */
9/*  This software, and all works of authorship, whether in source or       */
10/*  object code form as indicated by the copyright notice(s) included      */
11/*  herein (collectively, the "Work") is made available, and may only be   */
12/*  used, modified, and distributed under the FreeType Project License,    */
13/*  LICENSE.TXT.  Additionally, subject to the terms and conditions of the */
14/*  FreeType Project License, each contributor to the Work hereby grants   */
15/*  to any individual or legal entity exercising permissions granted by    */
16/*  the FreeType Project License and this section (hereafter, "You" or     */
17/*  "Your") a perpetual, worldwide, non-exclusive, no-charge,              */
18/*  royalty-free, irrevocable (except as stated in this section) patent    */
19/*  license to make, have made, use, offer to sell, sell, import, and      */
20/*  otherwise transfer the Work, where such license applies only to those  */
21/*  patent claims licensable by such contributor that are necessarily      */
22/*  infringed by their contribution(s) alone or by combination of their    */
23/*  contribution(s) with the Work to which such contribution(s) was        */
24/*  submitted.  If You institute patent litigation against any entity      */
25/*  (including a cross-claim or counterclaim in a lawsuit) alleging that   */
26/*  the Work or a contribution incorporated within the Work constitutes    */
27/*  direct or contributory patent infringement, then any patent licenses   */
28/*  granted to You under this License for that Work shall terminate as of  */
29/*  the date such litigation is filed.                                     */
30/*                                                                         */
31/*  By using, modifying, or distributing the Work you indicate that you    */
32/*  have read and understood the terms and conditions of the               */
33/*  FreeType Project License as well as those provided in this section,    */
34/*  and you accept them fully.                                             */
35/*                                                                         */
36/***************************************************************************/
37
38
39#include "cf2ft.h"
40#include FT_INTERNAL_DEBUG_H
41
42#include "cf2glue.h"
43#include "cf2font.h"
44#include "cf2hints.h"
45#include "cf2intrp.h"
46
47
48  /*************************************************************************/
49  /*                                                                       */
50  /* The macro FT_COMPONENT is used in trace mode.  It is an implicit      */
51  /* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log  */
52  /* messages during execution.                                            */
53  /*                                                                       */
54#undef  FT_COMPONENT
55#define FT_COMPONENT  trace_cf2hints
56
57
58  typedef struct  CF2_HintMoveRec_
59  {
60    size_t     j;          /* index of upper hint map edge   */
61    CF2_Fixed  moveUp;     /* adjustment to optimum position */
62
63  } CF2_HintMoveRec, *CF2_HintMove;
64
65
66  /* Compute angular momentum for winding order detection.  It is called */
67  /* for all lines and curves, but not necessarily in element order.     */
68  static CF2_Int
69  cf2_getWindingMomentum( CF2_Fixed  x1,
70                          CF2_Fixed  y1,
71                          CF2_Fixed  x2,
72                          CF2_Fixed  y2 )
73  {
74    /* cross product of pt1 position from origin with pt2 position from  */
75    /* pt1; we reduce the precision so that the result fits into 32 bits */
76
77    return ( x1 >> 16 ) * ( ( y2 - y1 ) >> 16 ) -
78           ( y1 >> 16 ) * ( ( x2 - x1 ) >> 16 );
79  }
80
81
82  /*
83   * Construct from a StemHint; this is used as a parameter to
84   * `cf2_blues_capture'.
85   * `hintOrigin' is the character space displacement of a seac accent.
86   * Adjust stem hint for darkening here.
87   *
88   */
89  static void
90  cf2_hint_init( CF2_Hint            hint,
91                 const CF2_ArrStack  stemHintArray,
92                 size_t              indexStemHint,
93                 const CF2_Font      font,
94                 CF2_Fixed           hintOrigin,
95                 CF2_Fixed           scale,
96                 FT_Bool             bottom )
97  {
98    CF2_Fixed               width;
99    const CF2_StemHintRec*  stemHint;
100
101
102    FT_ZERO( hint );
103
104    stemHint = (const CF2_StemHintRec*)cf2_arrstack_getPointer(
105                                         stemHintArray,
106                                         indexStemHint );
107
108    width = stemHint->max - stemHint->min;
109
110    if ( width == cf2_intToFixed( -21 ) )
111    {
112      /* ghost bottom */
113
114      if ( bottom )
115      {
116        hint->csCoord = stemHint->max;
117        hint->flags   = CF2_GhostBottom;
118      }
119      else
120        hint->flags = 0;
121    }
122
123    else if ( width == cf2_intToFixed( -20 ) )
124    {
125      /* ghost top */
126
127      if ( bottom )
128        hint->flags = 0;
129      else
130      {
131        hint->csCoord = stemHint->min;
132        hint->flags   = CF2_GhostTop;
133      }
134    }
135
136    else if ( width < 0 )
137    {
138      /* inverted pair */
139
140      /*
141       * Hints with negative widths were produced by an early version of a
142       * non-Adobe font tool.  The Type 2 spec allows edge (ghost) hints
143       * with negative widths, but says
144       *
145       *   All other negative widths have undefined meaning.
146       *
147       * CoolType has a silent workaround that negates the hint width; for
148       * permissive mode, we do the same here.
149       *
150       * Note: Such fonts cannot use ghost hints, but should otherwise work.
151       * Note: Some poor hints in our faux fonts can produce negative
152       *       widths at some blends.  For example, see a light weight of
153       *       `u' in ASerifMM.
154       *
155       */
156      if ( bottom )
157      {
158        hint->csCoord = stemHint->max;
159        hint->flags   = CF2_PairBottom;
160      }
161      else
162      {
163        hint->csCoord = stemHint->min;
164        hint->flags   = CF2_PairTop;
165      }
166    }
167
168    else
169    {
170      /* normal pair */
171
172      if ( bottom )
173      {
174        hint->csCoord = stemHint->min;
175        hint->flags   = CF2_PairBottom;
176      }
177      else
178      {
179        hint->csCoord = stemHint->max;
180        hint->flags   = CF2_PairTop;
181      }
182    }
183
184    /* Now that ghost hints have been detected, adjust this edge for      */
185    /* darkening.  Bottoms are not changed; tops are incremented by twice */
186    /* `darkenY'.                                                         */
187    if ( cf2_hint_isTop( hint ) )
188      hint->csCoord += 2 * font->darkenY;
189
190    hint->csCoord += hintOrigin;
191    hint->scale    = scale;
192    hint->index    = indexStemHint;   /* index in original stem hint array */
193
194    /* if original stem hint has been used, use the same position */
195    if ( hint->flags != 0 && stemHint->used )
196    {
197      if ( cf2_hint_isTop( hint ) )
198        hint->dsCoord = stemHint->maxDS;
199      else
200        hint->dsCoord = stemHint->minDS;
201
202      cf2_hint_lock( hint );
203    }
204    else
205      hint->dsCoord = FT_MulFix( hint->csCoord, scale );
206  }
207
208
209  /* initialize an invalid hint map element */
210  static void
211  cf2_hint_initZero( CF2_Hint  hint )
212  {
213    FT_ZERO( hint );
214  }
215
216
217  FT_LOCAL_DEF( FT_Bool )
218  cf2_hint_isValid( const CF2_Hint  hint )
219  {
220    return (FT_Bool)( hint->flags != 0 );
221  }
222
223
224  static FT_Bool
225  cf2_hint_isPair( const CF2_Hint  hint )
226  {
227    return (FT_Bool)( ( hint->flags                      &
228                        ( CF2_PairBottom | CF2_PairTop ) ) != 0 );
229  }
230
231
232  static FT_Bool
233  cf2_hint_isPairTop( const CF2_Hint  hint )
234  {
235    return (FT_Bool)( ( hint->flags & CF2_PairTop ) != 0 );
236  }
237
238
239  FT_LOCAL_DEF( FT_Bool )
240  cf2_hint_isTop( const CF2_Hint  hint )
241  {
242    return (FT_Bool)( ( hint->flags                    &
243                        ( CF2_PairTop | CF2_GhostTop ) ) != 0 );
244  }
245
246
247  FT_LOCAL_DEF( FT_Bool )
248  cf2_hint_isBottom( const CF2_Hint  hint )
249  {
250    return (FT_Bool)( ( hint->flags                          &
251                        ( CF2_PairBottom | CF2_GhostBottom ) ) != 0 );
252  }
253
254
255  static FT_Bool
256  cf2_hint_isLocked( const CF2_Hint  hint )
257  {
258    return (FT_Bool)( ( hint->flags & CF2_Locked ) != 0 );
259  }
260
261
262  static FT_Bool
263  cf2_hint_isSynthetic( const CF2_Hint  hint )
264  {
265    return (FT_Bool)( ( hint->flags & CF2_Synthetic ) != 0 );
266  }
267
268
269  FT_LOCAL_DEF( void )
270  cf2_hint_lock( CF2_Hint  hint )
271  {
272    hint->flags |= CF2_Locked;
273  }
274
275
276  FT_LOCAL_DEF( void )
277  cf2_hintmap_init( CF2_HintMap   hintmap,
278                    CF2_Font      font,
279                    CF2_HintMap   initialMap,
280                    CF2_ArrStack  hintMoves,
281                    CF2_Fixed     scale )
282  {
283    FT_ZERO( hintmap );
284
285    /* copy parameters from font instance */
286    hintmap->hinted         = font->hinted;
287    hintmap->scale          = scale;
288    hintmap->font           = font;
289    hintmap->initialHintMap = initialMap;
290    /* will clear in `cf2_hintmap_adjustHints' */
291    hintmap->hintMoves      = hintMoves;
292  }
293
294
295  static FT_Bool
296  cf2_hintmap_isValid( const CF2_HintMap  hintmap )
297  {
298    return hintmap->isValid;
299  }
300
301
302  /* transform character space coordinate to device space using hint map */
303  static CF2_Fixed
304  cf2_hintmap_map( CF2_HintMap  hintmap,
305                   CF2_Fixed    csCoord )
306  {
307    if ( hintmap->count == 0 || ! hintmap->hinted )
308    {
309      /* there are no hints; use uniform scale and zero offset */
310      return FT_MulFix( csCoord, hintmap->scale );
311    }
312    else
313    {
314      /* start linear search from last hit */
315      CF2_UInt  i = hintmap->lastIndex;
316
317      FT_ASSERT( hintmap->lastIndex < CF2_MAX_HINT_EDGES );
318
319      /* search up */
320      while ( i < hintmap->count - 1                  &&
321              csCoord >= hintmap->edge[i + 1].csCoord )
322        i += 1;
323
324      /* search down */
325      while ( i > 0 && csCoord < hintmap->edge[i].csCoord )
326        i -= 1;
327
328      hintmap->lastIndex = i;
329
330      if ( i == 0 && csCoord < hintmap->edge[0].csCoord )
331      {
332        /* special case for points below first edge: use uniform scale */
333        return FT_MulFix( csCoord - hintmap->edge[0].csCoord,
334                          hintmap->scale ) +
335                 hintmap->edge[0].dsCoord;
336      }
337      else
338      {
339        /*
340         * Note: entries with duplicate csCoord are allowed.
341         * Use edge[i], the highest entry where csCoord >= entry[i].csCoord
342         */
343        return FT_MulFix( csCoord - hintmap->edge[i].csCoord,
344                          hintmap->edge[i].scale ) +
345                 hintmap->edge[i].dsCoord;
346      }
347    }
348  }
349
350
351  /*
352   * This hinting policy moves a hint pair in device space so that one of
353   * its two edges is on a device pixel boundary (its fractional part is
354   * zero).  `cf2_hintmap_insertHint' guarantees no overlap in CS
355   * space.  Ensure here that there is no overlap in DS.
356   *
357   * In the first pass, edges are adjusted relative to adjacent hints.
358   * Those that are below have already been adjusted.  Those that are
359   * above have not yet been adjusted.  If a hint above blocks an
360   * adjustment to an optimal position, we will try again in a second
361   * pass.  The second pass is top-down.
362   *
363   */
364
365  static void
366  cf2_hintmap_adjustHints( CF2_HintMap  hintmap )
367  {
368    size_t  i, j;
369
370
371    cf2_arrstack_clear( hintmap->hintMoves );      /* working storage */
372
373    /*
374     * First pass is bottom-up (font hint order) without look-ahead.
375     * Locked edges are already adjusted.
376     * Unlocked edges begin with dsCoord from `initialHintMap'.
377     * Save edges that are not optimally adjusted in `hintMoves' array,
378     * and process them in second pass.
379     */
380
381    for ( i = 0; i < hintmap->count; i++ )
382    {
383      FT_Bool  isPair = cf2_hint_isPair( &hintmap->edge[i] );
384
385
386      /* index of upper edge (same value for ghost hint) */
387      j = isPair ? i + 1 : i;
388
389      FT_ASSERT( j < hintmap->count );
390      FT_ASSERT( cf2_hint_isValid( &hintmap->edge[i] ) );
391      FT_ASSERT( cf2_hint_isValid( &hintmap->edge[j] ) );
392      FT_ASSERT( cf2_hint_isLocked( &hintmap->edge[i] ) ==
393                   cf2_hint_isLocked( &hintmap->edge[j] ) );
394
395      if ( !cf2_hint_isLocked( &hintmap->edge[i] ) )
396      {
397        /* hint edge is not locked, we can adjust it */
398        CF2_Fixed  fracDown = cf2_fixedFraction( hintmap->edge[i].dsCoord );
399        CF2_Fixed  fracUp   = cf2_fixedFraction( hintmap->edge[j].dsCoord );
400
401        /* calculate all four possibilities; moves down are negative */
402        CF2_Fixed  downMoveDown = 0 - fracDown;
403        CF2_Fixed  upMoveDown   = 0 - fracUp;
404        CF2_Fixed  downMoveUp   = ( fracDown == 0 )
405                                    ? 0
406                                    : cf2_intToFixed( 1 ) - fracDown;
407        CF2_Fixed  upMoveUp     = ( fracUp == 0 )
408                                    ? 0
409                                    : cf2_intToFixed( 1 ) - fracUp;
410
411        /* smallest move up */
412        CF2_Fixed  moveUp   = FT_MIN( downMoveUp, upMoveUp );
413        /* smallest move down */
414        CF2_Fixed  moveDown = FT_MAX( downMoveDown, upMoveDown );
415
416        /* final amount to move edge or edge pair */
417        CF2_Fixed  move;
418
419        CF2_Fixed  downMinCounter = CF2_MIN_COUNTER;
420        CF2_Fixed  upMinCounter   = CF2_MIN_COUNTER;
421        FT_Bool    saveEdge       = FALSE;
422
423
424        /* minimum counter constraint doesn't apply when adjacent edges */
425        /* are synthetic                                                */
426        /* TODO: doesn't seem a big effect; for now, reduce the code    */
427#if 0
428        if ( i == 0                                        ||
429             cf2_hint_isSynthetic( &hintmap->edge[i - 1] ) )
430          downMinCounter = 0;
431
432        if ( j >= hintmap->count - 1                       ||
433             cf2_hint_isSynthetic( &hintmap->edge[j + 1] ) )
434          upMinCounter = 0;
435#endif
436
437        /* is there room to move up?                                    */
438        /* there is if we are at top of array or the next edge is at or */
439        /* beyond proposed move up?                                     */
440        if ( j >= hintmap->count - 1                            ||
441             hintmap->edge[j + 1].dsCoord >=
442               hintmap->edge[j].dsCoord + moveUp + upMinCounter )
443        {
444          /* there is room to move up; is there also room to move down? */
445          if ( i == 0                                                 ||
446               hintmap->edge[i - 1].dsCoord <=
447                 hintmap->edge[i].dsCoord + moveDown - downMinCounter )
448          {
449            /* move smaller absolute amount */
450            move = ( -moveDown < moveUp ) ? moveDown : moveUp;  /* optimum */
451          }
452          else
453            move = moveUp;
454        }
455        else
456        {
457          /* is there room to move down? */
458          if ( i == 0                                                 ||
459               hintmap->edge[i - 1].dsCoord <=
460                 hintmap->edge[i].dsCoord + moveDown - downMinCounter )
461          {
462            move     = moveDown;
463            /* true if non-optimum move */
464            saveEdge = (FT_Bool)( moveUp < -moveDown );
465          }
466          else
467          {
468            /* no room to move either way without overlapping or reducing */
469            /* the counter too much                                       */
470            move     = 0;
471            saveEdge = TRUE;
472          }
473        }
474
475        /* Identify non-moves and moves down that aren't optimal, and save */
476        /* them for second pass.                                           */
477        /* Do this only if there is an unlocked edge above (which could    */
478        /* possibly move).                                                 */
479        if ( saveEdge                                    &&
480             j < hintmap->count - 1                      &&
481             !cf2_hint_isLocked( &hintmap->edge[j + 1] ) )
482        {
483          CF2_HintMoveRec  savedMove;
484
485
486          savedMove.j      = j;
487          /* desired adjustment in second pass */
488          savedMove.moveUp = moveUp - move;
489
490          cf2_arrstack_push( hintmap->hintMoves, &savedMove );
491        }
492
493        /* move the edge(s) */
494        hintmap->edge[i].dsCoord += move;
495        if ( isPair )
496          hintmap->edge[j].dsCoord += move;
497      }
498
499      /* assert there are no overlaps in device space */
500      FT_ASSERT( i == 0                                                   ||
501                 hintmap->edge[i - 1].dsCoord <= hintmap->edge[i].dsCoord );
502      FT_ASSERT( i < j                                                ||
503                 hintmap->edge[i].dsCoord <= hintmap->edge[j].dsCoord );
504
505      /* adjust the scales, avoiding divide by zero */
506      if ( i > 0 )
507      {
508        if ( hintmap->edge[i].csCoord != hintmap->edge[i - 1].csCoord )
509          hintmap->edge[i - 1].scale =
510            FT_DivFix(
511              hintmap->edge[i].dsCoord - hintmap->edge[i - 1].dsCoord,
512              hintmap->edge[i].csCoord - hintmap->edge[i - 1].csCoord );
513      }
514
515      if ( isPair )
516      {
517        if ( hintmap->edge[j].csCoord != hintmap->edge[j - 1].csCoord )
518          hintmap->edge[j - 1].scale =
519            FT_DivFix(
520              hintmap->edge[j].dsCoord - hintmap->edge[j - 1].dsCoord,
521              hintmap->edge[j].csCoord - hintmap->edge[j - 1].csCoord );
522
523        i += 1;     /* skip upper edge on next loop */
524      }
525    }
526
527    /* second pass tries to move non-optimal hints up, in case there is */
528    /* room now                                                         */
529    for ( i = cf2_arrstack_size( hintmap->hintMoves ); i > 0; i-- )
530    {
531      CF2_HintMove  hintMove = (CF2_HintMove)
532                      cf2_arrstack_getPointer( hintmap->hintMoves, i - 1 );
533
534
535      j = hintMove->j;
536
537      /* this was tested before the push, above */
538      FT_ASSERT( j < hintmap->count - 1 );
539
540      /* is there room to move up? */
541      if ( hintmap->edge[j + 1].dsCoord >=
542             hintmap->edge[j].dsCoord + hintMove->moveUp + CF2_MIN_COUNTER )
543      {
544        /* there is more room now, move edge up */
545        hintmap->edge[j].dsCoord += hintMove->moveUp;
546
547        if ( cf2_hint_isPair( &hintmap->edge[j] ) )
548        {
549          FT_ASSERT( j > 0 );
550          hintmap->edge[j - 1].dsCoord += hintMove->moveUp;
551        }
552      }
553    }
554  }
555
556
557  /* insert hint edges into map, sorted by csCoord */
558  static void
559  cf2_hintmap_insertHint( CF2_HintMap  hintmap,
560                          CF2_Hint     bottomHintEdge,
561                          CF2_Hint     topHintEdge )
562  {
563    CF2_UInt  indexInsert;
564
565    /* set default values, then check for edge hints */
566    FT_Bool   isPair         = TRUE;
567    CF2_Hint  firstHintEdge  = bottomHintEdge;
568    CF2_Hint  secondHintEdge = topHintEdge;
569
570
571    /* one or none of the input params may be invalid when dealing with */
572    /* edge hints; at least one edge must be valid                      */
573    FT_ASSERT( cf2_hint_isValid( bottomHintEdge ) ||
574               cf2_hint_isValid( topHintEdge )    );
575
576    /* determine how many and which edges to insert */
577    if ( !cf2_hint_isValid( bottomHintEdge ) )
578    {
579      /* insert only the top edge */
580      firstHintEdge = topHintEdge;
581      isPair        = FALSE;
582    }
583    else if ( !cf2_hint_isValid( topHintEdge ) )
584    {
585      /* insert only the bottom edge */
586      isPair = FALSE;
587    }
588
589    /* paired edges must be in proper order */
590    if ( isPair                                         &&
591         topHintEdge->csCoord < bottomHintEdge->csCoord )
592      return;
593
594    /* linear search to find index value of insertion point */
595    indexInsert = 0;
596    for ( ; indexInsert < hintmap->count; indexInsert++ )
597    {
598      if ( hintmap->edge[indexInsert].csCoord >= firstHintEdge->csCoord )
599        break;
600    }
601
602    /*
603     * Discard any hints that overlap in character space.  Most often, this
604     * is while building the initial map, where captured hints from all
605     * zones are combined.  Define overlap to include hints that `touch'
606     * (overlap zero).  Hiragino Sans/Gothic fonts have numerous hints that
607     * touch.  Some fonts have non-ideographic glyphs that overlap our
608     * synthetic hints.
609     *
610     * Overlap also occurs when darkening stem hints that are close.
611     *
612     */
613    if ( indexInsert < hintmap->count )
614    {
615      /* we are inserting before an existing edge:    */
616      /* verify that an existing edge is not the same */
617      if ( hintmap->edge[indexInsert].csCoord == firstHintEdge->csCoord )
618        return; /* ignore overlapping stem hint */
619
620      /* verify that a new pair does not straddle the next edge */
621      if ( isPair                                                        &&
622           hintmap->edge[indexInsert].csCoord <= secondHintEdge->csCoord )
623        return; /* ignore overlapping stem hint */
624
625      /* verify that we are not inserting between paired edges */
626      if ( cf2_hint_isPairTop( &hintmap->edge[indexInsert] ) )
627        return; /* ignore overlapping stem hint */
628    }
629
630    /* recompute device space locations using initial hint map */
631    if ( cf2_hintmap_isValid( hintmap->initialHintMap ) &&
632         !cf2_hint_isLocked( firstHintEdge )            )
633    {
634      if ( isPair )
635      {
636        /* Use hint map to position the center of stem, and nominal scale */
637        /* to position the two edges.  This preserves the stem width.     */
638        CF2_Fixed  midpoint  = cf2_hintmap_map(
639                                 hintmap->initialHintMap,
640                                 ( secondHintEdge->csCoord +
641                                   firstHintEdge->csCoord ) / 2 );
642        CF2_Fixed  halfWidth = FT_MulFix(
643                                 ( secondHintEdge->csCoord -
644                                   firstHintEdge->csCoord ) / 2,
645                                 hintmap->scale );
646
647
648        firstHintEdge->dsCoord  = midpoint - halfWidth;
649        secondHintEdge->dsCoord = midpoint + halfWidth;
650      }
651      else
652        firstHintEdge->dsCoord = cf2_hintmap_map( hintmap->initialHintMap,
653                                                  firstHintEdge->csCoord );
654    }
655
656    /*
657     * Discard any hints that overlap in device space; this can occur
658     * because locked hints have been moved to align with blue zones.
659     *
660     * TODO: Although we might correct this later during adjustment, we
661     * don't currently have a way to delete a conflicting hint once it has
662     * been inserted.  See v2.030 MinionPro-Regular, 12 ppem darkened,
663     * initial hint map for second path, glyph 945 (the perispomeni (tilde)
664     * in U+1F6E, Greek omega with psili and perispomeni).  Darkening is
665     * 25.  Pair 667,747 initially conflicts in design space with top edge
666     * 660.  This is because 667 maps to 7.87, and the top edge was
667     * captured by a zone at 8.0.  The pair is later successfully inserted
668     * in a zone without the top edge.  In this zone it is adjusted to 8.0,
669     * and no longer conflicts with the top edge in design space.  This
670     * means it can be included in yet a later zone which does have the top
671     * edge hint.  This produces a small mismatch between the first and
672     * last points of this path, even though the hint masks are the same.
673     * The density map difference is tiny (1/256).
674     *
675     */
676
677    if ( indexInsert > 0 )
678    {
679      /* we are inserting after an existing edge */
680      if ( firstHintEdge->dsCoord < hintmap->edge[indexInsert - 1].dsCoord )
681        return;
682    }
683
684    if ( indexInsert < hintmap->count )
685    {
686      /* we are inserting before an existing edge */
687      if ( isPair )
688      {
689        if ( secondHintEdge->dsCoord > hintmap->edge[indexInsert].dsCoord )
690          return;
691      }
692      else
693      {
694        if ( firstHintEdge->dsCoord > hintmap->edge[indexInsert].dsCoord )
695          return;
696      }
697    }
698
699    /* make room to insert */
700    {
701      CF2_UInt  iSrc = hintmap->count - 1;
702      CF2_UInt  iDst = isPair ? hintmap->count + 1 : hintmap->count;
703
704      CF2_UInt  count = hintmap->count - indexInsert;
705
706
707      if ( iDst >= CF2_MAX_HINT_EDGES )
708      {
709        FT_TRACE4(( "cf2_hintmap_insertHint: too many hintmaps\n" ));
710        return;
711      }
712
713      while ( count-- )
714        hintmap->edge[iDst--] = hintmap->edge[iSrc--];
715
716      /* insert first edge */
717      hintmap->edge[indexInsert] = *firstHintEdge;         /* copy struct */
718      hintmap->count += 1;
719
720      if ( isPair )
721      {
722        /* insert second edge */
723        hintmap->edge[indexInsert + 1] = *secondHintEdge;  /* copy struct */
724        hintmap->count                += 1;
725      }
726    }
727
728    return;
729  }
730
731
732  /*
733   * Build a map from hints and mask.
734   *
735   * This function may recur one level if `hintmap->initialHintMap' is not yet
736   * valid.
737   * If `initialMap' is true, simply build initial map.
738   *
739   * Synthetic hints are used in two ways.  A hint at zero is inserted, if
740   * needed, in the initial hint map, to prevent translations from
741   * propagating across the origin.  If synthetic em box hints are enabled
742   * for ideographic dictionaries, then they are inserted in all hint
743   * maps, including the initial one.
744   *
745   */
746  FT_LOCAL_DEF( void )
747  cf2_hintmap_build( CF2_HintMap   hintmap,
748                     CF2_ArrStack  hStemHintArray,
749                     CF2_ArrStack  vStemHintArray,
750                     CF2_HintMask  hintMask,
751                     CF2_Fixed     hintOrigin,
752                     FT_Bool       initialMap )
753  {
754    FT_Byte*  maskPtr;
755
756    CF2_Font         font = hintmap->font;
757    CF2_HintMaskRec  tempHintMask;
758
759    size_t   bitCount, i;
760    FT_Byte  maskByte;
761
762
763    /* check whether initial map is constructed */
764    if ( !initialMap && !cf2_hintmap_isValid( hintmap->initialHintMap ) )
765    {
766      /* make recursive call with initialHintMap and temporary mask; */
767      /* temporary mask will get all bits set, below */
768      cf2_hintmask_init( &tempHintMask, hintMask->error );
769      cf2_hintmap_build( hintmap->initialHintMap,
770                         hStemHintArray,
771                         vStemHintArray,
772                         &tempHintMask,
773                         hintOrigin,
774                         TRUE );
775    }
776
777    if ( !cf2_hintmask_isValid( hintMask ) )
778    {
779      /* without a hint mask, assume all hints are active */
780      cf2_hintmask_setAll( hintMask,
781                           cf2_arrstack_size( hStemHintArray ) +
782                             cf2_arrstack_size( vStemHintArray ) );
783      if ( !cf2_hintmask_isValid( hintMask ) )
784          return;                   /* too many stem hints */
785    }
786
787    /* begin by clearing the map */
788    hintmap->count     = 0;
789    hintmap->lastIndex = 0;
790
791    /* make a copy of the hint mask so we can modify it */
792    tempHintMask = *hintMask;
793    maskPtr      = cf2_hintmask_getMaskPtr( &tempHintMask );
794
795    /* use the hStem hints only, which are first in the mask */
796    bitCount = cf2_arrstack_size( hStemHintArray );
797
798    /* Defense-in-depth.  Should never return here. */
799    if ( bitCount > hintMask->bitCount )
800        return;
801
802    /* synthetic embox hints get highest priority */
803    if ( font->blues.doEmBoxHints )
804    {
805      CF2_HintRec  dummy;
806
807
808      cf2_hint_initZero( &dummy );   /* invalid hint map element */
809
810      /* ghost bottom */
811      cf2_hintmap_insertHint( hintmap,
812                              &font->blues.emBoxBottomEdge,
813                              &dummy );
814      /* ghost top */
815      cf2_hintmap_insertHint( hintmap,
816                              &dummy,
817                              &font->blues.emBoxTopEdge );
818    }
819
820    /* insert hints captured by a blue zone or already locked (higher */
821    /* priority)                                                      */
822    for ( i = 0, maskByte = 0x80; i < bitCount; i++ )
823    {
824      if ( maskByte & *maskPtr )
825      {
826        /* expand StemHint into two `CF2_Hint' elements */
827        CF2_HintRec  bottomHintEdge, topHintEdge;
828
829
830        cf2_hint_init( &bottomHintEdge,
831                       hStemHintArray,
832                       i,
833                       font,
834                       hintOrigin,
835                       hintmap->scale,
836                       TRUE /* bottom */ );
837        cf2_hint_init( &topHintEdge,
838                       hStemHintArray,
839                       i,
840                       font,
841                       hintOrigin,
842                       hintmap->scale,
843                       FALSE /* top */ );
844
845        if ( cf2_hint_isLocked( &bottomHintEdge ) ||
846             cf2_hint_isLocked( &topHintEdge )    ||
847             cf2_blues_capture( &font->blues,
848                                &bottomHintEdge,
849                                &topHintEdge )   )
850        {
851          /* insert captured hint into map */
852          cf2_hintmap_insertHint( hintmap, &bottomHintEdge, &topHintEdge );
853
854          *maskPtr &= ~maskByte;      /* turn off the bit for this hint */
855        }
856      }
857
858      if ( ( i & 7 ) == 7 )
859      {
860        /* move to next mask byte */
861        maskPtr++;
862        maskByte = 0x80;
863      }
864      else
865        maskByte >>= 1;
866    }
867
868    /* initial hint map includes only captured hints plus maybe one at 0 */
869
870    /*
871     * TODO: There is a problem here because we are trying to build a
872     *       single hint map containing all captured hints.  It is
873     *       possible for there to be conflicts between captured hints,
874     *       either because of darkening or because the hints are in
875     *       separate hint zones (we are ignoring hint zones for the
876     *       initial map).  An example of the latter is MinionPro-Regular
877     *       v2.030 glyph 883 (Greek Capital Alpha with Psili) at 15ppem.
878     *       A stem hint for the psili conflicts with the top edge hint
879     *       for the base character.  The stem hint gets priority because
880     *       of its sort order.  In glyph 884 (Greek Capital Alpha with
881     *       Psili and Oxia), the top of the base character gets a stem
882     *       hint, and the psili does not.  This creates different initial
883     *       maps for the two glyphs resulting in different renderings of
884     *       the base character.  Will probably defer this either as not
885     *       worth the cost or as a font bug.  I don't think there is any
886     *       good reason for an accent to be captured by an alignment
887     *       zone.  -darnold 2/12/10
888     */
889
890    if ( initialMap )
891    {
892      /* Apply a heuristic that inserts a point for (0,0), unless it's     */
893      /* already covered by a mapping.  This locks the baseline for glyphs */
894      /* that have no baseline hints.                                      */
895
896      if ( hintmap->count == 0                           ||
897           hintmap->edge[0].csCoord > 0                  ||
898           hintmap->edge[hintmap->count - 1].csCoord < 0 )
899      {
900        /* all edges are above 0 or all edges are below 0; */
901        /* construct a locked edge hint at 0               */
902
903        CF2_HintRec  edge, invalid;
904
905
906        cf2_hint_initZero( &edge );
907
908        edge.flags = CF2_GhostBottom |
909                     CF2_Locked      |
910                     CF2_Synthetic;
911        edge.scale = hintmap->scale;
912
913        cf2_hint_initZero( &invalid );
914        cf2_hintmap_insertHint( hintmap, &edge, &invalid );
915      }
916    }
917    else
918    {
919      /* insert remaining hints */
920
921      maskPtr = cf2_hintmask_getMaskPtr( &tempHintMask );
922
923      for ( i = 0, maskByte = 0x80; i < bitCount; i++ )
924      {
925        if ( maskByte & *maskPtr )
926        {
927          CF2_HintRec  bottomHintEdge, topHintEdge;
928
929
930          cf2_hint_init( &bottomHintEdge,
931                         hStemHintArray,
932                         i,
933                         font,
934                         hintOrigin,
935                         hintmap->scale,
936                         TRUE /* bottom */ );
937          cf2_hint_init( &topHintEdge,
938                         hStemHintArray,
939                         i,
940                         font,
941                         hintOrigin,
942                         hintmap->scale,
943                         FALSE /* top */ );
944
945          cf2_hintmap_insertHint( hintmap, &bottomHintEdge, &topHintEdge );
946        }
947
948        if ( ( i & 7 ) == 7 )
949        {
950          /* move to next mask byte */
951          maskPtr++;
952          maskByte = 0x80;
953        }
954        else
955          maskByte >>= 1;
956      }
957    }
958
959    /*
960     * Note: The following line is a convenient place to break when
961     *       debugging hinting.  Examine `hintmap->edge' for the list of
962     *       enabled hints, then step over the call to see the effect of
963     *       adjustment.  We stop here first on the recursive call that
964     *       creates the initial map, and then on each counter group and
965     *       hint zone.
966     */
967
968    /* adjust positions of hint edges that are not locked to blue zones */
969    cf2_hintmap_adjustHints( hintmap );
970
971    /* save the position of all hints that were used in this hint map; */
972    /* if we use them again, we'll locate them in the same position    */
973    if ( !initialMap )
974    {
975      for ( i = 0; i < hintmap->count; i++ )
976      {
977        if ( !cf2_hint_isSynthetic( &hintmap->edge[i] ) )
978        {
979          /* Note: include both valid and invalid edges            */
980          /* Note: top and bottom edges are copied back separately */
981          CF2_StemHint  stemhint = (CF2_StemHint)
982                          cf2_arrstack_getPointer( hStemHintArray,
983                                                   hintmap->edge[i].index );
984
985
986          if ( cf2_hint_isTop( &hintmap->edge[i] ) )
987            stemhint->maxDS = hintmap->edge[i].dsCoord;
988          else
989            stemhint->minDS = hintmap->edge[i].dsCoord;
990
991          stemhint->used = TRUE;
992        }
993      }
994    }
995
996    /* hint map is ready to use */
997    hintmap->isValid = TRUE;
998
999    /* remember this mask has been used */
1000    cf2_hintmask_setNew( hintMask, FALSE );
1001  }
1002
1003
1004  FT_LOCAL_DEF( void )
1005  cf2_glyphpath_init( CF2_GlyphPath         glyphpath,
1006                      CF2_Font              font,
1007                      CF2_OutlineCallbacks  callbacks,
1008                      CF2_Fixed             scaleY,
1009                      /* CF2_Fixed  hShift, */
1010                      CF2_ArrStack          hStemHintArray,
1011                      CF2_ArrStack          vStemHintArray,
1012                      CF2_HintMask          hintMask,
1013                      CF2_Fixed             hintOriginY,
1014                      const CF2_Blues       blues,
1015                      const FT_Vector*      fractionalTranslation )
1016  {
1017    FT_ZERO( glyphpath );
1018
1019    glyphpath->font      = font;
1020    glyphpath->callbacks = callbacks;
1021
1022    cf2_arrstack_init( &glyphpath->hintMoves,
1023                       font->memory,
1024                       &font->error,
1025                       sizeof ( CF2_HintMoveRec ) );
1026
1027    cf2_hintmap_init( &glyphpath->initialHintMap,
1028                      font,
1029                      &glyphpath->initialHintMap,
1030                      &glyphpath->hintMoves,
1031                      scaleY );
1032    cf2_hintmap_init( &glyphpath->firstHintMap,
1033                      font,
1034                      &glyphpath->initialHintMap,
1035                      &glyphpath->hintMoves,
1036                      scaleY );
1037    cf2_hintmap_init( &glyphpath->hintMap,
1038                      font,
1039                      &glyphpath->initialHintMap,
1040                      &glyphpath->hintMoves,
1041                      scaleY );
1042
1043    glyphpath->scaleX = font->innerTransform.a;
1044    glyphpath->scaleC = font->innerTransform.c;
1045    glyphpath->scaleY = font->innerTransform.d;
1046
1047    glyphpath->fractionalTranslation = *fractionalTranslation;
1048
1049#if 0
1050    glyphpath->hShift = hShift;       /* for fauxing */
1051#endif
1052
1053    glyphpath->hStemHintArray = hStemHintArray;
1054    glyphpath->vStemHintArray = vStemHintArray;
1055    glyphpath->hintMask       = hintMask;      /* ptr to current mask */
1056    glyphpath->hintOriginY    = hintOriginY;
1057    glyphpath->blues          = blues;
1058    glyphpath->darken         = font->darkened; /* TODO: should we make copies? */
1059    glyphpath->xOffset        = font->darkenX;
1060    glyphpath->yOffset        = font->darkenY;
1061    glyphpath->miterLimit     = 2 * FT_MAX(
1062                                     cf2_fixedAbs( glyphpath->xOffset ),
1063                                     cf2_fixedAbs( glyphpath->yOffset ) );
1064
1065    /* .1 character space unit */
1066    glyphpath->snapThreshold = cf2_floatToFixed( 0.1f );
1067
1068    glyphpath->moveIsPending = TRUE;
1069    glyphpath->pathIsOpen    = FALSE;
1070    glyphpath->pathIsClosing = FALSE;
1071    glyphpath->elemIsQueued  = FALSE;
1072  }
1073
1074
1075  FT_LOCAL_DEF( void )
1076  cf2_glyphpath_finalize( CF2_GlyphPath  glyphpath )
1077  {
1078    cf2_arrstack_finalize( &glyphpath->hintMoves );
1079  }
1080
1081
1082  /*
1083   * Hint point in y-direction and apply outerTransform.
1084   * Input `current' hint map (which is actually delayed by one element).
1085   * Input x,y point in Character Space.
1086   * Output x,y point in Device Space, including translation.
1087   */
1088  static void
1089  cf2_glyphpath_hintPoint( CF2_GlyphPath  glyphpath,
1090                           CF2_HintMap    hintmap,
1091                           FT_Vector*     ppt,
1092                           CF2_Fixed      x,
1093                           CF2_Fixed      y )
1094  {
1095    FT_Vector  pt;   /* hinted point in upright DS */
1096
1097
1098    pt.x = FT_MulFix( glyphpath->scaleX, x ) +
1099             FT_MulFix( glyphpath->scaleC, y );
1100    pt.y = cf2_hintmap_map( hintmap, y );
1101
1102    ppt->x = FT_MulFix( glyphpath->font->outerTransform.a, pt.x )   +
1103               FT_MulFix( glyphpath->font->outerTransform.c, pt.y ) +
1104               glyphpath->fractionalTranslation.x;
1105    ppt->y = FT_MulFix( glyphpath->font->outerTransform.b, pt.x )   +
1106               FT_MulFix( glyphpath->font->outerTransform.d, pt.y ) +
1107               glyphpath->fractionalTranslation.y;
1108  }
1109
1110
1111  /*
1112   * From two line segments, (u1,u2) and (v1,v2), compute a point of
1113   * intersection on the corresponding lines.
1114   * Return false if no intersection is found, or if the intersection is
1115   * too far away from the ends of the line segments, u2 and v1.
1116   *
1117   */
1118  static FT_Bool
1119  cf2_glyphpath_computeIntersection( CF2_GlyphPath     glyphpath,
1120                                     const FT_Vector*  u1,
1121                                     const FT_Vector*  u2,
1122                                     const FT_Vector*  v1,
1123                                     const FT_Vector*  v2,
1124                                     FT_Vector*        intersection )
1125  {
1126    /*
1127     * Let `u' be a zero-based vector from the first segment, `v' from the
1128     * second segment.
1129     * Let `w 'be the zero-based vector from `u1' to `v1'.
1130     * `perp' is the `perpendicular dot product'; see
1131     * http://mathworld.wolfram.com/PerpDotProduct.html.
1132     * `s' is the parameter for the parametric line for the first segment
1133     * (`u').
1134     *
1135     * See notation in
1136     * http://softsurfer.com/Archive/algorithm_0104/algorithm_0104B.htm.
1137     * Calculations are done in 16.16, but must handle the squaring of
1138     * line lengths in character space.  We scale all vectors by 1/32 to
1139     * avoid overflow.  This allows values up to 4095 to be squared.  The
1140     * scale factor cancels in the divide.
1141     *
1142     * TODO: the scale factor could be computed from UnitsPerEm.
1143     *
1144     */
1145
1146#define cf2_perp( a, b )                                    \
1147          ( FT_MulFix( a.x, b.y ) - FT_MulFix( a.y, b.x ) )
1148
1149  /* round and divide by 32 */
1150#define CF2_CS_SCALE( x )         \
1151          ( ( (x) + 0x10 ) >> 5 )
1152
1153    FT_Vector  u, v, w;      /* scaled vectors */
1154    CF2_Fixed  denominator, s;
1155
1156
1157    u.x = CF2_CS_SCALE( u2->x - u1->x );
1158    u.y = CF2_CS_SCALE( u2->y - u1->y );
1159    v.x = CF2_CS_SCALE( v2->x - v1->x );
1160    v.y = CF2_CS_SCALE( v2->y - v1->y );
1161    w.x = CF2_CS_SCALE( v1->x - u1->x );
1162    w.y = CF2_CS_SCALE( v1->y - u1->y );
1163
1164    denominator = cf2_perp( u, v );
1165
1166    if ( denominator == 0 )
1167      return FALSE;           /* parallel or coincident lines */
1168
1169    s = FT_DivFix( cf2_perp( w, v ), denominator );
1170
1171    intersection->x = u1->x + FT_MulFix( s, u2->x - u1->x );
1172    intersection->y = u1->y + FT_MulFix( s, u2->y - u1->y );
1173
1174    /*
1175     * Special case snapping for horizontal and vertical lines.
1176     * This cleans up intersections and reduces problems with winding
1177     * order detection.
1178     * Sample case is sbc cd KozGoPr6N-Medium.otf 20 16685.
1179     * Note: these calculations are in character space.
1180     *
1181     */
1182
1183    if ( u1->x == u2->x                                                     &&
1184         cf2_fixedAbs( intersection->x - u1->x ) < glyphpath->snapThreshold )
1185      intersection->x = u1->x;
1186    if ( u1->y == u2->y                                                     &&
1187         cf2_fixedAbs( intersection->y - u1->y ) < glyphpath->snapThreshold )
1188      intersection->y = u1->y;
1189
1190    if ( v1->x == v2->x                                                     &&
1191         cf2_fixedAbs( intersection->x - v1->x ) < glyphpath->snapThreshold )
1192      intersection->x = v1->x;
1193    if ( v1->y == v2->y                                                     &&
1194         cf2_fixedAbs( intersection->y - v1->y ) < glyphpath->snapThreshold )
1195      intersection->y = v1->y;
1196
1197    /* limit the intersection distance from midpoint of u2 and v1 */
1198    if ( cf2_fixedAbs( intersection->x - ( u2->x + v1->x ) / 2 ) >
1199           glyphpath->miterLimit                                   ||
1200         cf2_fixedAbs( intersection->y - ( u2->y + v1->y ) / 2 ) >
1201           glyphpath->miterLimit                                   )
1202      return FALSE;
1203
1204    return TRUE;
1205  }
1206
1207
1208  /*
1209   * Push the cached element (glyphpath->prevElem*) to the outline
1210   * consumer.  When a darkening offset is used, the end point of the
1211   * cached element may be adjusted to an intersection point or we may
1212   * synthesize a connecting line to the current element.  If we are
1213   * closing a subpath, we may also generate a connecting line to the start
1214   * point.
1215   *
1216   * This is where Character Space (CS) is converted to Device Space (DS)
1217   * using a hint map.  This calculation must use a HintMap that was valid
1218   * at the time the element was saved.  For the first point in a subpath,
1219   * that is a saved HintMap.  For most elements, it just means the caller
1220   * has delayed building a HintMap from the current HintMask.
1221   *
1222   * Transform each point with outerTransform and call the outline
1223   * callbacks.  This is a general 3x3 transform:
1224   *
1225   *   x' = a*x + c*y + tx, y' = b*x + d*y + ty
1226   *
1227   * but it uses 4 elements from CF2_Font and the translation part
1228   * from CF2_GlyphPath.
1229   *
1230   */
1231  static void
1232  cf2_glyphpath_pushPrevElem( CF2_GlyphPath  glyphpath,
1233                              CF2_HintMap    hintmap,
1234                              FT_Vector*     nextP0,
1235                              FT_Vector      nextP1,
1236                              FT_Bool        close )
1237  {
1238    CF2_CallbackParamsRec  params;
1239
1240    FT_Vector*  prevP0;
1241    FT_Vector*  prevP1;
1242
1243    FT_Vector  intersection    = { 0, 0 };
1244    FT_Bool    useIntersection = FALSE;
1245
1246
1247    FT_ASSERT( glyphpath->prevElemOp == CF2_PathOpLineTo ||
1248               glyphpath->prevElemOp == CF2_PathOpCubeTo );
1249
1250    if ( glyphpath->prevElemOp == CF2_PathOpLineTo )
1251    {
1252      prevP0 = &glyphpath->prevElemP0;
1253      prevP1 = &glyphpath->prevElemP1;
1254    }
1255    else
1256    {
1257      prevP0 = &glyphpath->prevElemP2;
1258      prevP1 = &glyphpath->prevElemP3;
1259    }
1260
1261    /* optimization: if previous and next elements are offset by the same */
1262    /* amount, then there will be no gap, and no need to compute an       */
1263    /* intersection.                                                      */
1264    if ( prevP1->x != nextP0->x || prevP1->y != nextP0->y )
1265    {
1266      /* previous element does not join next element:             */
1267      /* adjust end point of previous element to the intersection */
1268      useIntersection = cf2_glyphpath_computeIntersection( glyphpath,
1269                                                           prevP0,
1270                                                           prevP1,
1271                                                           nextP0,
1272                                                           &nextP1,
1273                                                           &intersection );
1274      if ( useIntersection )
1275      {
1276        /* modify the last point of the cached element (either line or */
1277        /* curve)                                                      */
1278        *prevP1 = intersection;
1279      }
1280    }
1281
1282    params.pt0 = glyphpath->currentDS;
1283
1284    switch( glyphpath->prevElemOp )
1285    {
1286    case CF2_PathOpLineTo:
1287      params.op = CF2_PathOpLineTo;
1288
1289      /* note: pt2 and pt3 are unused */
1290
1291      if ( close )
1292      {
1293        /* use first hint map if closing */
1294        cf2_glyphpath_hintPoint( glyphpath,
1295                                 &glyphpath->firstHintMap,
1296                                 &params.pt1,
1297                                 glyphpath->prevElemP1.x,
1298                                 glyphpath->prevElemP1.y );
1299      }
1300      else
1301      {
1302        cf2_glyphpath_hintPoint( glyphpath,
1303                                 hintmap,
1304                                 &params.pt1,
1305                                 glyphpath->prevElemP1.x,
1306                                 glyphpath->prevElemP1.y );
1307      }
1308
1309      /* output only non-zero length lines */
1310      if ( params.pt0.x != params.pt1.x || params.pt0.y != params.pt1.y )
1311      {
1312        glyphpath->callbacks->lineTo( glyphpath->callbacks, &params );
1313
1314        glyphpath->currentDS = params.pt1;
1315      }
1316      break;
1317
1318    case CF2_PathOpCubeTo:
1319      params.op = CF2_PathOpCubeTo;
1320
1321      /* TODO: should we intersect the interior joins (p1-p2 and p2-p3)? */
1322      cf2_glyphpath_hintPoint( glyphpath,
1323                               hintmap,
1324                               &params.pt1,
1325                               glyphpath->prevElemP1.x,
1326                               glyphpath->prevElemP1.y );
1327      cf2_glyphpath_hintPoint( glyphpath,
1328                               hintmap,
1329                               &params.pt2,
1330                               glyphpath->prevElemP2.x,
1331                               glyphpath->prevElemP2.y );
1332      cf2_glyphpath_hintPoint( glyphpath,
1333                               hintmap,
1334                               &params.pt3,
1335                               glyphpath->prevElemP3.x,
1336                               glyphpath->prevElemP3.y );
1337
1338      glyphpath->callbacks->cubeTo( glyphpath->callbacks, &params );
1339
1340      glyphpath->currentDS = params.pt3;
1341
1342      break;
1343    }
1344
1345    if ( !useIntersection || close )
1346    {
1347      /* insert connecting line between end of previous element and start */
1348      /* of current one                                                   */
1349      /* note: at the end of a subpath, we might do both, so use `nextP0' */
1350      /* before we change it, below                                       */
1351
1352      if ( close )
1353      {
1354        /* if we are closing the subpath, then nextP0 is in the first     */
1355        /* hint zone                                                      */
1356        cf2_glyphpath_hintPoint( glyphpath,
1357                                 &glyphpath->firstHintMap,
1358                                 &params.pt1,
1359                                 nextP0->x,
1360                                 nextP0->y );
1361      }
1362      else
1363      {
1364        cf2_glyphpath_hintPoint( glyphpath,
1365                                 hintmap,
1366                                 &params.pt1,
1367                                 nextP0->x,
1368                                 nextP0->y );
1369      }
1370
1371      if ( params.pt1.x != glyphpath->currentDS.x ||
1372           params.pt1.y != glyphpath->currentDS.y )
1373      {
1374        /* length is nonzero */
1375        params.op  = CF2_PathOpLineTo;
1376        params.pt0 = glyphpath->currentDS;
1377
1378        /* note: pt2 and pt3 are unused */
1379        glyphpath->callbacks->lineTo( glyphpath->callbacks, &params );
1380
1381        glyphpath->currentDS = params.pt1;
1382      }
1383    }
1384
1385    if ( useIntersection )
1386    {
1387      /* return intersection point to caller */
1388      *nextP0 = intersection;
1389    }
1390  }
1391
1392
1393  /* push a MoveTo element based on current point and offset of current */
1394  /* element                                                            */
1395  static void
1396  cf2_glyphpath_pushMove( CF2_GlyphPath  glyphpath,
1397                          FT_Vector      start )
1398  {
1399    CF2_CallbackParamsRec  params;
1400
1401
1402    params.op  = CF2_PathOpMoveTo;
1403    params.pt0 = glyphpath->currentDS;
1404
1405    /* Test if move has really happened yet; it would have called */
1406    /* `cf2_hintmap_build' to set `isValid'.                   */
1407    if ( !cf2_hintmap_isValid( &glyphpath->hintMap ) )
1408    {
1409      /* we are here iff first subpath is missing a moveto operator: */
1410      /* synthesize first moveTo to finish initialization of hintMap */
1411      cf2_glyphpath_moveTo( glyphpath,
1412                            glyphpath->start.x,
1413                            glyphpath->start.y );
1414    }
1415
1416    cf2_glyphpath_hintPoint( glyphpath,
1417                             &glyphpath->hintMap,
1418                             &params.pt1,
1419                             start.x,
1420                             start.y );
1421
1422    /* note: pt2 and pt3 are unused */
1423    glyphpath->callbacks->moveTo( glyphpath->callbacks, &params );
1424
1425    glyphpath->currentDS    = params.pt1;
1426    glyphpath->offsetStart0 = start;
1427  }
1428
1429
1430  /*
1431   * All coordinates are in character space.
1432   * On input, (x1, y1) and (x2, y2) give line segment.
1433   * On output, (x, y) give offset vector.
1434   * We use a piecewise approximation to trig functions.
1435   *
1436   * TODO: Offset true perpendicular and proper length
1437   *       supply the y-translation for hinting here, too,
1438   *       that adds yOffset unconditionally to *y.
1439   */
1440  static void
1441  cf2_glyphpath_computeOffset( CF2_GlyphPath  glyphpath,
1442                               CF2_Fixed      x1,
1443                               CF2_Fixed      y1,
1444                               CF2_Fixed      x2,
1445                               CF2_Fixed      y2,
1446                               CF2_Fixed*     x,
1447                               CF2_Fixed*     y )
1448  {
1449    CF2_Fixed  dx = x2 - x1;
1450    CF2_Fixed  dy = y2 - y1;
1451
1452
1453    /* note: negative offsets don't work here; negate deltas to change */
1454    /* quadrants, below                                                */
1455    if ( glyphpath->font->reverseWinding )
1456    {
1457      dx = -dx;
1458      dy = -dy;
1459    }
1460
1461    *x = *y = 0;
1462
1463    if ( !glyphpath->darken )
1464        return;
1465
1466    /* add momentum for this path element */
1467    glyphpath->callbacks->windingMomentum +=
1468      cf2_getWindingMomentum( x1, y1, x2, y2 );
1469
1470    /* note: allow mixed integer and fixed multiplication here */
1471    if ( dx >= 0 )
1472    {
1473      if ( dy >= 0 )
1474      {
1475        /* first quadrant, +x +y */
1476
1477        if ( dx > 2 * dy )
1478        {
1479          /* +x */
1480          *x = 0;
1481          *y = 0;
1482        }
1483        else if ( dy > 2 * dx )
1484        {
1485          /* +y */
1486          *x = glyphpath->xOffset;
1487          *y = glyphpath->yOffset;
1488        }
1489        else
1490        {
1491          /* +x +y */
1492          *x = FT_MulFix( cf2_floatToFixed( 0.7 ),
1493                          glyphpath->xOffset );
1494          *y = FT_MulFix( cf2_floatToFixed( 1.0 - 0.7 ),
1495                          glyphpath->yOffset );
1496        }
1497      }
1498      else
1499      {
1500        /* fourth quadrant, +x -y */
1501
1502        if ( dx > -2 * dy )
1503        {
1504          /* +x */
1505          *x = 0;
1506          *y = 0;
1507        }
1508        else if ( -dy > 2 * dx )
1509        {
1510          /* -y */
1511          *x = -glyphpath->xOffset;
1512          *y = glyphpath->yOffset;
1513        }
1514        else
1515        {
1516          /* +x -y */
1517          *x = FT_MulFix( cf2_floatToFixed( -0.7 ),
1518                          glyphpath->xOffset );
1519          *y = FT_MulFix( cf2_floatToFixed( 1.0 - 0.7 ),
1520                          glyphpath->yOffset );
1521        }
1522      }
1523    }
1524    else
1525    {
1526      if ( dy >= 0 )
1527      {
1528        /* second quadrant, -x +y */
1529
1530        if ( -dx > 2 * dy )
1531        {
1532          /* -x */
1533          *x = 0;
1534          *y = 2 * glyphpath->yOffset;
1535        }
1536        else if ( dy > -2 * dx )
1537        {
1538          /* +y */
1539          *x = glyphpath->xOffset;
1540          *y = glyphpath->yOffset;
1541        }
1542        else
1543        {
1544          /* -x +y */
1545          *x = FT_MulFix( cf2_floatToFixed( 0.7 ),
1546                          glyphpath->xOffset );
1547          *y = FT_MulFix( cf2_floatToFixed( 1.0 + 0.7 ),
1548                          glyphpath->yOffset );
1549        }
1550      }
1551      else
1552      {
1553        /* third quadrant, -x -y */
1554
1555        if ( -dx > -2 * dy )
1556        {
1557          /* -x */
1558          *x = 0;
1559          *y = 2 * glyphpath->yOffset;
1560        }
1561        else if ( -dy > -2 * dx )
1562        {
1563          /* -y */
1564          *x = -glyphpath->xOffset;
1565          *y = glyphpath->yOffset;
1566        }
1567        else
1568        {
1569          /* -x -y */
1570          *x = FT_MulFix( cf2_floatToFixed( -0.7 ),
1571                          glyphpath->xOffset );
1572          *y = FT_MulFix( cf2_floatToFixed( 1.0 + 0.7 ),
1573                          glyphpath->yOffset );
1574        }
1575      }
1576    }
1577  }
1578
1579
1580  /*
1581   * The functions cf2_glyphpath_{moveTo,lineTo,curveTo,closeOpenPath} are
1582   * called by the interpreter with Character Space (CS) coordinates.  Each
1583   * path element is placed into a queue of length one to await the
1584   * calculation of the following element.  At that time, the darkening
1585   * offset of the following element is known and joins can be computed,
1586   * including possible modification of this element, before mapping to
1587   * Device Space (DS) and passing it on to the outline consumer.
1588   *
1589   */
1590  FT_LOCAL_DEF( void )
1591  cf2_glyphpath_moveTo( CF2_GlyphPath  glyphpath,
1592                        CF2_Fixed      x,
1593                        CF2_Fixed      y )
1594  {
1595    cf2_glyphpath_closeOpenPath( glyphpath );
1596
1597    /* save the parameters of the move for later, when we'll know how to */
1598    /* offset it;                                                        */
1599    /* also save last move point */
1600    glyphpath->currentCS.x = glyphpath->start.x = x;
1601    glyphpath->currentCS.y = glyphpath->start.y = y;
1602
1603    glyphpath->moveIsPending = TRUE;
1604
1605    /* ensure we have a valid map with current mask */
1606    if ( !cf2_hintmap_isValid( &glyphpath->hintMap ) ||
1607         cf2_hintmask_isNew( glyphpath->hintMask )   )
1608      cf2_hintmap_build( &glyphpath->hintMap,
1609                         glyphpath->hStemHintArray,
1610                         glyphpath->vStemHintArray,
1611                         glyphpath->hintMask,
1612                         glyphpath->hintOriginY,
1613                         FALSE );
1614
1615    /* save a copy of current HintMap to use when drawing initial point */
1616    glyphpath->firstHintMap = glyphpath->hintMap;     /* structure copy */
1617  }
1618
1619
1620  FT_LOCAL_DEF( void )
1621  cf2_glyphpath_lineTo( CF2_GlyphPath  glyphpath,
1622                        CF2_Fixed      x,
1623                        CF2_Fixed      y )
1624  {
1625    CF2_Fixed  xOffset, yOffset;
1626    FT_Vector  P0, P1;
1627    FT_Bool    newHintMap;
1628
1629    /*
1630     * New hints will be applied after cf2_glyphpath_pushPrevElem has run.
1631     * In case this is a synthesized closing line, any new hints should be
1632     * delayed until this path is closed (`cf2_hintmask_isNew' will be
1633     * called again before the next line or curve).
1634     */
1635
1636    /* true if new hint map not on close */
1637    newHintMap = cf2_hintmask_isNew( glyphpath->hintMask ) &&
1638                 !glyphpath->pathIsClosing;
1639
1640    /*
1641     * Zero-length lines may occur in the charstring.  Because we cannot
1642     * compute darkening offsets or intersections from zero-length lines,
1643     * it is best to remove them and avoid artifacts.  However, zero-length
1644     * lines in CS at the start of a new hint map can generate non-zero
1645     * lines in DS due to hint substitution.  We detect a change in hint
1646     * map here and pass those zero-length lines along.
1647     */
1648
1649    /*
1650     * Note: Find explicitly closed paths here with a conditional
1651     *       breakpoint using
1652     *
1653     *         !gp->pathIsClosing && gp->start.x == x && gp->start.y == y
1654     *
1655     */
1656
1657    if ( glyphpath->currentCS.x == x &&
1658         glyphpath->currentCS.y == y &&
1659         !newHintMap                 )
1660      /*
1661       * Ignore zero-length lines in CS where the hint map is the same
1662       * because the line in DS will also be zero length.
1663       *
1664       * Ignore zero-length lines when we synthesize a closing line because
1665       * the close will be handled in cf2_glyphPath_pushPrevElem.
1666       */
1667      return;
1668
1669    cf2_glyphpath_computeOffset( glyphpath,
1670                                 glyphpath->currentCS.x,
1671                                 glyphpath->currentCS.y,
1672                                 x,
1673                                 y,
1674                                 &xOffset,
1675                                 &yOffset );
1676
1677    /* construct offset points */
1678    P0.x = glyphpath->currentCS.x + xOffset;
1679    P0.y = glyphpath->currentCS.y + yOffset;
1680    P1.x = x + xOffset;
1681    P1.y = y + yOffset;
1682
1683    if ( glyphpath->moveIsPending )
1684    {
1685      /* emit offset 1st point as MoveTo */
1686      cf2_glyphpath_pushMove( glyphpath, P0 );
1687
1688      glyphpath->moveIsPending = FALSE;  /* adjust state machine */
1689      glyphpath->pathIsOpen    = TRUE;
1690
1691      glyphpath->offsetStart1 = P1;              /* record second point */
1692    }
1693
1694    if ( glyphpath->elemIsQueued )
1695    {
1696      FT_ASSERT( cf2_hintmap_isValid( &glyphpath->hintMap ) ||
1697                 glyphpath->hintMap.count == 0              );
1698
1699      cf2_glyphpath_pushPrevElem( glyphpath,
1700                                  &glyphpath->hintMap,
1701                                  &P0,
1702                                  P1,
1703                                  FALSE );
1704    }
1705
1706    /* queue the current element with offset points */
1707    glyphpath->elemIsQueued = TRUE;
1708    glyphpath->prevElemOp   = CF2_PathOpLineTo;
1709    glyphpath->prevElemP0   = P0;
1710    glyphpath->prevElemP1   = P1;
1711
1712    /* update current map */
1713    if ( newHintMap )
1714      cf2_hintmap_build( &glyphpath->hintMap,
1715                         glyphpath->hStemHintArray,
1716                         glyphpath->vStemHintArray,
1717                         glyphpath->hintMask,
1718                         glyphpath->hintOriginY,
1719                         FALSE );
1720
1721    glyphpath->currentCS.x = x;     /* pre-offset current point */
1722    glyphpath->currentCS.y = y;
1723  }
1724
1725
1726  FT_LOCAL_DEF( void )
1727  cf2_glyphpath_curveTo( CF2_GlyphPath  glyphpath,
1728                         CF2_Fixed      x1,
1729                         CF2_Fixed      y1,
1730                         CF2_Fixed      x2,
1731                         CF2_Fixed      y2,
1732                         CF2_Fixed      x3,
1733                         CF2_Fixed      y3 )
1734  {
1735    CF2_Fixed  xOffset1, yOffset1, xOffset3, yOffset3;
1736    FT_Vector  P0, P1, P2, P3;
1737
1738
1739    /* TODO: ignore zero length portions of curve?? */
1740    cf2_glyphpath_computeOffset( glyphpath,
1741                                 glyphpath->currentCS.x,
1742                                 glyphpath->currentCS.y,
1743                                 x1,
1744                                 y1,
1745                                 &xOffset1,
1746                                 &yOffset1 );
1747    cf2_glyphpath_computeOffset( glyphpath,
1748                                 x2,
1749                                 y2,
1750                                 x3,
1751                                 y3,
1752                                 &xOffset3,
1753                                 &yOffset3 );
1754
1755    /* add momentum from the middle segment */
1756    glyphpath->callbacks->windingMomentum +=
1757      cf2_getWindingMomentum( x1, y1, x2, y2 );
1758
1759    /* construct offset points */
1760    P0.x = glyphpath->currentCS.x + xOffset1;
1761    P0.y = glyphpath->currentCS.y + yOffset1;
1762    P1.x = x1 + xOffset1;
1763    P1.y = y1 + yOffset1;
1764    /* note: preserve angle of final segment by using offset3 at both ends */
1765    P2.x = x2 + xOffset3;
1766    P2.y = y2 + yOffset3;
1767    P3.x = x3 + xOffset3;
1768    P3.y = y3 + yOffset3;
1769
1770    if ( glyphpath->moveIsPending )
1771    {
1772      /* emit offset 1st point as MoveTo */
1773      cf2_glyphpath_pushMove( glyphpath, P0 );
1774
1775      glyphpath->moveIsPending = FALSE;
1776      glyphpath->pathIsOpen    = TRUE;
1777
1778      glyphpath->offsetStart1 = P1;              /* record second point */
1779    }
1780
1781    if ( glyphpath->elemIsQueued )
1782    {
1783      FT_ASSERT( cf2_hintmap_isValid( &glyphpath->hintMap ) ||
1784                 glyphpath->hintMap.count == 0              );
1785
1786      cf2_glyphpath_pushPrevElem( glyphpath,
1787                                  &glyphpath->hintMap,
1788                                  &P0,
1789                                  P1,
1790                                  FALSE );
1791    }
1792
1793    /* queue the current element with offset points */
1794    glyphpath->elemIsQueued = TRUE;
1795    glyphpath->prevElemOp   = CF2_PathOpCubeTo;
1796    glyphpath->prevElemP0   = P0;
1797    glyphpath->prevElemP1   = P1;
1798    glyphpath->prevElemP2   = P2;
1799    glyphpath->prevElemP3   = P3;
1800
1801    /* update current map */
1802    if ( cf2_hintmask_isNew( glyphpath->hintMask ) )
1803      cf2_hintmap_build( &glyphpath->hintMap,
1804                         glyphpath->hStemHintArray,
1805                         glyphpath->vStemHintArray,
1806                         glyphpath->hintMask,
1807                         glyphpath->hintOriginY,
1808                         FALSE );
1809
1810    glyphpath->currentCS.x = x3;       /* pre-offset current point */
1811    glyphpath->currentCS.y = y3;
1812  }
1813
1814
1815  FT_LOCAL_DEF( void )
1816  cf2_glyphpath_closeOpenPath( CF2_GlyphPath  glyphpath )
1817  {
1818    if ( glyphpath->pathIsOpen )
1819    {
1820      /*
1821       * A closing line in Character Space line is always generated below
1822       * with `cf2_glyphPath_lineTo'.  It may be ignored later if it turns
1823       * out to be zero length in Device Space.
1824       */
1825      glyphpath->pathIsClosing = TRUE;
1826
1827      cf2_glyphpath_lineTo( glyphpath,
1828                            glyphpath->start.x,
1829                            glyphpath->start.y );
1830
1831      /* empty the final element from the queue and close the path */
1832      if ( glyphpath->elemIsQueued )
1833        cf2_glyphpath_pushPrevElem( glyphpath,
1834                                    &glyphpath->hintMap,
1835                                    &glyphpath->offsetStart0,
1836                                    glyphpath->offsetStart1,
1837                                    TRUE );
1838
1839      /* reset state machine */
1840      glyphpath->moveIsPending = TRUE;
1841      glyphpath->pathIsOpen    = FALSE;
1842      glyphpath->pathIsClosing = FALSE;
1843      glyphpath->elemIsQueued  = FALSE;
1844    }
1845  }
1846
1847
1848/* END */
1849