HLFX.Ru Forum
профиль •  правила •  регистрация •  календарь •  народ •  FAQ •  поиск •  новое •  сутки •  главная •  выход  
HLFX.Ru Forum HLFX.Ru Forum > Теория и практика > Half-Life SDK > bitmap fonts ?
  Предыдущая тема   Следующая тема
Автор
Тема Новая тема    Ответить
daku
Частый гость

Дата регистрации: Oct 2011
Проживает: (void)
Сообщений: 93

Рейтинг



bitmap fonts ?

Hi i have trouble with bitmap fonts. i have fonts in .fnt format and CFont loader class.

Font file is loaded and with it i have no errors but if i want to write something with that font then on

C++ Source Code:
1
if( ch->page != page )
2
{
3
  page = ch->page;
4
  glBindTexture(GL_TEXTURE_2D, pages[page]); //TGA
5
}


cpp file
C++ Source Code:
1
#include <windows.h>
2
#include <gl/gl.h>
3
#include "gl/glext.h"
4
#include "hud.h"
5
#include "cl_util.h"
6
 
7
#include "cfont.h"
8
 
9
//#include "bsprenderer.h"
10
#include "tex_header.h"
11
 
12
 
13
typedef unsigned int        UINT;
14
#include <iostream>
15
using namespace std;
16
// Implement private helper classes for loading the bitmap font files
17
 
18
class CFontLoader
19
{
20
public:
21
  CFontLoader(FILE *f, CFont *font, const char *fontFile);
22
 
23
  virtual int Load() = 0; // Must be implemented by derived class
24
 
25
protected:
26
  void LoadPage(int id, const char *pageFile, const char *fontFile);
27
  void SetFontInfo(int outlineThickness);
28
  void SetCommonInfo(int fontHeight, int base, int scaleW, int scaleH, int pages, bool isPacked);
29
  void AddChar(int id, int x, int y, int w, int h, int xoffset, int yoffset, int xadvance, int page, int chnl);
30
  void AddKerningPair(int first, int second, int amount);
31
 
32
  FILE *f;
33
  CFont *font;
34
  const char *fontFile;
35
 
36
  int outlineThickness;
37
};
38
 
39
class CFontLoaderTextFormat : public CFontLoader
40
{
41
public:
42
  CFontLoaderTextFormat(FILE *f, CFont *font, const char *fontFile);
43
 
44
  int Load();
45
 
46
  int SkipWhiteSpace(std::string &str, int start);
47
  int FindEndOfToken(std::string &str, int start);
48
 
49
  void InterpretInfo(std::string &str, int start);
50
  void InterpretCommon(std::string &str, int start);
51
  void InterpretChar(std::string &str, int start);
52
  void InterpretSpacing(std::string &str, int start);
53
  void InterpretKerning(std::string &str, int start);
54
  void InterpretPage(std::string &str, int start, const char *fontFile);
55
};
56
 
57
 
58
int CFont::Init(const char *fontFile)
59
{
60
 
61
  char fontFilewithmod[64];
62
  sprintf(fontFilewithmod,"cszd/%s",fontFile);
63
 
64
  // Load the font
65
  FILE *f = fopen(fontFilewithmod, "rb");
66
  if (f==NULL) return -1; //фUйл н: оHqлDЩ!!!
67
 
68
  // Determine format by reading the first bytes of the file
69
  char str[4] = {0};
70
  fread(str, 3, 1, f);
71
  fseek(f, 0, SEEK_SET);
72
 
73
  CFontLoader *loader = 0;
74
 
75
  loader = new CFontLoaderTextFormat(f, this, fontFile);
76
 
77
  // r - result???
78
  int r = loader->Load();
79
  //delete loader;
80
 
81
  return r;
82
}
83
 
84
CFont::CFont()
85
{
86
  fontHeight = 0;
87
  base = 0;
88
  scaleW = 0;
89
  scaleH = 0;
90
  scale = 1.0f;
91
  //render = 0;
92
  hasOutline = false;
93
  encoding = NONE;
94
}
95
 
96
CFont::~CFont()
97
{
98
  std::map<int, SCharDescr*>::iterator it = chars.begin();
99
  while( it != chars.end() )
100
  {
101
    delete it->second;
102
    it++;
103
  }
104
 
105
}
106
 
107
// Internal
108
SCharDescr *CFont::GetChar(int id)
109
{
110
  std::map<int, SCharDescr*>::iterator it = chars.find(id);
111
  if( it == chars.end() ) return 0;
112
 
113
  return it->second;
114
}
115
 
116
// Internal
117
float CFont::AdjustForKerningPairs(int first, int second)
118
{
119
  SCharDescr *ch = GetChar(first);
120
  if( ch == 0 ) return 0;
121
  for( UINT n = 0; n < ch->kerningPairs.size(); n += 2 )
122
  {
123
    if( ch->kerningPairs[n] == second )
124
      return ch->kerningPairs[n+1] * scale;
125
  }
126
 
127
  return 0;
128
}
129
 
