-
Notifications
You must be signed in to change notification settings - Fork 128
/
ttf.d
5197 lines (4507 loc) · 195 KB
/
ttf.d
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
359
360
361
362
363
364
365
366
367
368
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
401
402
403
404
405
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
444
445
446
447
448
449
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/++
TrueType Font rendering. Meant to be used with [arsd.simpledisplay], but it doesn't actually require that. Port of stb_truetype plus D wrappers for convenience.
Credits: Started as a copy of stb_truetype by Sean Barrett and ketmar helped
with expansions.
+/
module arsd.ttf;
// stb_truetype.h - v1.19 - public domain
// authored from 2009-2016 by Sean Barrett / RAD Game Tools
//
// http://nothings.org/stb/stb_truetype.h
//
// port to D by adam d. ruppe (v.6) and massively updated ketmar. see the link above for more info about the lib and real author.
// here's some D convenience functions
// need to do some print glyphs t it....
///
struct TtfFont {
stbtt_fontinfo font;
///
this(in ubyte[] data) {
load(data);
}
///
void load(in ubyte[] data) {
if(stbtt_InitFont(&font, data.ptr, stbtt_GetFontOffsetForIndex(data.ptr, 0)) == 0)
throw new Exception("load font problem");
}
/// Note that you must stbtt_FreeBitmap(returnValue.ptr, null); this thing or it will leak!!!!
ubyte[] renderCharacter(dchar c, int size, out int width, out int height, float shift_x = 0.0, float shift_y = 0.0) {
auto ptr = stbtt_GetCodepointBitmapSubpixel(&font, 0.0,stbtt_ScaleForPixelHeight(&font, size),
shift_x, shift_y, c, &width, &height, null,null);
return ptr[0 .. width * height];
}
///
void getStringSize(in char[] s, int size, out int width, out int height) {
float xpos=0;
auto scale = stbtt_ScaleForPixelHeight(&font, size);
int ascent, descent, line_gap;
stbtt_GetFontVMetrics(&font, &ascent,&descent,&line_gap);
auto baseline = cast(int) (ascent*scale);
import std.math;
int maxWidth;
foreach(i, dchar ch; s) {
int advance,lsb;
auto x_shift = xpos - floor(xpos);
stbtt_GetCodepointHMetrics(&font, ch, &advance, &lsb);
int x0, y0, x1, y1;
stbtt_GetCodepointBitmapBoxSubpixel(&font, ch, scale,scale,x_shift,0, &x0,&y0,&x1,&y1);
maxWidth = cast(int)(xpos + x1);
xpos += (advance * scale);
if (i + 1 < s.length)
xpos += scale*stbtt_GetCodepointKernAdvance(&font, ch,s[i+1]);
}
width = maxWidth;
height = size;
}
///
ubyte[] renderString(in char[] s, int size, out int width, out int height) {
float xpos=0;
auto scale = stbtt_ScaleForPixelHeight(&font, size);
int ascent, descent, line_gap;
stbtt_GetFontVMetrics(&font, &ascent,&descent,&line_gap);
auto baseline = cast(int) (ascent*scale);
import std.math;
int swidth;
int sheight;
getStringSize(s, size, swidth, sheight);
auto screen = new ubyte[](swidth * sheight);
foreach(i, dchar ch; s) {
int advance,lsb;
auto x_shift = xpos - floor(xpos);
stbtt_GetCodepointHMetrics(&font, ch, &advance, &lsb);
int cw, cheight;
auto c = renderCharacter(ch, size, cw, cheight, x_shift, 0.0);
scope(exit) stbtt_FreeBitmap(c.ptr, null);
int x0, y0, x1, y1;
stbtt_GetCodepointBitmapBoxSubpixel(&font, ch, scale,scale,x_shift,0, &x0,&y0,&x1,&y1);
int x = cast(int) xpos + x0;
int y = baseline + y0;
int cx = 0;
foreach(index, pixel; c) {
if(cx == cw) {
cx = 0;
y++;
x = cast(int) xpos + x0;
}
auto offset = swidth * y + x;
if(offset >= screen.length)
break;
int val = (cast(int) pixel * (255 - screen[offset]) / 255);
if(val > 255)
val = 255;
screen[offset] += cast(ubyte)(val);
x++;
cx++;
}
//stbtt_MakeCodepointBitmapSubpixel(&font, &screen[(baseline + y0) * swidth + cast(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale, x_shift,0, ch);
// note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong
// because this API is really for baking character bitmaps into textures. if you want to render
// a sequence of characters, you really need to render each bitmap to a temp buffer, then
// "alpha blend" that into the working buffer
xpos += (advance * scale);
if (i + 1 < s.length)
xpos += scale*stbtt_GetCodepointKernAdvance(&font, ch,s[i+1]);
}
width = swidth;
height = sheight;
return screen;
}
// ~this() {}
}
/// Version of OpenGL you want it to use. Currently only two options.
enum OpenGlFontGLVersion {
old, /// old style glBegin/glEnd stuff
shader, /// newer style shader stuff
}
/+
This is mostly there if you want to draw different pieces together in
different colors or across different boxes (see what text didn't fit, etc.).
Used only with [OpenGlLimitedFont] right now.
+/
struct DrawingTextContext {
const(char)[] text; /// remaining text
float x; /// current position of the baseline
float y; /// ditto
const int left; /// bounding box, if applicable
const int top; /// ditto
const int right; /// ditto
const int bottom; /// ditto
}
abstract class OpenGlLimitedFontBase() {
void createShaders() {}
abstract uint glFormat();
abstract void startDrawing(Color color);
abstract void addQuad(
float s0, float t0, float x0, float y0,
float s1, float t1, float x1, float y1
);
abstract void finishDrawing();
// FIXME: does this kern?
// FIXME: it would be cool if it did per-letter transforms too like word art. make it tangent to some baseline
import arsd.simpledisplay;
static private int nextPowerOfTwo(int v) {
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
}
uint _tex;
stbtt_bakedchar[] charInfo;
import arsd.color;
/++
Tip: if color == Color.transparent, it will not actually attempt to draw to OpenGL. You can use this
to help plan pagination inside the bounding box.
+/
public final DrawingTextContext drawString(int x, int y, in char[] text, Color color = Color.white, Rectangle boundingBox = Rectangle.init) {
if(boundingBox == Rectangle.init) {
// if you hit a newline, at least keep it aligned here if something wasn't
// explicitly given.
boundingBox.left = x;
boundingBox.top = y;
boundingBox.right = int.max;
boundingBox.bottom = int.max;
}
DrawingTextContext dtc = DrawingTextContext(text, x, y, boundingBox.tupleof);
drawString(dtc, color);
return dtc;
}
/++
It won't attempt to draw partial characters if it butts up against the bounding box, unless
word wrap was impossible. Use clipping if you need to cover that up and guarantee it never goes
outside the bounding box ever.
+/
public final void drawString(ref DrawingTextContext context, Color color = Color.white) {
bool actuallyDraw = color != Color.transparent;
if(actuallyDraw) {
startDrawing(color);
}
bool newWord = true;
bool atStartOfLine = true;
float currentWordLength;
int currentWordCharsRemaining;
void calculateWordInfo() {
const(char)[] copy = context.text;
currentWordLength = 0.0;
currentWordCharsRemaining = 0;
while(copy.length) {
auto ch = copy[0];
copy = copy[1 .. $];
currentWordCharsRemaining++;
if(ch <= 32)
break; // not in a word anymore
if(ch < firstChar || ch > lastChar)
continue;
const b = charInfo[cast(int) ch - cast(int) firstChar];
currentWordLength += b.xadvance;
}
}
bool newline() {
context.x = context.left;
context.y += lineHeight;
atStartOfLine = true;
if(context.y + descent > context.bottom)
return false;
return true;
}
while(context.text.length) {
if(newWord) {
calculateWordInfo();
newWord = false;
if(context.x + currentWordLength > context.right) {
if(!newline())
break; // ran out of space
}
}
// FIXME i should prolly UTF-8 decode....
dchar ch = context.text[0];
context.text = context.text[1 .. $];
if(currentWordCharsRemaining) {
currentWordCharsRemaining--;
if(currentWordCharsRemaining == 0)
newWord = true;
}
if(ch == '\t') {
context.x += 20;
continue;
}
if(ch == '\n') {
if(newline())
continue;
else
break;
}
if(ch < firstChar || ch > lastChar) {
if(ch == ' ')
context.x += lineHeight / 4; // fake space if not available in formal font (I recommend you do include it though)
continue;
}
const b = charInfo[cast(int) ch - cast(int) firstChar];
int round_x = STBTT_ifloor((context.x + b.xoff) + 0.5f);
int round_y = STBTT_ifloor((context.y + b.yoff) + 0.5f);
// box to draw on the screen
auto x0 = round_x;
auto y0 = round_y;
auto x1 = round_x + b.x1 - b.x0;
auto y1 = round_y + b.y1 - b.y0;
// is that outside the bounding box we should draw in?
// if so on x, wordwrap to the next line. if so on y,
// return prematurely and let the user context handle it if needed.
// box to fetch off the surface
auto s0 = b.x0 * ipw;
auto t0 = b.y0 * iph;
auto s1 = b.x1 * ipw;
auto t1 = b.y1 * iph;
if(actuallyDraw) {
addQuad(s0, t0, x0, y0, s1, t1, x1, y1);
}
context.x += b.xadvance;
}
if(actuallyDraw)
finishDrawing();
}
private {
const dchar firstChar;
const dchar lastChar;
const int pw;
const int ph;
const float ipw;
const float iph;
}
public const int lineHeight; /// metrics
public const int ascent; /// ditto
public const int descent; /// ditto
public const int line_gap; /// ditto;
/++
+/
public this(const ubyte[] ttfData, float fontPixelHeight, dchar firstChar = 32, dchar lastChar = 127) {
assert(lastChar > firstChar);
assert(fontPixelHeight > 0);
this.firstChar = firstChar;
this.lastChar = lastChar;
int numChars = 1 + cast(int) lastChar - cast(int) firstChar;
lineHeight = cast(int) (fontPixelHeight + 0.5);
import std.math;
// will most likely be 512x512ish; about 256k likely
int height = cast(int) (fontPixelHeight + 1) * cast(int) (sqrt(cast(float) numChars) + 1);
height = nextPowerOfTwo(height);
int width = height;
this.pw = width;
this.ph = height;
ipw = 1.0f / pw;
iph = 1.0f / ph;
int len = width * height;
//import std.stdio; writeln(len);
import core.stdc.stdlib;
ubyte[] buffer = (cast(ubyte*) malloc(len))[0 .. len];
if(buffer is null) assert(0);
scope(exit) free(buffer.ptr);
charInfo.length = numChars;
int ascent, descent, line_gap;
if(stbtt_BakeFontBitmap(
ttfData.ptr, 0,
fontPixelHeight,
buffer.ptr, width, height,
cast(int) firstChar, numChars,
charInfo.ptr,
&ascent, &descent, &line_gap
) == 0)
throw new Exception("bake font didn't work");
this.ascent = ascent;
this.descent = descent;
this.line_gap = line_gap;
assert(openGLCurrentContext() !is null);
glGenTextures(1, &_tex);
glBindTexture(GL_TEXTURE_2D, _tex);
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexImage2D(
GL_TEXTURE_2D,
0,
glFormat,
width,
height,
0,
glFormat,
GL_UNSIGNED_BYTE,
buffer.ptr);
checkGlError();
glBindTexture(GL_TEXTURE_2D, 0);
createShaders();
}
}
/++
Note that the constructor calls OpenGL functions and thus this must be called AFTER
the context creation, e.g. on simpledisplay's window first visible delegate.
Any text with characters outside the range you bake in the constructor are simply
ignored - that's why it is called "limited" font. The [TtfFont] struct can generate
any string on-demand which is more flexible, and even faster for strings repeated
frequently, but slower for frequently-changing or one-off strings. That's what this
class is made for.
History:
Added April 24, 2020
+/
final class OpenGlLimitedFont(OpenGlFontGLVersion ver = OpenGlFontGLVersion.old) : OpenGlLimitedFontBase!() {
import arsd.color;
import arsd.simpledisplay;
public this(const ubyte[] ttfData, float fontPixelHeight, dchar firstChar = 32, dchar lastChar = 127) {
super(ttfData, fontPixelHeight, firstChar, lastChar);
}
override uint glFormat() {
// on new-style opengl this is the required value
static if(ver == OpenGlFontGLVersion.shader)
return GL_RED;
else
return GL_ALPHA;
}
static if(ver == OpenGlFontGLVersion.shader) {
private OpenGlShader shader;
private static struct Vertex {
this(float a, float b, float c, float d, float e = 0.0) {
t[0] = a;
t[1] = b;
xyz[0] = c;
xyz[1] = d;
xyz[2] = e;
}
float[2] t;
float[3] xyz;
}
private GlObject!Vertex glo;
// GL_DYNAMIC_DRAW FIXME
private Vertex[] vertixes;
private uint[] indexes;
public BasicMatrix!(4, 4) mymatrix;
public BasicMatrix!(4, 4) projection;
override void createShaders() {
mymatrix.loadIdentity();
projection.loadIdentity();
shader = new OpenGlShader(
OpenGlShader.Source(GL_VERTEX_SHADER, `
#version 330 core
`~glo.generateShaderDefinitions()~`
out vec2 texCoord;
uniform mat4 mymatrix;
uniform mat4 projection;
void main() {
gl_Position = projection * mymatrix * vec4(xyz, 1.0);
texCoord = t;
}
`),
OpenGlShader.Source(GL_FRAGMENT_SHADER, `
#version 330 core
in vec2 texCoord;
out vec4 FragColor;
uniform vec4 color;
uniform sampler2D tex;
void main() {
FragColor = color * vec4(1, 1, 1, texture(tex, texCoord).r);
}
`),
);
}
}
override void startDrawing(Color color) {
glBindTexture(GL_TEXTURE_2D, _tex);
static if(ver == OpenGlFontGLVersion.shader) {
shader.use();
shader.uniforms.color() = OGL.vec4f(cast(float)color.r/255.0, cast(float)color.g/255.0, cast(float)color.b/255.0, cast(float)color.a / 255.0);
shader.uniforms.mymatrix() = OGL.mat4x4f(mymatrix.data);
shader.uniforms.projection() = OGL.mat4x4f(projection.data);
} else {
glColor4f(cast(float)color.r/255.0, cast(float)color.g/255.0, cast(float)color.b/255.0, cast(float)color.a / 255.0);
}
}
override void addQuad(
float s0, float t0, float x0, float y0,
float s1, float t1, float x1, float y1
) {
static if(ver == OpenGlFontGLVersion.shader) {
auto idx = cast(int) vertixes.length;
vertixes ~= [
Vertex(s0, t0, x0, y0),
Vertex(s1, t0, x1, y0),
Vertex(s1, t1, x1, y1),
Vertex(s0, t1, x0, y1),
];
indexes ~= [
idx + 0,
idx + 1,
idx + 3,
idx + 1,
idx + 2,
idx + 3,
];
} else {
glBegin(GL_QUADS);
glTexCoord2f(s0, t0); glVertex2f(x0, y0);
glTexCoord2f(s1, t0); glVertex2f(x1, y0);
glTexCoord2f(s1, t1); glVertex2f(x1, y1);
glTexCoord2f(s0, t1); glVertex2f(x0, y1);
glEnd();
}
}
override void finishDrawing() {
static if(ver == OpenGlFontGLVersion.shader) {
glo = new typeof(glo)(vertixes, indexes);
glo.draw();
vertixes = vertixes[0..0];
vertixes.assumeSafeAppend();
indexes = indexes[0..0];
indexes.assumeSafeAppend();
}
glBindTexture(GL_TEXTURE_2D, 0); // unbind the texture
}
}
// test program
/+
int main(string[] args)
{
import std.conv;
import arsd.simpledisplay;
int c = (args.length > 1 ? to!int(args[1]) : 'a'), s = (args.length > 2 ? to!int(args[2]) : 20);
import std.file;
auto font = TtfFont(cast(ubyte[]) /*import("sans-serif.ttf"));//*/std.file.read(args.length > 3 ? args[3] : "sans-serif.ttf"));
int w, h;
auto bitmap = font.renderString("Hejlqo, world!qMpj", s, w, h);
auto img = new Image(w, h);
for (int j=0; j < h; ++j) {
for (int i=0; i < w; ++i)
img.putPixel(i, j, Color(0, (bitmap[j*w+i] > 128) ? 255 : 0, 0));
}
img.displayImage();
return 0;
}
+/
// STB_TTF FOLLOWS
nothrow @trusted @nogc:
version = STB_RECT_PACK_VERSION;
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
// //
// // SAMPLE PROGRAMS
// //
//
// Incomplete text-in-3d-api example, which draws quads properly aligned to be lossless
//
/+
#if 0
#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
#include "stb_truetype.h"
unsigned char ttf_buffer[1<<20];
unsigned char temp_bitmap[512*512];
stbtt_bakedchar cdata[96]; // ASCII 32..126 is 95 glyphs
GLuint ftex;
void my_stbtt_initfont(void)
{
fread(ttf_buffer, 1, 1<<20, fopen("c:/windows/fonts/times.ttf", "rb"));
stbtt_BakeFontBitmap(ttf_buffer,0, 32.0, temp_bitmap,512,512, 32,96, cdata); // no guarantee this fits!
// can free ttf_buffer at this point
glGenTextures(1, &ftex);
glBindTexture(GL_TEXTURE_2D, ftex);
glTexImage2D(GL_TEXTURE_2D, 0, GL_ALPHA, 512,512, 0, GL_ALPHA, GL_UNSIGNED_BYTE, temp_bitmap);
// can free temp_bitmap at this point
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
}
void my_stbtt_print(float x, float y, char *text)
{
// assume orthographic projection with units = screen pixels, origin at top left
glEnable(GL_TEXTURE_2D);
glBindTexture(GL_TEXTURE_2D, ftex);
glBegin(GL_QUADS);
while (*text) {
if (*text >= 32 && *text < 128) {
stbtt_aligned_quad q;
stbtt_GetBakedQuad(cdata, 512,512, *text-32, &x,&y,&q,1);//1=opengl & d3d10+,0=d3d9
glTexCoord2f(q.s0,q.t1); glVertex2f(q.x0,q.y0);
glTexCoord2f(q.s1,q.t1); glVertex2f(q.x1,q.y0);
glTexCoord2f(q.s1,q.t0); glVertex2f(q.x1,q.y1);
glTexCoord2f(q.s0,q.t0); glVertex2f(q.x0,q.y1);
}
++text;
}
glEnd();
}
#endif
//
//
// ////////////////////////////////////////////////////////////////////////////
//
// Complete program (this compiles): get a single bitmap, print as ASCII art
//
#if 0
#include <stdio.h>
#define STB_TRUETYPE_IMPLEMENTATION // force following include to generate implementation
#include "stb_truetype.h"
char ttf_buffer[1<<25];
int main(int argc, char **argv)
{
stbtt_fontinfo font;
unsigned char *bitmap;
int w,h,i,j,c = (argc > 1 ? atoi(argv[1]) : 'a'), s = (argc > 2 ? atoi(argv[2]) : 20);
fread(ttf_buffer, 1, 1<<25, fopen(argc > 3 ? argv[3] : "c:/windows/fonts/arialbd.ttf", "rb"));
stbtt_InitFont(&font, ttf_buffer, stbtt_GetFontOffsetForIndex(ttf_buffer,0));
bitmap = stbtt_GetCodepointBitmap(&font, 0,stbtt_ScaleForPixelHeight(&font, s), c, &w, &h, 0,0);
for (j=0; j < h; ++j) {
for (i=0; i < w; ++i)
putchar(" .:ioVM@"[bitmap[j*w+i]>>5]);
putchar('\n');
}
return 0;
}
#endif
//
// Output:
//
// .ii.
// @@@@@@.
// V@Mio@@o
// :i. V@V
// :oM@@M
// :@@@MM@M
// @@o o@M
// :@@. M@M
// @@@o@@@@
// :M@@V:@@.
//
//////////////////////////////////////////////////////////////////////////////
//
// Complete program: print "Hello World!" banner, with bugs
//
#if 0
char buffer[24<<20];
unsigned char screen[20][79];
int main(int arg, char **argv)
{
stbtt_fontinfo font;
int i,j,ascent,baseline,ch=0;
float scale, xpos=2; // leave a little padding in case the character extends left
char *text = "Heljo World!"; // intentionally misspelled to show 'lj' brokenness
fread(buffer, 1, 1000000, fopen("c:/windows/fonts/arialbd.ttf", "rb"));
stbtt_InitFont(&font, buffer, 0);
scale = stbtt_ScaleForPixelHeight(&font, 15);
stbtt_GetFontVMetrics(&font, &ascent,0,0);
baseline = (int) (ascent*scale);
while (text[ch]) {
int advance,lsb,x0,y0,x1,y1;
float x_shift = xpos - (float) floor(xpos);
stbtt_GetCodepointHMetrics(&font, text[ch], &advance, &lsb);
stbtt_GetCodepointBitmapBoxSubpixel(&font, text[ch], scale,scale,x_shift,0, &x0,&y0,&x1,&y1);
stbtt_MakeCodepointBitmapSubpixel(&font, &screen[baseline + y0][(int) xpos + x0], x1-x0,y1-y0, 79, scale,scale,x_shift,0, text[ch]);
// note that this stomps the old data, so where character boxes overlap (e.g. 'lj') it's wrong
// because this API is really for baking character bitmaps into textures. if you want to render
// a sequence of characters, you really need to render each bitmap to a temp buffer, then
// "alpha blend" that into the working buffer
xpos += (advance * scale);
if (text[ch+1])
xpos += scale*stbtt_GetCodepointKernAdvance(&font, text[ch],text[ch+1]);
++ch;
}
for (j=0; j < 20; ++j) {
for (i=0; i < 78; ++i)
putchar(" .:ioVM@"[screen[j][i]>>5]);
putchar('\n');
}
return 0;
}
#endif
+/
// ////////////////////////////////////////////////////////////////////////////
// ////////////////////////////////////////////////////////////////////////////
// //
// // INTEGRATION WITH YOUR CODEBASE
// //
// // The following sections allow you to supply alternate definitions
// // of C library functions used by stb_truetype, e.g. if you don't
// // link with the C runtime library.
// #define your own (u)stbtt_int8/16/32 before including to override this
alias stbtt_uint8 = ubyte;
alias stbtt_int8 = byte;
alias stbtt_uint16 = ushort;
alias stbtt_int16 = short;
alias stbtt_uint32 = uint;
alias stbtt_int32 = int;
//typedef char stbtt__check_size32[sizeof(stbtt_int32)==4 ? 1 : -1];
//typedef char stbtt__check_size16[sizeof(stbtt_int16)==2 ? 1 : -1];
int STBTT_ifloor(T) (in T x) pure { pragma(inline, true); import std.math : floor; return cast(int)floor(x); }
int STBTT_iceil(T) (in T x) pure { pragma(inline, true); import std.math : ceil; return cast(int)ceil(x); }
T STBTT_sqrt(T) (in T x) pure { pragma(inline, true); import std.math : sqrt; return sqrt(x); }
T STBTT_pow(T) (in T x, in T y) pure { pragma(inline, true); import std.math : pow; return pow(x, y); }
T STBTT_fmod(T) (in T x, in T y) { pragma(inline, true); import std.math : fmod; return fmod(x, y); }
T STBTT_cos(T) (in T x) pure { pragma(inline, true); import std.math : cos; return cos(x); }
T STBTT_acos(T) (in T x) pure { pragma(inline, true); import std.math : acos; return acos(x); }
T STBTT_fabs(T) (in T x) pure { pragma(inline, true); import std.math : abs; return abs(x); }
// #define your own functions "STBTT_malloc" / "STBTT_free" to avoid malloc.h
void* STBTT_malloc (uint size, const(void)* uptr) { pragma(inline, true); import core.stdc.stdlib : malloc; return malloc(size); }
void STBTT_free (void *ptr, const(void)* uptr) { pragma(inline, true); import core.stdc.stdlib : free; free(ptr); }
/*
#ifndef STBTT_malloc
#include <stdlib.h>
#define STBTT_malloc(x,u) ((void)(u),malloc(x))
#define STBTT_free(x,u) ((void)(u),free(x))
#endif
*/
//alias STBTT_assert = assert;
uint STBTT_strlen (const(void)* p) { pragma(inline, true); import core.stdc.string : strlen; return (p !is null ? cast(uint)strlen(cast(const(char)*)p) : 0); }
void STBTT_memcpy (void* d, const(void)* s, uint count) { pragma(inline, true); import core.stdc.string : memcpy; if (count > 0) memcpy(d, s, count); }
void STBTT_memset (void* d, uint v, uint count) { pragma(inline, true); import core.stdc.string : memset; if (count > 0) memset(d, v, count); }
// /////////////////////////////////////////////////////////////////////////////
// /////////////////////////////////////////////////////////////////////////////
// //
// // INTERFACE
// //
// //
// private structure
struct stbtt__buf {
ubyte *data;
int cursor;
int size;
}
//////////////////////////////////////////////////////////////////////////////
//
// TEXTURE BAKING API
//
// If you use this API, you only have to call two functions ever.
//
struct stbtt_bakedchar {
ushort x0,y0,x1,y1; // coordinates of bbox in bitmap
float xoff,yoff,xadvance;
}
/+
STBTT_DEF int stbtt_BakeFontBitmap(const(ubyte)* data, int offset, // font location (use offset=0 for plain .ttf)
float pixel_height, // height of font in pixels
ubyte *pixels, int pw, int ph, // bitmap to be filled in
int first_char, int num_chars, // characters to bake
stbtt_bakedchar *chardata, // you allocate this, it's num_chars long
int* ascent, int * descent, int* line_gap); // metrics for use later too
+/
// if return is positive, the first unused row of the bitmap
// if return is negative, returns the negative of the number of characters that fit
// if return is 0, no characters fit and no rows were used
// This uses a very crappy packing.
struct stbtt_aligned_quad {
float x0,y0,s0,t0; // top-left
float x1,y1,s1,t1; // bottom-right
}
/+
STBTT_DEF void stbtt_GetBakedQuad(const(stbtt_bakedchar)* chardata, int pw, int ph, // same data as above
int char_index, // character to display
float *xpos, float *ypos, // pointers to current position in screen pixel space
stbtt_aligned_quad *q, // output: quad to draw
int opengl_fillrule); // true if opengl fill rule; false if DX9 or earlier
+/
// Call GetBakedQuad with char_index = 'character - first_char', and it
// creates the quad you need to draw and advances the current position.
//
// The coordinate system used assumes y increases downwards.
//
// Characters will extend both above and below the current position;
// see discussion of "BASELINE" above.
//
// It's inefficient; you might want to c&p it and optimize it.
// ////////////////////////////////////////////////////////////////////////////
//
// NEW TEXTURE BAKING API
//
// This provides options for packing multiple fonts into one atlas, not
// perfectly but better than nothing.
struct stbtt_packedchar {
ushort x0,y0,x1,y1; // coordinates of bbox in bitmap
float xoff,yoff,xadvance;
float xoff2,yoff2;
}
//typedef struct stbtt_pack_context stbtt_pack_context;
//typedef struct stbtt_fontinfo stbtt_fontinfo;
//#ifndef STB_RECT_PACK_VERSION
//typedef struct stbrp_rect stbrp_rect;
//#endif
//STBTT_DEF int stbtt_PackBegin(stbtt_pack_context *spc, ubyte *pixels, int width, int height, int stride_in_bytes, int padding, void *alloc_context);
// Initializes a packing context stored in the passed-in stbtt_pack_context.
// Future calls using this context will pack characters into the bitmap passed
// in here: a 1-channel bitmap that is width * height. stride_in_bytes is
// the distance from one row to the next (or 0 to mean they are packed tightly
// together). "padding" is the amount of padding to leave between each
// character (normally you want '1' for bitmaps you'll use as textures with
// bilinear filtering).
//
// Returns 0 on failure, 1 on success.
//STBTT_DEF void stbtt_PackEnd (stbtt_pack_context *spc);
// Cleans up the packing context and frees all memory.
//#define STBTT_POINT_SIZE(x) (-(x))
/+
STBTT_DEF int stbtt_PackFontRange(stbtt_pack_context *spc, const(ubyte)* fontdata, int font_index, float font_size,
int first_unicode_char_in_range, int num_chars_in_range, stbtt_packedchar *chardata_for_range);
+/
// Creates character bitmaps from the font_index'th font found in fontdata (use
// font_index=0 if you don't know what that is). It creates num_chars_in_range
// bitmaps for characters with unicode values starting at first_unicode_char_in_range
// and increasing. Data for how to render them is stored in chardata_for_range;
// pass these to stbtt_GetPackedQuad to get back renderable quads.
//
// font_size is the full height of the character from ascender to descender,
// as computed by stbtt_ScaleForPixelHeight. To use a point size as computed
// by stbtt_ScaleForMappingEmToPixels, wrap the point size in STBTT_POINT_SIZE()
// and pass that result as 'font_size':
// ..., 20 , ... // font max minus min y is 20 pixels tall
// ..., STBTT_POINT_SIZE(20), ... // 'M' is 20 pixels tall
struct stbtt_pack_range {
float font_size;
int first_unicode_codepoint_in_range; // if non-zero, then the chars are continuous, and this is the first codepoint
int *array_of_unicode_codepoints; // if non-zero, then this is an array of unicode codepoints
int num_chars;
stbtt_packedchar *chardata_for_range; // output
ubyte h_oversample, v_oversample; // don't set these, they're used internally
}
//STBTT_DEF int stbtt_PackFontRanges(stbtt_pack_context *spc, const(ubyte)* fontdata, int font_index, stbtt_pack_range *ranges, int num_ranges);
// Creates character bitmaps from multiple ranges of characters stored in
// ranges. This will usually create a better-packed bitmap than multiple
// calls to stbtt_PackFontRange. Note that you can call this multiple
// times within a single PackBegin/PackEnd.
//STBTT_DEF void stbtt_PackSetOversampling(stbtt_pack_context *spc, unsigned int h_oversample, unsigned int v_oversample);
// Oversampling a font increases the quality by allowing higher-quality subpixel
// positioning, and is especially valuable at smaller text sizes.
//
// This function sets the amount of oversampling for all following calls to
// stbtt_PackFontRange(s) or stbtt_PackFontRangesGatherRects for a given
// pack context. The default (no oversampling) is achieved by h_oversample=1
// and v_oversample=1. The total number of pixels required is
// h_oversample*v_oversample larger than the default; for example, 2x2
// oversampling requires 4x the storage of 1x1. For best results, render
// oversampled textures with bilinear filtering. Look at the readme in
// stb/tests/oversample for information about oversampled fonts
//
// To use with PackFontRangesGather etc., you must set it before calls
// call to PackFontRangesGatherRects.
/+
STBTT_DEF void stbtt_GetPackedQuad(const(stbtt_packedchar)* chardata, int pw, int ph, // same data as above
int char_index, // character to display
float *xpos, float *ypos, // pointers to current position in screen pixel space
stbtt_aligned_quad *q, // output: quad to draw
int align_to_integer);
STBTT_DEF int stbtt_PackFontRangesGatherRects(stbtt_pack_context *spc, const(stbtt_fontinfo)* info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);
STBTT_DEF void stbtt_PackFontRangesPackRects(stbtt_pack_context *spc, stbrp_rect *rects, int num_rects);
STBTT_DEF int stbtt_PackFontRangesRenderIntoRects(stbtt_pack_context *spc, const(stbtt_fontinfo)* info, stbtt_pack_range *ranges, int num_ranges, stbrp_rect *rects);
+/
// Calling these functions in sequence is roughly equivalent to calling
// stbtt_PackFontRanges(). If you more control over the packing of multiple
// fonts, or if you want to pack custom data into a font texture, take a look
// at the source to of stbtt_PackFontRanges() and create a custom version
// using these functions, e.g. call GatherRects multiple times,
// building up a single array of rects, then call PackRects once,
// then call RenderIntoRects repeatedly. This may result in a
// better packing than calling PackFontRanges multiple times
// (or it may not).
// this is an opaque structure that you shouldn't mess with which holds
// all the context needed from PackBegin to PackEnd.
struct stbtt_pack_context {
void *user_allocator_context;
void *pack_info;
int width;
int height;
int stride_in_bytes;
int padding;
uint h_oversample, v_oversample;
ubyte *pixels;
void *nodes;
}
// ////////////////////////////////////////////////////////////////////////////
//
// FONT LOADING
//