-
Notifications
You must be signed in to change notification settings - Fork 5
/
daisy.hh
1521 lines (1261 loc) · 56.7 KB
/
daisy.hh
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
// daisy - a simple, tiny, very fast, well-documented, Windows only, header-only library for 2D primitive and text rendering using D3D9 & GDI, written in C++17
// - written by munteanu octavian-adrian (https://github.com/sse2/daisy)
// - MIT license (see end of file or github repo LICENSE.txt if you're unfamiliar with it)
#ifndef _SSE2_DAISY_INCLUDE_GUARD
#define _SSE2_DAISY_INCLUDE_GUARD
// you can replace this with your own includes if you don't want to use the standard library,
// however you'll need to provide your own implementations for the stl containers and they need to be at least mostly compatible with the ones provided by the standard library
#ifndef DAISY_NO_STL
// stl includes
#include <unordered_map> // std::unordered_map
#include <string_view> // std::string_view
#include <vector> // std::vector
#include <array> // std::array
#include <atomic> // std::atomic
#include <memory> // std::unique_ptr, std::make_unique
#include <cstdint> // uint/int types, fabsf, fmodf
namespace stl = std;
#endif // DAISY_NO_STL
// d3d9
#include <d3d9.h>
namespace daisy
{
// our color struct
struct color_t
{
union {
struct
{
uint8_t b, g, r, a;
} chan;
uint32_t bgra;
};
constexpr color_t ( uint8_t _r = 255, uint8_t _g = 255, uint8_t _b = 255, uint8_t _a = 255 ) noexcept
: chan ( { _b, _g, _r, _a } )
{
}
/// <summary>
/// returns a new color based on hue, saturation and variance values
/// </summary>
/// <param name="hue">float between [0, 360] which represents hue of color</param>
/// <param name="saturation">float between [0, 1] which represents percentage of saturation, where 0 means desaturated (black and white) and 1 means saturated</param>
/// <param name="variance">float between [0, 1] which represents percentage of variance, where 0 means black and 1 means "colored"</param>
/// <returns></returns>
static color_t from_hsv ( float hue, float saturation, float variance )
{
color_t ret;
float C = saturation * variance;
float X = C * ( 1 - fabsf ( fmodf ( hue / 60.f, 2 ) - 1 ) );
float m = variance - C;
float r, g, b;
if ( hue >= 0.f && hue < 60.f )
{
r = C, g = X, b = 0.f;
}
else if ( hue >= 60.f && hue < 120.f )
{
r = X, g = C, b = 0.f;
}
else if ( hue >= 120.f && hue < 180 )
{
r = 0.f, g = C, b = X;
}
else if ( hue >= 180.f && hue < 240.f )
{
r = 0.f, g = X, b = C;
}
else if ( hue >= 240.f && hue < 300.f )
{
r = X, g = 0.f, b = C;
}
else
{
r = C, g = 0.f, b = X;
}
ret.chan.r = static_cast< unsigned char > ( ( r + m ) * 255 );
ret.chan.g = static_cast< unsigned char > ( ( g + m ) * 255 );
ret.chan.b = static_cast< unsigned char > ( ( b + m ) * 255 );
ret.chan.a = 255;
return ret;
}
};
// our vertex struct
struct daisy_vtx_t
{
float m_pos[ 4 ]; // x,y,z,rhw
D3DCOLOR m_col;
float m_uv[ 2 ];
};
// buffer
struct renderbuffer_t
{
stl::unique_ptr< uint8_t[] > m_data { nullptr };
uint32_t m_capacity { 0 }, m_size { 0 };
};
// kind of calls submitted
enum class daisy_call_kind : uint8_t
{
CALL_TRI = 0,
CALL_VTXSHADER,
CALL_PIXSHADER,
CALL_SCISSOR
};
// used for text calls
enum daisy_text_align : uint16_t
{
TEXT_ALIGN_DEFAULT = 0,
TEXT_ALIGNX_LEFT = 1 << 0,
TEXT_ALIGNX_CENTER = 1 << 1,
TEXT_ALIGNX_RIGHT = 1 << 2,
TEXT_ALIGNY_TOP = 1 << 3,
TEXT_ALIGNY_CENTER = 1 << 4,
TEXT_ALIGNY_BOTTOM = 1 << 5,
};
// flags for font ctor
enum daisy_font_flags : uint8_t
{
FONT_DEFAULT = 0,
FONT_BOLD = 1 << 0,
FONT_ITALIC = 1 << 1
};
using uv_t = stl::array< float, 4 >;
struct point_t
{
float x, y;
};
struct daisy_drawcall_t
{
daisy_call_kind m_kind;
union {
// for CALL_TRI
struct
{
IDirect3DTexture9 *m_texture_handle;
uint32_t m_primitives, m_vertices, m_indices;
} m_tri;
// for shader pop/push calls
struct
{
void *m_shader_handle;
} m_shader;
// for scissor pop/push calls
struct
{
point_t m_position, m_size;
} m_scissor;
};
};
// this is the only global object. we need this because the alternative would be passing around the pointer to each texture atlas and font wrapper instance
// we don't really *need* it but it makes the code more readable
struct daisy_t
{
static inline IDirect3DDevice9 *s_device = nullptr;
};
class c_daisy_resettable_object
{
public:
/// <summary>
/// called on device reset (pre/post)
/// </summary>
/// <param name="pre_reset">if this is called before device is reset</param>
/// <returns>true on success, false otherwise</returns>
virtual bool reset ( bool pre_reset = false ) noexcept = 0;
};
// our font wrapper class
class c_fontwrapper : public c_daisy_resettable_object
{
private:
// members
stl::unordered_map< wchar_t, uv_t > m_coords;
stl::string_view m_family;
IDirect3DTexture9 *m_texture_handle;
float m_scale;
uint32_t m_width, m_height, m_spacing, m_size, m_quality;
uint8_t m_flags;
private:
// methods
/// <summary>
/// actually creates font instance and atlas
/// </summary>
/// <returns>true on succesful font creation, false otherwise</returns>
bool create_ex ( ) noexcept
{
if ( !daisy_t::s_device )
return false;
HDC gdi_ctx = nullptr;
HGDIOBJ gdi_font = nullptr, prev_gdi_font = nullptr, prev_bitmap = nullptr;
HBITMAP bitmap = nullptr;
// function could be possibly called by reset handler
if ( this->m_texture_handle )
this->m_texture_handle->Release ( );
// create GDI context
gdi_ctx = CreateCompatibleDC ( nullptr );
SetMapMode ( gdi_ctx, MM_TEXT );
// create GDI font
this->create_gdi_font ( gdi_ctx, &gdi_font );
prev_gdi_font = SelectObject ( gdi_ctx, gdi_font );
// set default atlas size
this->m_width = this->m_height = 128;
// ensure our atlas is big enough
while ( this->paint_or_measure_alphabet ( gdi_ctx, true ) == 2 )
{
this->m_width *= 2;
this->m_height *= 2;
}
D3DCAPS9 caps { };
HRESULT res = daisy_t::s_device->GetDeviceCaps ( &caps );
if ( res != D3D_OK )
return false;
// ensure our atlas isn't above max texture cap
// @todo; use texatlas
if ( this->m_width > static_cast< uint32_t > ( caps.MaxTextureWidth ) )
{
this->m_scale = static_cast< float > ( caps.MaxTextureWidth ) / this->m_width;
this->m_width = this->m_height = caps.MaxTextureWidth;
bool first_iteration = true;
do
{
if ( !first_iteration )
this->m_scale *= 0.9f;
DeleteObject ( SelectObject ( gdi_ctx, prev_gdi_font ) );
this->create_gdi_font ( gdi_ctx, &gdi_font );
prev_gdi_font = SelectObject ( gdi_ctx, gdi_font );
first_iteration = false;
} while ( this->paint_or_measure_alphabet ( gdi_ctx, true ) == 2 );
}
// create dx9 tex
res = daisy_t::s_device->CreateTexture ( this->m_width, this->m_height, 1, D3DUSAGE_DYNAMIC, D3DFMT_A4R4G4B4, D3DPOOL_DEFAULT, &this->m_texture_handle, nullptr );
if ( res != D3D_OK || !this->m_texture_handle )
return false;
DWORD *bitmap_bits = nullptr;
BITMAPINFO bitmap_ctx { };
bitmap_ctx.bmiHeader.biSize = sizeof ( BITMAPINFOHEADER );
bitmap_ctx.bmiHeader.biWidth = this->m_width;
bitmap_ctx.bmiHeader.biHeight = -static_cast< int32_t > ( this->m_height );
bitmap_ctx.bmiHeader.biPlanes = 1;
bitmap_ctx.bmiHeader.biCompression = BI_RGB;
bitmap_ctx.bmiHeader.biBitCount = 32;
bitmap = CreateDIBSection ( gdi_ctx, &bitmap_ctx, DIB_RGB_COLORS, reinterpret_cast< void ** > ( &bitmap_bits ), nullptr, 0 );
if ( !bitmap )
return false;
prev_bitmap = SelectObject ( gdi_ctx, bitmap );
SetTextColor ( gdi_ctx, RGB ( 255, 255, 255 ) );
SetBkColor ( gdi_ctx, 0x00000000 );
SetTextAlign ( gdi_ctx, TA_TOP );
// to note: paint_alphabet returns 0 on success
if ( this->paint_or_measure_alphabet ( gdi_ctx, false ) )
return false;
D3DLOCKED_RECT locked_rect;
if ( this->m_texture_handle->LockRect ( 0, &locked_rect, nullptr, 0 ) != D3D_OK )
return false;
uint8_t *dst_row = static_cast< uint8_t * > ( locked_rect.pBits );
BYTE alpha;
// write to texture
for ( uint32_t y = 0; y < this->m_height; y++ )
{
uint16_t *dst = reinterpret_cast< uint16_t * > ( dst_row );
for ( uint32_t x = 0; x < this->m_width; x++ )
{
alpha = ( ( bitmap_bits[ this->m_width * y + x ] & 0xff ) >> 4 );
if ( alpha > 0 )
{
*dst++ = ( ( alpha << 12 ) | 0x0fff );
}
else
{
*dst++ = 0x0000;
}
}
dst_row += locked_rect.Pitch;
}
if ( this->m_texture_handle->UnlockRect ( 0 ) != D3D_OK )
return false;
// clean up
SelectObject ( gdi_ctx, prev_bitmap );
SelectObject ( gdi_ctx, prev_gdi_font );
DeleteObject ( bitmap );
DeleteObject ( gdi_font );
DeleteDC ( gdi_ctx );
return true;
}
/// <summary>
/// creates GDI font
/// </summary>
/// <param name="context">GDI context</param>
/// <param name="gdi_font">font GDI object</param>
void create_gdi_font ( HDC context, HGDIOBJ *gdi_font ) noexcept
{
*gdi_font = CreateFontA ( -MulDiv ( this->m_size, static_cast< int > ( GetDeviceCaps ( context, LOGPIXELSY ) * this->m_scale ), 72 ),
0, 0, 0, ( this->m_flags & daisy_font_flags::FONT_BOLD ) ? FW_BOLD : FW_NORMAL, ( this->m_flags & daisy_font_flags::FONT_ITALIC ) ? TRUE : FALSE,
FALSE, FALSE, DEFAULT_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, this->m_quality, VARIABLE_PITCH, this->m_family.data ( ) );
}
/// <summary>
/// measures or paints alphabet
/// </summary>
/// <param name="context">GDI context</param>
/// <param name="measure">if we should only measure, not paint alphabet</param>
/// <returns>0 on success, 1 on GDI error, 2 if texture atlas can't contain our glyphs</returns>
int paint_or_measure_alphabet ( HDC context, bool measure = false ) noexcept
{
SIZE size;
wchar_t chr[] = L"x\0\0";
if ( !GetTextExtentPoint32W ( context, chr, 1, &size ) )
return 1;
// thanks dex for help with this
const auto unicode_ranges_size = GetFontUnicodeRanges ( context, nullptr );
if ( !unicode_ranges_size )
return 1;
auto glyph_sets_memory = stl::make_unique< uint8_t[] > ( unicode_ranges_size );
if ( !glyph_sets_memory )
return 1;
auto glyph_sets = reinterpret_cast< GLYPHSET * > ( glyph_sets_memory.get ( ) );
if ( !GetFontUnicodeRanges ( context, glyph_sets ) )
return 1;
this->m_spacing = static_cast< uint32_t > ( ceil ( size.cy * 0.3f ) );
uint32_t x = this->m_spacing;
uint32_t y = 0;
// iterate glyph ranges
for ( uint32_t r = 0; r < glyph_sets->cRanges; ++r )
{
// iterate glyphs
for ( auto ch = glyph_sets->ranges[ r ].wcLow; ch < ( glyph_sets->ranges[ r ].wcLow + glyph_sets->ranges[ r ].cGlyphs ); ++ch )
{
// get metrics of the current character
if ( !GetTextExtentPoint32W ( context, &ch, 1, &size ) )
continue;
if ( x + size.cx + this->m_spacing > this->m_width )
{
x = this->m_spacing;
y += size.cy + 1;
}
// ran out of space in texture
if ( y + size.cy > this->m_height )
return 2;
if ( !measure )
{
if ( !ExtTextOutW ( context, x + 0, y + 0, ETO_OPAQUE, nullptr, &ch, 1, nullptr ) )
return 1;
this->m_coords[ static_cast< uint16_t > ( ch ) ][ 0 ] = ( static_cast< float > ( x + 0 - this->m_spacing ) ) / this->m_width;
this->m_coords[ static_cast< uint16_t > ( ch ) ][ 1 ] = ( static_cast< float > ( y + 0 + 0 ) ) / this->m_height;
this->m_coords[ static_cast< uint16_t > ( ch ) ][ 2 ] = ( static_cast< float > ( x + size.cx + this->m_spacing ) ) / this->m_width;
this->m_coords[ static_cast< uint16_t > ( ch ) ][ 3 ] = ( static_cast< float > ( y + size.cy + 0 ) ) / this->m_height;
}
x += size.cx + ( 2 * this->m_spacing );
}
}
return 0;
}
public:
// inits everything with 0
c_fontwrapper ( ) noexcept
: m_family ( ), m_texture_handle ( nullptr ), m_scale ( 0.f ), m_width ( 0 ), m_height ( 0 ), m_spacing ( 0 ), m_size ( 0 ), m_quality ( NONANTIALIASED_QUALITY ), m_flags ( 0 )
{
}
// disallow copying
c_fontwrapper ( const c_fontwrapper & ) = delete;
c_fontwrapper &operator= ( const c_fontwrapper & ) = delete;
/// <summary>
/// creates font instance and atlas
/// </summary>
/// <param name="family">font family name, for example "Arial" (to note; fonts added by AddFontMemResourceEx also work)</param>
/// <param name="height">font height</param>
/// <param name="quality">font quality (NONANTIALIASED_QUALITY, CLEARTYPE_NATURAL_QUALITY etc.)</param>
/// <param name="flags">font flags (see enum daisy_font_flags; FONT_DEFAULT, FONT_BOLD, FONT_ITALIC)</param>
/// <returns>true on succesful font creation, false otherwise</returns>
[[nodiscard]] bool create ( const stl::string_view family, uint32_t height, uint32_t quality, uint8_t flags ) noexcept
{
this->m_family = family;
this->m_size = height;
this->m_flags = flags;
this->m_quality = quality;
this->m_scale = 1.f;
this->m_spacing = 0;
return this->create_ex ( );
}
/// <summary>
/// returns measured text extent in pixels
/// </summary>
/// <typeparam name="t">iteratable text container (only char and wchar_t accepted currently)</typeparam>
/// <param name="text">text to measure</param>
/// <returns>point_t containing width and height of measured text</returns>
template < typename t = stl::string_view >
point_t text_extent ( t text ) noexcept
{
float row_width = 0.f;
float row_height = ( this->m_coords[ static_cast< wchar_t > ( 32 ) ][ 3 ] - this->m_coords[ static_cast< wchar_t > ( 32 ) ][ 1 ] ) * this->m_height;
float width = 0.f;
float height = row_height;
for ( const auto c : text )
{
if ( c == '\n' )
{
row_width = 0.f;
height += row_height;
}
if ( c < ' ' )
continue;
float tx1 = this->m_coords[ static_cast< wchar_t > ( c ) ][ 0 ];
float tx2 = this->m_coords[ static_cast< wchar_t > ( c ) ][ 2 ];
row_width += ( tx2 - tx1 ) * this->m_width - 2.f * this->m_spacing;
if ( row_width > width )
width = row_width;
}
return { width, height };
}
/// <summary>
/// called on device reset (pre/post)
/// </summary>
/// <param name="pre_reset">if this is called before device is reset</param>
/// <returns>true on success, false otherwise</returns>
[[nodiscard]] virtual bool reset ( bool pre_reset = false ) noexcept override
{
if ( !pre_reset )
return this->create_ex ( );
else if ( this->m_texture_handle )
this->m_texture_handle->Release ( );
return true;
}
/// <summary>
/// erases the font
/// </summary>
void erase ( ) noexcept
{
if ( this->m_texture_handle )
this->m_texture_handle->Release ( );
this->m_coords.clear ( );
this->m_size = this->m_spacing = this->m_flags = 0;
this->m_scale = 1.f;
this->m_family = "";
}
// getters
/// <summary>
/// get UV coordinates of glyph
/// </summary>
/// <typeparam name="t">char, wchar_t</typeparam>
/// <param name="glyph">character to get glyph UV coordinates for</param>
/// <returns>UV coordinates of glyph</returns>
template < typename t = char >
const uv_t &coords ( t glyph ) const noexcept
{
if ( this->m_coords.find ( glyph ) != this->m_coords.end ( ) )
return this->m_coords.at ( glyph );
static uv_t null_uv { 0.f, 0.f, 0.f, 0.f };
return null_uv;
}
/// <summary>
/// get font spacing
/// </summary>
/// <returns>font spacing</returns>
uint32_t spacing ( ) const noexcept
{
return this->m_spacing;
}
/// <summary>
/// get font width
/// </summary>
/// <returns>font width</returns>
uint32_t width ( ) const noexcept
{
return this->m_width;
}
/// <summary>
/// get font height
/// </summary>
/// <returns>font height</returns>
uint32_t height ( ) const noexcept
{
return this->m_height;
}
/// <summary>
/// get font scale
/// </summary>
/// <returns>font scale</returns>
float scale ( ) const noexcept
{
return this->m_scale;
}
/// <summary>
/// get texture handle
/// </summary>
/// <returns>texture handle</returns>
IDirect3DTexture9 *texture_handle ( ) const noexcept
{
return this->m_texture_handle;
}
};
class c_texatlas : public c_daisy_resettable_object
{
private:
stl::unordered_map< uint32_t, uv_t > m_coords;
point_t m_cursor, m_dimensions;
IDirect3DTexture9 *m_texture_handle;
float m_max_height;
public:
c_texatlas ( ) noexcept
: m_cursor ( { 0.f, 0.f } ), m_dimensions ( { 0.f, 0.f } ), m_texture_handle ( nullptr ), m_max_height ( 0.f )
{
}
// disable copying
c_texatlas ( const c_texatlas & ) = delete;
c_texatlas &operator= ( const c_texatlas & ) = delete;
/// <summary>
/// creates a texture atlas
/// </summary>
/// <param name="dimensions">texture atlas dimensions</param>
/// <returns>true on success, false otherwise</returns>
[[nodiscard]] bool create ( const point_t &dimensions ) noexcept
{
if ( !daisy_t::s_device )
return false;
this->m_dimensions = dimensions;
this->m_cursor = point_t { 0.f, 0.f };
this->m_max_height = 0.f;
if ( daisy_t::s_device->CreateTexture ( static_cast< UINT > ( dimensions.x ), static_cast< UINT > ( dimensions.y ), 1, D3DUSAGE_DYNAMIC, D3DFMT_A8R8G8B8, D3DPOOL_DEFAULT, &this->m_texture_handle, nullptr ) != D3D_OK )
return false;
return true;
}
/// <summary>
/// called on device reset (pre/post)
/// </summary>
/// <param name="pre_reset">if this is called before device is reset</param>
/// <returns>true on success, false otherwise</returns>
[[nodiscard]] virtual bool reset ( bool pre_reset = false ) noexcept override
{
if ( !pre_reset )
return this->create ( this->m_dimensions );
else if ( this->m_texture_handle )
this->m_texture_handle->Release ( );
return true;
}
/// <summary>
/// appends a texture to the texture atlas
/// </summary>
/// <param name="uuid">uuid of texture (can be whatever you want as long as it's unique per texture)</param>
/// <param name="dimensions">dimensions of texture in pixels</param>
/// <param name="tex_data">A8R8G8B8 texture data</param>
/// <param name="tex_size">size of texture data in bytes</param>
/// <returns>true on success, false otherwise</returns>
bool append ( const uint32_t uuid, const point_t &dimensions, uint8_t *tex_data, uint32_t tex_size ) noexcept
{
if ( !tex_data || !tex_size )
return false;
// go down if not enough space left
if ( this->m_cursor.x + dimensions.x > this->m_dimensions.x )
{
this->m_cursor.y += this->m_max_height;
this->m_cursor.x = this->m_max_height = 0.f;
}
// not enough space left
if ( this->m_cursor.y + dimensions.y > this->m_dimensions.y )
return false;
// ensure we set max height
if ( this->m_max_height < dimensions.y )
this->m_max_height = dimensions.y;
// lock tex
D3DLOCKED_RECT tex_locked_rect;
if ( this->m_texture_handle->LockRect ( 0, &tex_locked_rect, NULL, 0 ) != D3D_OK )
return false;
// copy tex data over
for ( int y = 0; y < dimensions.y; ++y )
{
for ( int x = 0; x < dimensions.x; ++x )
{
const uint8_t *source_pixel = tex_data + static_cast< uint32_t > ( dimensions.x ) * 4 * y + x * 4;
// ensure the texture size matches what we expect
if ( static_cast< uint32_t > ( dimensions.x ) * 4 * y + x * 4 > tex_size )
return false;
uint8_t *destination_pixel = static_cast< uint8_t * > ( tex_locked_rect.pBits ) + tex_locked_rect.Pitch * ( static_cast< uint32_t > ( this->m_cursor.y ) + y ) + ( static_cast< uint32_t > ( this->m_cursor.x ) + x ) * 4;
destination_pixel[ 0 ] = source_pixel[ 2 ];
destination_pixel[ 1 ] = source_pixel[ 1 ];
destination_pixel[ 2 ] = source_pixel[ 0 ];
destination_pixel[ 3 ] = source_pixel[ 3 ];
}
}
this->m_texture_handle->UnlockRect ( 0 );
// set uv mins/maxs
auto start_uv = point_t { this->m_cursor.x / this->m_dimensions.x, this->m_cursor.y / this->m_dimensions.y };
auto end_uv = point_t { start_uv.x + dimensions.x / this->m_dimensions.x, start_uv.y + dimensions.y / this->m_dimensions.y };
this->m_coords[ uuid ] = uv_t { start_uv.x, start_uv.y, end_uv.x, end_uv.y };
// move cursor over
this->m_cursor.x += dimensions.x;
return true;
}
/// <summary>
/// get UV coordinates of texture
/// </summary>
/// <param name="glyph">character to get texture UV coordinates for</param>
/// <returns>UV coordinates of texture</returns>
const uv_t &coords ( uint32_t uuid ) const noexcept
{
if ( this->m_coords.find ( uuid ) != this->m_coords.end ( ) )
return this->m_coords.at ( uuid );
static uv_t null_uv { 0.f, 0.f, 0.f, 0.f };
return null_uv;
}
/// <summary>
/// get texture handle
/// </summary>
/// <returns>texture handle</returns>
IDirect3DTexture9 *texture_handle ( ) const noexcept
{
return this->m_texture_handle;
}
};
class c_renderqueue : public c_daisy_resettable_object
{
private:
IDirect3DVertexBuffer9 *m_vertex_buffer;
IDirect3DIndexBuffer9 *m_index_buffer;
renderbuffer_t m_vtxs, m_idxs;
stl::vector< daisy_drawcall_t > m_drawcalls;
// update d3d9 sided vtx/idx buffers
bool m_update;
// reallocate d3d9 buffers
bool m_realloc_vtx, m_realloc_idx;
private:
/// <summary>
/// ensures buffers have enough capacity for the draw call
/// </summary>
/// <param name="vertices_to_add">vertices to be added to buffer</param>
/// <param name="indices_to_add">indices to be added to buffer</param>
void ensure_buffers_capacity ( const uint32_t vertices_to_add, const uint32_t indices_to_add ) noexcept
{
// check vtxbuf
if ( this->m_vtxs.m_size + vertices_to_add > this->m_vtxs.m_capacity )
{
// set new capacity
while ( this->m_vtxs.m_size + vertices_to_add > this->m_vtxs.m_capacity )
this->m_vtxs.m_capacity = this->m_vtxs.m_capacity * 2;
// create new vertex buf
auto new_vtx = stl::make_unique< uint8_t[] > ( this->m_vtxs.m_capacity * sizeof ( daisy_vtx_t ) );
if ( new_vtx )
{
// copy old data over
memcpy ( new_vtx.get ( ), this->m_vtxs.m_data.get ( ), this->m_vtxs.m_size * sizeof ( daisy_vtx_t ) );
// d3d9 buf needs to be reallocated on new flush (we could do this here, however this ensures we're in the d3d9 rendering thread)
this->m_realloc_vtx = true;
// replace old data
this->m_vtxs.m_data.swap ( new_vtx );
}
}
// check idxbuf
if ( this->m_idxs.m_size + indices_to_add > this->m_idxs.m_capacity )
{
// set capacity
while ( this->m_idxs.m_size + indices_to_add > this->m_idxs.m_capacity )
this->m_idxs.m_capacity = this->m_idxs.m_capacity * 2;
// create new vertex buf
auto new_idx = stl::make_unique< uint8_t[] > ( this->m_idxs.m_capacity * sizeof ( uint16_t ) );
if ( new_idx )
{
// copy old data over
memcpy ( new_idx.get ( ), this->m_idxs.m_data.get ( ), this->m_idxs.m_size * sizeof ( uint16_t ) );
// d3d9 buf needs to be reallocated on new flush (we could do this here, however this ensures we're in the d3d9 rendering thread)
this->m_realloc_idx = true;
// replace old data
this->m_idxs.m_data.swap ( new_idx );
}
}
}
/// <summary>
/// checks if call can be batched
/// </summary>
/// <param name="texture_handle">texture handle</param>
/// <returns>0 if we can't batch this call, index offset on success</returns>
uint32_t begin_batch ( IDirect3DTexture9 *texture_handle = nullptr ) const noexcept
{
uint32_t additional = 0;
// attempt to batch drawcall
if ( !this->m_drawcalls.empty ( ) )
{
auto &last_call = this->m_drawcalls.back ( );
if ( last_call.m_kind == daisy_call_kind::CALL_TRI && last_call.m_tri.m_texture_handle == texture_handle )
{
// we can batch this call
additional = last_call.m_tri.m_vertices;
}
}
return additional;
}
/// <summary>
/// appends call to batch if possible
/// </summary>
/// <param name="additional_indices">return value of begin_batch() call</param>
/// <param name="vertices">vertices in call</param>
/// <param name="indices">indices in call</param>
/// <param name="primitives">primitives in call</param>
/// <param name="texture_handle">texutre handle</param>
void end_batch ( uint32_t additional_indices, uint32_t vertices, uint32_t indices, uint32_t primitives, IDirect3DTexture9 *texture_handle = nullptr )
{
// call can't be batched
if ( !additional_indices )
{
daisy_drawcall_t d { };
d.m_kind = daisy_call_kind::CALL_TRI;
d.m_tri.m_indices = indices;
d.m_tri.m_vertices = vertices;
d.m_tri.m_texture_handle = texture_handle;
d.m_tri.m_primitives = primitives;
this->m_drawcalls.push_back ( stl::move ( d ) );
}
// call is batched
else
{
auto &last_call = this->m_drawcalls.back ( );
last_call.m_tri.m_vertices += vertices;
last_call.m_tri.m_indices += indices;
last_call.m_tri.m_primitives += primitives;
}
// need to update gpu-side buffers
this->m_update = true;
}
public:
c_renderqueue ( ) noexcept
: m_vertex_buffer ( nullptr ), m_index_buffer ( nullptr ), m_update ( true ), m_realloc_vtx ( false ), m_realloc_idx ( false )
{
}
// disallow copying
c_renderqueue ( const c_renderqueue & ) = delete;
c_renderqueue &operator= ( const c_renderqueue & ) = delete;
/// <summary>
/// initializes current queue by initializing vertex and index buffers
/// </summary>
/// <param name="max_verts">max capacity of vertex buffer</param>
/// <param name="max_indices">max capacity of index buffer</param>
/// <returns>true on success, false otherwise</returns>
[[nodiscard]] bool create ( const uint32_t max_verts = 32767, const uint32_t max_indices = 65535 ) noexcept
{
if ( !daisy_t::s_device )
return false;
// create d3d9 buffers
if ( !this->m_vertex_buffer )
if ( daisy_t::s_device->CreateVertexBuffer ( sizeof ( daisy_vtx_t ) * max_verts, D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, ( D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1 ), D3DPOOL_DEFAULT, &this->m_vertex_buffer, nullptr ) < 0 )
return false;
if ( !this->m_index_buffer )
if ( daisy_t::s_device->CreateIndexBuffer ( sizeof ( uint16_t ) * max_indices, D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, D3DPOOL_DEFAULT, &this->m_index_buffer, nullptr ) < 0 )
return false;
// create local buffers
if ( !this->m_vtxs.m_data.get ( ) )
{
this->m_vtxs.m_data = stl::make_unique< uint8_t[] > ( sizeof ( daisy_vtx_t ) * max_verts );
this->m_vtxs.m_capacity = max_verts;
this->m_vtxs.m_size = 0;
}
if ( !this->m_idxs.m_data )
{
this->m_idxs.m_data = stl::make_unique< uint8_t[] > ( sizeof ( uint16_t ) * max_indices );
this->m_idxs.m_capacity = max_indices;
this->m_idxs.m_size = 0;
}
if ( !this->m_vtxs.m_data || !this->m_idxs.m_data )
return false;
return true;
}
/// <summary>
/// wipes data from local buffers
/// </summary>
void clear ( ) noexcept
{
this->m_vtxs.m_size = 0;
this->m_idxs.m_size = 0;
if ( !this->m_drawcalls.empty ( ) )
this->m_drawcalls.clear ( );
}
/// <summary>
/// called on device reset (pre/post)
/// </summary>
/// <param name="pre_reset">if this is called before device is reset</param>
/// <returns>true on success, false otherwise</returns>
[[nodiscard]] virtual bool reset ( bool pre_reset = false ) noexcept override
{
if ( !pre_reset )
return this->create ( this->m_vtxs.m_capacity, this->m_idxs.m_capacity );
else
{
if ( this->m_vertex_buffer )
{
this->m_vertex_buffer->Release ( );
this->m_vertex_buffer = nullptr;
}
if ( this->m_index_buffer )
{
this->m_index_buffer->Release ( );
this->m_index_buffer = nullptr;
}
}
return true;
}
/// <summary>
/// copies data from local buffer to d3d9 buffers
/// </summary>
void update ( ) noexcept
{
if ( !daisy_t::s_device )
return;
// checking realloc
if ( this->m_realloc_vtx )
{
this->m_vertex_buffer->Release ( );
if ( daisy_t::s_device->CreateVertexBuffer ( static_cast< UINT > ( this->m_vtxs.m_capacity * sizeof ( daisy_vtx_t ) ), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, ( D3DFVF_XYZRHW | D3DFVF_DIFFUSE | D3DFVF_TEX1 ), D3DPOOL_DEFAULT, &this->m_vertex_buffer, nullptr ) < 0 )
return;
this->m_realloc_vtx = false;
}
if ( this->m_realloc_idx )
{
this->m_index_buffer->Release ( );
if ( daisy_t::s_device->CreateIndexBuffer ( static_cast< UINT > ( this->m_idxs.m_capacity * sizeof ( uint16_t ) ), D3DUSAGE_DYNAMIC | D3DUSAGE_WRITEONLY, D3DFMT_INDEX16, D3DPOOL_DEFAULT, &this->m_index_buffer, nullptr ) < 0 )
return;
this->m_realloc_idx = false;
}
daisy_vtx_t *vert;
uint16_t *indx;
// lock buffers
if ( this->m_vertex_buffer->Lock ( 0, static_cast< UINT > ( this->m_vtxs.m_size * sizeof ( daisy_vtx_t ) ), ( void ** ) &vert, D3DLOCK_DISCARD ) < 0 )
return;
if ( this->m_index_buffer->Lock ( 0, static_cast< UINT > ( this->m_idxs.m_size * sizeof ( uint16_t ) ), ( void ** ) &indx, D3DLOCK_DISCARD ) < 0 )
{
this->m_vertex_buffer->Unlock ( );
return;
}
// we can just memcpy these
memcpy ( vert, this->m_vtxs.m_data.get ( ), sizeof ( daisy_vtx_t ) * this->m_vtxs.m_size );
memcpy ( indx, this->m_idxs.m_data.get ( ), sizeof ( uint16_t ) * this->m_idxs.m_size );
// unlock and ret
this->m_vertex_buffer->Unlock ( );
this->m_index_buffer->Unlock ( );
// we no longer need to update
this->m_update = false;
}
/// <summary>
/// flushes vertices and indices to d3d9 buffer if an update is required and actually draws primitives