130
float CFont::GetTextWidth(const char *text, int count)
131
{
132
  if( count <= 0 )
133
    count = GetTextLength(text);
134
 
135
  float x = 0;
136
 
137
  for( int n = 0; n < count; )
138
  {
139
    int charId = GetTextChar(text,n,&n);
140
 
141
    SCharDescr *ch = GetChar(charId);
142
    if( ch == 0 ) ch = &defChar;
143
 
144
    x += scale * (ch->xAdv);
145
 
146
    if( n < count )
147
      x += AdjustForKerningPairs(charId, GetTextChar(text,n));
148
  }
149
 
150
  return x;
151
}
152
 
153
// Internal
154
// Returns the number of bytes in the string until the null char
155
int CFont::GetTextLength(const char *text)
156
{
157
  return (int)strlen(text);
158
}
159
 
160
// Internal
161
int CFont::GetTextChar(const char *text, int pos, int *nextPos)
162
{
163
  int ch;
164
  unsigned int len;
165
 
166
  len = 1;
167
  ch = (unsigned char)text[pos];
168
 
169
  if( nextPos ) *nextPos = pos + len;
170
  return ch;
171
}
172
 
173
void CFont::InternalWrite(float x, float y, float z, const char *text,int _r, int _g,int _b,int _a, int count, float spacing,float newscale)
174
{
175
 
176
  int page = -1;
177
 
178
  glEnable(GL_TEXTURE_2D);
179
 
180
  //	y -= (newscale * fontHeight)/2;
181
 
182
  for( int n = 0; n < count; )
183
  {
184
    int charId = GetTextChar(text, n, &n);
185
    SCharDescr *ch = GetChar(charId);
186
    if( ch == 0 ) ch = &defChar;
187
    if(ch == NULL)
188
      return;
189
 
190
    // Map the center of the texel to the corners
191
    // in order to get pixel perfect mapping
192
    float u = (float(ch->srcX)+0.5f) / scaleW;
193
    float v = (float(ch->srcY)+0.5f) / scaleH;
194
    float u2 = u + float(ch->srcW) / scaleW;
195
    float v2 = v + float(ch->srcH) / scaleH;
196
 
197
    float a = newscale * float(ch->xAdv);
198
    float w = newscale * float(ch->srcW);
199
    float h = newscale * float(ch->srcH);
200
    float ox = newscale * float(ch->xOff);
201
    float oy = newscale * float(ch->yOff);
202
 
203
  //C:нU DHUн
цq :Dл
 Y
фH нU дуой H:DHу:
204
    glEnable(GL_TEXTURE_2D);
205
 
206
    if( ch->page != page )
207
    {
208
      page = ch->page;
209
      //	glBindTexture(GL_TEXTURE_2D, pages[page]); //TGA
210
    }
211
    gEngfuncs.Con_Printf( "%d\n",&defChar );
212
 
213
 
214
    glColor4ub(_r,_g,_b,_a);
215
    glEnable(GL_BLEND);
216
    glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); //
н
Dу: Uльфу в HU
217
 
218
    //top left
219
    glBegin(GL_QUADS);
220
    glTexCoord2f(u,v);
221
    glVertex3f(x+ox, y+oy, z);
222
    //top right
223
    glTexCoord2f(u2,v);
224
    glVertex3f(x+w+ox, y+oy, z);
225
    //bottom right
226
    glTexCoord2f(u2,v2);
227
    glVertex3f(x+w+ox, y+h+oy, z);
228
    //bottom left
229
    glTexCoord2f(u,v2);
230
    glVertex3f(x+ox, y+h+oy, z);
231
    glEnd();
232
 
233
    glDisable(GL_BLEND);
234
 
235
    x += a;
236
    if( charId == ' ' )
237
      x += spacing;
238
 
239
    if( n < count )
240
      x += AdjustForKerningPairs(charId, GetTextChar(text,n));
241
  }
242
 
243
}
244
 
245
int CFont::Write(float x, float y, float z, const char *text,int r, int g,int b,int a, int count, unsigned int mode,float newscale,bool shadow)
246
{
247
  if( count <= 0 )
248
    count = GetTextLength(text);
249
 
250
  if( mode == FONT_ALIGN_CENTER )
251
  {
252
    float w = GetTextWidth(text, count);
253
    x -= w/2*newscale; // mcc fix auto scale
254
  }
255
  else if( mode == FONT_ALIGN_RIGHT )
256
  {
257
    float w = GetTextWidth(text, count);
258
    x -= w*newscale;// mcc fix auto scale
259
  }
260
 
261
  if (shadow) InternalWrite(x+1, y+1, z, text,0,0,0,255, count,0,newscale);
262
  InternalWrite(x, y, z, text,r,g,b,a, count,0,newscale);
263
 
264
  return GetTextWidth(text, count);
265
}
266
 
267
 
268
//=============================================================================
269
// CFontLoader
270
//
271
// This is the base class for all loader classes. This is the only class
272
// that has access to and knows how to set the CFont members.
273
//=============================================================================
274
 
