-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathglemu.cpp
2242 lines (1939 loc) · 106 KB
/
glemu.cpp
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
//NOTE(Ray):GLEMU implementation file is seperated for reading convience only
#ifdef YOYOIMPL
namespace OpenGLEmu
{
GLEMURenderCommandList command_list;
//Samplers
SamplerDescriptor defaults;
SamplerDescriptor samplerdescriptor;
SamplerState default_sampler_state;
DepthStencilDescription default_depth_stencil_description;
DepthStencilDescription current_depth_stencil_description;
DepthStencilDescription ds;
uint32_t current_reference_value;
bool is_stencil_enabled;
DepthStencilState default_depth_stencil_state;
DepthStencilState curent_depth_stencil_state;
RenderShader default_shader;
GLProgram default_program;
GLProgram current_program;
AnythingCache buffercache;
//NOTE(Ray):intention was variable sized buffers for uniforms but decided on not using
//Moving to fixed size vectors for each shader set since there should be only one set of uniforms
//per shader. simpler easier but will keep cpubuffers around for variable size implementation
//later which we will sure use later for something else.
AnythingCache cpubuffercache;
AnythingCache programcache;
AnythingCache depth_stencil_state_cache;//We cache the depthstates here so we dont create any more than neccessarry.
//the amount of these will probably be limited so once created we will probably wont need to free as far as I can tell.
AnythingCache gl_texturecache;//In order to properly handle deleted textures across multiple objects we offer a way to query for and tracking of ..
//delted adn allocated textures.
memory_index default_buffer_size;
DrawCallTables draw_tables;
ResourceManagementTables resource_managment_tables;
uint32_t uniform_buffer_bindkey = 0;//OPENGLEMU reserves the zero bind key for cpu bindings no one else can use this key for cpu bindings.
YoyoVector currently_bound_buffers;
YoyoVector currently_bound_frag_textures;
float2 range_of_current_bound_buffers;//x start index into currentbound buffers and y is count to iterate over.
float2 range_of_current_bound_frag_textures;//x start index into currentbound buffers and y is count to iterate over.
GLTexture default_texture;
float4 default_tex_data[4];
uint32_t draw_index;
//Mutexes
TicketMutex texture_mutex;
TicketMutex buffer_mutex;////NOTE(Ray):current not used
//Used to be spritebatch needs a new home
uint32_t current_buffer_index;
uint32_t buffer_count;
uint32_t buffer_size;
DispatchSemaphoreT semaphore;
GPUBuffer buffer[3];
MemoryArena arena[3];
GPUBuffer atlas_index_buffer[3];
MemoryArena atlas_index_arena[3];
//??
// GPUBuffer matrix_variable_size_buffer[3];
// MemoryArena matrix_variable_size_arena[3];
//matrix buffer add on for those who might need it.
GPUBuffer matrix_buffer;//uniform
MemoryArena matrix_buffer_arena;
bool debug_out_program_change = false;
bool debug_out_high = false;
bool debug_out_general = true;
bool debug_out_uniforms = false;
bool debug_out_signpost = true;
RenderPipelineState prev_frame_pipeline_state;
RenderPipelineState default_pipeline_state;
Texture default_depth_stencil_texture;
void VerifyCommandBuffer(GLEMUBufferState state)
{
u32 current_command_index = 0;
uint32_t index = 0;
while (index < command_list.count)
{
GLEMUCommandHeader* header = (GLEMUCommandHeader*)command_list.buffer.base;
GLEMUBufferState command_type = header->type;
if(index == command_list.count)
{
Assert(state == header->type);
}
++index;
}
}
VertexDescriptor CreateDefaultVertexDescriptor()
{
VertexDescriptor vertex_descriptor = RenderEncoderCode::NewVertexDescriptor();
//vertesx descriptors
VertexAttributeDescriptor vad;
vad.format = VertexFormatFloat3;
vad.offset = 0;
vad.buffer_index = 0;
RenderEncoderCode::AddVertexAttribute(&vertex_descriptor,vad);
VertexAttributeDescriptor vcad;
vcad.format = VertexFormatFloat4;
vcad.offset = float3::size();
vcad.buffer_index = 0;
RenderEncoderCode::AddVertexAttribute(&vertex_descriptor,vcad);
VertexAttributeDescriptor uv_ad;
uv_ad.format = VertexFormatFloat2;
uv_ad.offset = float3::size() + float4::size();
uv_ad.buffer_index = 0;
RenderEncoderCode::AddVertexAttribute(&vertex_descriptor,uv_ad);
//vertex layouts
VertexBufferLayoutDescriptor vbld;
vbld.step_function = step_function_per_vertex;
vbld.step_rate = 1;
vbld.stride = float3::size() + float4::size() + float2::size();
RenderEncoderCode::AddVertexLayout(&vertex_descriptor,vbld);
return vertex_descriptor;
}
DepthStencilDescription CreateDefaultDepthStencilDescription()
{
DepthStencilDescription depth_desc = RendererCode::CreateDepthStencilDescriptor();
depth_desc.depthWriteEnabled = false;
depth_desc.depthCompareFunction = compare_func_always;
return depth_desc;
}
DepthStencilState CreateDefaultDepthState()
{
DepthStencilState depth_state = RendererCode::NewDepthStencilStateWithDescriptor(&default_depth_stencil_description);
AnythingCacheCode::AddThing(&depth_stencil_state_cache,&default_depth_stencil_description,&depth_state);
return depth_state;
}
YoyoVector temp_deleted_tex_entries;
uint64_t glemu_tex_id;
//Need to initialize these.
RenderPassDescriptor default_render_pass_descriptor;
RenderPassBuffer pass_buffer;
void APInit()
{
command_list.buffer = PlatformAllocatePartition(MegaBytes(20));
is_stencil_enabled = false;
float2 dim = RendererCode::dim;
TextureDescriptor depth_texture_desc = RendererCode::Texture2DDescriptorWithPixelFormat(PixelFormatDepth32Float_Stencil8,dim.x(),dim.y(),false);
depth_texture_desc.usage = TextureUsageRenderTarget;
depth_texture_desc.storageMode = StorageModePrivate;
depth_texture_desc.pixelFormat = PixelFormatDepth32Float_Stencil8;
Texture depth_texture = RendererCode::NewTextureWithDescriptor(depth_texture_desc);
RenderPassDescriptor sp_rp_desc = RenderEncoderCode::NewRenderPassDescriptor();
//depth attachment description
sp_rp_desc.depth_attachment.description.texture = depth_texture;
sp_rp_desc.depth_attachment.description.loadAction = LoadActionClear;
sp_rp_desc.depth_attachment.description.storeAction = StoreActionStore;
sp_rp_desc.depth_attachment.clear_depth = 1.0f;
//stencil attachment description
sp_rp_desc.stencil_attachment.description.texture = depth_texture;
sp_rp_desc.stencil_attachment.description.loadAction = LoadActionClear;
sp_rp_desc.stencil_attachment.description.storeAction = StoreActionStore;
sp_rp_desc.stencil_attachment.clearStencil = 0.0f;
sp_rp_desc.depth_attachment = sp_rp_desc.depth_attachment;
sp_rp_desc.stencil_attachment = sp_rp_desc.stencil_attachment;
RendererCode::SetRenderPassDescriptor(&sp_rp_desc);
RenderPassColorAttachmentDescriptor sprite_rp_ca_desc = {};
sprite_rp_ca_desc.clear_color = float4(0.392f,0.584f,0.929f,1);//corflower blue of course
sprite_rp_ca_desc.description.loadAction = LoadActionLoad;
sprite_rp_ca_desc.description.storeAction = StoreActionStore;
RenderEncoderCode::AddRenderPassColorAttachment(&sp_rp_desc,&sprite_rp_ca_desc);
RenderEncoderCode::SetRenderPassColorAttachmentDescriptor(&sp_rp_desc,0);
default_render_pass_descriptor = sp_rp_desc;
RenderMaterial material = SpriteBatchCode::CreateSpriteBatchMaterials("spritebatch_vs_matrix_indexed","spritebatch_fs_single_sampler","Test matrix buffer");
default_pipeline_state = material.pipeline_state;
for(int i = 0;i < buffer_count;++i)
{
uint32_t size = (uint32_t)buffer_size;
buffer[i] = RenderGPUMemory::NewBufferWithLength(size,ResourceStorageModeShared);
//Assert(buffer[i].buffer);
arena[i] = AllocatePartition(size,buffer[i].data);
//NOTE(RAY):Same of max sprites for this sprite batch perhaps we should just take and set the max number of sprites
//to be used per batch or capacity as another way to put it.
uint32_t atlas_index_buffer_size = (size / SIZE_OF_SPRITE_IN_BYTES) * sizeof(uint32_t);
atlas_index_buffer[i] = RenderGPUMemory::NewBufferWithLength(atlas_index_buffer_size,ResourceStorageModeShared);
//Assert(atlas_index_buffer[i].buffer);
atlas_index_arena[i] = AllocatePartition(atlas_index_buffer_size,atlas_index_buffer[i].data);
// matrix_variable_size_arena[i] = AllocatePartition(atlas_index_buffer_size,matrix_variable_size_buffer[i].data);
}
uint32_t size = (uint32_t)buffer_size;
matrix_buffer = RenderGPUMemory::NewBufferWithLength(size,ResourceStorageModeShared);
Assert(matrix_buffer.buffer);
matrix_buffer_arena = AllocatePartition(size,matrix_buffer.data);
}
void Init()
{
RenderCache::Init(MAX_PSO_STATES);
glemu_tex_id = 0;
//TODO(Ray):Make this resizable. GIve more control to the user over the allocation space usage
//lifetimes without too much hassle.
// default_buffer_size = MegaBytes(1);
default_buffer_size = MegaBytes(2);
buffer_count = 3;
buffer_size = 1024 * SIZE_OF_SPRITE_IN_BYTES;
temp_deleted_tex_entries = YoyoInitVector(1,GLTextureKey,false);
semaphore = RenderSynchronization::DispatchSemaphoreCreate(buffer_count);
//NOTE(RAY):We are intentionally using a lower number here to create collisions while testing and ensuring hashtable
//is robust. Increase this number to pretty much make sure collisions will be fewer if at all.
// The typical storage requirement is 4 bytes (64bits) per as the
//storage is of uint64.
#define SIZE_OF_CACHE_TABLES 9973
#define SIZE_OF_CACHE_TABLES_SMALL 9973 /// probably large enough for most small use cache to avoid collisions
AnythingRenderSamplerStateCache::Init(SIZE_OF_CACHE_TABLES_SMALL);
AnythingCacheCode::Init(&buffercache,SIZE_OF_CACHE_TABLES_SMALL,sizeof(TripleGPUBuffer),sizeof(uint64_t));
AnythingCacheCode::Init(&programcache,SIZE_OF_CACHE_TABLES,sizeof(GLProgram),sizeof(GLProgramKey));
AnythingCacheCode::Init(&cpubuffercache,SIZE_OF_CACHE_TABLES,sizeof(CPUBuffer),sizeof(uint64_t));
AnythingCacheCode::Init(&depth_stencil_state_cache,SIZE_OF_CACHE_TABLES,sizeof(DepthStencilState),sizeof(DepthStencilDescription));
AnythingCacheCode::Init(&gl_texturecache,SIZE_OF_CACHE_TABLES,sizeof(GLTexture),sizeof(GLTextureKey),true);
samplerdescriptor = RendererCode::CreateSamplerDescriptor();
defaults = samplerdescriptor;
VertexDescriptor vd = CreateDefaultVertexDescriptor();
default_program = AddProgramFromMainLibrary("spritebatch_vs_matrix_indexed","spritebatch_fs_single_sampler",vd);
default_shader = default_program.shader;
default_depth_stencil_description = CreateDefaultDepthStencilDescription();
default_depth_stencil_state = CreateDefaultDepthState();
//create default uniform cpu buffer
CreateCPUBufferAtBinding(uniform_buffer_bindkey,MegaBytes(10));
draw_tables.uniform_binding_table = YoyoInitVector(1,UniformBindingTableEntry,false);
draw_tables.texture_binding_table = YoyoInitVector(1,TextureBindingTableEntry,false);
draw_tables.buffer_binding_table = YoyoInitVector(1,BufferBindingTableEntry,false);
resource_managment_tables = {};
AnythingCacheCode::Init(&resource_managment_tables.released_textures_table,SIZE_OF_CACHE_TABLES,sizeof(ReleasedTextureEntry),sizeof(GLTextureKey),true);
currently_bound_buffers = YoyoInitVector(1,BufferBindingTableEntry,false);
currently_bound_frag_textures = YoyoInitVector(1,FragmentShaderTextureBindingTableEntry,false);
range_of_current_bound_buffers = float2(0.0f);
range_of_current_bound_frag_textures = float2(0.0f);
float2 dim = float2(2,2);
float4 b = float4(0.0f);
for(int i = 0;i < 4;++i)
{
default_tex_data[i] = b;
}
default_texture = TexImage2D(&default_tex_data,dim,PixelFormatRGBA8Unorm,TextureUsageShaderRead);
default_texture.sampler = GetDefaultSampler();
OpenGLEmu::APInit();
}
//NOTE(Ray):So when you delete a texture we mark it deleted and add to a deleted table...
//Everytime a texture is used for a frame we keep it around for n frames... if it gets used the counter resets...
//If it is never used after N frames limit we actually release it.
//TODO(Ray):Later what we could do here is result a texture if it matches the dimensions of another texture.
//than if the amount of unused textures grows beyone a certain limit release the resources back to the GPU.
//Could use resource heaps if we really want to ball before now... just doing the easiest thing.
//For now we just do the N frame counting scheme and revisit this later.
void GLDeleteTexture(GLTexture* texture)
{
BeginTicketMutex(&texture_mutex);
GLTextureKey ttk = {};
ttk.format = texture->texture.descriptor.pixelFormat;
ttk.width = texture->texture.descriptor.width;
ttk.height = texture->texture.descriptor.height;
ttk.sample_count = texture->texture.descriptor.sampleCount;
ttk.storage_mode = texture->texture.descriptor.storageMode;
//ttk.allowGPUOptimizedContents = texture->texture.descriptor.allowGPUOptimizedContents;
ttk.gl_tex_id = texture->id;
//If we are not in the texturecache cant delete it since its not a texture we know about.
//And is not already been added to the released textures table.
if(AnythingCacheCode::DoesThingExist(&gl_texturecache,&ttk))
{
if(!AnythingCacheCode::DoesThingExist(&resource_managment_tables.released_textures_table,&ttk))
{
GLTexture* tex = GetThingPtr(&gl_texturecache,&ttk,GLTexture);
Assert(!texture->texture.is_released);
if(!tex->texture.is_released)
{
Assert(!tex->texture.is_released);
ReleasedTextureEntry rte = {};
rte.tex_key = ttk;
rte.delete_count = GLEMU_DEFAULT_TEXTURE_DELETE_COUNT;
rte.current_count = 0;
rte.thread_id = YoyoGetThreadID();
PlatformOutput(true,"BeginDeleteTexture id %d generated on thread %d on thread %d ¥n",texture->id,texture->gen_thread,rte.thread_id);
rte.is_free = false;
// tex->texture.is_released = true;
AnythingCacheCode::AddThingFL(&resource_managment_tables.released_textures_table,&ttk,&rte);
}
}
}
EndTicketMutex(&texture_mutex);
}
//NOTE(Ray)IMPORTANT:This must be used in a thread safe only section of code
//Actually this should only be used in one place that I can think of. Kind of a dumb
//function tbh
static inline uint64_t GLEMuGetNextTextureID()
{
return ++glemu_tex_id;
}
bool GLIsValidTexture(GLTexture texture)
{
bool result = false;
BeginTicketMutex(&texture_mutex);
GLTextureKey ttk = {};
ttk.format = texture.texture.descriptor.pixelFormat;
ttk.width = texture.texture.descriptor.width;
ttk.height = texture.texture.descriptor.height;
ttk.sample_count = texture.texture.descriptor.sampleCount;
ttk.storage_mode = texture.texture.descriptor.storageMode;
//ttk.allowGPUOptimizedContents = texture.texture.descriptor.allowGPUOptimizedContents;
ttk.gl_tex_id = texture.id;
if(!AnythingCacheCode::DoesThingExist(&gl_texturecache,&ttk))
{
result = false;
}
else if(!AnythingCacheCode::DoesThingExist(&resource_managment_tables.released_textures_table,&ttk))
{
result = true;
}
else
{
result = false;
}
EndTicketMutex(&texture_mutex);
return result;
}
void CheckPurgeTextures()
{
//NOTE(RAY):Making sure that we do not add or remove textures at this point or beyond.
BeginTicketMutex(&texture_mutex);
int pop_count = 0;
for(int i = 0;i < resource_managment_tables.released_textures_table.anythings.count;++i)
{
ReleasedTextureEntry* rte = YoyoGetVectorElement(ReleasedTextureEntry,&resource_managment_tables.released_textures_table.anythings,i);
if(rte)
{
++rte->current_count;
if(rte->current_count >= rte->delete_count && rte->is_free == false)
{
if(AnythingCacheCode::DoesThingExist(&gl_texturecache,&rte->tex_key))
{
GLTexture* tex = GetThingPtr(&gl_texturecache,&rte->tex_key,GLTexture);
if(tex->texture.descriptor.usage == 5)
{
continue;
}
Assert(tex->id == rte->tex_key.gl_tex_id);
Assert(tex->texture.state);
Assert(!tex->texture.is_released);
Assert(!tex->is_released);
//NOTE(RAY):There is some unknown crash inside set purgable state //TODO(Ray):Need to figure out what is causing it.
PlatformOutput(true,"Finalalize delete texture id %d generated on thread %d on thread %d \n",tex->id,tex->gen_thread,rte->thread_id);
RendererCode::ReleaseTexture(&tex->texture);
tex->is_released = true;
tex->texture.is_released = true;
}
#if GLEMU_DEBUG
else
{
Assert(false);
}
#endif
YoyoStretchPushBack(&temp_deleted_tex_entries,rte->tex_key);
rte->tex_key = {};
rte->thread_id = 0;
rte->current_count = 0;
rte->is_free = true;
}
}
}
for(int i = 0;i < temp_deleted_tex_entries.count;++i)
{
GLTextureKey* tkey = (GLTextureKey*)temp_deleted_tex_entries.base + i;
AnythingCacheCode::RemoveThingFL(&resource_managment_tables.released_textures_table,tkey);
AnythingCacheCode::RemoveThingFL(&gl_texturecache,tkey);
}
YoyoClearVector(&temp_deleted_tex_entries);
EndTicketMutex(&texture_mutex);
}
SamplerState GetSamplerStateWithDescriptor(SamplerDescriptor desc)
{
SamplerState* result;
if(AnythingRenderSamplerStateCache::DoesSamplerStateExists(&desc))
{
result = AnythingRenderSamplerStateCache::GetSamplerState(&desc);
}
else
{
SamplerState new_sampler_state = RenderGPUMemory::NewSamplerStateWithDescriptor(&desc);
AnythingRenderSamplerStateCache::AddSamplerState(&desc,&new_sampler_state);
result = AnythingRenderSamplerStateCache::GetSamplerState(&desc);
}
//Assert(result);
return (*result);
}
//Draw call and bindings
UniformBindingTableEntry GetUniEntryForDrawCall(uint32_t index)
{
UniformBindingTableEntry result = {};
UniformBindingTableEntry* entry = YoyoGetVectorElement(UniformBindingTableEntry,&draw_tables.uniform_binding_table,index);
if(entry)
{
result = *entry;
}
return result;
}
//end Draw
SamplerDescriptor GetSamplerDescriptor()
{
return samplerdescriptor;
}
SamplerDescriptor GetDefaultDescriptor()
{
return defaults;
}
SamplerState GetDefaultSampler()
{
default_sampler_state = GetSamplerStateWithDescriptor(defaults);
return default_sampler_state;
}
//Depth and Stencil
DepthStencilDescription GetDefaultDepthStencilDescriptor()
{
return default_depth_stencil_description;
}
DepthStencilState GetOrCreateDepthStencilState(DepthStencilDescription desc)
{
DepthStencilState result = {};
if(AnythingCacheCode::DoesThingExist(&depth_stencil_state_cache,&desc))
{
result = GetThingCopy(&depth_stencil_state_cache,(void*)&desc,DepthStencilState);
}
else
{
result = RendererCode::NewDepthStencilStateWithDescriptor(&desc);
result.desc = desc;
AnythingCacheCode::AddThing(&depth_stencil_state_cache,(void*)&desc,&result);
}
Assert(desc.depthCompareFunction == result.desc.depthCompareFunction);
Assert(desc.depthWriteEnabled == result.desc.depthWriteEnabled);
Assert(desc.backFaceStencil.stencilFailureOperation == result.desc.backFaceStencil.stencilFailureOperation);
Assert(desc.backFaceStencil.depthFailureOperation == result.desc.backFaceStencil.depthFailureOperation);
Assert(desc.backFaceStencil.stencilCompareFunction == result.desc.backFaceStencil.stencilCompareFunction);
Assert(desc.backFaceStencil.write_mask == result.desc.backFaceStencil.write_mask);
Assert(desc.backFaceStencil.read_mask == result.desc.backFaceStencil.read_mask);
Assert(desc.backFaceStencil.enabled == result.desc.backFaceStencil.enabled);
Assert(desc.frontFaceStencil.stencilFailureOperation == result.desc.frontFaceStencil.stencilFailureOperation);
Assert(desc.frontFaceStencil.depthFailureOperation == result.desc.frontFaceStencil.depthFailureOperation);
Assert(desc.frontFaceStencil.stencilCompareFunction == result.desc.frontFaceStencil.stencilCompareFunction);
Assert(desc.frontFaceStencil.write_mask == result.desc.frontFaceStencil.write_mask);
Assert(desc.frontFaceStencil.read_mask == result.desc.frontFaceStencil.read_mask);
Assert(desc.frontFaceStencil.enabled == result.desc.frontFaceStencil.enabled);
return result;
}
//Buffers
void CreateBufferAtBinding(uint64_t bindkey)
{
TripleGPUBuffer buffer = {};
for(int i = 0;i < 3;++i)
{
uint32_t size = (uint32_t)default_buffer_size;
buffer.buffer[i] = RenderGPUMemory::NewBufferWithLength(size,ResourceStorageModeShared);
Assert(buffer.buffer[i].data);
buffer.arena[i] = AllocatePartition(size,buffer.buffer[i].data);
}
uint64_t tt = bindkey;
AnythingCacheCode::AddThing(&buffercache,(void*)&tt,&buffer);
}
void AddBindingToBuffer(uint64_t buffer_key,uint64_t key)
{
uint64_t tt = key;
if(!AnythingCacheCode::DoesThingExist(&buffercache,&tt))
{
uint64_t* ptr = YoyoGetElementByHash(uint64_t,&buffercache.hash,&buffer_key,buffercache.hash.key_size);
YoyoAddElementToHashTable(&buffercache.hash,(void*)&tt,buffercache.key_size,ptr);
}
}
TripleGPUBuffer* GetBufferAtBinding(uint64_t bindkey)
{
uint64_t tt = bindkey;
return GetThingPtr(&buffercache,(void*)&tt,TripleGPUBuffer);
}
YoyoVector GetBufferList()
{
return buffercache.anythings;
}
YoyoVector GetProgramList()
{
return programcache.anythings;
}
YoyoVector GetTextureList()
{
return gl_texturecache.anythings;
}
void AddFragTextureBinding(GLTexture texture,uint32_t tex_index,uint32_t sampler_index)
{
Assert(texture.texture.state);
Assert(texture.sampler.state);
if(GLIsValidTexture(texture))
{
}
else
{
texture = default_texture;
}
FragmentShaderTextureBindingTableEntry entry = {};
entry.tex_index = tex_index;
entry.sampler_index = sampler_index;
entry.texture = texture;
YoyoStretchPushBack(¤tly_bound_frag_textures,entry);
float2 start_count = range_of_current_bound_frag_textures;
start_count += float2(0,1);
range_of_current_bound_frag_textures = start_count;
}
void AddFragTextureBinding(GLTexture texture,uint32_t index)
{
// Assert(!texture.texture.is_released);
Assert(texture.texture.state);
Assert(texture.sampler.state);
if(GLIsValidTexture(texture))
{
}
else
{
texture = default_texture;
}
FragmentShaderTextureBindingTableEntry entry = {};
entry.tex_index = index;
entry.sampler_index = index;
entry.texture = texture;
YoyoStretchPushBack(¤tly_bound_frag_textures,entry);
float2 start_count = range_of_current_bound_frag_textures;
start_count += float2(0,1);
range_of_current_bound_frag_textures = start_count;
}
//TODO(Ray):Add and test this someday
/*
void AddVertTextureBinding(Texture texture,uint32_t index)
{
FragmentShaderTextureBindingTableEntry entry;
entry.index = index;
entry.texture = texture;
YoyoStretchPushBack(¤tly_bound_frag_textures,entry);
float2 start_count = range_of_current_bound_frag_textures;
start_count += float2(0,1);
range_of_current_bound_frag_textures = start_count;
}
*/
void AddBufferBinding(uint64_t bind_key,uint64_t index,uint64_t offset)
{
BufferBindingTableEntry entry = {};
entry.key = bind_key;
entry.offset = offset;//NOTE(Ray):For now we will just hold the hole buffer rather than a key
entry.index = index;
YoyoStretchPushBack(¤tly_bound_buffers,entry);
float2 start_count = range_of_current_bound_buffers;
start_count += float2(0,1);
range_of_current_bound_buffers = start_count;
}
//CPU Only buffers mainly for uniforms
void CreateCPUBufferAtBinding(uint64_t bindkey,memory_index size)
{
//Start size will be something basic like 10k but resize at the end a
CPUBuffer buffer = {};
buffer.buffer = PlatformAllocatePartition(size);
buffer.ranges = YoyoInitVectorSize(1,float2::size(),false);
uint64_t tt = bindkey;
AnythingCacheCode::AddThing(&cpubuffercache,(void*)&tt,&buffer);
}
//Add a key to the list pointing to the buffer that is previously allocated.
//if the key is a duplicate no need to add it.
void AddCPUBindingToBuffer(uint64_t buffer_key,uint64_t key)
{
uint64_t tt = key;
if(!AnythingCacheCode::DoesThingExist(&cpubuffercache,&tt))
{
uint64_t* ptr = YoyoGetElementByHash(uint64_t,&cpubuffercache.hash,&buffer_key,cpubuffercache.hash.key_size);
YoyoAddElementToHashTable(&cpubuffercache.hash,(void*)&tt,cpubuffercache.key_size,ptr);
}
}
CPUBuffer* GetCPUBufferAtBinding(uint64_t bindkey)
{
if(cpubuffercache.key_size > 0)
{
uint64_t tt = bindkey;
return GetThingPtr(&cpubuffercache,(void*)&tt,CPUBuffer);
}
else
{
return 0;
}
}
YoyoVector GetCPUBufferList()
{
return cpubuffercache.anythings;
}
UniformBindResult AddUniformDataAtBinding(uint64_t bindkey,void* uniform_data,memory_index size)
{
UniformBindResult result;
CPUBuffer* buf = GetCPUBufferAtBinding(bindkey);
float2 oldft = float2(0.0f);
//This is hard to grasp make it easier to understand
//---------
float2* ft = YoyoPeekVectorElement(float2,&buf->ranges);
if(ft)
{
oldft = *ft;
}
float2 newft = float2(oldft.y(),oldft.y() + size);
YoyoStretchPushBack(&buf->ranges,newft);
partition_push_params params = DefaultPartitionParams();
params.Flags = PartitionFlag_None;
//copy uni data into buffer
//TODO(Ray):Allow for resizing
void* dst = (void*)PushSize(&buf->buffer, size,params);
if(uniform_data)
memcpy(dst,uniform_data,(uint32_t)newft.y());
result.ptr = dst;
result.data_index = buf->ranges.count - 1;
return result;
}
BufferOffsetResult GetUniformAtBinding(uint64_t bindkey,uint32_t index)
{
BufferOffsetResult result = {};
CPUBuffer* buf = GetCPUBufferAtBinding(bindkey);
float2* range_ptr = YoyoGetVectorElement(float2,&buf->ranges,index);
if(range_ptr)
{
float2 range = *range_ptr;
Assert(buf->buffer.used >= (uint32_t)range.y());
Assert((uint32_t)range.y() <= buf->buffer.size);
Assert(buf->buffer.used >= (uint32_t)range.x());
Assert((uint32_t)range.x() <= buf->buffer.size);
result.ptr = (void*)((uint8_t*)buf->buffer.base + (uint32_t)range.x());
result.size = range.y() - range.x();
}
else
{
result.ptr = nullptr;
result.size = 0;
}
return result;
}
//Shaders
GLProgram GetDefaultProgram()
{
return default_program;
}
GLProgram AddProgramFromSource(const char* v_s,const char* vs_name,const char* f_s,const char* fs_name,VertexDescriptor vd)
{
RenderShader s = {};
RenderShaderCode::InitShader(&s,(char*)v_s,(char*)vs_name,(char*)f_s,(char*)fs_name);
GLProgram result= {};
result.shader = s;
result.vd = vd;
result.last_fragment_buffer_binding = uniform_buffer_bindkey;
result.last_fragment_data_index = 0;
result.last_vertex_buffer_binding = uniform_buffer_bindkey;
result.last_vertex_data_index = 0;
GLProgramKey program_hash_key = {(uint64_t)s.vs_object,(uint64_t)s.ps_object};
AnythingCacheCode::AddThing(&programcache,(void*)&program_hash_key,&result);
GLProgram* p = GetProgramPtr(program_hash_key);
return result;
}
//NOTE(Ray):TODO(Ray):What would be nice is if we had some introspection into the shader and could get
//out and build the vertex description from that.
//Than use that to also drive what buffers we will need etc... for simpler and faster iteration times.
GLProgram AddProgramFromMainLibrary(const char* vs_name,const char* fs_name,VertexDescriptor vd)
{
RenderShader s = {};
RenderShaderCode::InitShaderFromDefaultLib(&s,vs_name,fs_name);
GLProgram result = {};
result.shader = s;
result.vd = vd;
result.last_fragment_buffer_binding = uniform_buffer_bindkey;
result.last_fragment_data_index = 0;
result.last_vertex_buffer_binding = uniform_buffer_bindkey;
result.last_vertex_data_index = 0;
GLProgram* p;
GLProgramKey program_hash_key = {(uint64_t)s.vs_object,(uint64_t)s.ps_object};
if(!AnythingCacheCode::DoesThingExist(&programcache,(void*)&program_hash_key))
{
AnythingCacheCode::AddThing(&programcache,(void*)&program_hash_key,&result);
}
else
{
p = (GLProgram*)AnythingCacheCode::GetThing(&programcache,(void*)&program_hash_key);
Assert(p);
}
p = GetProgramPtr(program_hash_key);
return result;
}
GLProgram GetProgram(GLProgramKey key)
{
return GetThingCopy(&programcache,&key,GLProgram);
}
GLProgram* GetProgramPtr(GLProgramKey key)
{
return GetThingPtr(&programcache,&key,GLProgram);
}
uint32_t GetDepthStencilStateCount()
{
return depth_stencil_state_cache.anythings.count;
}
DepthStencilDescription GetCurrentDepthStencilState()
{
return ds;
}
uint32_t GetCurrentStencilReferenceValue()
{
return current_reference_value;
}
UniformBindResult AddUniData(uint32_t buffer_binding,uint32_t data_index,GLProgram* p,uint32_t size)
{
BufferOffsetResult last = OpenGLEmu::GetUniformAtBinding(buffer_binding,data_index);
return AddUniformDataAtBinding(buffer_binding,last.ptr,size);
}
GLTexture TexImage2D(void* texels,float2 dim,PixelFormat format,SamplerDescriptor sd,TextureUsage usage)
{
BeginTicketMutex(&texture_mutex);
Assert(texels);
GLTexture texture = {};
texture.sampler = OpenGLEmu::GetDefaultSampler();
TextureDescriptor td = {};
td = RendererCode::Texture2DDescriptorWithPixelFormat(format,dim.x(),dim.y(),false);
#if OSX
td.storageMode = StorageModeManaged;
#endif
td.usage = (TextureUsage)usage;
texture.texture = RendererCode::NewTextureWithDescriptor(td);
//NOTE(Ray):This is ok as long as we are not releasing any descriptors but as soon as we did...
//we have to make sure this is a valid sampler that we add here and not one scheduled for deletion.
texture.sampler = OpenGLEmu::GetSamplerStateWithDescriptor(sd);
if(texels)
{
RenderRegion region;
region.origin = float3(0);
region.size = dim;
//TODO(Ray):We will need a more comprehensive way to check that we are passing in the proper parameters
//to Replace REgions for packed and compressed formats and proper bytes sizes to multiply width and
//for 1d arrays should pass in 0
int byte_size_of_format = 4;
#if IOS && !(OSX || __x86_64__ || __i386__)
if(format == PixelFormatABGR4Unorm)
byte_size_of_format = 2;
#endif
RenderGPUMemory::ReplaceRegion(texture.texture,region,0,texels,byte_size_of_format * dim.x());
}
texture.gen_thread = YoyoGetThreadID();
texture.id = GLEMuGetNextTextureID();
GLTextureKey k = {};
k.format = texture.texture.descriptor.pixelFormat;
k.width = texture.texture.descriptor.width;
k.height = texture.texture.descriptor.height;
k.sample_count = texture.texture.descriptor.sampleCount;
k.storage_mode = texture.texture.descriptor.storageMode;
//k.allowGPUOptimizedContents = texture.texture.descriptor.allowGPUOptimizedContents;
k.gl_tex_id = texture.id;
texture.texture.is_released = false;
texture.is_released = false;
if(!AnythingCacheCode::AddThingFL(&gl_texturecache,&k,&texture))
{
PlatformOutput(true,"Texture already Exist was not added to texture cache \n");
}
PlatformOutput(true,"TextureCreated id %d generated on thread %d on thread %d \n",texture.id,texture.gen_thread);
EndTicketMutex(&texture_mutex);
return texture;
}
GLTexture TexImage2D(void* texels,float2 dim,PixelFormat format,TextureUsage usage)
{
SamplerDescriptor sd = OpenGLEmu::GetDefaultDescriptor();
sd.r_address_mode = SamplerAddressModeClampToEdge;
sd.s_address_mode = SamplerAddressModeClampToEdge;
sd.min_filter = SamplerMinMagFilterLinear;
sd.mag_filter = SamplerMinMagFilterLinear;
return TexImage2D(texels,dim,format,sd,usage);
}
//NOTE(Ray):No uniform state can be larger than 2kb limitation of the SetVertexBytes API in METAL
//NOTE(Ray):Unlike gl We provide the last known state of the uniform data to the user so they can manipulate
//it how they see fit at each state more explicitely.
void* SetUniformsFragment_(memory_index size)
{
Assert(size <= KiloBytes(4));
GLProgramKey key = {(uint64_t)current_program.shader.vs_object,(uint64_t)current_program.shader.ps_object};
GLProgram* p = OpenGLEmu::GetProgramPtr(key);
Assert(p);
UniformBindResult result = AddUniData(p->last_fragment_buffer_binding,p->last_fragment_data_index,p,size);
p->last_fragment_data_index = result.data_index;
p->last_fragment_buffer_binding = p->last_fragment_buffer_binding;
return result.ptr;
}
void* SetUniformsVertex_(memory_index size)
{
Assert(size <= KiloBytes(4));
GLProgramKey key = {(uint64_t)current_program.shader.vs_object,(uint64_t)current_program.shader.ps_object};
GLProgram* p = OpenGLEmu::GetProgramPtr(key);
Assert(p);
UniformBindResult result = AddUniData(p->last_vertex_buffer_binding,p->last_vertex_data_index,p,size);
p->last_vertex_data_index = result.data_index;
p->last_vertex_buffer_binding = p->last_vertex_buffer_binding;
return result.ptr;
}
//NOTE(Ray):No sparse entries in tables.
uint32_t AddDrawCallEntry(BufferOffsetResult v_uni_bind,BufferOffsetResult f_uni_bind,BufferOffsetResult tex_binds)
{
UniformBindingTableEntry ue;
ue.call_index = draw_index;
ue.v_size = v_uni_bind.size;
ue.v_data = v_uni_bind.ptr;
ue.f_size = f_uni_bind.size;
ue.f_data = f_uni_bind.ptr;
uint32_t vf_index = YoyoStretchPushBack(&draw_tables.uniform_binding_table,ue);
TextureBindingTableEntry tex_entry;
tex_entry.call_index = draw_index;
tex_entry.size = tex_binds.size;
tex_entry.texture_ptr = tex_binds.ptr;
uint32_t index = YoyoStretchPushBack(&draw_tables.texture_binding_table,tex_entry);
draw_index++;
Assert(index == vf_index);
return index;
}
void EndDraw(uint32_t unit_size)
{
range_of_current_bound_buffers = float2(range_of_current_bound_buffers.y());
range_of_current_bound_frag_textures = float2(range_of_current_bound_frag_textures.y());
draw_index++;
}
//Commands
static inline void AddHeader(GLEMUBufferState type)
{
GLEMUCommandHeader* header = PushStruct(&command_list.buffer,GLEMUCommandHeader);
header->type = type;
}
#define AddCommand(type) (type*)AddCommand_(sizeof(type));
static inline void* AddCommand_(uint32_t size)
{
++command_list.count;
return PushSize(&command_list.buffer,size);
}
void PreFrameSetup()
{
command_list.buffer.used = 0;
command_list.count = 0;
uint32_t bi = current_buffer_index;
arena[bi].used = 0;
atlas_index_arena[bi].used = 0;
matrix_buffer_arena.used = 0;
draw_index = 0;
//reset all uniform buffers
CPUBuffer* ub = OpenGLEmu::GetCPUBufferAtBinding(0);
if(ub)
{
YoyoClearVector(&ub->ranges);
YoyoClearVector(&ub->unit_sizes);
ub->entry_count = 0;
ub->buffer.used = 0;
}
//Reset shader binding back to zero
YoyoVector pl = OpenGLEmu::GetProgramList();
for(int i = 0;i < pl.count;++i)
{
GLProgram* program = (GLProgram*)pl.base + i;
program->last_fragment_buffer_binding = 0;
program->last_fragment_data_index = 0;
program->last_vertex_buffer_binding = 0;
program->last_vertex_data_index = 0;
}
YoyoVector bl = OpenGLEmu::GetBufferList();
for (int i = 0; i < bl.count; ++i)
{
TripleGPUBuffer* buffer;
buffer = (TripleGPUBuffer*)bl.base + i;
buffer->from_to = float2(0.0f);
buffer->from_to_bytes = float2(0.0f);
buffer->arena[bi].used = 0;
buffer->current_count = 0;
}
YoyoClearVector(&draw_tables.uniform_binding_table);
YoyoClearVector(&draw_tables.texture_binding_table);
YoyoClearVector(¤tly_bound_buffers);
YoyoClearVector(¤tly_bound_frag_textures);