-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathpx_render.h
executable file
·2268 lines (1993 loc) · 75.5 KB
/
px_render.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
/* -----------------------------------------------------------------------------
Copyright (c) 2018 Jose L. Hidalgo (PpluX)
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.
----------------------------------------------------------------------------- */
// USAGE
//
// In *ONE* C++ file you need to declare
// #define PX_RENDER_IMPLEMENTATION
// before including the file that contains px_render.h
#ifndef PX_RENDER
#define PX_RENDER
#include <stdint.h>
// -- Uniforms ---------------------------------------------------------------
//
// Automatic uniforms:
// mat4 u_model
// mat3 u_normal --> computed as the 3x3 Inverse Transpose of u_model
// mat4 u_view
// mat4 u_projection
// mat4 u_modelView
// mat4 u_modelViewProjection
// mat4 u_viewProjection
// Inverses:
// mat4 u_invModel
// mat4 u_invView
// mat4 u_invProjection
// mat4 u_invModelView
// mat4 u_invModelViewProjection
// mat4 u_invViewProjection
//
// For simplicity user uniform data will be an array of vec4
// defined as:
// vec4 u_data[num]
//
// Samplers:
// u_tex0
// u_tex1
// ...
// u_texN (N = kMaxTextureUnits)
namespace px_render {
struct RenderContext;
union Vec2 {
struct {
float x,y;
} v;
struct {
float r,g;
} c;
float f[2];
};
union Vec3 {
struct {
float x,y,z;
} v;
struct {
float r,g,b;
} c;
float f[3];
};
union Vec4 {
struct {
float x,y,z,w;
} v;
struct {
float r,g,b,a;
} c;
float f[4];
};
union Mat4 {
struct {
float m11,m21,m31,m41;
float m12,m22,m32,m42;
float m13,m23,m33,m43;
float m14,m24,m34,m44;
} m;
Vec4 column[4];
float f[16];
static Mat4 Identity() {
return Mat4 {
1.0f, 0.0f, 0.0f, 0.0f,
0.0f, 1.0f, 0.0f, 0.0f,
0.0f, 0.0f, 1.0f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f,
};
}
static Mat4 Mult(const Mat4 &a, const Mat4 &b);
static Vec4 Mult(const Mat4 &a, const Vec4 &b);
static Mat4 Inverse(const Mat4&);
static Mat4 Transpose(const Mat4&);
// Retunrs a Transformation Matrix computed as Scale, then a Rotation, finally a Translation
// note, scale x,y,z = axis, w = angle (in radians)
static Mat4 SRT(const Vec3 &scale, const Vec4 &rotate_axis_angle, const Vec3 &translate);
};
static const size_t kMaxVertexAttribs = 16;
static const size_t kMaxTextureUnits = 16;
struct Usage {
enum Enum {
Static,
Dynamic,
Stream,
};
};
struct BufferType {
enum Enum {
Invalid = 0,
Vertex,
Index,
};
};
struct TextureType {
enum Enum {
Invalid = 0,
T1D,
T2D,
T3D,
CubeMap,
};
};
struct TexelsFormat {
enum Enum {
None = 0,
R_U8,
RG_U8,
RGB_U8,
RGBA_U8,
Depth_U16,
DepthStencil_U16,
Depth_U24,
DepthStencil_U24,
};
};
struct SamplerWrapping {
enum Enum {
Repeat,
MirroredRepeat,
Clamp,
};
};
struct SamplerFiltering {
enum Enum {
Nearest,
Linear,
NearestMipmapNearest,
NearestMipmapLinear,
LinearMipmapNearest,
LinearMipmapLinear,
};
};
struct Primitive {
enum Enum {
Lines,
Triangles,
Points,
};
};
struct Cull {
enum Enum {
Disabled,
Front,
Back,
};
};
struct BlendFactor {
enum Enum {
Zero,
One,
SrcColor,
OneMinusSrcColor,
SrcAlpha,
OneMinusSrcAlpha,
DstColor,
OneMinusDstColor,
DstAlpha,
OneMinusDstAlpha,
SrcAlphaSaturated,
BlendColor,
OneMinusBlendColor,
BlendAlpha,
OneMinusBlendAlpha,
};
};
struct BlendOp {
enum Enum {
Add,
Substract,
ReverseSubstract,
Min,
Max
};
};
struct CompareFunc {
enum Enum {
Disabled,
Never,
Less,
LessEqual,
Equal,
NotEqual,
GreaterEqual,
Greater,
Always,
};
};
struct VertexFormat {
enum Enum {
//-------------------------------
Undefined = 0,
Float = 0x1,
Int8 = 0x2,
UInt8 = 0x3,
Int16 = 0x4,
UInt16 = 0x5,
Int32 = 0x6,
UInt32 = 0x7,
//-------------------------------
NumComponents1 = 0x10,
NumComponents2 = 0x20,
NumComponents3 = 0x30,
NumComponents4 = 0x40,
//-------------------------------
Normalized = 0x100,
//-------------------------------
Float1 = Float | NumComponents1,
Float2 = Float | NumComponents2,
Float3 = Float | NumComponents3,
Float4 = Float | NumComponents4,
//-------------------------------
TypeMask = 0xF,
TypeShift = 0,
NumComponentsMask = 0xF0,
NumComponentsShift = 4,
FlagsMask = 0xF00,
FlagsShift = 8,
};
};
struct VertexStep {
enum Enum {
PerVertex,
PerInstance,
};
};
struct VertexDeclaration {
// name is not needed if you are using attribute layout qualifiers
const char *name = nullptr;
uint32_t format = 0;
uint32_t buffer_index = 0;
VertexStep::Enum vertex_step = VertexStep::PerVertex;
// offset & stride = 0 will be computed once the whole pipeline is set
// normally you should not try to manipulate them.
uint32_t offset = 0;
uint32_t stride = 0;
};
struct IndexFormat {
enum Enum {
UInt8,
UInt16,
UInt32,
};
};
struct GPUResource {
struct Type {
enum Enum {
Invalid,
Texture,
Buffer,
Pipeline,
Framebuffer,
};
};
RenderContext* ctx;
uint32_t id;
Type::Enum type;
};
struct Texture : public GPUResource {
Texture(RenderContext* ctx = nullptr, uint32_t id = 0) : GPUResource{ctx, id, Type::Texture} {}
struct Info {
uint16_t width = 1;
uint16_t height = 1;
uint16_t depth = 1;
SamplerFiltering::Enum minification_filter = SamplerFiltering::Linear;
SamplerFiltering::Enum magnification_filter = SamplerFiltering::Linear;
SamplerWrapping::Enum wrapping[3] = { SamplerWrapping::Repeat, SamplerWrapping::Repeat, SamplerWrapping::Repeat };
TexelsFormat::Enum format = TexelsFormat::None;
Usage::Enum usage = Usage::Static;
TextureType::Enum type = TextureType::T2D;
};
};
struct Buffer : public GPUResource {
Buffer(RenderContext *ctx = nullptr, uint32_t id = 0) : GPUResource{ctx, id, Type::Buffer} {}
struct Info {
BufferType::Enum type = BufferType::Invalid;
uint32_t size = 0; // size in bytes
Usage::Enum usage = Usage::Static;
};
};
struct Framebuffer : public GPUResource {
Framebuffer(RenderContext *ctx = nullptr, uint32_t id = 0) : GPUResource{ctx, id, Type::Framebuffer} {}
struct Info {
Texture::Info color_texture_info;
Texture::Info depth_stencil_texture_info;
uint16_t num_color_textures = 1;
};
Texture color_texture(uint16_t index = 0) const;
Texture depth_stencil_texture() const;
};
struct Pipeline : public GPUResource {
Pipeline(RenderContext *ctx = nullptr, uint32_t id = 0) : GPUResource{ctx, id, Type::Pipeline} {}
struct Info {
struct {
const char* vertex;
const char* fragment;
} shader = {};
uint32_t uniform_size = 0; // this must be multiple of sizeof(vec4)
VertexDeclaration attribs[kMaxVertexAttribs] = {};
TextureType::Enum textures[kMaxTextureUnits] = {};
Primitive::Enum primitive = Primitive::Triangles;
Cull::Enum cull = Cull::Back;
struct {
BlendFactor::Enum src_rgb = BlendFactor::SrcAlpha;
BlendFactor::Enum dst_rgb = BlendFactor::OneMinusSrcAlpha;
BlendOp::Enum op_rgb = BlendOp::Add;
BlendFactor::Enum src_alpha = BlendFactor::SrcAlpha;
BlendFactor::Enum dst_alpha = BlendFactor::OneMinusSrcAlpha;
BlendOp::Enum op_alpha = BlendOp::Add;
Vec4 color = {0.0f, 0.0f, 0.0f, 0.0f};
bool enabled = false;
} blend;
CompareFunc::Enum depth_func = CompareFunc::Less;
bool rgba_write = true;
bool depth_write = true;
};
};
struct DisplayList {
DisplayList();
~DisplayList();
DisplayList(const DisplayList &d) = delete;
DisplayList(DisplayList &&d) {
data_ = d.data_;
d.data_ = nullptr;
}
DisplayList& operator=(const DisplayList&) = delete;
DisplayList& operator=(DisplayList &&d) {
data_ = d.data_;
d.data_ = nullptr;
}
// Helper macro to define properties... yeah, ugly but
// convenient.
#define PROP(type, name, ...) \
type name = __VA_ARGS__;\
Self& set_##name(const type &c) { name = c; return *this; }
#define PROP_PTR(type, name) \
const type *name = nullptr;\
Self& set_##name(const type *c) { name = c; return *this; }
#define PROP_ARRAY(type, count, name) \
type name[count] = {};\
Self& set_##name(size_t i, const type &c) { name[i] = c; return *this; }
struct ClearData {
typedef ClearData Self;
PROP(Vec4, color, {0.0f, 0.0f, 0.0f, 1.0f});
PROP(float, depth, 1.0f);
PROP(int32_t, stencil, 0);
PROP(bool, clear_color, true);
PROP(bool, clear_depth, true);
PROP(bool, clear_stencil, false);
};
struct SetupViewData {
typedef SetupViewData Self;
struct Viewport {
uint16_t x,y,width, height;
};
PROP(Viewport, viewport, {});
PROP(Mat4, view_matrix, Mat4::Identity());
PROP(Mat4, projection_matrix, Mat4::Identity());
PROP(Framebuffer, framebuffer, {})
};
struct SetupPipelineData {
typedef SetupPipelineData Self;
PROP(Pipeline, pipeline, {});
PROP_ARRAY(Texture, kMaxTextureUnits, texture);
PROP_ARRAY(Buffer, kMaxVertexAttribs, buffer);
PROP(Vec4, scissor, {});
PROP(Mat4, model_matrix, Mat4::Identity());
PROP_PTR(void, uniforms);
};
struct RenderData {
typedef RenderData Self;
PROP(Buffer, index_buffer, {});
PROP(uint32_t, offset, 0);
PROP(uint32_t, count, 0);
PROP(uint32_t, instances, 1);
PROP(IndexFormat::Enum, type, IndexFormat::UInt16);
};
struct FillBufferData {
typedef FillBufferData Self;
PROP(Buffer, buffer, {});
PROP(uint32_t, offset, 0);
PROP(uint32_t, size, 0);
PROP_PTR(void,data); // data could be null if you're for example building mipmaps only...
};
struct FillTextureData {
typedef FillTextureData Self;
PROP(Texture, texture, {});
PROP(uint16_t, offset_x, 0);
PROP(uint16_t, offset_y, 0);
PROP(uint16_t, offset_z, 0);
PROP(uint16_t, width, 0); // if 0 --> texture.width
PROP(uint16_t, height, 0); // if 0 --> texture.height
PROP(uint16_t, depth, 0); // if 0 --> texture.depth
PROP(bool, build_mipmap, false);
PROP_PTR(void,data);
};
#undef PROP
#undef PROP_PTR
#undef PROP_ARRAY
// clears previous contents, and prepares the display list to
// be filled from the start.
void reset();
// finishes last command added to the display list, copying everything it needs
// internally. This is optional as long as you submit displaylist immediately after
// they are filled. If you plan to store a display list you must call finish to ensure
// all data is copied.
void commitLastCommand();
// -- Add then modify API --------------------------------
// *WARNING* the result reference of these methods is only
// valid up until any other command is added to the DisplayList
// you should always add, modify, and forget about the variable.
// Do not keep the reference!! in any form.
ClearData& clearCommand();
SetupViewData &setupViewCommand();
SetupPipelineData& setupPipelineCommand();
RenderData& renderCommand();
FillBufferData& fillBufferCommand();
FillTextureData& fillTextureCommand();
//--------------------------------------------------------
void add(const ClearData&d) { clearCommand() = d;}
void add(const SetupViewData &d) { setupViewCommand() = d; }
void add(const SetupPipelineData &d) { setupPipelineCommand() = d; }
void add(const RenderData &d) { renderCommand() = d; }
void add(const FillBufferData &d) { fillBufferCommand() = d; }
void add(const FillTextureData &d) { fillTextureCommand() = d; }
DisplayList& destroy(const Texture &t);
DisplayList& destroy(const Buffer &b);
DisplayList& destroy(const Pipeline&p);
DisplayList& destroy(const Framebuffer &fb);
DisplayList clone() const;
struct Data;
struct Command;
Data *data_ = nullptr;
};
struct RenderContextParams {
// Max number of any element is 2^20... the other 12 bits are
// reserved to detect dangling pointers.
uint32_t max_textures = 128;
uint32_t max_buffers = 128;
uint32_t max_framebuffers = 128;
uint32_t max_pipelines = 64;
// if no error callback is provider, stderr will be used to spit
// out possible problems. Once an error is produced, there is no
// guarantee that any given command will not end in crashing the app.
void (*on_error_callback)(const char *error) = nullptr;
};
struct RenderContext {
RenderContext();
~RenderContext();
// allocate resources to handle all objects that can be created later
void init(const RenderContextParams ¶ms = RenderContextParams());
// marks the render context for destruction on the next executeOnGPU
void finish();
Texture createTexture(const Texture::Info &info);
Buffer createBuffer(const Buffer::Info &info);
Pipeline createPipeline(const Pipeline::Info &info);
Framebuffer createFramebuffer(const Framebuffer::Info &info);
// submits a display list, stealing all of its content, and resetting the
// object to a default initial state.
void submitDisplayList(DisplayList *dl);
// submits a display list, stealing all of its content, and resetting the
// object to a default initial state. It also issues a FrameSwap.
void submitDisplayListAndSwap(DisplayList *dl);
void submitDisplayList(DisplayList &&dl);
void submitDisplayListAndSwap(DisplayList &&dl);
void submitDisplayListCopy(const DisplayList &dl) { submitDisplayList(dl.clone()); }
void submitDisplayListCopyAndSwap(const DisplayList &dl) { submitDisplayListAndSwap(dl.clone()); }
struct Result {
enum Enum {
Finished = 0, //> stop calling executeOnGPU
OK, //> Last executeOnGPU ended OK
OK_Swap, //> Last executeOnGPU ended OK and swap is needed
// to present results to the user.
};
};
// This method should be called in a loop from the thread that
// created the render context until it returns Result::Finished.
// If returns OK_Swap you should call the proper swap command of
// the window.
Result::Enum executeOnGPU();
RenderContext(const RenderContext&) = delete;
RenderContext& operator=(const RenderContext&) = delete;
struct Data;
Data *data_ = nullptr;
};
}
#endif // PX_RENDER
#if defined(PX_RENDER_IMPLEMENTATION) && !defined(PX_RENDER_IMPLEMENTATION_DONE)
#define PX_RENDER_IMPLEMENTATION_DONE
#if !defined(PX_RENDER_BACKEND_GL) \
&& !defined(PX_RENDER_BACKEND_GLES)
# define PX_REDER_BACKEND_GL
#endif
#ifndef PX_RENDER_DEBUG_LEVEL
#define PX_RENDER_DEBUG_LEVEL 100
#endif
#ifndef PX_RENDER_DEBUG_FUNC
# ifdef PX_RENDER_DEBUG
# define PX_RENDER_DEBUG_FUNC(LEVEL,...) {if(LEVEL< PX_RENDER_DEBUG_LEVEL) {fprintf(stdout, __VA_ARGS__);fflush(stdout);}}
# else
# define PX_RENDER_DEBUG_FUNC(...) /*nothing*/
# endif
#endif
#include <vector>
#include <algorithm>
#include <memory>
#include <thread>
#include <condition_variable>
#include <type_traits>
#include <atomic>
#include <list>
#include <mutex>
#include <string>
#include <cstring>
#include <cmath>
#include <cassert>
#include <cstdarg>
namespace px_render {
template<class T>
struct Mem {
std::unique_ptr<T[]> data;
size_t count = 0;
T& operator[](size_t pos) {
assert(pos < count && "Invalid position...");
return data[pos];
}
const T& operator[](size_t pos) const {
assert(pos < count && "Invalid position...");
return data[pos];
}
Mem() {}
Mem(Mem &&m) {
data = std::move(m.data);
count = m.count;
m.count = 0;
}
Mem(const Mem &m) = delete;
Mem& operator=(Mem &&) = delete;
Mem& operator=(const Mem &) = delete;
void copy(const T* ptr, size_t c) {
data = std::make_unique<T[]>(c);
for (size_t i = 0; i < c; ++i) {
data[i] = ptr[i];
}
count = c;
}
void copy(const Mem &m) { copy(m.data.get(), m.count); }
void alloc(size_t c) {
data = std::make_unique<T[]>(c);
count = c;
}
};
// -- Implementation -------------------------------------------------------
struct InstanceBase {
uint32_t version = 0;
std::atomic<uint32_t> state = {0};
bool acquire() {
uint32_t v = (version+1);
if (!v) v = 1;
uint32_t e = 0;
if (state.compare_exchange_weak(e, v)) {
version = v;
return true;
}
return false;
}
void release() {
state = 0;
}
};
struct PipelineInstance : public InstanceBase {
Pipeline::Info info;
// Internal copy of strings
Mem<char> vertex_shader;
Mem<char> fragment_shader;
Mem<char> attributes[kMaxVertexAttribs];
};
struct BufferInstance : public InstanceBase{
Buffer::Info info;
};
struct TextureInstance : public InstanceBase{
Texture::Info info;
size_t bytes_per_pixel = 0;
};
struct FramebufferInstance : public InstanceBase{
Framebuffer::Info info;
Mem<Texture> color_texture;
Texture depth_texture;
};
struct BackEnd;
static size_t ComputeVertexSize(uint32_t format) {
uint32_t type = (format & VertexFormat::TypeMask)>> VertexFormat::TypeShift;
uint32_t count = (format & VertexFormat::NumComponentsMask) >> VertexFormat::NumComponentsShift;
uint32_t result = count;
switch (type) {
// 1
case VertexFormat::Int8: break;
case VertexFormat::UInt8: break;
// 2
case VertexFormat::Int16:
case VertexFormat::UInt16: result *=2; break;
// 4
case VertexFormat::Int32:
case VertexFormat::UInt32:
case VertexFormat::Float: result *= 4; break;
default:
// ERROR
return 0;
}
return result;
}
struct DisplayList::Command {
struct Type {
enum Enum {
Invalid = 0,
Clear,
TextureData,
BufferData,
SetupView,
SetupPipeline,
FillBuffer,
FillTexture,
Render,
DestroyResource,
Scissor,
};
};
static const size_t kPayloadSize = std::max<size_t>({
sizeof(ClearData),
sizeof(SetupViewData),
sizeof(SetupPipelineData),
sizeof(RenderData),
sizeof(FillBufferData),
sizeof(FillTextureData),
});
//static const size_t kPayloadSizeAligned64 =(kPayloadSize+7)>>3;
Type::Enum type = Type::Invalid;
uint8_t data[kPayloadSize];
uint32_t payload_index = (uint32_t)-1;
};
struct DisplayList::Data {
std::vector<Command> commands;
std::vector<Mem<uint8_t>> payloads;
bool last_command_patched = true;
void reset() {
commands.clear();
payloads.clear();
last_command_patched = true;
}
void copy(const Data &d) {
commands = d.commands; // relay on copy from std::vector
// since Mem<T> doesn't allow copy, we explicitly copy each
// element.
payloads.resize(d.payloads.size());
for (size_t i = 0; i < d.payloads.size(); ++i) {
payloads[i].copy(d.payloads[i]);
}
last_command_patched = d.last_command_patched;
}
};
struct RenderContext::Data {
static const uint32_t kNumStoredFrames = 4;
struct RenderElement {
DisplayList::Data display_list;
std::condition_variable cv;
std::mutex mutex;
bool empty = true;
bool swap = false;
};
bool marked_for_finish = false;
uint32_t r_list_pos = 0;
RenderElement list[kNumStoredFrames];
std::atomic<uint32_t> w_list_pos = {};
// instances ---------------------------------
Mem<PipelineInstance> pipelines;
Mem<BufferInstance> buffers;
Mem<TextureInstance> textures;
Mem<FramebufferInstance> framebuffers;
// Render State ------------------------------
Mat4 view_matrix;
Mat4 inv_view_matrix;
bool inv_view_matrix_computed = false;
Mat4 projection_matrix;
Mat4 inv_projection_matrix;
bool inv_projection_matrix_computed = false;
Mat4 model_matrix;
RenderContextParams params;
DisplayList::SetupPipelineData last_pipeline = {};
// Back end -----------------------------------
BackEnd *back_end = nullptr;
};
static void OnError(const RenderContext::Data *ctx, const char *format, ...) {
va_list args;
va_start(args, format);
char buffer[2048];
std::vsnprintf(buffer, 2048, format, args);
va_end(args);
PX_RENDER_DEBUG_FUNC(0, "px_render ERROR --> %s\n", buffer);
if (ctx->params.on_error_callback) {
ctx->params.on_error_callback(buffer);
} else {
assert(!"FATAL ERROR");
}
}
template<class T>
static uint32_t AcquireResource(RenderContext *ctx, Mem<T> *pool) {
uint32_t try_count = 10; //<... should never need this but...
while (try_count--) {
for (uint32_t i = 0; i < pool->count; ++i) {
if ((*pool)[i].acquire()) {
uint32_t version = (*pool)[i].version;
uint32_t result = i | (version << 20);
PX_RENDER_DEBUG_FUNC(100, "AcquireResource %s [%u (%u,%u)]\n", typeid(T).name(), result, i, version);
return result;
}
}
}
// ... no luck
OnError(ctx->data_, "Could not allocate instance of type[T]");
return 0;
}
static uint32_t IDToIndex(uint32_t id) {
return id & 0x000FFFFF;
}
static std::pair<uint32_t, uint32_t> IDToIndexAndVersion(uint32_t id) {
uint32_t pos = id & 0x000FFFFF;
uint32_t version = (id & 0xFFF00000)>>20;
return {pos,version};
}
template<class T>
static bool CheckValidResource(const RenderContext::Data *ctx, uint32_t id, const Mem<T> *pool) {
auto pv = IDToIndexAndVersion(id);
uint32_t pos = pv.first;
uint32_t version = pv.second;
const T* result = &(*pool)[pos];
uint32_t real_version = (result->state.load() & 0xFFF);
if (real_version == version) {
return true;
}
PX_RENDER_DEBUG_FUNC(10,"Ivalid Resource %s [%u (%u,%u != %u)]\n", typeid(T).name(), id, pos, version, real_version);
return false;
}
template<class T>
static void CheckValidResourceOrError(const RenderContext::Data *ctx, uint32_t id, const Mem<T> *pool) {
if (!CheckValidResource(ctx, id, pool)) {
auto pv = IDToIndexAndVersion(id);
OnError(ctx, "Invalid Resource Pointer (Dangling reference) ref %u --> pos %u, version %u", id, pv.first, pv.second);
}
}
template<class T, class B>
static std::pair<T*,B*> GetResource(RenderContext::Data *ctx, uint32_t id, Mem<T> *instance_array, Mem<B> *backend_array) {
CheckValidResourceOrError(ctx, id, instance_array);
uint32_t index = IDToIndex(id);
return {&(*instance_array)[index], &(*backend_array)[index]};
}
template<class T>
static T* GetResource(RenderContext::Data *ctx, uint32_t id, Mem<T> *instance_array) {
CheckValidResourceOrError(ctx, id, instance_array);
uint32_t index = IDToIndex(id);
return &(*instance_array)[index];
}
static void InitBackEnd(BackEnd **b, const RenderContextParams ¶ms);
static void DestroyBackEnd(BackEnd **b);
static void ExecuteDisplayList(RenderContext::Data *data, const DisplayList::Data *dl);
static void PatchLastDisplayListCommand(DisplayList::Data *dl);
static void SubmitDisplayList(RenderContext::Data *d, DisplayList::Data &&dl, bool swap) {
PatchLastDisplayListCommand(&dl);
uint32_t p = (d->w_list_pos.fetch_add(1))%RenderContext::Data::kNumStoredFrames;
auto &re = d->list[p];
std::unique_lock<std::mutex> lk(re.mutex);
re.cv.wait(lk, [&re, &d]{return re.empty || d->marked_for_finish;});
if (!d->marked_for_finish) {
re.display_list = std::move(dl);
re.empty = false;
re.swap = swap;
}
lk.unlock();
}
RenderContext::RenderContext() {
data_ = new Data();
}
RenderContext::~RenderContext() {
delete data_;
data_ = nullptr;
}
void RenderContext::init(const RenderContextParams ¶ms) {
data_->params = params;
data_->pipelines.alloc(params.max_pipelines);
data_->framebuffers.alloc(params.max_framebuffers);
data_->buffers.alloc(params.max_buffers);
data_->textures.alloc(params.max_textures);
InitBackEnd(&data_->back_end, params);
}
DisplayList::DisplayList() {
data_ = new Data();
}
DisplayList::~DisplayList() {
delete data_;
data_ = nullptr;
}
DisplayList DisplayList::clone() const {
DisplayList copy;
copy.data_->copy(*data_);
return copy;
}
Texture RenderContext::createTexture(const Texture::Info &info) {
if (info.format == TexelsFormat::None) return Texture();
uint32_t id = AcquireResource(this, &data_->textures);
uint32_t pos = IDToIndex(id);
TextureInstance &i_obj = data_->textures.data[pos];
i_obj.info = info;
switch(info.format) {
case TexelsFormat::R_U8:
i_obj.bytes_per_pixel = 1;
break;
case TexelsFormat::RG_U8:
i_obj.bytes_per_pixel = 2;
break;
case TexelsFormat::RGB_U8:
i_obj.bytes_per_pixel = 3;
break;
case TexelsFormat::RGBA_U8:
i_obj.bytes_per_pixel = 4;
break;
case TexelsFormat::Depth_U16:
i_obj.bytes_per_pixel = 2;
break;
case TexelsFormat::DepthStencil_U16:
i_obj.bytes_per_pixel = 4;
break;
}
return Texture{this, id};
}
Buffer RenderContext::createBuffer(const Buffer::Info &info) {
uint32_t id = AcquireResource(this, &data_->buffers);
uint32_t pos = IDToIndex(id);
BufferInstance &i_obj = data_->buffers.data[pos];
i_obj.info = info;
return Buffer{this,id};
}