275
CFontLoader::CFontLoader(FILE *f, CFont *font, const char *fontFile)
276
{
277
  this->f = f;
278
  this->font = font;
279
  this->fontFile = fontFile;
280
 
281
  outlineThickness = 0;
282
}
283
 
284
void CFontLoader::LoadPage(int id, const char *pageFile, const char *fontFile)
285
{
286
  // зUузU H:DHуq
287
  string str;
288
 
289
  // Load the texture from the same directory as the font descriptor file
290
 
291
  // Find the directory
292
  str = fontFile;
293
  for( size_t n = 0; (n = str.find('/', n)) != string::npos; ) str.replace(n, 1, "\\");
294
  size_t i = str.rfind('\\');
295
  if( i != string::npos )
296
    str = str.substr(0, i+1);
297
  else
298
    str = "";
299
 
300
  // Load the font textures
301
  str += pageFile;
302
 
303
  //font->pages[id] = gEngfuncs.pfnSPR_Load(str.c_str()); //SPR
304
  font->pages[id] = glLoadTgaFromPak((char*)str.c_str());// TGA (???)
305
}
306
 
307
void CFontLoader::SetFontInfo(int outlineThickness)
308
{
309
  this->outlineThickness = outlineThickness;
310
}
311
 
312
void CFontLoader::SetCommonInfo(int fontHeight, int base, int scaleW, int scaleH, int pages, bool isPacked)
313
{
314
  font->fontHeight = fontHeight;
315
  font->base = base;
316
  font->scaleW = scaleW;
317
  font->scaleH = scaleH;
318
  // вqд:лЩ: Uз: од DHUн
цq Y
фHU
319
  font->pages.resize(pages);
320
  for( int n = 0; n < pages; n++ )
321
    font->pages[n] = 0;
322
 
323
 
324
  if( isPacked && outlineThickness )
325
    font->hasOutline = true;
326
}
327
 
328
void CFontLoader::AddChar(int id, int x, int y, int w, int h, int xoffset, int yoffset, int xadvance, int page, int chnl)
329
{
330
  // Convert to a 4 element vector
331
  // TODO: Does this depend on hardware? It probably does
332
  if     ( chnl == 1 ) chnl = 0x00010000;  // Blue channel
333
    else if( chnl == 2 ) chnl = 0x00000100;  // Green channel
334
      else if( chnl == 4 ) chnl = 0x00000001;  // Red channel
335
        else if( chnl == 8 ) chnl = 0x01000000;  // Alpha channel
336
          else chnl = 0;
337
 
338
  if( id >= 0 )
339
  {
340
    SCharDescr *ch = new SCharDescr;
341
    ch->srcX = x;
342
    ch->srcY = y;
343
    ch->srcW = w;
344
    ch->srcH = h;
345
    ch->xOff = xoffset;
346
    ch->yOff = yoffset;
347
    ch->xAdv = xadvance;
348
    ch->page = page;
349
    ch->chnl = chnl;
350
 
351
    font->chars.insert(std::map<int, SCharDescr*>::value_type(id, ch));
352
  }
353
 
354
  if( id == -1 )
355
  {
356
    font->defChar.srcX = x;
357
    font->defChar.srcY = y;
358
    font->defChar.srcW = w;
359
    font->defChar.srcH = h;
360
    font->defChar.xOff = xoffset;
361
    font->defChar.yOff = yoffset;
362
    font->defChar.xAdv = xadvance;
363
    font->defChar.page = page;
364
    font->defChar.chnl = chnl;
365
  }
366
}
367
 
368
void CFontLoader::AddKerningPair(int first, int second, int amount)
369
{
370
  if( first >= 0 && first < 256 && font->chars[first] )
371
  {
372
    font->chars[first]->kerningPairs.push_back(second);
373
    font->chars[first]->kerningPairs.push_back(amount);
374
  }
375
}
376
 
377
//=============================================================================
378
// CFontLoaderTextFormat
379
//
380
// This class implements the logic for loading a BMFont file in text format
381
//=============================================================================
382
 
383
CFontLoaderTextFormat::CFontLoaderTextFormat(FILE *f, CFont *font, const char *fontFile) : CFontLoader(f, font, fontFile)
384
{
385
}
386
 
387
int CFontLoaderTextFormat::Load()
388
{
389
  string line;
390
 
391
  while( !feof(f) )
392
  {
393
    // Read until line feed (or EOF)
394
    line = "";
395
    line.reserve(256);
396
    while( !feof(f) )
397
    {
398
      char ch;
399
      if( fread(&ch, 1, 1, f) )
400
      {
401
        if( ch != '\n' )
402
          line += ch;
403
        else
404
          break;
405
      }
406
    }
407
 
408
    // Skip white spaces
409
    int pos = SkipWhiteSpace(line, 0);
410
 
411
    // Read token
412
    int pos2 = FindEndOfToken(line, pos);
413
    string token = line.substr(pos, pos2-pos);
414
 
415
    // Interpret line
416
    if( token == "info" )
417
      InterpretInfo(line, pos2);
418
    else if( token == "common" )
419
      InterpretCommon(line, pos2);
420
    else if( token == "char" )
421
      InterpretChar(line, pos2);
422
    else if( token == "kerning" )
423
      InterpretKerning(line, pos2);
424
    else if( token == "page" )
425
      InterpretPage(line, pos2, fontFile);
426
  }
427
 
428
  fclose(f);
429
 
430
  // Success
431
  return 0;
432
}
433
 
