summaryrefslogtreecommitdiff
path: root/scripts/lib/fontbuild/mix.py
blob: 519b50d953aa5a20590c5b7b62113524844ca525 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
# Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.


from numpy import array, append
import copy
import json
from robofab.objects.objectsRF import RPoint
from robofab.world import OpenFont
from decomposeGlyph import decomposeGlyph


class FFont:
    "Font wrapper for floating point operations"
    
    def __init__(self,f=None):
        self.glyphs = {}
        self.hstems = []
        self.vstems = []
        self.kerning = {}
        if isinstance(f,FFont):
            #self.glyphs = [g.copy() for g in f.glyphs]
            for key,g in f.glyphs.iteritems():
                self.glyphs[key] = g.copy()
            self.hstems = list(f.hstems)
            self.vstems = list(f.vstems)
            self.kerning = dict(f.kerning)
        elif f != None:
            self.copyFromFont(f)

    def copyFromFont(self, f):
        for g in f:
            self.glyphs[g.name] = FGlyph(g)
        self.hstems = [s for s in f.info.postscriptStemSnapH]
        self.vstems = [s for s in f.info.postscriptStemSnapV]
        self.kerning = f.kerning.asDict()


    def copyToFont(self, f):
        for g in f:
            try:
                gF = self.glyphs[g.name]
                gF.copyToGlyph(g)
            except:
                print "Copy to glyph failed for" + g.name
        f.info.postscriptStemSnapH = self.hstems
        f.info.postscriptStemSnapV = self.vstems
        for pair in self.kerning:
            f.kerning[pair] = self.kerning[pair]

    def getGlyph(self, gname):
        try:
            return self.glyphs[gname]
        except:
            return None
        
    def setGlyph(self, gname, glyph):
        self.glyphs[gname] = glyph
    
    def addDiff(self,b,c):
        newFont = FFont(self)
        for key,g in newFont.glyphs.iteritems():
            gB = b.getGlyph(key)
            gC = c.getGlyph(key)
            try:
                newFont.glyphs[key] = g.addDiff(gB,gC)
            except:
                print "Add diff failed for '%s'" %key
        return newFont

class FGlyph:
    "provides a temporary floating point compatible glyph data structure"
    
    def __init__(self, g=None):
        self.contours = []
        self.width = 0.
        self.components = []
        self.anchors = []
        if g != None:
            self.copyFromGlyph(g)
        
    def copyFromGlyph(self,g):
        self.name = g.name
        valuesX = []
        valuesY = []
        self.width = len(valuesX)
        valuesX.append(g.width)
        for c in g.components:
            self.components.append((len(valuesX), len(valuesY)))
            valuesX.append(c.scale[0])
            valuesY.append(c.scale[1])
            valuesX.append(c.offset[0])
            valuesY.append(c.offset[1])

        for a in g.anchors:
            self.anchors.append((len(valuesX), len(valuesY)))
            valuesX.append(a.x)
            valuesY.append(a.y)

        for i in range(len(g)):
            self.contours.append([])
            for j in range (len(g[i].points)):
                self.contours[i].append((len(valuesX), len(valuesY)))
                valuesX.append(g[i].points[j].x)
                valuesY.append(g[i].points[j].y)

        self.dataX = array(valuesX, dtype=float)
        self.dataY = array(valuesY, dtype=float)
        
    def copyToGlyph(self,g):
        g.width = self._derefX(self.width)
        if len(g.components) == len(self.components):
            for i in range(len(self.components)):
                g.components[i].scale = (self._derefX(self.components[i][0] + 0, asInt=False),
                                         self._derefY(self.components[i][1] + 0, asInt=False))
                g.components[i].offset = (self._derefX(self.components[i][0] + 1),
                                          self._derefY(self.components[i][1] + 1))
        if len(g.anchors) == len(self.anchors):
            for i in range(len(self.anchors)):
                g.anchors[i].x = self._derefX( self.anchors[i][0])
                g.anchors[i].y = self._derefY( self.anchors[i][1])
        for i in range(len(g)) :
            for j in range (len(g[i].points)):
                g[i].points[j].x = self._derefX(self.contours[i][j][0])
                g[i].points[j].y = self._derefY(self.contours[i][j][1])

    def isCompatible(self, g):
        return (len(self.dataX) == len(g.dataX) and
                len(self.dataY) == len(g.dataY) and
                len(g.contours) == len(self.contours))
    
    def __add__(self,g):
        if self.isCompatible(g):
            newGlyph = self.copy()
            newGlyph.dataX = self.dataX + g.dataX
            newGlyph.dataY = self.dataY + g.dataY
            return newGlyph
        else:
            print "Add failed for '%s'" %(self.name)
            raise Exception
    
    def __sub__(self,g):
        if self.isCompatible(g):
            newGlyph = self.copy()
            newGlyph.dataX = self.dataX - g.dataX
            newGlyph.dataY = self.dataY - g.dataY
            return newGlyph
        else:
            print "Subtract failed for '%s'" %(self.name)
            raise Exception
    
    def __mul__(self,scalar):
        newGlyph = self.copy()
        newGlyph.dataX = self.dataX * scalar
        newGlyph.dataY = self.dataY * scalar
        return newGlyph
    
    def scaleX(self,scalar):
        newGlyph = self.copy()
        if len(self.dataX) > 0:
            newGlyph.dataX = self.dataX * scalar
            for i in range(len(newGlyph.components)):
                newGlyph.dataX[newGlyph.components[i][0]] = self.dataX[newGlyph.components[i][0]]
        return newGlyph
        
    def shift(self,ammount):
        newGlyph = self.copy()
        newGlyph.dataX = self.dataX + ammount
        for i in range(len(newGlyph.components)):
            newGlyph.dataX[newGlyph.components[i][0]] = self.dataX[newGlyph.components[i][0]]
        return newGlyph
    
    def interp(self, g, v):
        gF = self.copy()
        if not self.isCompatible(g):
            print "Interpolate failed for '%s'; outlines incompatible" %(self.name)
            raise Exception
        
        gF.dataX += (g.dataX - gF.dataX) * v.x
        gF.dataY += (g.dataY - gF.dataY) * v.y
        return gF
    
    def copy(self):
        ng = FGlyph()
        ng.contours = list(self.contours)
        ng.width = self.width
        ng.components = list(self.components)
        ng.anchors = list(self.anchors)
        ng.dataX = self.dataX.copy()
        ng.dataY = self.dataY.copy()
        ng.name = self.name
        return ng
    
    def _derefX(self,id, asInt=True):
        val = self.dataX[id]
        return int(round(val)) if asInt else val
    
    def _derefY(self,id, asInt=True):
        val = self.dataY[id]
        return int(round(val)) if asInt else val
    
    def addDiff(self,gB,gC):
        newGlyph = self + (gB - gC)
        return newGlyph
        
    

