summaryrefslogtreecommitdiff
path: root/src/ftgl/FTFont/FTBufferFont.cpp
blob: e48e2ab62e93f79b3ce64d21e9893d8856778cf2 (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
/*
 * FTGL - OpenGL font library
 *
 * Copyright (c) 2008 Sam Hocevar <sam@zoy.org>
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 */

#include "config.h"

#include <wchar.h>

#include "FTGL/ftgl.h"

#include "FTInternals.h"
#include "FTBufferFontImpl.h"


//
//  FTBufferFont
//


FTBufferFont::FTBufferFont(char const *fontFilePath) :
    FTFont(new FTBufferFontImpl(this, fontFilePath))
{}


FTBufferFont::FTBufferFont(unsigned char const *pBufferBytes,
                           size_t bufferSizeInBytes) :
    FTFont(new FTBufferFontImpl(this, pBufferBytes, bufferSizeInBytes))
{}


FTBufferFont::~FTBufferFont()
{}


FTGlyph* FTBufferFont::MakeGlyph(FT_GlyphSlot ftGlyph)
{
    FTBufferFontImpl *myimpl = dynamic_cast<FTBufferFontImpl *>(impl);
    if(!myimpl)
    {
        return NULL;
    }

    return myimpl->MakeGlyphImpl(ftGlyph);
}


//
//  FTBufferFontImpl
//


FTBufferFontImpl::FTBufferFontImpl(FTFont *ftFont, const char* fontFilePath) :
    FTFontImpl(ftFont, fontFilePath),
    buffer(new FTBuffer())
{
    load_flags = FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP;

    glGenTextures(BUFFER_CACHE_SIZE, idCache);

    for(int i = 0; i < BUFFER_CACHE_SIZE; i++)
    {
        stringCache[i] = NULL;
        glBindTexture(GL_TEXTURE_2D, idCache[i]);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    }

    lastString = 0;
}


FTBufferFontImpl::FTBufferFontImpl(FTFont *ftFont,
                                   const unsigned char *pBufferBytes,
                                   size_t bufferSizeInBytes) :
    FTFontImpl(ftFont, pBufferBytes, bufferSizeInBytes),
    buffer(new FTBuffer())
{
    load_flags = FT_LOAD_NO_HINTING | FT_LOAD_NO_BITMAP;

    glGenTextures(BUFFER_CACHE_SIZE, idCache);

    for(int i = 0; i < BUFFER_CACHE_SIZE; i++)
    {
        stringCache[i] = NULL;
        glBindTexture(GL_TEXTURE_2D, idCache[i]);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    }

    lastString = 0;
}


FTBufferFontImpl::~FTBufferFontImpl()
{
    glDeleteTextures(BUFFER_CACHE_SIZE, idCache);

    for(int i = 0; i < BUFFER_CACHE_SIZE; i++)
    {
        if(stringCache[i])
        {
            free(stringCache[i]);
        }
    }

    delete buffer;
}


FTGlyph* FTBufferFontImpl::MakeGlyphImpl(FT_GlyphSlot ftGlyph)
{
    return new FTBufferGlyph(ftGlyph, buffer);
}


bool FTBufferFontImpl::FaceSize(const unsigned int size,
                                const unsigned int res)
{
    for(int i = 0; i < BUFFER_CACHE_SIZE; i++)
    {
        if(stringCache[i])
        {
            free(stringCache[i]);
            stringCache[i] = NULL;
        }
    }

    return FTFontImpl::FaceSize(size, res);
}


static inline GLuint NextPowerOf2(GLuint in)
{
     in -= 1;

     in |= in >> 16;
     in |= in >> 8;
     in |= in >> 4;
     in |= in >> 2;
     in |= in >> 1;

     return in + 1;
}


inline int StringCompare(void const *a, char const *b, int len)
{
    return len < 0 ? strcmp((char const *)a, b)
                   : strncmp((char const *)a, b, len);
}


inline int StringCompare(void const *a, wchar_t const *b, int len)
{
    return len < 0 ? wcscmp((wchar_t const *)a, b)
                   : wcsncmp((wchar_t const *)a, b, len);
}


inline char *StringCopy(char const *s, int len)
{
    if(len < 0)
    {
        return strdup(s);
    }
    else
    {
#ifdef HAVE_STRNDUP
        return strndup(s, len);
#else
        char *s2 = (char*)malloc(len + 1);
        memcpy(s2, s, len);
        s2[len] = 0;
        return s2;
#endif
    }
}


inline wchar_t *StringCopy(wchar_t const *s, int len)
{
    if(len < 0)
    {
#if defined HAVE_WCSDUP
        return wcsdup(s);
#else
        len = (int)wcslen(s);
#endif
    }

    wchar_t *s2 = (wchar_t *)malloc((len + 1) * sizeof(wchar_t));
    memcpy(s2, s, len * sizeof(wchar_t));
    s2[len] = 0;
    return s2;
}


template <typename T>
inline FTPoint FTBufferFontImpl::RenderI(const T* string, const int len,
                                         FTPoint position, FTPoint spacing,
                                         int renderMode)
{
    const float padding = 3.0f;
    int width, height, texWidth, texHeight;
    int cacheIndex = -1;
    bool inCache = false;

    // Protect blending functions, GL_BLEND and GL_TEXTURE_2D
    glPushAttrib(GL_COLOR_BUFFER_BIT | GL_ENABLE_BIT);

    // Protect glPixelStorei() calls
    glPushClientAttrib(GL_CLIENT_PIXEL_STORE_BIT);

    glEnable(GL_BLEND);
    glEnable(GL_TEXTURE_2D);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); // GL_ONE

    // Search whether the string is already in a texture we uploaded
    for(int n = 0; n < BUFFER_CACHE_SIZE; n++)
    {
        int i = (lastString + n + BUFFER_CACHE_SIZE) % BUFFER_CACHE_SIZE;

        if(stringCache[i] && !StringCompare(stringCache[i], string, len))
        {
            cacheIndex = i;
            inCache = true;
            break;
        }
    }

    // If the string was not found, we need to put it in the cache and compute
    // its new bounding box.
    if(!inCache)
    {
        // FIXME: this cache is not very efficient. We should first expire
        // strings that are not used very often.
        cacheIndex = lastString;
        lastString = (lastString + 1) % BUFFER_CACHE_SIZE;

        if(stringCache[cacheIndex])
        {
            free(stringCache[cacheIndex]);
        }
        // FIXME: only the first N bytes are copied; we want the first N chars.
        stringCache[cacheIndex] = StringCopy(string, len);
        bboxCache[cacheIndex] = BBox(string, len, FTPoint(), spacing);
    }

    FTBBox bbox = bboxCache[cacheIndex];

    width = static_cast<int>(bbox.Upper().X() - bbox.Lower().X()
                              + padding + padding + 0.5);
    height = static_cast<int>(bbox.Upper().Y() - bbox.Lower().Y()
                               + padding + padding + 0.5);

    texWidth = NextPowerOf2(width);
    texHeight = NextPowerOf2(height);

    glBindTexture(GL_TEXTURE_2D, idCache[cacheIndex]);

    // If the string was not found, we need to render the text in a new
    // texture buffer, then upload it to the OpenGL layer.
    if(!inCache)
    {
        buffer->Size(texWidth, texHeight);
        buffer->Pos(FTPoint(padding, padding) - bbox.Lower());

        advanceCache[cacheIndex] =
              FTFontImpl::Render(string, len, FTPoint(), spacing, renderMode);

        glBindTexture(GL_TEXTURE_2D, idCache[cacheIndex]);

        glPixelStorei(GL_UNPACK_LSB_FIRST, GL_FALSE);
        glPixelStorei(GL_UNPACK_ROW_LENGTH, 0);
        glPixelStorei(GL_UNPACK_ALIGNMENT, 1);

        /* TODO: use glTexSubImage2D later? */
        glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, texWidth, texHeight, 0,
                     GL_ALPHA, GL_UNSIGNED_BYTE, (GLvoid *)buffer->Pixels());

        buffer->Size(0, 0);
    }

    FTPoint low = position + bbox.Lower();
    FTPoint up = position + bbox.Upper();

    glBegin(GL_QUADS);
        glNormal3f(0.0f, 0.0f, 1.0f);
        glTexCoord2f(padding / texWidth,
                     (texHeight - height + padding) / texHeight);
        glVertex2f(low.Xf(), up.Yf());
        glTexCoord2f(padding / texWidth,
                     (texHeight - padding) / texHeight);
        glVertex2f(low.Xf(), low.Yf());
        glTexCoord2f((width - padding) / texWidth,
                     (texHeight - padding) / texHeight);
        glVertex2f(up.Xf(), low.Yf());
        glTexCoord2f((width - padding) / texWidth,
                     (texHeight - height + padding) / texHeight);
        glVertex2f(up.Xf(), up.Yf());
    glEnd();

    glPopClientAttrib();
    glPopAttrib();

    return position + advanceCache[cacheIndex];
}


FTPoint FTBufferFontImpl::Render(const char * string, const int len,
                                 FTPoint position, FTPoint spacing,
                                 int renderMode)
{
    return RenderI(string, len, position, spacing, renderMode);
}


FTPoint FTBufferFontImpl::Render(const wchar_t * string, const int len,
                                 FTPoint position, FTPoint spacing,
                                 int renderMode)
{
    return RenderI(string, len, position, spacing, renderMode);
}