434
int CFontLoaderTextFormat::SkipWhiteSpace(string &str, int start)
435
{
436
  UINT n = start;
437
  while( n < str.size() )
438
  {
439
    char ch = str[n];
440
    if( ch != ' ' &&
441
    ch != '\t' &&
442
    ch != '\r' &&
443
    ch != '\n' )
444
    break;
445
 
446
    ++n;
447
  }
448
 
449
  return n;
450
}
451
 
452
int CFontLoaderTextFormat::FindEndOfToken(string &str, int start)
453
{
454
  UINT n = start;
455
  if( str[n] == '"' )
456
  {
457
    n++;
458
    while( n < str.size() )
459
    {
460
      char ch = str[n];
461
      if( ch == '"' )
462
      {
463
        // Include the last quote char in the token
464
        ++n;
465
        break;
466
      }
467
      ++n;
468
    }
469
  }
470
  else
471
  {
472
    while( n < str.size() )
473
    {
474
      char ch = str[n];
475
      if( ch == ' ' ||
476
        ch == '\t' ||
477
      ch == '\r' ||
478
      ch == '\n' ||
479
      ch == '=' )
480
      break;
481
 
482
      ++n;
483
    }
484
  }
485
 
486
  return n;
487
}
488
 
489
void CFontLoaderTextFormat::InterpretKerning(string &str, int start)
490
{
491
  // Read the attributes
492
  int first = 0;
493
  int second = 0;
494
  int amount = 0;
495
 
496
  int pos, pos2 = start;
497
  while( true )
498
  {
499
    pos = SkipWhiteSpace(str, pos2);
500
    pos2 = FindEndOfToken(str, pos);
501
 
502
    string token = str.substr(pos, pos2-pos);
503
 
504
    pos = SkipWhiteSpace(str, pos2);
505
    if( pos == str.size() || str[pos] != '=' ) break;
506
 
507
    pos = SkipWhiteSpace(str, pos+1);
508
    pos2 = FindEndOfToken(str, pos);
509
 
510
    string value = str.substr(pos, pos2-pos);
511
 
512
    if( token == "first" )
513
      first = strtol(value.c_str(), 0, 10);
514
    else if( token == "second" )
515
      second = strtol(value.c_str(), 0, 10);
516
    else if( token == "amount" )
517
      amount = strtol(value.c_str(), 0, 10);
518
 
519
    if( pos == str.size() ) break;
520
  }
521
 
522
  // Store the attributes
523
  AddKerningPair(first, second, amount);
524
}
525
 
526
void CFontLoaderTextFormat::InterpretChar(string &str, int start)
527
{
528
  // Read all attributes
529
  int id = 0;
530
  int x = 0;
531
  int y = 0;
532
  int width = 0;
533
  int height = 0;
534
  int xoffset = 0;
535
  int yoffset = 0;
536
  int xadvance = 0;
537
  int page = 0;
538
  int chnl = 0;
539
 
540
  int pos, pos2 = start;
541
  while( true )
542
  {
543
    pos = SkipWhiteSpace(str, pos2);
544
    pos2 = FindEndOfToken(str, pos);
545
 
546
    string token = str.substr(pos, pos2-pos);
547
 
548
    pos = SkipWhiteSpace(str, pos2);
549
    if( pos == str.size() || str[pos] != '=' ) break;
550
 
551
    pos = SkipWhiteSpace(str, pos+1);
552
    pos2 = FindEndOfToken(str, pos);
553
 
554
    string value = str.substr(pos, pos2-pos);
555
 
556
    if( token == "id" )
557
      id = strtol(value.c_str(), 0, 10);
558
    else if( token == "x" )
559
      x = strtol(value.c_str(), 0, 10);
560
    else if( token == "y" )
561
      y = strtol(value.c_str(), 0, 10);
562
    else if( token == "width" )
563
      width = strtol(value.c_str(), 0, 10);
564
    else if( token == "height" )
565
      height = strtol(value.c_str(), 0, 10);
566
    else if( token == "xoffset" )
567
      xoffset = strtol(value.c_str(), 0, 10);
568
    else if( token == "yoffset" )
569
      yoffset = strtol(value.c_str(), 0, 10);
570
    else if( token == "xadvance" )
571
      xadvance = strtol(value.c_str(), 0, 10);
572
    else if( token == "page" )
573
      page = strtol(value.c_str(), 0, 10);
574
    else if( token == "chnl" )
575
      chnl = strtol(value.c_str(), 0, 10);
576
 
577
    if( pos == str.size() ) break;
578
  }
579
 
580
  // Store the attributes
581
  AddChar(id, x, y, width, height, xoffset, yoffset, xadvance, page, chnl);
582
}
583
 