class Master:

    def __init__(self, font=None, v=0, kernlist=None, overlay=None,
                 anchorPath=None):
        if isinstance(font, FFont):
            self.font = None
            self.ffont = font
        elif isinstance(font,str):
            self.openFont(font,overlay, anchorPath)
        elif isinstance(font,Mix):
            self.font = font
        else:
            self.font = font
            self.ffont = FFont(font)
        if isinstance(v,float) or isinstance(v,int):
            self.v = RPoint(v, v)
        else:
            self.v = v
        if kernlist != None:
            kerns = [i.strip().split() for i in open(kernlist).readlines()]
            
            self.kernlist = [{'left':k[0], 'right':k[1], 'value': k[2]} 
                            for k in kerns 
                            if not k[0].startswith("#")
                            and not k[0] == ""]
            #TODO implement class based kerning / external kerning file
    
    def openFont(self, path, overlayPath=None, anchorPath=None):
        self.font = OpenFont(path)
        for g in self.font:
          size = len(g)
          csize = len(g.components)
          if (size > 0 and csize > 0):
            decomposeGlyph(self.font, g.name)

        if overlayPath != None:
            overlayFont = OpenFont(overlayPath)
            font = self.font
            for overlayGlyph in overlayFont:
                font.insertGlyph(overlayGlyph)

        # work around a bug with vfb2ufo in which anchors are dropped from
        # glyphs containing components and no contours. "anchorPath" should
        # point to the output of src/v2/get_dropped_anchors.py
        if anchorPath:
            anchorData = json.load(open(anchorPath))
            for glyphName, anchors in anchorData.items():
                glyph = self.font[glyphName]
                for name, (x, y) in anchors.items():
                    glyph.appendAnchor(str(name), (x, y))

        self.ffont = FFont(self.font)


class Mix:
    def __init__(self,masters,v):
        self.masters = masters
        if isinstance(v,float) or isinstance(v,int):
            self.v = RPoint(v,v)
        else:
            self.v = v
    
    def getFGlyph(self, master, gname):
        if isinstance(master.font, Mix):
            return font.mixGlyphs(gname)
        return master.ffont.getGlyph(gname)
    
    def getGlyphMasters(self,gname):
        masters = self.masters
        if len(masters) <= 2:
            return self.getFGlyph(masters[0], gname), self.getFGlyph(masters[-1], gname)
    
    def generateFFont(self):
        ffont = FFont(self.masters[0].ffont)
        for key,g in ffont.glyphs.iteritems():
            ffont.glyphs[key] = self.mixGlyphs(key)
        ffont.kerning = self.mixKerns()
        return ffont
    
    def generateFont(self, baseFont):
        newFont = baseFont.copy()
        #self.mixStems(newFont)  todo _ fix stems code
        for g in newFont:
            gF = self.mixGlyphs(g.name)
            if gF == None:
                g.mark = True
            else:
                gF.copyToGlyph(g)
        newFont.kerning.clear()
        newFont.kerning.update(self.mixKerns() or {})
        return newFont
    
    def mixGlyphs(self,gname):
        gA,gB = self.getGlyphMasters(gname)        
        try:
            return gA.interp(gB,self.v)
        except:
            print "mixglyph failed for %s" %(gname)
            if gA != None:
                return gA.copy()

    def getKerning(self, master):
        if isinstance(master.font, Mix):
            return master.font.mixKerns()
        return master.ffont.kerning

    def mixKerns(self):
        masters = self.masters
        kA, kB = self.getKerning(masters[0]), self.getKerning(masters[-1])
        return interpolateKerns(kA, kB, self.v)


def narrowFLGlyph(g, gThin, factor=.75):
    gF = FGlyph(g)
    if not isinstance(gThin,FGlyph):
        gThin = FGlyph(gThin)
    gCondensed = gThin.scaleX(factor)
    try:
        gNarrow = gF + (gCondensed - gThin)
        gNarrow.copyToGlyph(g)
    except:
        print "No dice for: " + g.name
            
def interpolate(a,b,v,e=0):
    if e == 0:
        return a+(b-a)*v
    qe = (b-a)*v*v*v + a   #cubic easing
    le = a+(b-a)*v   # linear easing
    return le + (qe-le) * e
    
def interpolateKerns(kA, kB, v):
    kerns = {}
    for pair in kA.keys():
        matchedKern = kB.get(pair)
        # if matchedkern == None:
        #     matchedkern = Kern(kA)
        #     matchedkern.value = 0
        if matchedKern != None:
            kerns[pair] = interpolate(kA[pair], matchedKern, v.x)
    return kerns