TextNode.cc 13.8 KB
Newer Older
Jan Möbius's avatar
Jan Möbius committed
1
2
3
/*===========================================================================*\
 *                                                                           *
 *                              OpenFlipper                                  *
Jan Möbius's avatar
Jan Möbius committed
4
 *      Copyright (C) 2001-2011 by Computer Graphics Group, RWTH Aachen      *
Jan Möbius's avatar
Jan Möbius committed
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
 *                           www.openflipper.org                             *
 *                                                                           *
 *---------------------------------------------------------------------------*
 *  This file is part of OpenFlipper.                                        *
 *                                                                           *
 *  OpenFlipper is free software: you can redistribute it and/or modify      *
 *  it under the terms of the GNU Lesser General Public License as           *
 *  published by the Free Software Foundation, either version 3 of           *
 *  the License, or (at your option) any later version with the              *
 *  following exceptions:                                                    *
 *                                                                           *
 *  If other files instantiate templates or use macros                       *
 *  or inline functions from this file, or you compile this file and         *
 *  link it with other files to produce an executable, this file does        *
 *  not by itself cause the resulting executable to be covered by the        *
 *  GNU Lesser General Public License. This exception does not however       *
 *  invalidate any other reasons why the executable file might be            *
 *  covered by the GNU Lesser General Public License.                        *
 *                                                                           *
 *  OpenFlipper is distributed in the hope that it will be useful,           *
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of           *
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the            *
 *  GNU Lesser General Public License for more details.                      *
 *                                                                           *
 *  You should have received a copy of the GNU LesserGeneral Public          *
 *  License along with OpenFlipper. If not,                                  *
 *  see <http://www.gnu.org/licenses/>.                                      *
 *                                                                           *
\*===========================================================================*/

/*===========================================================================*\
 *                                                                           *
Jan Möbius's avatar
Jan Möbius committed
37
 *   $Revision$                                                       *
Jan Möbius's avatar
Jan Möbius committed
38
39
40
41
 *   $Author$                                                      *
 *   $Date$                   *
 *                                                                           *
\*===========================================================================*/
Jan Möbius's avatar
 
Jan Möbius committed
42
43
44
45
46
47
48
49
50
51




//=============================================================================
//
//  CLASS TextNode - IMPLEMENTATION
//
//=============================================================================

52

Jan Möbius's avatar
 
Jan Möbius committed
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

//== INCLUDES =================================================================

#include "TextNode.hh"
#include "../GL/gl.hh"
#include <stdlib.h>


//== NAMESPACES ===============================================================