584
void CFontLoaderTextFormat::InterpretCommon(string &str, int start)
585
{
586
  int fontHeight;
587
  int base;
588
  int scaleW;
589
  int scaleH;
590
  int pages;
591
  int packed;
592
 
593
  // Read all attributes
594
  int pos, pos2 = start;
595
  while( true )
596
  {
597
    pos = SkipWhiteSpace(str, pos2);
598
    pos2 = FindEndOfToken(str, pos);
599
 
600
    string token = str.substr(pos, pos2-pos);
601
 
602
    pos = SkipWhiteSpace(str, pos2);
603
    if( pos == str.size() || str[pos] != '=' ) break;
604
 
605
    pos = SkipWhiteSpace(str, pos+1);
606
    pos2 = FindEndOfToken(str, pos);
607
 
608
    string value = str.substr(pos, pos2-pos);
609
 
610
    if( token == "lineHeight" )
611
      fontHeight = (short)strtol(value.c_str(), 0, 10);
612
    else if( token == "base" )
613
      base = (short)strtol(value.c_str(), 0, 10);
614
    else if( token == "scaleW" )
615
      scaleW = (short)strtol(value.c_str(), 0, 10);
616
    else if( token == "scaleH" )
617
      scaleH = (short)strtol(value.c_str(), 0, 10);
618
    else if( token == "pages" )
619
      pages = strtol(value.c_str(), 0, 10);
620
    else if( token == "packed" )
621
      packed = strtol(value.c_str(), 0, 10);
622
 
623
    if( pos == str.size() ) break;
624
  }
625
 
626
  SetCommonInfo(fontHeight, base, scaleW, scaleH, pages, packed ? true : false);
627
}
628
 
629
void CFontLoaderTextFormat::InterpretInfo(string &str, int start)
630
{
631
  int outlineThickness;
632
 
633
  // Read all attributes
634
  int pos, pos2 = start;
635
  while( true )
636
  {
637
    pos = SkipWhiteSpace(str, pos2);
638
    pos2 = FindEndOfToken(str, pos);
639
 
640
    string token = str.substr(pos, pos2-pos);
641
 
642
    pos = SkipWhiteSpace(str, pos2);
643
    if( pos == str.size() || str[pos] != '=' ) break;
644
 
645
    pos = SkipWhiteSpace(str, pos+1);
646
    pos2 = FindEndOfToken(str, pos);
647
 
648
    string value = str.substr(pos, pos2-pos);
649
 
650
    if( token == "outline" )
651
      outlineThickness = (short)strtol(value.c_str(), 0, 10);
652
 
653
    if( pos == str.size() ) break;
654
  }
655
 
656
  SetFontInfo(outlineThickness);
657
}
658
 
659
void CFontLoaderTextFormat::InterpretPage(string &str, int start, const char *fontFile)
660
{
661
  int id = 0;
662
  string file;
663
 
664
  // Read all attributes
665
  int pos, pos2 = start;
666
  while( true )
667
  {
668
    pos = SkipWhiteSpace(str, pos2);
669
    pos2 = FindEndOfToken(str, pos);
670
 
671
    string token = str.substr(pos, pos2-pos);
672
 
673
    pos = SkipWhiteSpace(str, pos2);
674
    if( pos == str.size() || str[pos] != '=' ) break;
675
 
676
    pos = SkipWhiteSpace(str, pos+1);
677
    pos2 = FindEndOfToken(str, pos);
678
 
679
    string value = str.substr(pos, pos2-pos);
680
 
681
    if( token == "id" )
682
      id = strtol(value.c_str(), 0, 10);
683
    else if( token == "file" )
684
      file = value.substr(1, value.length()-2);
685
 
686
    if( pos == str.size() ) break;
687
  }
688
 
689
  LoadPage(id, file.c_str(), fontFile);
690
}
691
 
