-
Notifications
You must be signed in to change notification settings - Fork 2
/
sdf.h
3247 lines (3000 loc) · 366 KB
/
sdf.h
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
// https://github.com/Flix01/Header-Only-GL-Helpers
//
/** MIT License
*
* Copyright (c) 2017 Flix (https://github.com/Flix01/)
*
* 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.
*/
/** EMBEDDED FONT LICENSE
* This file embeds a sdf-AngelFont version of DejaVuSansCondensed-Bold.
* It was derived from DejaVuSerifCondensed-Bold.ttf.
* DejaVuSerifCondensed-Bold.ttf is released under the DejaVu Fonts License v1.00.
* The license can be found at this permalink: http://www.fontsquirrel.com/license/dejavu-sans
* The embedded font can be disabled by defining SDF_NO_EMBEDDED_FONT before including this file.
*/
// WHAT'S THIS
/*
This file is intended to be used to load AngelFont text-based (= not binary or XML-based) Signed Distance Fonts (SDF) files
and to display them onscreen, NOT INSIDE A 3D WORLD, but as a screen overlay in normal openGL rendering.
This is typically used for title/subtitle/credit screens and things like that...
Dependencies:
1) Needs OpenGL WITH SHADER support.
2) Implementation depends on STL.
*/
// HOW TO CREATE COMPATIBLE FONTS:
/*
The best solution I've found is the java program: runnable-hiero.jar, available here: https://libgdx.badlogicgames.com/tools.html
This is how I usually generate the fonts using Hiero:
I STRICTLY follow all the guidelines under "Generating the font" in https://github.com/libgdx/libgdx/wiki/Distance-field-fonts,
with the following changes:
0) I always choose a bold font (and I prefer bold-condensed whenever available).
1) I always use "Rendering" set to "Java".
2) I can add additional codepoints directly in the "Sample Text" edit box (after that I select "Glyph cache" and "reset cache" to update them).
3) I always output a single .png page (support for multiple pages is yet to come).
4) The "Scale" value must be the last to be set: the docs suggest 32, but if you have a fast PC try something bigger (48 or 64).
5) The output .png size can be easily reduced by using 3rd party programs (e.g. pngnq -n 48 myImage.png).
*/
/* MINIMAL BASIC USAGE (Just to see something on screen: the API is much more complex):
0) At the top of your main.cpp file:
#define SDF_IMPLEMENTATION
#include <sdf.h> // this file
// Note that the OpenGL headers must be included BEFORE including <sdf.h>
1) Inside InitGL():
Sdf::SdfCharset* gDefaultCharset = Sdf::SdfAddDefaultCharset(); // DejaVuSerifCondensed-Bold
Sdf::SdfTextChunk* gTextChunks = Sdf::SdfAddTextChunk(gDefaultCharset);
Sdf::SdfAddText(gTextChunks,"This is a test text.");
// Please do not delete gDefaultCharset and gTextChunks yourself!
2) At the end of DrawGL():
float viewport[4];glGetFloatv(GL_VIEWPORT,viewport);
Sdf::SdfRender(viewport,(float)(glutGet(GLUT_ELAPSED_TIME)*0.001)); // Last arg is probably used only for text animations and for this example can probably be left to zero
// The line above should render all the active SdfTextChunks
3) Inside DestroyGL():
Sdf::SdfDestroy(); // Frees everything
*/
#ifndef SDF_H_
#define SDF_H_
#include <stdarg.h> // va_list, va_start, va_end
#ifndef SDF_NO_NAMESPACE
namespace Sdf {
#endif
#ifndef SDF_VEC2_REPLACEMENT
struct SdfVec2 {
float x,y;
SdfVec2() : x(0),y(0) {}
SdfVec2(float _x,float _y) : x(_x),y(_y) {}
inline const float& operator[](int i) const {return (const float&) (*((const float*)this + i));}
inline float& operator[](int i) {return (float&) (*((float*)this + i));}
inline SdfVec2 operator*(const SdfVec2& r) const {return SdfVec2(x*r.x,y*r.y);}
inline SdfVec2 operator*(float f) const {return SdfVec2(x*f,y*f);}
inline SdfVec2 operator+(const SdfVec2& r) const {return SdfVec2(x+r.x,y+r.y);}
inline SdfVec2 operator-(const SdfVec2& r) const {return SdfVec2(x-r.x,y-r.y);}
};
# ifndef SDF_NO_NAMESPACE
typedef SdfVec2 Vec2;
# endif
#endif
#ifndef SDF_VEC4_REPLACEMENT
struct SdfVec4 {
float x,y,z,w;
SdfVec4() : x(0),y(0),z(0),w(0) {}
SdfVec4(float _x,float _y,float _z,float _w) : x(_x),y(_y),z(_z),w(_w) {}
inline const float& operator[](int i) const {return (const float&) (*((const float*)this + i));}
inline float& operator[](int i) {return (float&) (*((float*)this + i));}
};
# ifndef SDF_NO_NAMESPACE
typedef SdfVec4 Vec4;
# endif
#endif
// Mandatory Stuff---------------------------------
void SdfDestroy();
// Charsets --------------------------------------------------------------------------------------
struct SdfCharsetProperties {
bool flipYOffset;
SdfCharsetProperties(bool _flipYOffset=false) : flipYOffset(_flipYOffset) {}
};
// Tip: load the texture into fntTexture (owned by you), before calling these methods
struct SdfCharset* SdfAddCharsetFromFile(const char* fntFilePath,GLuint fntTexture,const SdfCharsetProperties& properties=SdfCharsetProperties(),bool charsetWillDeleteFntTexture=false);
struct SdfCharset* SdfAddCharsetFromMemory(const void* data,unsigned int data_size,GLuint fntTexture,const SdfCharsetProperties& properties=SdfCharsetProperties(),bool charsetWillDeleteFntTexture=false);
// Same as above, except that the texture is created internally from a 32 bit raw RGBA image (with no additional stride). It must be: sizeof(fntRGBAData)=4*fntRGBAWidth*fntRGBAHeight
struct SdfCharset* SdfAddCharsetAndTextureFromMemory(const void* fntData,unsigned int fntDataSize,const void* fntRGBAData,int fntRGBAWidth,int fntRGBAHeight,const SdfCharsetProperties& properties=SdfCharsetProperties());
#ifndef SDF_NO_EMBEDDED_FONT
// In this case a fntTexture is always handled for you (and destroyed in the SdfCharset destructor)
struct SdfCharset* SdfAddDefaultCharset(const SdfCharsetProperties& properties=SdfCharsetProperties());
#endif //SDF_NO_EMBEDDED_FONT
//-------------------------------------------------------------------------------------------------
// TextChunks -------------------------------------------------------------------------------------
enum SDFTextBufferType {
SDF_BT_REGULAR=0,
SDF_BT_OUTLINE=1,
SDF_BT_SHADOWED=2
};
enum SDFHAlignment {
SDF_LEFT=0,
SDF_CENTER,
SDF_RIGHT,
SDF_JUSTIFY
};
enum SDFVAlignment {
SDF_TOP=0,
SDF_MIDDLE,
SDF_BOTTOM
};
struct SdfTextChunkProperties {
SdfVec2 boundsCenter; // in normalized units relative to the screen size
SdfVec2 boundsHalfSize; // in normalized units relative to the screen size
float maxNumTextLines; // This will determine the font size ( = boundsSizeInPixels/maxNumTextLines )
float lineHeightOverride; // Used if > 0.f. Usually LineHeight is something like 1.2f [that means 1.2f times the FontSize(==FontHeight)]
SDFHAlignment halign;
SDFVAlignment valign;
SdfTextChunkProperties(float _maxNumTextLines=20,SDFHAlignment _halign=SDF_CENTER,SDFVAlignment _valign=SDF_MIDDLE,const SdfVec2& _boundsCenter=SdfVec2(.5f,.5f),const SdfVec2& _boundsHalfSize=SdfVec2(.5f,.5f),float _lineHeightOverride=0.f) {
boundsCenter = _boundsCenter;
boundsHalfSize = _boundsHalfSize;
maxNumTextLines = _maxNumTextLines;
lineHeightOverride = _lineHeightOverride;
halign = _halign;
valign = _valign;
}
};
struct SdfTextChunk* SdfAddTextChunk(struct SdfCharset* _charset,int sdfBufferType=SDF_BT_OUTLINE, const SdfTextChunkProperties& properties=SdfTextChunkProperties(),bool preferStreamDrawBufferUsage=false);
SdfTextChunkProperties& SdfTextChunkGetProperties(struct SdfTextChunk* textChunk);
const SdfTextChunkProperties& SdfTextChunkGetProperties(const struct SdfTextChunk* textChunk);
void SdfTextChunkSetStyle(struct SdfTextChunk* textChunk,int sdfTextBufferType=SDF_BT_OUTLINE);
int SdfTextChunkGetStyle(const struct SdfTextChunk* textChunk);
void SdfTextChunkSetMute(struct SdfTextChunk* textChunk,bool flag); // Mute makes it invisible
bool SdfTextChunkGetMute(const struct SdfTextChunk* textChunk);
void SdfRemoveTextChunk(struct SdfTextChunk* chunk);
void SdfRemoveAllTextChunks();
//--------------------------------------------------------------------------------------------------
// Text---------------------------------------------------------------------------------------------
struct SdfTextColor {
SdfVec4 colorTopLeft;
SdfVec4 colorTopRight;
SdfVec4 colorBottomLeft;
SdfVec4 colorBottomRight;
SdfTextColor(const SdfVec4& color=SdfVec4(1,1,1,1)) : colorTopLeft(color),colorTopRight(color),colorBottomLeft(color),colorBottomRight(color) {}
SdfTextColor(const SdfVec4& colorTop,const SdfVec4& colorBottom) : colorTopLeft(colorTop),colorTopRight(colorTop),colorBottomLeft(colorBottom),colorBottomRight(colorBottom) {}
SdfTextColor(const SdfVec4& _colorTopLeft,const SdfVec4& _colorTopRight,const SdfVec4& _colorBottomLeft,const SdfVec4& _colorBottomRight)
: colorTopLeft(_colorTopLeft),colorTopRight(_colorTopRight),colorBottomLeft(_colorBottomLeft),colorBottomRight(_colorBottomRight) {}
SdfTextColor(const unsigned int& in) {
const float s = 1.0f/255.0f;
const SdfVec4 color(
((in >> 0) & 0xFF) * s,
((in >> 8) & 0xFF) * s,
((in >> 16) & 0xFF) * s,
((in >> 24) & 0xFF) * s);
colorTopLeft=colorTopRight=colorBottomLeft=colorBottomRight=color;
}
static void SetDefault(const SdfTextColor& defaultColor, bool updateAllExistingTextChunks=false);
};
static SdfTextColor SdfTextDefaultColor;
void SdfAddText(struct SdfTextChunk* chunk,const char* startText,bool italic=false,const SdfTextColor* pSdfTextColor=NULL,const SdfVec2* textScaling=NULL,const char* endText=NULL,const SDFHAlignment* phalignOverride=NULL,bool fakeBold=false);
void SdfAddTextWithTags(struct SdfTextChunk* chunk,const char* startText,const char* endText=NULL);
void SdfAddTextFormatted(struct SdfTextChunk* chunk,bool italic,const SdfTextColor* pSdfTextColor,const SdfVec2* textScaling,const SDFHAlignment* phalignOverride,bool fakeBold,const char* text,...);
void SdfAddTextFormattedWithTags(struct SdfTextChunk* chunk,const char* text,...);
void SdfClearText(struct SdfTextChunk* chunk);
//---------------------------------------------------------------------------------------------------
void SdfRender(const float pViewport[4],float globalTime); // pViewport is [x,y,width,height] in screen coordinates, not in framebuffer coords.
// Optional/Extra methods:---------------------------------------------------------------
enum SDFAnimationMode {
SDF_AM_NONE = 0,
SDF_AM_MANUAL, // This mode uses a SdfAnimation (= a series of SdfAnimationKeyFrames)
SDF_AM_FADE_IN,
SDF_AM_ZOOM_IN,
SDF_AM_APPEAR_IN,
SDF_AM_LEFT_IN,
SDF_AM_RIGHT_IN,
SDF_AM_TOP_IN,
SDF_AM_BOTTOM_IN,
SDF_AM_FADE_OUT,
SDF_AM_ZOOM_OUT,
SDF_AM_APPEAR_OUT,
SDF_AM_LEFT_OUT,
SDF_AM_RIGHT_OUT,
SDF_AM_TOP_OUT,
SDF_AM_BOTTOM_OUT,
SDF_AM_BLINK,
SDF_AM_PULSE,
SDF_AM_FLASH,
SDF_AM_TYPING
};
struct SdfAnimationKeyFrame {
SdfVec2 offset;
SdfVec2 scale; // better not use this, as it's not centered correctly (= it affects offset)
float alpha;
int startChar,endChar;
float timeInSeconds; // of the transition between the previous one and this
SdfAnimationKeyFrame(float _timeInSeconds=0.f,float _alpha=1.f,int _startChar=0,int _endChar=-1,const SdfVec2& _offset=SdfVec2(0,0),const SdfVec2& _scale=SdfVec2(1,1)) :
offset(_offset),scale(_scale),alpha(_alpha),startChar(_startChar),endChar(_endChar),timeInSeconds(_timeInSeconds)
{}
};
struct SdfAnimation* SdfAddAnimation();
void SdfAnimationSetLoopingParams(struct SdfAnimation* animation,bool mustLoop,bool mustHideTextWhenFinishedIfNotLooping=true);
float SdfAnimationAddKeyFrame(struct SdfAnimation* animation,const SdfAnimationKeyFrame& keyFrame); // returns the animation total length in seconds so far
void SdfAnimationClear(struct SdfAnimation* animation); // clears all SdfKeyFrames
void SdfRemoveAnimation(struct SdfAnimation* animation); // "animation" no more usable
void SdfRemoveAllAnimations();
struct SdfAnimationParams {
float speed,timeOffset;
int startChar,endChar;
SdfAnimationParams()
{
speed = 1.f;timeOffset=0.f;
startChar=0;endChar=-1;
}
};
struct SdfGlobalParams {
SdfVec2 offset,scale;
float alpha;
int startChar,endChar;
SdfGlobalParams()
{
offset=SdfVec2(0,0);
scale=SdfVec2(1,1);
alpha=1.0f;
startChar=0;endChar=-1;
}
};
// Once an animation is active (from its mode), it plays if the text chunk is not mute.
// When it ends the mode can be set to SDF_AM_NONE and the text chunk BAN be set to mute.
// Only a manual animation can have a looping mode.
void SdfTextChunkSetManualAnimation(struct SdfTextChunk* chunk,struct SdfAnimation* animation);
const struct SdfAnimation* SdfTextChunkGetManualAnimation(const struct SdfTextChunk* chunk);
struct SdfAnimation* SdfTextChunkGetManualAnimation(struct SdfTextChunk* chunk);
void SdfTextChunkSetAnimationParams(struct SdfTextChunk* chunk,const SdfAnimationParams& params=SdfAnimationParams());
const SdfAnimationParams& SdfTextChunkGetAnimationParams(const struct SdfTextChunk* chunk);
SdfAnimationParams& SdfTextChunkGetAnimationParams(struct SdfTextChunk* chunk);
void SdfTextChunkSetGlobalParams(struct SdfTextChunk* chunk,const SdfGlobalParams& params=SdfGlobalParams());
const SdfGlobalParams& SdfTextChunkGetGlobalParams(const struct SdfTextChunk* chunk);
SdfGlobalParams& SdfTextChunkGetGlobalParams(struct SdfTextChunk* chunk);
void SdfTextChunkSetAnimationMode(struct SdfTextChunk* chunk,SDFAnimationMode mode=SDF_AM_NONE);
SDFAnimationMode SdfTextChunkGetAnimationMode(const struct SdfTextChunk* chunk);
//------------------------------------------------------------------------------------------
#ifndef SDF_NO_NAMESPACE
} //namespace
#endif
#endif //SDF_H_
#ifdef SDF_IMPLEMENTATION
#ifndef SDF_IMPLEMENTATION_H
#define SDF_IMPLEMENTATION_H
#include <stdio.h> // FILE* used in SdfCharset::GetFileContent(...)
#include <ctype.h> // tolower
#include <stdint.h> // uint8_t
#ifndef SDF_ASSERT
#include <assert.h>
#define SDF_ASSERT(X) assert(X)
#endif //SDF_ASSERT
#ifndef SdfVector
#include <vector>
#define SdfVector std::vector
#endif
#ifndef SdfMap
//#include <hashtable.h>
//#define SdfMap std::hashtable
#include <map>
#define SdfMap std::map
//#include <unordered_map>
//#define SdfMap std::unordered_map
#endif
#ifndef SdfUIntPair
#include <utility> // std::pair
#define SdfUIntPair std::pair<unsigned int,unsigned int>
#endif
#ifndef SDF_MALLOC
#define SDF_MALLOC(X) malloc(X)
#endif
#ifndef SDF_FREE
#define SDF_FREE(X) free(X)
#endif
#ifndef SDF_PLACEMENT_NEW
struct SdfPlacementNewDummy {};
inline void* operator new(size_t, SdfPlacementNewDummy, void* ptr) { return ptr; }
inline void operator delete(void*, SdfPlacementNewDummy, void*) {}
#define SDF_PLACEMENT_NEW(_PTR) new(SdfPlacementNewDummy(), _PTR)
#endif
#ifndef SDF_NO_NAMESPACE
namespace Sdf {
#endif //SDF_NO_NAMESPACE
class UTF8Helper {
/* All the code in this class is based on the code found at: http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
This is the license of the ORIGINAL work at http://bjoern.hoehrmann.de/utf-8/decoder/dfa/:
Copyright (c) 2008-2009 Bjoern Hoehrmann <[email protected]>
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
All the things I've added to the original code are in the public domain (but be warned that might be wrong and incorrected...)
*/
public:
protected:
UTF8Helper() {}
public:
enum {
UTF8_ACCEPT=0,
UTF8_REJECT=1
};
protected:
inline static uint8_t utf8d(uint32_t byte) {
static const uint8_t _utf8d[] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 00..1f
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 20..3f
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 40..5f
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, // 60..7f
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9, // 80..9f
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, // a0..bf
8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, // c0..df
0xa,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x3,0x4,0x3,0x3, // e0..ef
0xb,0x6,0x6,0x6,0x5,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8,0x8, // f0..ff
0x0,0x1,0x2,0x3,0x5,0x8,0x7,0x1,0x1,0x1,0x4,0x6,0x1,0x1,0x1,0x1, // s0..s0
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,0,1,0,1,1,1,1,1,1, // s1..s2
1,2,1,1,1,1,1,2,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1, // s3..s4
1,2,1,1,1,1,1,1,1,2,1,1,1,1,1,1,1,1,1,1,1,1,1,3,1,3,1,1,1,1,1,1, // s5..s6
1,3,1,1,1,1,1,3,1,3,1,1,1,1,1,1,1,3,1,1,1,1,1,1,1,1,1,1,1,1,1,1, // s7..s8
};
return _utf8d[byte];
}
public:
inline static uint32_t decode(uint32_t* state, uint32_t* codep, uint32_t byte) {
uint32_t type = utf8d(byte);
*codep = (*state != UTF8_ACCEPT) ?
(byte & 0x3fu) | (*codep << 6) :
(0xff >> type) & (byte);
*state = utf8d(256 + *state*16 + type);
return *state;
}
}; // class
static SdfTextColor gSdfTextDefaultColor(SdfVec4(1,1,1,1));
static SdfVec2 gSdfDisplaySize(800,450);
class SdfVertexBuffer {
public:
void clear() {verts.clear();}
~SdfVertexBuffer() {if (vbo) glDeleteBuffers(1,&vbo);}
void updateBoundVbo() const {
const GLenum drawMode = preferStreamDrawBufferUsage ? GL_STREAM_DRAW : GL_STATIC_DRAW;
//glBufferData(GL_ARRAY_BUFFER, verts.size()*sizeof(VertexDeclaration),verts.size()!=0 ? &verts[0].posAndUV.x : NULL, drawMode);return;
if (maxVertsSize<(int)verts.size()) maxVertsSize=(int)verts.size();
glBufferData(GL_ARRAY_BUFFER, maxVertsSize*sizeof(VertexDeclaration), NULL, drawMode);
if (verts.size()>0) {
glBufferSubData(GL_ARRAY_BUFFER,0,verts.size()*sizeof(VertexDeclaration),&verts[0].posAndUV.x);
//fprintf(stderr,"%d indices\n",verts.size());
}
}
inline int getType() const {return type;}
inline void setType(int _type) {type=_type;}
inline const SdfVec4* getColorOfVert(int num) const {return (int)verts.size()>num*6 ? &verts[num*6].color : NULL;}
inline int size() const {return verts.size();}
inline int numChars() const {return verts.size()/6;}
#ifndef _MSC_VER // Not sure, but old cl compilers can have problems here
protected:
#endif //_MSC_VER
SdfVertexBuffer(int _type=SDF_BT_OUTLINE,bool _preferStreamDrawBufferUsage=false) : type(_type),preferStreamDrawBufferUsage(_preferStreamDrawBufferUsage) {maxVertsSize=0;vbo=0;}
struct VertexDeclaration {
SdfVec4 posAndUV;
SdfVec4 color;
};
SdfVector<VertexDeclaration> verts;
GLuint vbo;
int type;
bool preferStreamDrawBufferUsage;
mutable int maxVertsSize;
friend struct SdfCharset;
friend struct SdfTextChunk;
friend void SdfRender(const float pViewport[4],float globalTime);
friend bool SdfTextChunkEdit(SdfTextChunk* sdfTextChunk,char* buffer,int bufferSize);
};
struct SdfCharDescriptor
{
unsigned int Id; // The character id.
float X, Y; // The left and top position of the character image in the texture.
float Width, Height; // The width and height of the character image in the texture.
float XOffset, YOffset; // How much the current position should be offset when copying the image from the texture to the screen ( top/left offsets ).
float XOffset2, YOffset2; // How much the current position should be offset when copying the image from the texture to the screen ( lower/right offsets ).
float XAdvance; // How much the current position should be advanced after drawing the character.
unsigned char Page; // The texture page where the character image is found.
SdfCharDescriptor() : Id(0), X( 0 ), Y( 0 ), Width( 0 ), Height( 0 ), XOffset( 0 ), YOffset( 0 ), XOffset2( 0 ), YOffset2( 0 ),
XAdvance( 0 ), Page( 0 )
{ }
};
struct SdfAnimation {
//public:
SdfAnimation() {totalTime=0.f;}
SdfAnimation(const SdfAnimation& o) {*this=o;totalTime=0.f;}
SdfAnimation(const SdfVector<SdfAnimationKeyFrame>& _keyFrames) {cloneKeyFramesFrom(_keyFrames);totalTime=0.f;looping=false;mustMuteAtEnd=true;}
~SdfAnimation() {}
const SdfAnimation& operator=(const SdfAnimation& o) {
cloneKeyFramesFrom(o.keyFrames);
return *this;
}
//protected:
SdfVector<SdfAnimationKeyFrame> keyFrames;
float totalTime;
bool looping;
bool mustMuteAtEnd;
inline void cloneKeyFramesFrom(const SdfVector<SdfAnimationKeyFrame>& _keyFrames) {
// deep clone keyframes
const int nkf = _keyFrames.size();
keyFrames.clear();keyFrames.reserve(nkf);
for (int i=0;i<nkf;i++) keyFrames[i] = _keyFrames[i];
}
inline float addKeyFrame(const SdfAnimationKeyFrame& kf) {
keyFrames.push_back(kf);
totalTime+=kf.timeInSeconds;
return totalTime;
}
inline bool removeKeyFrameAt(int i) {
if (i<0 || i>=(int)keyFrames.size()) return false;
for (int j=i,jsz=keyFrames.size()-1;j<jsz;j++) keyFrames[j] = keyFrames[j+1];
keyFrames.pop_back();
update();
return true;
}
inline void clear() {keyFrames.clear();totalTime=0.f;}
inline void update() {
totalTime = 0.f;
for (int i=0,isz=keyFrames.size();i<isz;i++) {
totalTime+=keyFrames[i].timeInSeconds;
}
}
};
struct SdfTextChunk {
SdfTextChunkProperties props;
const SdfCharset* charset;
SdfVertexBuffer* buffer;
int numValidGlyphs;
mutable bool dirty;
SdfVec2 shadowOffsetInPixels;
bool mute;
SDFAnimationMode animationMode;
SdfAnimation* manualAnimationRef;
float animationStartTime;
SdfAnimationParams animationParams;
SdfGlobalParams globalParams;
struct TextBit {
SdfVector<SdfCharDescriptor> charDescriptors;
SdfVector<float> kernings;
SdfVec2 scaling;
SdfTextColor sdfTextColor;
bool italic;
int hAlignment;
};
SdfVector<TextBit> textBits;
SdfTextChunk() {charset=NULL;buffer=NULL;numValidGlyphs=0;shadowOffsetInPixels.x=shadowOffsetInPixels.y=4.f;mute = false;animationMode=SDF_AM_NONE;manualAnimationRef=NULL;animationStartTime=-1.f;tmpVisible = true;tmpLocalTime=0.f;}
SdfTextChunk(const SdfCharset* _charset,int bufferType,const SdfTextChunkProperties& properties=SdfTextChunkProperties(),bool preferStreamDrawBufferUsage=false) {
buffer = (SdfVertexBuffer*) SDF_MALLOC(sizeof(SdfVertexBuffer));
SDF_PLACEMENT_NEW (buffer) SdfVertexBuffer(bufferType,preferStreamDrawBufferUsage);
SDF_ASSERT(buffer);
charset = _charset;
SDF_ASSERT(charset);
props = properties;
dirty = true;
numValidGlyphs=0;
shadowOffsetInPixels.x=shadowOffsetInPixels.y=4.f;
mute = false;
animationMode=SDF_AM_NONE;manualAnimationRef=NULL;animationStartTime=-1.f;
tmpVisible = true;tmpLocalTime=0.f;
}
~SdfTextChunk() {
if (buffer) {
buffer->~SdfVertexBuffer();
SDF_FREE(buffer);
buffer=NULL;
}
}
inline void setMute(bool flag) {
if (mute!=flag) {
animationStartTime = -1.f;
mute = flag;
}
}
// These tmp variables are valid per frame and set by next methods:
mutable bool tmpVisible;
mutable float tmpLocalTime;
mutable SdfAnimationKeyFrame tmpKeyFrame;
inline static float Lerp(float t,float v0,float v1) {return v0+t*(v1-v0);}
inline static int LerpInt(float t,int v0,int v1) {return v0+(int)((t*(float)(v1-v0))+0.5f);}
inline static void Lerp(float t,SdfAnimationKeyFrame& kfOut,const SdfAnimationKeyFrame& kf0,const SdfAnimationKeyFrame& kf1,int numGlyphs) {
kfOut.alpha = (kf0.alpha==kf1.alpha) ? kf0.alpha : Lerp(t,kf0.alpha,kf1.alpha);
kfOut.offset.x = (kf0.offset.x==kf1.offset.x) ? kf0.offset.x : Lerp(t,kf0.offset.x,kf1.offset.x);
kfOut.offset.y = (kf0.offset.y==kf1.offset.y) ? kf0.offset.y : Lerp(t,kf0.offset.y,kf1.offset.y);
kfOut.scale.x = (kf0.scale.x==kf1.scale.x) ? kf0.scale.x : Lerp(t,kf0.scale.x,kf1.scale.x);
kfOut.scale.y = (kf0.scale.y==kf1.scale.y) ? kf0.scale.y : Lerp(t,kf0.scale.y,kf1.scale.y);
kfOut.startChar = (kf0.startChar==kf1.startChar) ? kf0.startChar : LerpInt(t,kf0.startChar,kf1.startChar);
kfOut.endChar = (kf0.endChar==kf1.endChar) ? kf0.endChar : LerpInt(t,(kf0.endChar<0)?numGlyphs:kf0.endChar,(kf1.endChar<0)?numGlyphs:kf1.endChar);
}
inline bool checkVisibleAndEvalutateAnimationIfNecessary(float time) {
if (mute || (animationMode==SDF_AM_MANUAL && (!manualAnimationRef || manualAnimationRef->keyFrames.size()==0 || manualAnimationRef->totalTime==0.f))) return (tmpVisible=false);
if (animationStartTime < 0) animationStartTime = time;
tmpLocalTime=(time-animationStartTime)*animationParams.speed-animationParams.timeOffset;
if (tmpLocalTime<0) return (tmpVisible=false);
if (animationMode==SDF_AM_MANUAL && tmpLocalTime>manualAnimationRef->totalTime) {
// return (tmpVisible=false);
if (!manualAnimationRef->looping) {
animationStartTime=-1.f;animationMode=SDF_AM_NONE;
if (manualAnimationRef->mustMuteAtEnd) {setMute(true);return (tmpVisible=false);}
else {/*tmpKeyFrame = SdfAnimationKeyFrame();*/setMute(false);return (tmpVisible=true);}
}
else if (manualAnimationRef->totalTime>0.f) {
while (tmpLocalTime>manualAnimationRef->totalTime) {tmpLocalTime-=manualAnimationRef->totalTime;animationStartTime+=manualAnimationRef->totalTime;}
//fprintf(stderr,"time: %1.4f/%1.4f (%d frames)\n",tmpLocalTime,manualAnimationRef->totalTime,manualAnimationRef->keyFrames.size());
}
}
// evalutate animation here:
tmpKeyFrame = SdfAnimationKeyFrame();
switch (animationMode) {
case SDF_AM_FADE_IN: {if (tmpLocalTime<1.f) tmpKeyFrame.alpha = tmpLocalTime;else {setMute(false);animationStartTime=-1.f;animationMode=SDF_AM_NONE;}}
break;
case SDF_AM_FADE_OUT: {if (tmpLocalTime<1.f) tmpKeyFrame.alpha = 1.f-tmpLocalTime;else {setMute(true);animationStartTime=-1.f;animationMode=SDF_AM_NONE;return (tmpVisible=false);}}
break;
case SDF_AM_ZOOM_IN: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = tmpLocalTime; // in [0,1]
tmpLocalTime = (2.0f-tmpLocalTime); // in [2,1]
tmpLocalTime = tmpLocalTime*tmpLocalTime*tmpLocalTime; // in [8,1]
tmpKeyFrame.scale.x=tmpKeyFrame.scale.y = tmpLocalTime;
}
else {setMute(false);animationStartTime=-1.f;animationMode=SDF_AM_NONE;}}
break;
case SDF_AM_ZOOM_OUT: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = 1.f-tmpLocalTime;
tmpLocalTime = (1.0f+tmpLocalTime); // in [1,2]
tmpLocalTime = tmpLocalTime*tmpLocalTime*tmpLocalTime; // in [1,8]
tmpKeyFrame.scale.x=tmpKeyFrame.scale.y = tmpLocalTime;
}
else {setMute(true);animationStartTime=-1.f;animationMode=SDF_AM_NONE;return (tmpVisible=false);}}
break;
case SDF_AM_APPEAR_IN: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = tmpLocalTime; // in [0,1]
tmpLocalTime *= tmpLocalTime;
tmpKeyFrame.scale.y = tmpLocalTime;
}
else {setMute(false);animationStartTime=-1.f;animationMode=SDF_AM_NONE;}
}
break;
case SDF_AM_APPEAR_OUT: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = 1.f-tmpLocalTime;
tmpLocalTime = tmpKeyFrame.alpha;
tmpLocalTime *= tmpLocalTime;
tmpKeyFrame.scale.y = tmpLocalTime;
}
else {setMute(true);animationStartTime=-1.f;animationMode=SDF_AM_NONE;return (tmpVisible=false);}}
break;
case SDF_AM_LEFT_IN: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = tmpLocalTime; // in [0,1]
tmpLocalTime *= tmpLocalTime;
tmpKeyFrame.offset.x = -1.0f + tmpLocalTime;
}
else {setMute(false);animationStartTime=-1.f;animationMode=SDF_AM_NONE;}}
break;
case SDF_AM_LEFT_OUT: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = 1.f-tmpLocalTime;
tmpLocalTime = tmpKeyFrame.alpha;
tmpLocalTime *= tmpLocalTime;
tmpKeyFrame.offset.x = -1.0f + tmpLocalTime;
}
else {setMute(true);animationStartTime=-1.f;animationMode=SDF_AM_NONE;return (tmpVisible=false);}}
break;
case SDF_AM_RIGHT_IN: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = tmpLocalTime; // in [0,1]
tmpLocalTime *= tmpLocalTime;
tmpKeyFrame.offset.x = 1.0f - tmpLocalTime;
}
else {setMute(false);animationStartTime=-1.f;animationMode=SDF_AM_NONE;}}
break;
case SDF_AM_RIGHT_OUT: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = 1.f-tmpLocalTime;
tmpLocalTime = tmpKeyFrame.alpha;
tmpLocalTime *= tmpLocalTime;
tmpKeyFrame.offset.x = 1.0f - tmpLocalTime;
}
else {setMute(true);animationStartTime=-1.f;animationMode=SDF_AM_NONE;return (tmpVisible=false);}}
break;
case SDF_AM_TOP_IN: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = tmpLocalTime; // in [0,1]
tmpLocalTime *= tmpLocalTime;
tmpKeyFrame.offset.y = -1.0f + tmpLocalTime;
}
else {setMute(false);animationStartTime=-1.f;animationMode=SDF_AM_NONE;}}
break;
case SDF_AM_TOP_OUT: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = 1.f-tmpLocalTime;
tmpLocalTime = tmpKeyFrame.alpha;
tmpLocalTime *= tmpLocalTime;
tmpKeyFrame.offset.y = -1.0f + tmpLocalTime;
}
else {setMute(true);animationStartTime=-1.f;animationMode=SDF_AM_NONE;return (tmpVisible=false);}}
break;
case SDF_AM_BOTTOM_IN: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = tmpLocalTime; // in [0,1]
tmpLocalTime *= tmpLocalTime;
tmpKeyFrame.offset.y = 1.0f - tmpLocalTime;
}
else {setMute(false);animationStartTime=-1.f;animationMode=SDF_AM_NONE;}}
break;
case SDF_AM_BOTTOM_OUT: {
if (tmpLocalTime<1.f) {
tmpKeyFrame.alpha = 1.f-tmpLocalTime;
tmpLocalTime = tmpKeyFrame.alpha;
tmpLocalTime *= tmpLocalTime;
tmpKeyFrame.offset.y = 1.0f - tmpLocalTime;
}
else {setMute(true);animationStartTime=-1.f;animationMode=SDF_AM_NONE;return (tmpVisible=false);}}
break;
case SDF_AM_BLINK: {float tmp = (float) ((((int)(tmpLocalTime*100.f))%101)-50)*0.02f;tmpKeyFrame.alpha = tmp*tmp;}
break;
case SDF_AM_PULSE: {
tmpKeyFrame.scale.x=tmpKeyFrame.scale.y = 1.0f+((0.005f*20.f)/(float)(this->props.maxNumTextLines))*sinf(tmpLocalTime*10.0f);
}
break;
case SDF_AM_FLASH: {
if (tmpLocalTime<=1.0f) {
float tmp;
if (tmpLocalTime<=0.5f) tmp = tmpLocalTime*2.f; // 0->1
else tmp = 1.f-((tmpLocalTime-0.5f)*2.f); // 1->0
# ifndef SDF_AM_FLASH_ALORITHM
# define SDF_AM_FLASH_ALORITHM 3
# endif
tmpKeyFrame.alpha =
# if SDF_AM_FLASH_ALORITHM==0
tmp
# elif SDF_AM_FLASH_ALORITHM==1
tmp*tmp
# elif SDF_AM_FLASH_ALORITHM==2
tmp * tmp * (3.f - 2.f * tmp)
# else
tmp * tmp * tmp * (tmp * (tmp * 6.f - 15.f) + 10.f)
# endif
;
}
else {setMute(true);animationStartTime=-1.f;animationMode=SDF_AM_NONE;return (tmpVisible=false);}
}
break;
case SDF_AM_TYPING: {
static const float timePerChar = 0.15f;
const int numChars = buffer->numChars();
const float timeForAllChars = timePerChar * numChars;
//if (timeForAllChars>0) {
if (tmpLocalTime<=timeForAllChars) {
tmpKeyFrame.endChar = (int)(((tmpLocalTime/timeForAllChars)*(float)(numChars))+0.5f);
}
else {setMute(false);animationStartTime=-1.f;animationMode=SDF_AM_NONE;}
//}
//else {setMute(false);animationStartTime=-1.f;animationMode=SDF_AM_NONE;}
}
break;
case SDF_AM_MANUAL: {
const SdfAnimation& an = *manualAnimationRef;
const int nkf = an.keyFrames.size();
static SdfAnimationKeyFrame ZeroKF(0.f,0.f);
float sumTime = 0;int i=0;const SdfAnimationKeyFrame* kf = NULL;
for (i=0;i<nkf;i++) {
kf = &an.keyFrames[i];
if (kf->timeInSeconds==0.f) continue;
if (tmpLocalTime <= sumTime + kf->timeInSeconds) break;
sumTime+=kf->timeInSeconds;
}
//if (!kf) kf = (nkf>0 && animationParams.looping) ? &an.keyFrames[nkf-1] : &ZeroKF;
//fprintf(stderr,"FRAME: %d\n",i);
SDF_ASSERT(kf && kf->timeInSeconds);
const SdfAnimationKeyFrame* kf_prev = (i>=1 ? &an.keyFrames[i-1] : (nkf>0 &&
(tmpLocalTime>manualAnimationRef->totalTime && manualAnimationRef->looping) // Not sure what I meant here... now I'm just correcting what it was: "tmpLocalTime>manualAnimationRef->looping", but looping is a bool. What did I mean ?
) ? &an.keyFrames[nkf-1] : &ZeroKF);
const float deltaTime = (tmpLocalTime-sumTime)/kf->timeInSeconds; // in [0,1]
SDF_ASSERT(deltaTime>=0.f && deltaTime<=1.f);
Lerp(deltaTime,tmpKeyFrame,*kf_prev,*kf,buffer->numChars());
}
break;
default:
break;
}
const bool applyAnimationParams = true;
if (applyAnimationParams) {
// Here we apply animationParams to the calculated fields
tmpKeyFrame.alpha*=globalParams.alpha;
tmpKeyFrame.offset.x+=globalParams.offset.x;
tmpKeyFrame.offset.y+=globalParams.offset.y;
tmpKeyFrame.scale.x*=globalParams.scale.x;
tmpKeyFrame.scale.y*=globalParams.scale.y;
}
return (tmpVisible=(tmpLocalTime>=0));
}
inline bool setupUniformValuesAndDrawArrays(struct SdfShaderProgram* SP, bool shadowPass, const SdfVec2 &screenSize);
inline void addText(const char* startText,bool _italic,const SdfTextColor* pSdfTextColor,const SdfVec2* textScaling,const char* endText,const SDFHAlignment *phalignOverride, bool fakeBold);
inline void clearText() {
if (buffer) buffer->clear();
textBits.clear();
dirty=false;
numValidGlyphs=0;
}
inline void assignText(const char* startText,bool _italic,const SdfTextColor* pSdfTextColor,const SdfVec2* textScaling,const char* endText,const SDFHAlignment *phalignOverride, bool fakeBold) {
clearText();
addText(startText,_italic,pSdfTextColor,textScaling,endText,phalignOverride,fakeBold);
}
bool endText(SdfVec2 screenSize=SdfVec2(-1,-1));
};
struct SdfShaderProgram {
GLuint program;
GLint uniformLocationOrthoMatrix;
GLint uniformLocationSampler;
GLint uniformLocationOffsetAndScale;
GLint uniformLocationAlphaAndShadow;
bool wasLoadShaderProgramCalled; // if loadShaderProgram(...) fails, we don't want to keep calling it because program==0. So we can check this.
SdfShaderProgram() : program(0),uniformLocationOrthoMatrix(-1),uniformLocationSampler(-1),
uniformLocationOffsetAndScale(-1),uniformLocationAlphaAndShadow(-1),wasLoadShaderProgramCalled(false) {}
~SdfShaderProgram() {destroy();}
void destroy() {
if (program) {glDeleteProgram(program);program=0;}
wasLoadShaderProgramCalled=false;
uniformLocationOrthoMatrix=uniformLocationSampler=
uniformLocationOffsetAndScale=uniformLocationAlphaAndShadow=-1;
}
bool loadShaderProgram(bool forOutlineShaderProgram) {
if (program) return true;
wasLoadShaderProgramCalled = true;
program = CompileShaderProgramAndSetCorrectAttributeLocations(forOutlineShaderProgram);
if (program) {
uniformLocationOrthoMatrix = glGetUniformLocation(program,"ortho");
uniformLocationSampler = glGetUniformLocation(program,"Texture");
uniformLocationOffsetAndScale = glGetUniformLocation(program,"offsetAndScale");
uniformLocationAlphaAndShadow = glGetUniformLocation(program,"alphaAndShadow");
SDF_ASSERT(uniformLocationOrthoMatrix!=-1);
SDF_ASSERT(uniformLocationSampler!=-1);
SDF_ASSERT(uniformLocationOffsetAndScale!=-1);
SDF_ASSERT(uniformLocationAlphaAndShadow!=-1);
glUseProgram(program);
resetUniforms();
glUseProgram(0);
}
return program!=0;
}
void resetUniforms() {
resetUniformOrtho(800,450);
glUniform1i(uniformLocationSampler, 0);
setUniformOffsetAndScale();
setUniformAlphaAndShadow();
}
inline void setUniformOffsetAndScale(const SdfVec2& offset=SdfVec2(0,0),const SdfVec2& scale=SdfVec2(1,1)) {
glUniform4f(uniformLocationOffsetAndScale,offset.x,offset.y,scale.x,scale.y);
}
// Shadow must be < 1 only in the "shadow pass"
inline void setUniformAlphaAndShadow(const float alpha=1.f,const float shadow=1.f) {
glUniform2f(uniformLocationAlphaAndShadow,alpha,shadow);
}
void resetUniformOrtho(float displaySizeWidth=-1,float displaySizeHeight=-1) {
if (displaySizeWidth<=0) displaySizeWidth=gSdfDisplaySize.x;
if (displaySizeHeight<=0) displaySizeHeight=gSdfDisplaySize.y;
const float ortho[4][4] = {
{ 2.0f/displaySizeWidth, 0.0f, 0.0f, 0.0f },
{ 0.0f, 2.0f/-displaySizeHeight, 0.0f, 0.0f },
{ 0.0f, 0.0f, -1.0f, 0.0f },
{-1.0f, 1.0f, 0.0f, 1.0f },
};
glUniformMatrix4fv(uniformLocationOrthoMatrix, 1, GL_FALSE, &ortho[0][0]);
}
static const char** GetVertexShaderCodeForBothFonts() {
static const char* gVertexShaderSource[] = {
# ifdef SDFIMPL_SHADER_GL3
# if (defined(SDFIMPL_SHADER_GLES) || defined(__EMSCRIPTEN__))
"#version 300 es\n"
# else //SDFIMPL_SHADER_GLES
"#version 330\n"
# endif //SDFIMPL_SHADER_GLES
"precision highp float;\n"
"uniform mat4 ortho;\n"
"uniform vec4 offsetAndScale;\n"
"layout (location = 0 ) in vec2 Position;\n"
"layout (location = 1 ) in vec2 UV;\n"
"layout (location = 2 ) in vec4 Colour;\n"
"out vec2 Frag_UV;\n"
"out vec4 Frag_Colour;\n"
# else //!SDFIMPL_SHADER_GL3
# if (defined(SDFIMPL_SHADER_GLES) || defined(__EMSCRIPTEN__))
"#version 100\n"
"precision highp float;\n"
# endif //SDFIMPL_SHADER_GLES
"uniform mat4 ortho;\n"
"uniform vec4 offsetAndScale;\n"
"attribute vec2 Position;\n"
"attribute vec2 UV;\n"
"attribute vec4 Colour;\n"
"varying vec2 Frag_UV;\n"
"varying vec4 Frag_Colour;\n"
# endif //!SDFIMPL_SHADER_GL3
"void main()\n"
"{\n"
" Frag_UV = UV;\n"
" Frag_Colour = Colour;\n"
"\n"
" gl_Position = ortho*vec4(offsetAndScale.x+Position.x*offsetAndScale.z,offsetAndScale.y+Position.y*offsetAndScale.w,0,1);\n"
"}\n"
};
return &gVertexShaderSource[0];
}
static const char** GetFragmentShaderCodeForRegularFont() {
static const char* gFragmentShaderSource[] = {
# ifdef SDFIMPL_SHADER_GL3
# if (defined(SDFIMPL_SHADER_GLES) || defined(__EMSCRIPTEN__))
"#version 300 es\n"
# else //SDFIMPL_SHADER_GLES
"#version 330\n"
# endif //SDFIMPL_SHADER_GLES
"precision mediump float;\n"
"uniform lowp sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Colour;\n"
"out vec4 FragColor;\n"
# else //!SDFIMPL_SHADER_GL3
# if (defined(SDFIMPL_SHADER_GLES) || defined(__EMSCRIPTEN__))
"#version 100\n"
"#extension GL_OES_standard_derivatives : enable\n" // fwidth
"precision mediump float;\n"
# endif //SDFIMPL_SHADER_GLES
"uniform sampler2D Texture;\n"
"varying vec2 Frag_UV;\n"
"varying vec4 Frag_Colour;\n"
# endif //SDFIMPL_SHADER_GL3
"uniform vec2 alphaAndShadow;\n"
# ifdef SDFIMP_MSDF_MODE // never tested
"float median(float r, float g, float b) {\n"
" return max(min(r, g), min(max(r, g), b));\n"
"}\n"
# endif //SDFIMP_MSDF_MODE
"void main(void) {\n"
# ifndef SDFIMP_MSDF_MODE
"float dist = texture2D(Texture, Frag_UV.st).a; // retrieve distance from texture\n"
# else //SDFIMP_MSDF_MODE // never tested
"vec3 dist3 = texture2D(Texture, Frag_UV.st).rgb; // retrieve distance from texture\n"
"float dist = median(dist3.r, dist3.g, dist3.b);// - 0.5;\n"
# endif //SDFIMP_MSDF_MODE
# ifdef SDFIMP_SLOWER_SHADER
"float width = 0.7 * length(float2(dfdx(dist), dfdy(dist)));"
# else //SDFIMP_SLOWER_SHADER
"float width = fwidth(dist);"
# endif //SDFIMP_SLOWER_SHADER
"\n"
"float alphaThreshold = 0.5;\n"
"\n"
"vec3 fragcolor = Frag_Colour.rgb;\n"
"float alpha = smoothstep(alphaThreshold - width, alphaThreshold + width, dist);\n"
"\n"
# ifdef SDFIMPL_SHADER_GL3
"FragColor = vec4(fragcolor,alpha*Frag_Colour.a);\n"
# else //SDFIMPL_SHADER_GL3
"gl_FragColor = vec4(fragcolor*alphaAndShadow.y,alpha*alphaAndShadow.x*Frag_Colour.a);\n"
# endif //SDFIMPL_SHADER_GL3
"}\n"
};
return &gFragmentShaderSource[0];
}
static const char** GetFragmentShaderCodeForOutlineFont() {
static const char* gFragmentShaderSource[] = {
# ifdef SDFIMPL_SHADER_GL3
# if (defined(SDFIMPL_SHADER_GLES) || defined(__EMSCRIPTEN__))
"#version 300 es\n"
# else //SDFIMPL_SHADER_GLES
"#version 330\n"
# endif //SDFIMPL_SHADER_GLES
"precision mediump float;\n"
"uniform lowp sampler2D Texture;\n"
"in vec2 Frag_UV;\n"
"in vec4 Frag_Colour;\n"
"out vec4 FragColor;\n"
# else //!SDFIMPL_SHADER_GL3
# if (defined(SDFIMPL_SHADER_GLES) || defined(__EMSCRIPTEN__))
"#version 100\n"
"#extension GL_OES_standard_derivatives : enable\n" // fwidth
"precision mediump float;\n"
# endif //SDFIMPL_SHADER_GLES
"uniform sampler2D Texture;\n"
"varying vec2 Frag_UV;\n"
"varying vec4 Frag_Colour;\n"
# endif //SDFIMPL_SHADER_GL3
"uniform vec2 alphaAndShadow;\n"
# ifdef SDFIMP_MSDF_MODE // never tested
"float median(float r, float g, float b) {\n"
" return max(min(r, g), min(max(r, g), b));\n"
"}\n"
# endif //SDFIMP_MSDF_MODE
"void main(void) {\n"