namespace ACG {
namespace SceneGraph {


//== IMPLEMENTATION ==========================================================

69
70
71
72
73
74
75
76
// static members
QFont TextNode::qfont_ = QFont("Helvetica", 20);
GLuint TextNode::texture_ = 0;
int TextNode::imageWidth_ = 0;
bool TextNode::initialised_ = false;
std::map<char, unsigned int> TextNode::charToIndex_ = TextNode::createMap();
QColor TextNode::color_ = QColor(255, 0, 0);

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

//----------------------------------------------------------------------------


TextNode::
TextNode( BaseNode*    _parent,
          std::string  _name,
          TextMode     _textMode)
  : BaseNode(_parent, _name),
    size_(1),
    textMode_(_textMode),
    vbo_(0),
    vertexBuffer_(0),
    blendEnabled_(false),
    texture2dEnabled_(false),
    cullFaceEnabled_(false),
    blendSrc_(0),
    blendDest_(0)
{
  updateFont();
  updateVBO();
}



//----------------------------------------------------------------------------


Jan Möbius's avatar
 
Jan Möbius committed
105
106
107
TextNode::
~TextNode()
{
108
  glDeleteBuffers(1, &vbo_);
Jan Möbius's avatar
 
Jan Möbius committed
109
110
}

111
112
113
114
115

//----------------------------------------------------------------------------



Jan Möbius's avatar
 
Jan Möbius committed
116
117
void
TextNode::
118
boundingBox(Vec3d& /*_bbMin*/, Vec3d& /*_bbMax*/)
Jan Möbius's avatar
 
Jan Möbius committed
119
120
121
122
123
124
125
{
}


//----------------------------------------------------------------------------


Jan Möbius's avatar
Jan Möbius committed
126
DrawModes::DrawMode
Jan Möbius's avatar
 
Jan Möbius committed
127
TextNode::
Jan Möbius's avatar
Jan Möbius committed
128
availableDrawModes() const
Jan Möbius's avatar
 
Jan Möbius committed
129
130
{
  return ( DrawModes::POINTS |
Jan Möbius's avatar
Jan Möbius committed
131
132
           DrawModes::POINTS_SHADED |
           DrawModes::POINTS_COLORED );
Jan Möbius's avatar
 
Jan Möbius committed
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
void
TextNode::
setRenderingMode(TextMode _textMode) {
  textMode_ = _textMode;
}



//----------------------------------------------------------------------------


TextNode::TextMode
TextNode::
renderingMode() {
  return textMode_;
}



//----------------------------------------------------------------------------


void
TextNode::
setText(std::string _text) {
  text_ = _text; updateVBO();
}



//----------------------------------------------------------------------------


void
TextNode::
setSize(unsigned int _size) {
  size_ = _size; updateVBO();
}


//----------------------------------------------------------------------------


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
std::map<char, unsigned int>
TextNode::
createMap() {
  std::map<char, unsigned int> m;
  unsigned int i = 0;
  for (char c = ' '; c < '~'; ++c, ++i) {
    m[c] = i;
  }

  return m;
}


//----------------------------------------------------------------------------


void
TextNode::
enter(GLState& /*_state*/, const DrawModes::DrawMode& /*_drawmode*/) {
  // store current gl state
  cullFaceEnabled_ = glIsEnabled(GL_CULL_FACE);
  texture2dEnabled_ = glIsEnabled(GL_TEXTURE_2D);
  blendEnabled_ = glIsEnabled(GL_BLEND);
  glGetIntegerv(GL_BLEND_SRC, &blendSrc_);
  glGetIntegerv(GL_BLEND_DST, &blendDest_);

  // set texture and drawing states
  ACG::GLState::disable(GL_CULL_FACE);
  ACG::GLState::enable(GL_TEXTURE_2D);
  ACG::GLState::enable(GL_BLEND);
  ACG::GLState::blendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
}



//----------------------------------------------------------------------------


void
TextNode::
leave(GLState& /*_state*/, const DrawModes::DrawMode& /*_drawmode*/) {
223
  // restore the GLState as it was when entering TextNode
224
225
226
227
228
229
230
231
232
233
234
235
  if (cullFaceEnabled_)
    ACG::GLState::enable(GL_CULL_FACE);
  if (!texture2dEnabled_)
    ACG::GLState::disable(GL_TEXTURE_2D);
  if (!blendEnabled_)
    ACG::GLState::disable(GL_BLEND);

  ACG::GLState::blendFunc(blendSrc_, blendDest_);
}



Jan Möbius's avatar
 
Jan Möbius committed
236
237
238
239
240
//----------------------------------------------------------------------------


void
TextNode::
241
draw(GLState& _state, const DrawModes::DrawMode& /*_drawMode*/)
Jan Möbius's avatar
 
Jan Möbius committed
242
{
243
244
  if (!text_.empty()) {
    bindVBO();
245
246

    // do not rotate the quads in this case
247
248
249
250
251
252
253
254
255
256
257
258
    if (textMode_ == SCREEN_ALIGNED) {
      _state.push_modelview_matrix();
      Vec3d projected = _state.project(Vec3d(0.0, 0.0, 0.0));
      _state.reset_modelview();
      Vec3d unprojected = _state.unproject(projected);
      _state.translate(unprojected);
    }

    _state.push_modelview_matrix();
    _state.scale(size_);
    glDrawArrays(GL_QUADS, 0, text_.size() * 4);
    _state.pop_modelview_matrix();
Jan Möbius's avatar
 
Jan Möbius committed
259

260
261
262
263
    if (textMode_ == SCREEN_ALIGNED) {
      _state.pop_modelview_matrix();
    }
    unbindVBO();
Jan Möbius's avatar
 
Jan Möbius committed
264
  }
265
266
}

Jan Möbius's avatar
 
Jan Möbius committed
267

268
//----------------------------------------------------------------------------
Jan Möbius's avatar
 
Jan Möbius committed
269
270


271
272
273
quint32
TextNode::nearestPowerOfTwo(quint32 num) {
  quint32 n = num > 0 ? num - 1 : 0;
274
275
276
277
278
279
280

  n |= n >> 1;
  n |= n >> 2;
  n |= n >> 4;
  n |= n >> 8;
  n |= n >> 16;
  n++;
Jan Möbius's avatar
 
Jan Möbius committed
281

282
  return n;
Jan Möbius's avatar
 
Jan Möbius committed
283
284
285
286
287
288
}


//----------------------------------------------------------------------------


289
290
291
292
void
TextNode::setFont(const QFont& _font) {
  qfont_ = QFont(_font);
  initialised_ = false;
293
  updateFont();
294
295
296
297
298
299
  updateVBO();
}


//----------------------------------------------------------------------------

Jan Möbius's avatar
 
Jan Möbius committed
300
301
void
TextNode::
302
updateFont() {
303

304
  // do not generate a new texture for every TextNode unless necessary
305
306
307
308
309
310
  if (initialised_)
    return;

  QFontMetrics metric(qfont_);

  int height = metric.height();
311
  // ensure that the height of the texture is a power of 2
312
313
  int heightPow2 = nearestPowerOfTwo(height);
  int width = metric.maxWidth();
314
  // ensure that the width of the texture is a power of 2
315
316
317
318
319
320
321
322
323
324
325
  int widthPow2 = nearestPowerOfTwo(width);
  imageWidth_ = widthPow2 * numberOfChars_;

  QImage finalImage(imageWidth_, heightPow2, QImage::Format_ARGB32);
  finalImage.fill(Qt::transparent);
  QPainter painter;
  painter.begin(&finalImage);
  painter.setRenderHints(QPainter::HighQualityAntialiasing
                         | QPainter::TextAntialiasing);
  painter.setFont(qfont_);
  painter.setPen(color_);
326
327

  // characters are drawn aligned to the left into the QImage finalImage next to each other
328
329
330
331
332
333
  unsigned int i = 0;
  for (char c = ' '; c < '~'; ++c, ++i) {
    painter.drawText(i*widthPow2, 0, widthPow2, heightPow2, Qt::AlignLeft | Qt::AlignBottom, QString(c));
  }
  painter.end();

334
  // convert finalImage to an OpenGL friendly format
335
336
  finalImage = QGLWidget::convertToGLFormat(finalImage);

337
338
  // delete the old texture if it exists
  // and generate a new texture from finalImage
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
  glDeleteTextures(1, &texture_);
  glGenTextures(1, &texture_);
  ACG::GLState::bindTexture(GL_TEXTURE_2D, texture_);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
  glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
  glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, finalImage.width(), finalImage.height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, finalImage.bits());
  ACG::GLState::bindTexture(GL_TEXTURE_2D, 0);

  initialised_ = true;
}


//----------------------------------------------------------------------------


void
TextNode::
updateVBO() {
  if (text_.size() == 0)
    return;

  vertexBuffer_.clear();

364
365
366
367
368
  // generate a quad for each character next to each other
  // *--*--*----*-*
  // |  |  |    | |
  // |  |  |    | |
  // *--*--*----*-*
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
  QFontMetrics metric(qfont_);
  int maxWidth = metric.maxWidth();
  int avgWidth = metric.averageCharWidth();
  float lastCharRight = 0.0f;
  for (unsigned int i = 0; i < text_.size(); ++i) {

    // left and right vertex coordinates
    float width = (float) metric.width(text_[i]) / (float) maxWidth;
    float left, right;

    if (i == 0)
      left = 0.0f;
    else
      left = lastCharRight;

    right = (left + width);
    lastCharRight = right;

    // left and right texture coordinates
    int leftBearing = abs(metric.leftBearing(text_[i]));
    int rightBearing = abs(metric.rightBearing(text_[i]));
    int metricWidth = metric.width(text_[i]);

    // QFontMetrics does not seem to always give the correct width
    // therefore we add a margin so that characters are not cut off
    if (leftBearing + rightBearing < 0.1*maxWidth) {
      if (metricWidth + 0.25*maxWidth < maxWidth)
        metricWidth += 0.25*maxWidth;
      else
        metricWidth = maxWidth;
    } else {
      metricWidth += leftBearing + rightBearing;
Jan Möbius's avatar
Jan Möbius committed
401
    }
402
403

    float widthTx = (float) metricWidth / (float) imageWidth_;
404
405
    // get the starting position of the character in the texture
    // note that the characters are drawn aligned to the bottom left in in the texture
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
    float leftTx = ((float) charToIndex_[text_[i]] ) / (float) numberOfChars_;
    float rightTx = leftTx + widthTx;

    // bottom left
    vertexBuffer_.push_back(left);
    vertexBuffer_.push_back(0.0f);
    vertexBuffer_.push_back(0.0f);

    // texture coordinates
    vertexBuffer_.push_back(leftTx);
    vertexBuffer_.push_back(0.0f);

    // top left
    vertexBuffer_.push_back(left);
    vertexBuffer_.push_back(avgWidth*0.15);
    vertexBuffer_.push_back(0.0f);

    // texture coordinates
    vertexBuffer_.push_back(leftTx);
    vertexBuffer_.push_back(1.0f);

    // top right
    vertexBuffer_.push_back(right);
    vertexBuffer_.push_back(avgWidth*0.15);
    vertexBuffer_.push_back(0.0f);

    // texture coordinates
    vertexBuffer_.push_back(rightTx);
    vertexBuffer_.push_back(1.0f);

    // bottom right
    vertexBuffer_.push_back(right);
    vertexBuffer_.push_back(0.0f);
    vertexBuffer_.push_back(0.0f);

    // texture coordinates
    vertexBuffer_.push_back(rightTx);
    vertexBuffer_.push_back(0.0f);
Jan Möbius's avatar
Jan Möbius committed
444
  }
445
446
447
448
449

  glDeleteBuffers(1, &vbo_);
  glGenBuffers(1, &vbo_);
  ACG::GLState::bindBuffer(GL_ARRAY_BUFFER, vbo_);
  glBufferData(GL_ARRAY_BUFFER, vertexBuffer_.size() * sizeof(GLfloat), &vertexBuffer_[0], GL_DYNAMIC_DRAW);
Jan Möbius's avatar
 
Jan Möbius committed
450
451
}

452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483

//----------------------------------------------------------------------------


void
TextNode::
bindVBO() {
  ACG::GLState::bindBuffer(GL_ARRAY_BUFFER, vbo_);
  ACG::GLState::vertexPointer(3, GL_FLOAT, 5*sizeof(GLfloat), 0);
  ACG::GLState::enableClientState(GL_VERTEX_ARRAY);

  ACG::GLState::activeTexture(GL_TEXTURE0);
  ACG::GLState::texcoordPointer(2, GL_FLOAT, 5*sizeof(GLfloat), reinterpret_cast<void*>(3*sizeof(GLfloat)));
  ACG::GLState::enableClientState(GL_TEXTURE_COORD_ARRAY);

  ACG::GLState::bindTexture(GL_TEXTURE_2D, texture_);
}


//----------------------------------------------------------------------------


void
TextNode::
unbindVBO() {
  ACG::GLState::bindTexture(GL_TEXTURE_2D, 0);
  ACG::GLState::bindBuffer(GL_ARRAY_BUFFER, 0);
  ACG::GLState::disableClientState(GL_VERTEX_ARRAY);
  ACG::GLState::disableClientState(GL_TEXTURE_COORD_ARRAY);
}


Jan Möbius's avatar
 
Jan Möbius committed
484
485
486
487
//=============================================================================
} // namespace SceneGraph
} // namespace ACG
//=============================================================================