692
//=============================================================================
693
// CFontLoaderBinaryFormat
694
//
695
// This class implements the logic for loading a BMFont file in binary format
696
//=============================================================================
697
/*
698
CFontLoaderBinaryFormat::CFontLoaderBinaryFormat(FILE *f, CFont *font, const char *fontFile) : CFontLoader(f, font, fontFile)
699
{
700
}
701
 
702
int CFontLoaderBinaryFormat::Load()
703
{
704
	// Read and validate the tag. It should be 66, 77, 70, 2,
705
	// or 'BMF' and 2 where the number is the file version.
706
	char magicString[4];
707
	fread(magicString, 4, 1, f);
708
	if( strncmp(magicString, "BMF\003", 4) != 0 )
709
	{
710
		LOG(("Unrecognized format for '%s'", fontFile));
711
		fclose(f);
712
		return -1;
713
	}
714
 
715
	// Read each block
716
	char blockType;
717
	int blockSize;
718
	while( fread(&blockType, 1, 1, f) )
719
	{
720
		// Read the blockSize
721
		fread(&blockSize, 4, 1, f);
722
 
723
		switch( blockType )
724
		{
725
		case 1: // info
726
			ReadInfoBlock(blockSize);
727
			break;
728
		case 2: // common
729
			ReadCommonBlock(blockSize);
730
			break;
731
		case 3: // pages
732
			ReadPagesBlock(blockSize);
733
			break;
734
		case 4: // chars
735
			ReadCharsBlock(blockSize);
736
			break;
737
		case 5: // kerning pairs
738
			ReadKerningPairsBlock(blockSize);
739
			break;
740
		default:
741
			LOG(("Unexpected block type (%d)", blockType));
742
			fclose(f);
743
			return -1;
744
		}
745
	}
746
 
747
	fclose(f);
748
 
749
	// Success
750
	return 0;
751
}
752
 
753
void CFontLoaderBinaryFormat::ReadInfoBlock(int size)
754
{
755
#pragma pack(push)
756
#pragma pack(1)
757
struct infoBlock
758
{
759
    WORD fontSize;
760
    BYTE reserved:4;
761
    BYTE bold    :1;
762
    BYTE italic  :1;
763
    BYTE unicode :1;
764
    BYTE smooth  :1;
765
    BYTE charSet;
766
    WORD stretchH;
767
    BYTE aa;
768
    BYTE paddingUp;
769
    BYTE paddingRight;
770
    BYTE paddingDown;
771
    BYTE paddingLeft;
772
    BYTE spacingHoriz;
773
    BYTE spacingVert;
774
    BYTE outline;         // Added with version 2
775
    char fontName[1];
776
};
777
#pragma pack(pop)
778
 
779
	char *buffer = new char[size];
780
	fread(buffer, size, 1, f);
781
 
782
	// We're only interested in the outline thickness
783
	infoBlock *blk = (infoBlock*)buffer;
784
	SetFontInfo(blk->outline);
785
 
786
	delete[] buffer;
787
}
788
 
789
void CFontLoaderBinaryFormat::ReadCommonBlock(int size)
790
{
791
#pragma pack(push)
792
#pragma pack(1)
793
struct commonBlock
794
{
795
    WORD lineHeight;
796
    WORD base;
797
    WORD scaleW;
798
    WORD scaleH;
799
    WORD pages;
800
    BYTE packed  :1;
801
    BYTE reserved:7;
802
	BYTE alphaChnl;
803
	BYTE redChnl;
804
	BYTE greenChnl;
805
	BYTE blueChnl;
806
};
807
#pragma pack(pop)
808
 
809
	char *buffer = new char[size];
810
	fread(buffer, size, 1, f);
811
 
812
	commonBlock *blk = (commonBlock*)buffer;
813
 
814
	SetCommonInfo(blk->lineHeight, blk->base, blk->scaleW, blk->scaleH, blk->pages, blk->packed ? true : false);
815
 
816
	delete[] buffer;
817
}
818
 
819
void CFontLoaderBinaryFormat::ReadPagesBlock(int size)
820
{
821
#pragma pack(push)
822
#pragma pack(1)
823
struct pagesBlock
824
{
825
    char pageNames[1];
826
};
827
#pragma pack(pop)
828
 
829
	char *buffer = new char[size];
830
	fread(buffer, size, 1, f);
831
 
832
	pagesBlock *blk = (pagesBlock*)buffer;
833
 
834
	for( int id = 0, pos = 0; pos < size; id++ )
835
	{
836
		LoadPage(id, &blk->pageNames[pos], fontFile);
837
		pos += 1 + (int)strlen(&blk->pageNames[pos]);
838
	}
839
 
840
	delete[] buffer;
841
}
842
 
843
void CFontLoaderBinaryFormat::ReadCharsBlock(int size)
844
{
845
#pragma pack(push)
846
#pragma pack(1)
847
struct charsBlock
848
{
849
    struct charInfo
850
    {
851
        DWORD id;
852
        WORD  x;
853
        WORD  y;
854
        WORD  width;
855
        WORD  height;
856
        short xoffset;
857
        short yoffset;
858
        short xadvance;
859
        BYTE  page;
860
        BYTE  chnl;
861
    } chars[1];
862
};
863
#pragma pack(pop)
864
 
865
	char *buffer = new char[size];
866
	fread(buffer, size, 1, f);
867
 
868
	charsBlock *blk = (charsBlock*)buffer;
869
 
870
	for( int n = 0; int(n*sizeof(charsBlock::charInfo)) < size; n++ )
871
	{
872
		AddChar(blk->chars[n].id,
873
		        blk->chars[n].x,
874
				blk->chars[n].y,
875
				blk->chars[n].width,
876
				blk->chars[n].height,
877
				blk->chars[n].xoffset,
878
				blk->chars[n].yoffset,
879
				blk->chars[n].xadvance,
880
				blk->chars[n].page,
881
				blk->chars[n].chnl);
882
	}
883
 
884
	delete[] buffer;
885
}
886
 
887
void CFontLoaderBinaryFormat::ReadKerningPairsBlock(int size)
888
{
889
#pragma pack(push)
890
#pragma pack(1)
891
struct kerningPairsBlock
892
{
893
    struct kerningPair
894
    {
895
        DWORD first;
896
        DWORD second;
897
        short amount;
898
    } kerningPairs[1];
899
};
900
#pragma pack(pop)
901
 
902
	char *buffer = new char[size];
903
	fread(buffer, size, 1, f);
904
 
905
	kerningPairsBlock *blk = (kerningPairsBlock*)buffer;
906
 
907
	for( int n = 0; int(n*sizeof(kerningPairsBlock::kerningPair)) < size; n++ )
908
	{
909
		AddKerningPair(blk->kerningPairs[n].first,
910
		               blk->kerningPairs[n].second,
911
					   blk->kerningPairs[n].amount);
912
	}
913
 
914
	delete[] buffer;
915
}
916
*/


header file
C++ Source Code:
1
#pragma warning(disable:4786)
2
#ifndef FONT_H
3
#define FONT_H
4
#include <windows.h>
5
#include <gl/gl.h>
6
#include "gl/glext.h"
7
#include <vector>
8
#include <string>
9
#include <map>
10
 
11
//class CFont;
12
 
13
 
14
typedef int HSPRITE;	// handle to a graphic
15
 
16
const int FONT_ALIGN_LEFT    = 0;
17
const int FONT_ALIGN_CENTER  = 1;
18
const int FONT_ALIGN_RIGHT   = 2;
19
const int FONT_ALIGN_JUSTIFY = 3;
20
 
21
// олнUЩ DHуHуU був, уз
Hь буд: 
з nft фUйлU
22
struct SCharDescr
23
{
24
  SCharDescr() : srcX(0), srcY(0), srcW(0), srcH(0), xOff(0), yOff(0), xAdv(0), page(0) {}
25
 
26
  short srcX;
27
  short srcY;
28
  short srcW;
29
  short srcH;
30
  short xOff;
31
  short yOff;
32
  short xAdv;
33
  short page;
34
  unsigned int chnl;
35
 
36
  std::vector<int> kerningPairs; //D:ц 
нH:вUлq :ду бувU
37
};
38
 
39
enum EFontTextEncoding
40
{
41
  NONE,
42
  UTF8,
43
  UTF16
44
};
45
 
46
class CFont
47
{
48
public:
49
  CFont();
50
  ~CFont();
51
 
52
  int Init(const char *fontFile);
53
 
54
  //void SetTextEncoding(EFontTextEncoding encoding);
55
 
56
  float GetTextWidth(const char *text, int count);
57
  int Write(float x, float y, float z, const char *text, int r, int g,int b,int a,int count, unsigned int mode,float newscale, bool shadow);
58
  int Draw(float x, float y, float z, const char *text, int r, int g,int b,int a,int count, unsigned int mode, float newscale=1.0f, bool shadow=false)
59
  {
60
    return Write(x,y,z,text,r,g,b,a,count,mode,newscale,shadow);
61
  };
62
  //void WriteML(float x, float y, float z, const char *text, int count, unsigned int mode);
63
  //void WriteBox(float x, float y, float z, float width, const char *text, int count, unsigned mode);
64
 
65
  //void SetHeight(float h);
66
  //float GetHeight();
67
 
68
  //float GetBottomOffset();
69
  //float GetTopOffset();
70
 
71
  //void PrepareEffect();
72
  //void PreparePixelPerfectOutput();
73
protected:
74
  friend class CFontLoader; //ф:нд лUDD озовлЩ:H  оH:H:д обUoUHьDЩ U  Uбл

75
 
76
  void InternalWrite(float x, float y, float z, const char *text, int _r, int _g,int _b,int _a,int count, float spacing = 0,float newscale=1.0f);
77
 
78
  float AdjustForKerningPairs(int first, int second);
79
  SCharDescr *GetChar(int id);
80
 
81
  int GetTextLength(const char *text);
82
  int GetTextChar(const char *text, int pos, int *nextPos = 0);
83
  //int FindTextChar(const char *text, int start, int length, int ch);
84
 
85
  // --- обo
: нUDHой
 fnt
86
  short fontHeight; // total height of the font
87
  short base;       // y of base line
88
  short scaleW;
89
  short scaleH;
90
  SCharDescr defChar; //д:фUлHнqй D
вол 
 id бувq -1 , нUф
 он ну:н?
91
  bool hasOutline;
92
  float scale;
93
  EFontTextEncoding encoding;
94
 
95
  //CDynRender *render;
96
 
97
  std::map<int, SCharDescr*> chars; //C++. Уо 10. зучU: map (UDDоц
UH
внqй UDD
&#226<img src="images/smilies/wink.gif" border="0" alt="">.
98
  //std::vector<HSPRITE> pages; //SPR
99
  std::vector<int> pages;
100
  //std::string fxFile;
101
};
102
 
103
 
104
#endif
105
 
106
//GLuint glLoadTgaFromPak( char* name, int index = 0 );


maybe someone can help me

Отредактировано daku 15-05-2013 в 11:49

Сообщить модератору | | IP: Записан
Сообщение: 119905

Старое сообщение 15-05-2013 11:42
- За что?
Qwertyus
Житель форума

Группа: Неопытный
Дата регистрации: Apr 2006
Проживает: На берегу очень дикой реки
Сообщений: 815

Рейтинг



Steam HL is using these fonts:
valve\gfx\vgui\fonts\*.tga
Also it can use Windows fonts. Check:
valve\***_textscheme.txt
and
Half-Life\platform\resource\TrackerScheme.res

WON HL & Xash3D are using these fonts in most cases:
valve\fonts.wad
valve\gfx.wad

Сообщить модератору | | IP: Записан
Сообщение: 119917

Старое сообщение 15-05-2013 15:40
- За что?
 Дядя Миша
racing for fish

Дата регистрации: Oct 2005
Проживает: Кубань
Сообщений: 32202
Нанёс повреждений: 392 ед.

Рейтинг



Qwertyus VGUI юзает tga-шрифты во всех случаях.

__________________
My Projects: download page

F.A.Q по XashNT
Блог разработчика в телеграме

Цитата:

C:\DOCUME~1\C4C5~1\LOCALS~1\Temp\a33328if(72) : see declaration of 'size_t'

Сообщить модератору | | IP: Записан
Сообщение: 119919

Старое сообщение 15-05-2013 15:56
-
KiQ
Житель форума

Дата регистрации: Aug 2010
Проживает: Смоленск, Москва
Сообщений: 2088

Рейтинг



daku hmm. And where is trouble?

__________________
-Brain is dead-

Сообщить модератору | | IP: Записан
Сообщение: 119932

Старое сообщение 15-05-2013 19:43
- За что?
CrazyRussian
ололо

Дата регистрации: Apr 2009
Проживает: Город-курорт Ессентуки
Сообщений: 790
Возраст: 31

Рейтинг



Награды
 
[1 награда]


Цитата:
KiQ писал:
daku hmm. And where is trouble?

<Ванга>
C++ Source Code:
if( ch->page != page )
{
  page = ch->page;
  glBindTexture(GL_TEXTURE_2D, pages[page]); //TGA
}


У него в page какая то фигня типа -286331154, отчего он ловит access violation

</Ванга>

__________________
Трагическая новость: Пятеро инженеров Casio умерли от смеха, узнав что Samsung анонсировали часы с заявленным временем работы в 25 часов

Сообщить модератору | | IP: Записан
Сообщение: 119935

Старое сообщение 15-05-2013 19:49
- За что?
KiQ
Житель форума

Дата регистрации: Aug 2010
Проживает: Смоленск, Москва
Сообщений: 2088

Рейтинг



daku font class contains method for writing, why do not use it? Вообще код стремный какой-то, зачем столько классов плодить?

__________________
-Brain is dead-

Сообщить модератору | | IP: Записан
Сообщение: 119937

Старое сообщение 15-05-2013 20:52
- За что?
daku
Частый гость

Дата регистрации: Oct 2011
Проживает: (void)
Сообщений: 93

Рейтинг



i write strings with it but i have crash on 2-nd loading stage ( last 2 bars ) and game is stuck

Сообщить модератору | | IP: Записан
Сообщение: 119938

Старое сообщение 15-05-2013 21:05
- За что?
Тема: (Опционально)
Ваш ответ:



Переводчик транслита


[проверить длину сообщения]
Опции: Автоматическое формирование ссылок: автоматически добавлять [url] и [/url] вокруг интернет адресов.
Уведомление по E-Mail: отправить вам уведомление, если кто-то ответил в тему (только для зарегистрированных пользователей).
Отключить смайлики в сообщении: не преобразовывать текстовые смайлики в картинки.
Показать подпись: добавить вашу подпись в конец сообщения (только зарегистрированные пользователи могут иметь подписи).

Временная зона GMT. Текущее время 17:12. Новая тема    Ответить
  Предыдущая тема   Следующая тема
HLFX.Ru Forum HLFX.Ru Forum > Теория и практика > Half-Life SDK > bitmap fonts ?
Версия для печати | Отправить тему по E-Mail | Подписаться на эту тему

Быстрый переход:
Оцените эту тему:

Правила Форума:
Вы not можете создавать новые темы
Вы not можете отвечать в темы
Вы not можете прикреплять вложения
Вы not можете редактировать ваши сообщения
HTML Код ВЫКЛ
vB Код ВКЛ
Смайлики ВКЛ
[IMG] Код ВКЛ
 

< Обратная связь - HLFX.ru >

На основе vBulletin
Авторское право © 2000 - 2002, Jelsoft Enterprises Limited.
Дизайн и программирование: Crystice Softworks © 2005 - 2024